mirror of
https://github.com/zyycn/codex-proxy-rs.git
synced 2026-12-03 16:01:22 +00:00
Compare commits
26
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
99c5864914 | ||
|
|
060b275ce6 | ||
|
|
3c560b9276 | ||
|
|
77c42cea98 | ||
|
|
3eefb8d156 | ||
|
|
dd234c3619 | ||
|
|
df5d50bbf5 | ||
|
|
b5e691c63d | ||
|
|
2d0a52096a | ||
|
|
47620e217a | ||
|
|
48aeccd0e0 | ||
|
|
bdc618701b | ||
|
|
acd76a09dc | ||
|
|
808387442b | ||
|
|
5bc4e3e5c8 | ||
|
|
7e98130cac | ||
|
|
2821a5e3bd | ||
|
|
6a6a167d41 | ||
|
|
cffb6b35d2 | ||
|
|
17e50df06f | ||
|
|
f2d95cc3fa | ||
|
|
e4f6e1d4e3 | ||
|
|
66f650f097 | ||
|
|
ca4d02068a | ||
|
|
d185a639a9 | ||
|
|
3078dd9993 |
@@ -30,6 +30,8 @@
|
||||
|
||||
验证前按[界面验证](../../../../CONTRIBUTING.md#界面验证)明确本次受影响的用户路径、状态和通过条件。局部修改围绕受影响区域及相关操作验收;主题、窗口尺寸和空/加载/错误状态仅在受影响时补充,共用主题或基础组件变更按主题规范扩大范围
|
||||
|
||||
沿实际操作验证待确认、执行中、完成、失败与取消等受影响阶段,同时检查当前弹层和背景区域,核对应该出现的反馈与不应出现的状态。必要时延迟模拟响应以观察过渡状态,不能仅凭请求成功或截图齐全判定交互通过
|
||||
|
||||
通过后按[验证停止条件](../../../../CONTRIBUTING.md#验证)收尾;只有新改动、失败或未解疑点时补验相关部分。补交截图或 PR 材料时复用仍有效的运行证据
|
||||
|
||||
## 交付前
|
||||
@@ -42,7 +44,7 @@
|
||||
- **样式与状态**:是否使用对应 Token 与 utility,局部样式是否符合适用边界,受影响的主题、窄屏及交互状态是否正确
|
||||
- **模块归属**从调用方核对公开入口。页面或多文件组件通过 `index.vue` 提供界面,其他页面复用整页时引用所属模块的布局入口,独立复用的业务组件按领域放置
|
||||
- **Provider 边界**涉及账号操作、身份配置或定价时,沿接口响应、控件和提交载荷追踪同一条规则。服务端决定的能力使用接口字段,Provider 专属表单解释自己的字段,多个页面共用的编辑流程只维护一份。按[前端职责](../../../../docs/architecture.md#34-前端模块职责)核对归属
|
||||
- **查询与动作**:区分首次加载、刷新、分页、单行与批量操作,核对 loading、禁用状态的影响范围;沿用请求层错误处理,不在页面叠加同一错误的提示
|
||||
- **查询与动作**:区分首次加载、刷新、分页、单行与批量操作,明确当前动作的反馈归属及其他控件的禁用范围,避免同一动作在前后景重复显示执行反馈。待确认不等于已提交,复用交互时重新核对 loading、进度与结果的显示条件是否适用于当前动作;沿用请求层错误处理,不在页面叠加同一错误的提示
|
||||
- **运行证据**:按界面验证核对截图与实际交互,证据对应当前实现;页面 PR 的可访问图片和 Draft 条件按该节执行
|
||||
|
||||
交付简述所复用的页面或组件、实际验证范围及缺口;环境不足时如实说明,不能仅凭构建、源码或截图推断未验证的行为
|
||||
|
||||
Generated
+20
@@ -1887,6 +1887,7 @@ dependencies = [
|
||||
"tracing",
|
||||
"tracing-appender",
|
||||
"tracing-subscriber",
|
||||
"uuid",
|
||||
"wiremock",
|
||||
"yaml-rust2 0.13.2",
|
||||
]
|
||||
@@ -2707,6 +2708,12 @@ version = "0.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154"
|
||||
|
||||
[[package]]
|
||||
name = "lzma-rust2"
|
||||
version = "0.26.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4c7861572250348d13073a9035c6a83f3e583ec9a76a65ce92f338fe1107d8f5"
|
||||
|
||||
[[package]]
|
||||
name = "lzma-sys"
|
||||
version = "0.1.20"
|
||||
@@ -3404,6 +3411,7 @@ dependencies = [
|
||||
"reqwest",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sevenz-rust2",
|
||||
"sha2",
|
||||
"tar",
|
||||
"tempfile",
|
||||
@@ -4185,6 +4193,18 @@ dependencies = [
|
||||
"stable_deref_trait",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sevenz-rust2"
|
||||
version = "0.27.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2e668242e054ba8b7360918104c30c6685bdedf847909a784cf267d002f40a6a"
|
||||
dependencies = [
|
||||
"crc32fast",
|
||||
"js-sys",
|
||||
"lzma-rust2",
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sha1"
|
||||
version = "0.10.7"
|
||||
|
||||
@@ -79,7 +79,7 @@ impl Providers {
|
||||
)
|
||||
.await?;
|
||||
environment.host.report_startup_ready("OpenAI Provider");
|
||||
let antigravity = provider_antigravity::initialize(ports.clone())?;
|
||||
let antigravity = provider_antigravity::initialize(ports.clone()).await?;
|
||||
environment
|
||||
.host
|
||||
.report_startup_ready("Antigravity Provider");
|
||||
|
||||
@@ -263,10 +263,11 @@ impl ScheduledTask for FreezeRecoveryTask {
|
||||
context: WorkerCycleContext,
|
||||
) -> futures::future::BoxFuture<'_, Result<(), WorkerTaskError>> {
|
||||
Box::pin(async move {
|
||||
if context.cancellation().is_cancelled() {
|
||||
return Ok(());
|
||||
}
|
||||
self.run_cycle_inner().await;
|
||||
// 中止在途探测,避免把停机当成探测失败而延长冻结
|
||||
context
|
||||
.cancellation()
|
||||
.run_until_cancelled(self.run_cycle_inner())
|
||||
.await;
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
@@ -698,7 +698,7 @@ pub struct PreparedCredentialRotationFacts {
|
||||
pub plan_type: Option<String>,
|
||||
/// Token 刷新保留提交时的资料,不以准备阶段的副本覆盖新套餐
|
||||
pub preserve_profile: bool,
|
||||
/// 连接配置变更保留当前凭据健康状态与错误事实
|
||||
/// 凭据或连接配置更新保留提交时的健康状态与错误事实
|
||||
pub preserve_credential_state: bool,
|
||||
pub preserve_access_token_expiry: bool,
|
||||
pub provider_material: ProviderDocument,
|
||||
@@ -722,7 +722,7 @@ impl PreparedCredentialRotation {
|
||||
Self { facts, guard }
|
||||
}
|
||||
|
||||
/// 仅修改连接配置时,不把配置更新视为凭据恢复成功
|
||||
/// 更新本身不能证明账号已恢复时,保留提交时的状态
|
||||
#[must_use]
|
||||
pub fn preserving_credential_state(mut self) -> Self {
|
||||
self.facts.preserve_credential_state = true;
|
||||
|
||||
@@ -50,6 +50,8 @@ pub struct SystemUpdatePolicy {
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct SystemVersion {
|
||||
pub version: String,
|
||||
pub instance_id: String,
|
||||
pub restart_supported: bool,
|
||||
pub git_sha: String,
|
||||
pub build_time: String,
|
||||
pub deployment_mode: String,
|
||||
|
||||
@@ -55,37 +55,44 @@ impl ScheduledTask for ResetCreditAutomationTask {
|
||||
context: WorkerCycleContext,
|
||||
) -> futures::future::BoxFuture<'_, Result<(), WorkerTaskError>> {
|
||||
Box::pin(async move {
|
||||
let settings = self
|
||||
.settings
|
||||
.load_runtime_settings()
|
||||
context
|
||||
.cancellation()
|
||||
.run_until_cancelled(self.run_due())
|
||||
.await
|
||||
.map_err(|_| WorkerTaskError::safe("重置卡设置读取失败"))?;
|
||||
// 单轮有界,积压沿到期顺序继续;并发复用已有账号刷新配置
|
||||
let due = self
|
||||
.store
|
||||
.due_reset_credit_automations(Utc::now(), 100)
|
||||
.await
|
||||
.map_err(|_| WorkerTaskError::safe("重置卡计划读取失败"))?;
|
||||
let work = futures::stream::iter(due)
|
||||
.map(|account_id| async move {
|
||||
let id = ProviderAccountId::new(account_id.clone())
|
||||
.map_err(|_| WorkerTaskError::safe("重置卡账号 ID 不合法"))?;
|
||||
if let Err(error) = self.accounts.reconcile_reset_credit_automation(id).await {
|
||||
tracing::warn!(
|
||||
account_id,
|
||||
error_kind = error.kind().as_str(),
|
||||
"自动重置卡任务失败"
|
||||
);
|
||||
}
|
||||
Ok::<_, WorkerTaskError>(())
|
||||
})
|
||||
.buffer_unordered(settings.values.refresh_concurrency.max(1) as usize)
|
||||
.collect::<Vec<_>>();
|
||||
tokio::select! {
|
||||
() = context.cancellation().cancelled() => {},
|
||||
_ = tokio::time::timeout(Duration::from_secs(30), work) => {},
|
||||
}
|
||||
Ok(())
|
||||
.unwrap_or(Ok(()))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl ResetCreditAutomationTask {
|
||||
async fn run_due(&self) -> Result<(), WorkerTaskError> {
|
||||
let settings = self
|
||||
.settings
|
||||
.load_runtime_settings()
|
||||
.await
|
||||
.map_err(|_| WorkerTaskError::safe("重置卡设置读取失败"))?;
|
||||
// 单轮有界,积压沿到期顺序继续;并发复用已有账号刷新配置
|
||||
let due = self
|
||||
.store
|
||||
.due_reset_credit_automations(Utc::now(), 100)
|
||||
.await
|
||||
.map_err(|_| WorkerTaskError::safe("重置卡计划读取失败"))?;
|
||||
let work = futures::stream::iter(due)
|
||||
.map(|account_id| async move {
|
||||
let id = ProviderAccountId::new(account_id.clone())
|
||||
.map_err(|_| WorkerTaskError::safe("重置卡账号 ID 不合法"))?;
|
||||
if let Err(error) = self.accounts.reconcile_reset_credit_automation(id).await {
|
||||
tracing::warn!(
|
||||
account_id,
|
||||
error_kind = error.kind().as_str(),
|
||||
"自动重置卡任务失败"
|
||||
);
|
||||
}
|
||||
Ok::<_, WorkerTaskError>(())
|
||||
})
|
||||
.buffer_unordered(settings.values.refresh_concurrency.max(1) as usize)
|
||||
.collect::<Vec<_>>();
|
||||
let _ = tokio::time::timeout(Duration::from_secs(30), work).await;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,6 +27,8 @@ impl SystemOperations for RecordingSystemOperations {
|
||||
}
|
||||
Ok(SystemVersion {
|
||||
version: "1.0.0".to_owned(),
|
||||
instance_id: "test-instance".to_owned(),
|
||||
restart_supported: false,
|
||||
git_sha: "unknown".to_owned(),
|
||||
build_time: "unknown".to_owned(),
|
||||
deployment_mode: "source".to_owned(),
|
||||
|
||||
@@ -81,6 +81,8 @@ impl UpdateRequest {
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct SystemVersionView {
|
||||
version: String,
|
||||
instance_id: String,
|
||||
restart_supported: bool,
|
||||
git_sha: String,
|
||||
build_time: String,
|
||||
deployment_mode: String,
|
||||
@@ -97,6 +99,8 @@ impl From<SystemVersion> for SystemVersionView {
|
||||
Self {
|
||||
deployment_mode_label: deployment_mode_label(&version.deployment_mode).to_owned(),
|
||||
version: version.version,
|
||||
instance_id: version.instance_id,
|
||||
restart_supported: version.restart_supported,
|
||||
git_sha: version.git_sha,
|
||||
build_time: version.build_time,
|
||||
deployment_mode: version.deployment_mode,
|
||||
|
||||
@@ -11,6 +11,7 @@ use gateway_core::{
|
||||
error::ProviderErrorKind,
|
||||
policy::{ClientVersionRejection, CodexClientKind},
|
||||
};
|
||||
use gateway_protocol::http::preferred_response_request_id;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
pub use gateway_core::engine::execution::gateway_error_from_engine;
|
||||
@@ -170,8 +171,8 @@ pub fn engine_error_response(error: &EngineError) -> Response {
|
||||
};
|
||||
response.headers_mut().append(name, value);
|
||||
}
|
||||
if !response.headers().contains_key("x-request-id")
|
||||
&& !response.headers().contains_key("x-oai-request-id")
|
||||
if preferred_response_request_id(|name| response.headers().get(name)?.to_str().ok())
|
||||
.is_none()
|
||||
&& let Some(request_id) = error.upstream_request_id()
|
||||
&& let Ok(value) = HeaderValue::from_str(request_id.as_str())
|
||||
{
|
||||
|
||||
@@ -665,7 +665,7 @@ fn engine_error_response_with_headers(
|
||||
response_headers: &[ProviderResponseHeader],
|
||||
) -> Response {
|
||||
let response = engine_error_response(error);
|
||||
let failure_request_ids = ["x-request-id", "x-oai-request-id"]
|
||||
let failure_request_ids = gateway_protocol::http::RESPONSE_REQUEST_ID_HEADERS
|
||||
.into_iter()
|
||||
.flat_map(|name| {
|
||||
response
|
||||
@@ -678,8 +678,9 @@ fn engine_error_response_with_headers(
|
||||
.collect::<Vec<_>>();
|
||||
// 失败后仍须交付已采集的 turn state;只隔离 opening 身份,不丢弃会话状态
|
||||
let mut response = apply_provider_response_headers(response, response_headers);
|
||||
response.headers_mut().remove("x-request-id");
|
||||
response.headers_mut().remove("x-oai-request-id");
|
||||
for name in gateway_protocol::http::RESPONSE_REQUEST_ID_HEADERS {
|
||||
response.headers_mut().remove(name);
|
||||
}
|
||||
for (name, value) in failure_request_ids {
|
||||
response.headers_mut().append(name, value);
|
||||
}
|
||||
|
||||
@@ -37,11 +37,11 @@ pub(crate) fn with_model_request_id(
|
||||
let usable = |value: &HeaderValue| value.to_str().is_ok_and(|id| !id.trim().is_empty());
|
||||
if !headers.get("x-request-id").is_some_and(usable) {
|
||||
// 只有别名时沿用同一个上游值,避免外层 middleware 再填入入口 ID
|
||||
let client_id = headers
|
||||
.get("x-oai-request-id")
|
||||
.filter(|value| usable(value))
|
||||
.unwrap_or(&gateway_id)
|
||||
.clone();
|
||||
let client_id = gateway_protocol::http::preferred_response_request_id(|name| {
|
||||
headers.get(name)?.to_str().ok()
|
||||
})
|
||||
.and_then(|value| HeaderValue::from_str(value).ok())
|
||||
.unwrap_or_else(|| gateway_id.clone());
|
||||
headers.insert("x-request-id", client_id);
|
||||
}
|
||||
headers.insert("x-gateway-request-id", gateway_id);
|
||||
|
||||
@@ -7,6 +7,7 @@ use crate::{
|
||||
auth::{ClientKeyHeaders, authenticate_client, client_access_error_response},
|
||||
error::gateway_error_response,
|
||||
generation::{GenerationEndpoint, GenerationHttpRequest, execute_prepared_generation},
|
||||
router::IngressStarted,
|
||||
},
|
||||
};
|
||||
use axum::{
|
||||
@@ -15,18 +16,43 @@ use axum::{
|
||||
http::{HeaderMap, StatusCode},
|
||||
response::Response,
|
||||
};
|
||||
use std::net::SocketAddr;
|
||||
use std::{net::SocketAddr, time::Instant};
|
||||
|
||||
/// `POST /v1/responses`
|
||||
pub(crate) async fn responses(
|
||||
State(state): State<ApiState>,
|
||||
connect_info: Option<Extension<ConnectInfo<SocketAddr>>>,
|
||||
ingress_id: Option<Extension<tower_http::request_id::RequestId>>,
|
||||
ingress_started: Option<Extension<IngressStarted>>,
|
||||
headers: HeaderMap,
|
||||
body: Bytes,
|
||||
) -> Response {
|
||||
// Bytes extractor 已读完传输正文;此时尚未认证、解压或解析 JSON
|
||||
let mut encodings = headers.get_all(axum::http::header::CONTENT_ENCODING).iter();
|
||||
let encoding = match (encodings.next(), encodings.next()) {
|
||||
(None, _) => "identity",
|
||||
(Some(value), None) => value
|
||||
.to_str()
|
||||
.ok()
|
||||
.and_then(|value| {
|
||||
["identity", "gzip", "deflate", "zstd"]
|
||||
.into_iter()
|
||||
.find(|known| known.eq_ignore_ascii_case(value.trim()))
|
||||
})
|
||||
.unwrap_or("other"),
|
||||
_ => "other",
|
||||
};
|
||||
tracing::info!(target: "request_trace", stage = "http.body.received",
|
||||
receive_ms = ingress_started.map(|Extension(start)| start.0.elapsed().as_millis()),
|
||||
encoded_bytes = body.len(), content_encoding = encoding,
|
||||
"HTTP request body received");
|
||||
let service = state.data_plane().clone();
|
||||
let client = match authenticate_client(&service, &headers, ClientKeyHeaders::Bearer).await {
|
||||
let started = Instant::now();
|
||||
let authentication = authenticate_client(&service, &headers, ClientKeyHeaders::Bearer).await;
|
||||
tracing::info!(target: "request_trace", stage = "http.auth.finished",
|
||||
auth_ms = started.elapsed().as_millis(), accepted = authentication.is_ok(),
|
||||
"HTTP request authentication finished");
|
||||
let client = match authentication {
|
||||
Ok(client) => client,
|
||||
Err(error) => return client_access_error_response(error),
|
||||
};
|
||||
@@ -42,7 +68,12 @@ pub(crate) async fn responses(
|
||||
}
|
||||
};
|
||||
let execution = service.execution();
|
||||
let prepared = match execution.prepare_execution(client).await {
|
||||
let started = Instant::now();
|
||||
let preparation = execution.prepare_execution(client).await;
|
||||
tracing::info!(target: "request_trace", stage = "http.execution.prepared",
|
||||
prepare_ms = started.elapsed().as_millis(), accepted = preparation.is_ok(),
|
||||
"HTTP execution preparation finished");
|
||||
let prepared = match preparation {
|
||||
Ok(prepared) => prepared,
|
||||
Err(error) => return gateway_error_response(&error),
|
||||
};
|
||||
|
||||
@@ -143,9 +143,20 @@ pub(crate) fn decode_request_with_body(
|
||||
headers: &HeaderMap,
|
||||
max_decompressed_bytes: usize,
|
||||
) -> Result<(DecodedGenerationRequest, Bytes), RequestDecodeError> {
|
||||
let body = decompress_request_body(body, headers, max_decompressed_bytes)?;
|
||||
let decoded = decode_request_inner(&body, &OpenAiRequestHeaders::from_headers(headers))?;
|
||||
Ok((decoded, Bytes::copy_from_slice(&body)))
|
||||
let started = std::time::Instant::now();
|
||||
let decompressed = decompress_request_body(body, headers, max_decompressed_bytes);
|
||||
tracing::info!(target: "request_trace", stage = "http.body.decompressed",
|
||||
decompress_ms = started.elapsed().as_millis(),
|
||||
decoded_bytes = decompressed.as_ref().ok().map(|body| body.len()),
|
||||
accepted = decompressed.is_ok(), "HTTP request body decompressed");
|
||||
let body = decompressed?;
|
||||
let started = std::time::Instant::now();
|
||||
let decoded = decode_request_inner(&body, &OpenAiRequestHeaders::from_headers(headers))
|
||||
.map(|decoded| (decoded, Bytes::copy_from_slice(&body)));
|
||||
tracing::info!(target: "request_trace", stage = "http.body.decoded",
|
||||
decode_ms = started.elapsed().as_millis(), accepted = decoded.is_ok(),
|
||||
"HTTP request body decoded");
|
||||
decoded
|
||||
}
|
||||
|
||||
pub(super) fn decode_request_inner(
|
||||
|
||||
@@ -8,6 +8,7 @@ use axum::http::{HeaderName, HeaderValue, StatusCode};
|
||||
use gateway_core::engine::EngineError;
|
||||
use gateway_core::error::ProviderErrorKind;
|
||||
use gateway_core::event::ProviderResponseHeader;
|
||||
use gateway_protocol::http::{RESPONSE_REQUEST_ID_HEADERS, preferred_response_request_id};
|
||||
use serde_json::{Map, Value, json};
|
||||
use thiserror::Error;
|
||||
|
||||
@@ -119,9 +120,12 @@ pub(super) fn response_metadata_event(
|
||||
response_headers: &[ProviderResponseHeader],
|
||||
) -> String {
|
||||
let mut headers = response_event_headers(response_headers);
|
||||
let client_request_id = preferred_response_request_id(|name| headers.get(name)?.as_str())
|
||||
.unwrap_or(request_id)
|
||||
.to_owned();
|
||||
headers
|
||||
.entry("x-request-id".to_owned())
|
||||
.or_insert_with(|| Value::String(request_id.to_owned()));
|
||||
.or_insert(Value::String(client_request_id));
|
||||
json!({
|
||||
"type": "response.metadata",
|
||||
"headers": headers,
|
||||
@@ -149,7 +153,7 @@ fn response_event_headers(response_headers: &[ProviderResponseHeader]) -> Map<St
|
||||
let Ok(value) = std::str::from_utf8(header.value()) else {
|
||||
continue;
|
||||
};
|
||||
if matches!(name.as_str(), "x-request-id" | "x-oai-request-id")
|
||||
if RESPONSE_REQUEST_ID_HEADERS.contains(&name.as_str())
|
||||
&& (value.trim().is_empty() || http_value.to_str().is_err())
|
||||
{
|
||||
continue;
|
||||
@@ -182,8 +186,9 @@ pub(super) fn initial_engine_error_event(
|
||||
};
|
||||
if upstream.is_none() {
|
||||
// 会话 opening 身份不证明当前失败属于该请求;仅保留其他允许的会话头
|
||||
headers.remove("x-request-id");
|
||||
headers.remove("x-oai-request-id");
|
||||
for name in RESPONSE_REQUEST_ID_HEADERS {
|
||||
headers.remove(name);
|
||||
}
|
||||
}
|
||||
let status = if provider
|
||||
.is_some_and(|error| error.kind() == ProviderErrorKind::UpstreamCapacityUnavailable)
|
||||
@@ -221,7 +226,7 @@ pub(super) fn initial_engine_error_event(
|
||||
}
|
||||
|
||||
fn has_request_id(headers: &Map<String, Value>) -> bool {
|
||||
headers.contains_key("x-request-id") || headers.contains_key("x-oai-request-id")
|
||||
preferred_response_request_id(|name| headers.get(name)?.as_str()).is_some()
|
||||
}
|
||||
|
||||
pub(super) fn error_event(
|
||||
|
||||
@@ -46,6 +46,10 @@ pub(crate) fn router() -> Router<ApiState> {
|
||||
.merge(super::provider_endpoints::router())
|
||||
}
|
||||
|
||||
/// 在读取正文前保存入口时刻,交给端点区分接收与执行耗时
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) struct IngressStarted(pub(crate) std::time::Instant);
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) enum DataPlaneNamespace {
|
||||
V1,
|
||||
|
||||
@@ -19,7 +19,7 @@ use serde_json::json;
|
||||
use tower_http::request_id::RequestId;
|
||||
|
||||
use crate::client_error::{AccessRejection, ProtocolErrorBody};
|
||||
use crate::data_plane::router::DataPlaneNamespace;
|
||||
use crate::data_plane::router::{DataPlaneNamespace, IngressStarted};
|
||||
|
||||
pub(crate) async fn record_ingress(
|
||||
State(diagnostics): State<Arc<dyn OperationalDiagnostics>>,
|
||||
@@ -29,6 +29,9 @@ pub(crate) async fn record_ingress(
|
||||
let Some(namespace) = DataPlaneNamespace::for_path(request.uri().path()) else {
|
||||
return next.run(request).await;
|
||||
};
|
||||
request
|
||||
.extensions_mut()
|
||||
.insert(IngressStarted(std::time::Instant::now()));
|
||||
let correlation_id = request
|
||||
.extensions()
|
||||
.get::<RequestId>()
|
||||
|
||||
@@ -24,6 +24,27 @@ use tower::ServiceExt as _;
|
||||
|
||||
use super::{AdminTestFixture, AdminTestState, unavailable_system};
|
||||
|
||||
#[tokio::test]
|
||||
async fn version_should_expose_runtime_identity_and_restart_capability() {
|
||||
let fixture = crate::support::key_fixture().await;
|
||||
fixture.auth.insert_session("valid-session");
|
||||
let response = app(fixture.state())
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.uri("/api/admin/system/version")
|
||||
.header(header::COOKIE, "cpr_session=valid-session")
|
||||
.header("x-request-id", "req_system_version")
|
||||
.body(Body::empty())
|
||||
.expect("version request"),
|
||||
)
|
||||
.await
|
||||
.expect("version response");
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
let body = crate::support::response_json(response).await;
|
||||
assert_eq!(body["data"]["instanceId"], "test-instance");
|
||||
assert_eq!(body["data"]["restartSupported"], true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn update_detail_query_should_default_to_no_refresh_and_reject_unknown_fields() {
|
||||
let query: UpdateDetailQuery = serde_json::from_str("{}").expect("empty query object");
|
||||
|
||||
@@ -256,12 +256,20 @@ async fn request_middleware_sees_original_chat_and_preserves_the_endpoint() {
|
||||
let mut execution = Execution::new(Session::new(vec![created(), completed("ok")]));
|
||||
execution.middleware = Some(middleware.frozen());
|
||||
let fixture = Fixture::with_execution(execution).await;
|
||||
let response = fixture.post(chat_request(false)).await;
|
||||
let mut request = chat_request(false);
|
||||
request["stream_options"] = json!({"include_usage":true});
|
||||
request["messages"] = json!([
|
||||
{"role":"developer","content":"brief"},
|
||||
{"role":"system","content":null},
|
||||
{"role":"assistant","tool_calls":[]},
|
||||
{"role":"user","content":[{"type":"text","text":null},{"type":"text","text":"hello"}]}
|
||||
]);
|
||||
let response = fixture.post(request.clone()).await;
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
let downstream = json_body(response).await;
|
||||
assert_eq!(downstream["object"], "chat.completion");
|
||||
let observed = middleware.requests.lock().unwrap();
|
||||
assert_eq!(observed.as_slice(), [chat_request(false)]);
|
||||
assert_eq!(observed.as_slice(), [request]);
|
||||
assert_eq!(
|
||||
middleware.inner.endpoints.lock().unwrap().as_slice(),
|
||||
[PATH]
|
||||
|
||||
@@ -396,16 +396,16 @@ fn local_provider_capacity_exhaustion_should_map_to_service_unavailable() {
|
||||
);
|
||||
assert_eq!(
|
||||
projected.safe_message(),
|
||||
"The gateway account pool is busy."
|
||||
"No eligible account currently has capacity for this request."
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_eligible_provider_account_should_preserve_safe_provider_detail() {
|
||||
#[tokio::test]
|
||||
async fn no_eligible_provider_account_should_preserve_safe_provider_detail() {
|
||||
let detail = ClientVisibleUpstreamError::new(
|
||||
"no account is eligible for the requested model",
|
||||
Some("no_eligible_account".to_owned()),
|
||||
Some("account_unavailable_error".to_owned()),
|
||||
"This request requires an upstream WebSocket.",
|
||||
Some("websocket_account_unavailable".to_owned()),
|
||||
None,
|
||||
);
|
||||
let error = EngineError::Provider(
|
||||
ProviderError::new(
|
||||
@@ -419,17 +419,24 @@ fn no_eligible_provider_account_should_preserve_safe_provider_detail() {
|
||||
assert_eq!(gateway.kind(), GatewayErrorKind::NoAvailableProvider);
|
||||
assert_eq!(
|
||||
gateway.client_message(),
|
||||
"no account is eligible for the requested model"
|
||||
"This request requires an upstream WebSocket."
|
||||
);
|
||||
assert_eq!(gateway.client_error_code(), Some("no_eligible_account"));
|
||||
assert_eq!(
|
||||
gateway.client_error_type(),
|
||||
Some("account_unavailable_error")
|
||||
gateway.client_error_code(),
|
||||
Some("websocket_account_unavailable")
|
||||
);
|
||||
assert_eq!(gateway.client_error_type(), None);
|
||||
assert_eq!(
|
||||
gateway.safe_message(),
|
||||
"The gateway found no eligible account for this request."
|
||||
);
|
||||
let response = engine_error_response(&error);
|
||||
assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
|
||||
let body: serde_json::Value =
|
||||
serde_json::from_slice(&to_bytes(response.into_body(), usize::MAX).await.unwrap()).unwrap();
|
||||
assert_eq!(body["error"]["type"], "server_error");
|
||||
assert_eq!(body["error"]["code"], "websocket_account_unavailable");
|
||||
assert_eq!(body["error"]["message"], gateway.client_message());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -508,6 +515,7 @@ fn engine_provider_unsupported_capability_should_remain_unsupported() {
|
||||
|
||||
#[test]
|
||||
fn engine_provider_credential_failures_should_not_impersonate_client_auth_failures() {
|
||||
let mut messages = std::collections::HashSet::new();
|
||||
for kind in [
|
||||
ProviderErrorKind::Unauthorized,
|
||||
ProviderErrorKind::PermissionDenied,
|
||||
@@ -516,11 +524,19 @@ fn engine_provider_credential_failures_should_not_impersonate_client_auth_failur
|
||||
let mapped = gateway_error_from_engine(&error);
|
||||
|
||||
assert_eq!(mapped.kind(), GatewayErrorKind::UpstreamUnavailable);
|
||||
assert_eq!(
|
||||
mapped.safe_message(),
|
||||
"The upstream account cannot access the service."
|
||||
assert!(
|
||||
mapped
|
||||
.safe_message()
|
||||
.to_lowercase()
|
||||
.contains("upstream account")
|
||||
);
|
||||
messages.insert(mapped.safe_message().to_owned());
|
||||
}
|
||||
assert_eq!(
|
||||
messages.len(),
|
||||
2,
|
||||
"authentication and permission failures must be distinguishable"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -577,19 +593,29 @@ fn engine_provider_timeout_and_cancellation_should_remain_distinct() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn engine_provider_runtime_failures_should_collapse_to_safe_unavailability() {
|
||||
fn engine_provider_runtime_failures_preserve_the_cause_without_exposing_internal_details() {
|
||||
let mut messages = std::collections::HashSet::new();
|
||||
for kind in [
|
||||
ProviderErrorKind::Transport,
|
||||
ProviderErrorKind::Protocol,
|
||||
ProviderErrorKind::Unavailable,
|
||||
ProviderErrorKind::ProcessTerminated,
|
||||
] {
|
||||
let error = EngineError::Provider(ProviderError::new(kind, UpstreamSendState::Ambiguous));
|
||||
let error = EngineError::Provider(
|
||||
ProviderError::new(kind, UpstreamSendState::Ambiguous)
|
||||
.with_source(std::io::Error::other("PRIVATE_ENDPOINT_AND_CREDENTIAL")),
|
||||
);
|
||||
|
||||
let projected = gateway_error_from_engine(&error);
|
||||
assert_eq!(projected.kind(), GatewayErrorKind::UpstreamUnavailable);
|
||||
assert_eq!(projected.safe_message(), "Upstream service is unavailable.");
|
||||
assert!(!projected.client_message().contains("PRIVATE_"));
|
||||
messages.insert(projected.client_message().to_owned());
|
||||
}
|
||||
assert_eq!(
|
||||
messages.len(),
|
||||
4,
|
||||
"different failure causes must remain distinguishable"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -334,7 +334,7 @@ async fn request_settings_reach_query_terminal_without_mutating_authenticated_ba
|
||||
runtime["account_queue_timeout_seconds"] = serde_json::json!(30);
|
||||
runtime["switch_account_on_queue_failure"] = serde_json::json!(false);
|
||||
settings.runtime = serde_json::from_value(runtime).unwrap();
|
||||
settings.fast_mode = FastMode::Disabled;
|
||||
settings.fast_mode = Some(FastMode::Disabled);
|
||||
}),
|
||||
..Default::default()
|
||||
}));
|
||||
@@ -355,8 +355,12 @@ async fn request_settings_reach_query_terminal_without_mutating_authenticated_ba
|
||||
"model-a"
|
||||
);
|
||||
assert_ne!(
|
||||
execution.client.policy().account_scope().fast_mode(),
|
||||
FastMode::Disabled
|
||||
execution
|
||||
.client
|
||||
.policy()
|
||||
.account_scope()
|
||||
.fast_mode_override(),
|
||||
Some(FastMode::Disabled)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3300,6 +3300,12 @@ async fn response_ids_are_provider_and_client_independent() {
|
||||
(&[], MODEL_REQUEST_ID),
|
||||
(&[("x-request-id", "upstream-primary")], "upstream-primary"),
|
||||
(&[("x-oai-request-id", "upstream-alias")], "upstream-alias"),
|
||||
(
|
||||
&[("x-openai-request-id", "upstream-openai")],
|
||||
"upstream-openai",
|
||||
),
|
||||
(&[("x-ms-request-id", "upstream-ms")], "upstream-ms"),
|
||||
(&[("cf-ray", "trace-only")], MODEL_REQUEST_ID),
|
||||
(
|
||||
&[
|
||||
("x-request-id", "upstream-primary"),
|
||||
@@ -3315,6 +3321,22 @@ async fn response_ids_are_provider_and_client_independent() {
|
||||
"upstream-alias",
|
||||
),
|
||||
(&[("x-request-id", "")], MODEL_REQUEST_ID),
|
||||
(
|
||||
&[
|
||||
("x-request-id", "é"),
|
||||
("x-oai-request-id", " "),
|
||||
("x-openai-request-id", ""),
|
||||
("x-ms-request-id", "upstream-ms"),
|
||||
],
|
||||
"upstream-ms",
|
||||
),
|
||||
(
|
||||
&[
|
||||
("x-openai-request-id", "upstream-openai"),
|
||||
("x-ms-request-id", "upstream-ms"),
|
||||
],
|
||||
"upstream-openai",
|
||||
),
|
||||
];
|
||||
for provider in ["openai", "xai"] {
|
||||
for streaming in [false, true] {
|
||||
@@ -3343,6 +3365,11 @@ async fn response_ids_are_provider_and_client_independent() {
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
assert_eq!(response.headers()["x-request-id"], *expected);
|
||||
assert_eq!(response.headers()["x-gateway-request-id"], MODEL_REQUEST_ID);
|
||||
for (name, value) in *upstream_headers {
|
||||
if *name != "x-request-id" {
|
||||
assert_eq!(response.headers()[*name].as_bytes(), value.as_bytes());
|
||||
}
|
||||
}
|
||||
assert!(
|
||||
!to_bytes(response.into_body(), 64 * 1024)
|
||||
.await
|
||||
@@ -3359,7 +3386,12 @@ async fn failure_ids_prefer_the_actual_error_over_session_headers() {
|
||||
let admin = crate::admin::AdminTestFixture::new().await.services;
|
||||
for provider in ["openai", "xai"] {
|
||||
for streaming in [false, true] {
|
||||
for upstream_headers in [vec![], headers(&[("x-oai-request-id", "actual-error")])] {
|
||||
for upstream_headers in [
|
||||
vec![],
|
||||
headers(&[("x-oai-request-id", "actual-error")]),
|
||||
headers(&[("x-openai-request-id", "actual-error")]),
|
||||
headers(&[("x-ms-request-id", "actual-error")]),
|
||||
] {
|
||||
let expected = if upstream_headers.is_empty() {
|
||||
MODEL_REQUEST_ID
|
||||
} else {
|
||||
@@ -3367,7 +3399,7 @@ async fn failure_ids_prefer_the_actual_error_over_session_headers() {
|
||||
};
|
||||
let raw =
|
||||
Bytes::from_static(br#"{"error":{"message":"synthetic upstream detail"}}"#);
|
||||
let error =
|
||||
let mut error =
|
||||
ProviderError::new(ProviderErrorKind::InvalidRequest, UpstreamSendState::Sent)
|
||||
.with_client_visible_upstream_response(
|
||||
ClientVisibleUpstreamResponse::new(
|
||||
@@ -3377,12 +3409,25 @@ async fn failure_ids_prefer_the_actual_error_over_session_headers() {
|
||||
)
|
||||
.with_headers(upstream_headers),
|
||||
);
|
||||
if expected == "actual-error" {
|
||||
// 最终响应头优先于错误对象中残留的旧观测 ID
|
||||
error = error.with_upstream_request_id(OpaqueUpstreamValue::new("stale-fact"));
|
||||
}
|
||||
let session = failed_session(streaming, EngineError::Provider(error))
|
||||
.with_response_headers(headers(&[("x-request-id", "earlier-session")]));
|
||||
.with_response_headers(headers(&[
|
||||
("x-request-id", "earlier-session"),
|
||||
("x-openai-request-id", "earlier-openai"),
|
||||
("x-ms-request-id", "earlier-ms"),
|
||||
]));
|
||||
let response = response(&admin, provider, session, streaming).await;
|
||||
assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
|
||||
assert_eq!(response.headers()["x-request-id"], expected);
|
||||
assert_eq!(response.headers()["x-gateway-request-id"], MODEL_REQUEST_ID);
|
||||
for name in ["x-openai-request-id", "x-ms-request-id"] {
|
||||
if let Some(value) = response.headers().get(name) {
|
||||
assert_eq!(value, "actual-error");
|
||||
}
|
||||
}
|
||||
assert_eq!(to_bytes(response.into_body(), 4096).await.unwrap(), raw);
|
||||
}
|
||||
|
||||
@@ -3394,12 +3439,16 @@ async fn failure_ids_prefer_the_actual_error_over_session_headers() {
|
||||
.with_response_headers(headers(&[
|
||||
("x-request-id", "earlier-session"),
|
||||
("x-oai-request-id", "earlier-alias"),
|
||||
("x-openai-request-id", "earlier-openai"),
|
||||
("x-ms-request-id", "earlier-ms"),
|
||||
]));
|
||||
let response = response(&admin, provider, session, streaming).await;
|
||||
assert_eq!(response.status(), StatusCode::BAD_GATEWAY);
|
||||
assert_eq!(response.headers()["x-request-id"], "body-read-error");
|
||||
assert_eq!(response.headers().get_all("x-request-id").iter().count(), 1);
|
||||
assert!(response.headers().get("x-oai-request-id").is_none());
|
||||
assert!(response.headers().get("x-openai-request-id").is_none());
|
||||
assert!(response.headers().get("x-ms-request-id").is_none());
|
||||
assert_eq!(response.headers()["x-gateway-request-id"], MODEL_REQUEST_ID);
|
||||
}
|
||||
}
|
||||
@@ -3414,12 +3463,16 @@ async fn local_execution_failure_uses_the_existing_model_id() {
|
||||
failed_session(streaming, EngineError::Deadline).with_response_headers(headers(&[
|
||||
("x-request-id", "opening-primary"),
|
||||
("x-oai-request-id", "opening-alias"),
|
||||
("x-openai-request-id", "opening-openai"),
|
||||
("x-ms-request-id", "opening-ms"),
|
||||
("x-codex-turn-state", "retained-turn-state"),
|
||||
]));
|
||||
let response = response(&admin, provider, session, streaming).await;
|
||||
assert_eq!(response.headers()["x-request-id"], MODEL_REQUEST_ID);
|
||||
assert_eq!(response.headers()["x-gateway-request-id"], MODEL_REQUEST_ID);
|
||||
assert!(response.headers().get("x-oai-request-id").is_none());
|
||||
assert!(response.headers().get("x-openai-request-id").is_none());
|
||||
assert!(response.headers().get("x-ms-request-id").is_none());
|
||||
assert_eq!(
|
||||
response.headers()["x-codex-turn-state"],
|
||||
"retained-turn-state"
|
||||
|
||||
@@ -369,23 +369,25 @@ async fn classified_capacity_error_without_special_code_returns_retryable_websoc
|
||||
|
||||
#[tokio::test]
|
||||
async fn final_failure_headers_take_precedence_over_observed_opening_headers() {
|
||||
let provider = upstream_failure(403, b"", vec![header("x-oai-request-id", b"req_final")])
|
||||
.with_status(502)
|
||||
.with_upstream_request_id(OpaqueUpstreamValue::new("req_stale_fact"));
|
||||
let error = initial_error(
|
||||
EngineError::Provider(provider),
|
||||
vec![
|
||||
header("x-request-id", b"req_old_opening"),
|
||||
header("x-codex-turn-state", b"old-turn-state"),
|
||||
],
|
||||
)
|
||||
.await;
|
||||
assert_eq!(error["status"], 403);
|
||||
assert_eq!(error["headers"]["x-oai-request-id"], "req_final");
|
||||
assert!(error["headers"].get("x-request-id").is_none());
|
||||
assert!(!error.to_string().contains("req_old_opening"));
|
||||
assert!(!error.to_string().contains("req_stale_fact"));
|
||||
assert!(!error.to_string().contains("old-turn-state"));
|
||||
for name in ["x-oai-request-id", "x-openai-request-id", "x-ms-request-id"] {
|
||||
let provider = upstream_failure(403, b"", vec![header(name, b"req_final")])
|
||||
.with_status(502)
|
||||
.with_upstream_request_id(OpaqueUpstreamValue::new("req_stale_fact"));
|
||||
let error = initial_error(
|
||||
EngineError::Provider(provider),
|
||||
vec![
|
||||
header("x-request-id", b"req_old_opening"),
|
||||
header("x-codex-turn-state", b"old-turn-state"),
|
||||
],
|
||||
)
|
||||
.await;
|
||||
assert_eq!(error["status"], 403);
|
||||
assert_eq!(error["headers"][name], "req_final");
|
||||
assert!(error["headers"].get("x-request-id").is_none());
|
||||
assert!(!error.to_string().contains("req_old_opening"));
|
||||
assert!(!error.to_string().contains("req_stale_fact"));
|
||||
assert!(!error.to_string().contains("old-turn-state"));
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -398,6 +400,8 @@ async fn provider_failure_facts_survive_without_a_complete_http_response() {
|
||||
vec![
|
||||
header("x-request-id", b"req_old"),
|
||||
header("x-oai-request-id", b"req_old_alias"),
|
||||
header("x-openai-request-id", b"req_old_openai"),
|
||||
header("x-ms-request-id", b"req_old_ms"),
|
||||
header("x-codex-turn-state", b"observed-turn-state"),
|
||||
],
|
||||
)
|
||||
@@ -409,9 +413,11 @@ async fn provider_failure_facts_survive_without_a_complete_http_response() {
|
||||
"observed-turn-state"
|
||||
);
|
||||
assert!(error["headers"].get("x-oai-request-id").is_none());
|
||||
assert!(error["headers"].get("x-openai-request-id").is_none());
|
||||
assert!(error["headers"].get("x-ms-request-id").is_none());
|
||||
assert_eq!(
|
||||
error["error"]["message"],
|
||||
"Upstream service is unavailable."
|
||||
"Communication with the upstream service failed."
|
||||
);
|
||||
}
|
||||
|
||||
@@ -511,6 +517,8 @@ async fn opening_ids_stay_in_metadata_but_do_not_identify_initial_failures() {
|
||||
vec![
|
||||
header("x-request-id", b"req_old_opening"),
|
||||
header("x-oai-request-id", b"req_observed"),
|
||||
header("x-openai-request-id", b"req_observed_openai"),
|
||||
header("x-ms-request-id", b"req_observed_ms"),
|
||||
header("x-codex-turn-state", b"observed-turn-state"),
|
||||
header("x-future-header", b"future-value"),
|
||||
],
|
||||
@@ -525,6 +533,8 @@ async fn opening_ids_stay_in_metadata_but_do_not_identify_initial_failures() {
|
||||
"headers": {
|
||||
"x-request-id": "req_old_opening",
|
||||
"x-oai-request-id": "req_observed",
|
||||
"x-openai-request-id": "req_observed_openai",
|
||||
"x-ms-request-id": "req_observed_ms",
|
||||
"x-codex-turn-state": "observed-turn-state",
|
||||
"x-future-header": "future-value",
|
||||
},
|
||||
@@ -548,6 +558,46 @@ async fn opening_ids_stay_in_metadata_but_do_not_identify_initial_failures() {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn metadata_prefers_readable_upstream_aliases_before_the_model_id() {
|
||||
let cases: &[(&str, &[u8], Option<&str>)] = &[
|
||||
("x-oai-request-id", b"req_oai", Some("req_oai")),
|
||||
("X-OpenAI-Request-ID", b"req_openai", Some("req_openai")),
|
||||
("x-ms-request-id", b"req_ms", Some("req_ms")),
|
||||
("x-ms-request-id", b" \t ", None),
|
||||
("x-ms-request-id", b"\xc3\xa9", None),
|
||||
];
|
||||
for (name, value, expected) in cases {
|
||||
let trace = Arc::new(AtomicFailureTrace {
|
||||
initial_errors: Mutex::new(VecDeque::from([EngineError::Deadline])),
|
||||
..AtomicFailureTrace::default()
|
||||
});
|
||||
let (mut socket, _server) = connect(
|
||||
Arc::clone(&trace),
|
||||
vec![header("x-request-id", b"\xff"), header(name, value)],
|
||||
)
|
||||
.await;
|
||||
send_request(&mut socket).await;
|
||||
let metadata = next_event(&mut socket).await;
|
||||
assert_eq!(metadata["type"], "response.metadata");
|
||||
let model_id = trace.prepared_request_id.lock().unwrap().clone().unwrap();
|
||||
assert_eq!(
|
||||
metadata["headers"]["x-request-id"],
|
||||
expected.unwrap_or(&model_id)
|
||||
);
|
||||
assert_eq!(
|
||||
metadata["headers"][name.to_ascii_lowercase()].as_str(),
|
||||
*expected
|
||||
);
|
||||
let error = next_event(&mut socket).await;
|
||||
assert_eq!(error["type"], "error");
|
||||
assert_eq!(error["headers"]["x-request-id"], "req_ws_atomic");
|
||||
assert_eq!(error["headers"]["x-gateway-request-id"], "req_ws_atomic");
|
||||
assert!(error["headers"].get(name.to_ascii_lowercase()).is_none());
|
||||
socket.close(None).await.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn header_only_request_middleware_updates_websocket_turn_context() {
|
||||
let middleware = Arc::new(crate::data_plane::middleware::RequestMiddleware {
|
||||
@@ -746,13 +796,38 @@ async fn initial_continuation_recovery_delivers_the_official_client_replay_signa
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn locally_exhausted_account_pool_sends_one_official_usage_limit_error() {
|
||||
let provider = ProviderError::new(
|
||||
async fn account_selection_errors_distinguish_quota_from_websocket_requirements() {
|
||||
let exhausted = ProviderError::new(
|
||||
ProviderErrorKind::AccountPoolQuotaExhausted,
|
||||
UpstreamSendState::NotSent,
|
||||
);
|
||||
let error = initial_error(EngineError::Provider(provider), Vec::new()).await;
|
||||
assert_eq!(error["status"], 429);
|
||||
assert_eq!(error["error"]["type"], "usage_limit_reached");
|
||||
assert_eq!(error["error"]["code"], "usage_limit_reached");
|
||||
let incompatible = ProviderError::new(
|
||||
ProviderErrorKind::NoEligibleAccount,
|
||||
UpstreamSendState::NotSent,
|
||||
)
|
||||
.with_client_visible_upstream_error(ClientVisibleUpstreamError::new(
|
||||
"This request requires an upstream WebSocket.",
|
||||
Some("websocket_account_unavailable".to_owned()),
|
||||
None,
|
||||
));
|
||||
for (provider, status, kind, code) in [
|
||||
(exhausted, 429, "usage_limit_reached", "usage_limit_reached"),
|
||||
(
|
||||
incompatible,
|
||||
503,
|
||||
"server_error",
|
||||
"websocket_account_unavailable",
|
||||
),
|
||||
] {
|
||||
let error = initial_error(EngineError::Provider(provider), Vec::new()).await;
|
||||
assert_eq!(error["status"], status);
|
||||
assert_eq!(error["error"]["type"], kind);
|
||||
assert_eq!(error["error"]["code"], code);
|
||||
if status == 503 {
|
||||
assert_eq!(
|
||||
error["error"]["message"],
|
||||
"This request requires an upstream WebSocket."
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -313,6 +313,7 @@ fn response_create_should_reject_non_boolean_stream_without_disclosing_body_valu
|
||||
|
||||
#[derive(Default)]
|
||||
struct AtomicFailureTrace {
|
||||
prepared_request_id: Mutex<Option<String>>,
|
||||
starts: AtomicUsize,
|
||||
next_calls: AtomicUsize,
|
||||
committed: AtomicBool,
|
||||
@@ -414,8 +415,9 @@ struct AtomicFailureExecution {
|
||||
impl ExecutionService for AtomicFailureExecution {
|
||||
fn middleware_plan(
|
||||
&self,
|
||||
_: &gateway_core::engine::execution::PreparedRootExecution,
|
||||
prepared: &gateway_core::engine::execution::PreparedRootExecution,
|
||||
) -> Option<gateway_core::engine::middleware::FrozenMiddlewarePlan> {
|
||||
*self.trace.prepared_request_id.lock().unwrap() = Some(prepared.request_id().to_string());
|
||||
self.trace.middleware.clone()
|
||||
}
|
||||
|
||||
|
||||
@@ -255,3 +255,71 @@ async fn original_rejected_request_is_dumped_only_when_explicitly_enabled() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn responses_ingress_separates_body_receipt_from_decompression_and_decoding() {
|
||||
use std::io::Write as _;
|
||||
use tracing::instrument::WithSubscriber as _;
|
||||
|
||||
let recorder = Recorder {
|
||||
dump_enabled: false,
|
||||
events: Arc::default(),
|
||||
};
|
||||
let events = recorder.events.clone();
|
||||
let decoded = json!({"model":42,"input":"SENSITIVE_CONTENT".repeat(1024)}).to_string();
|
||||
let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast());
|
||||
encoder.write_all(decoded.as_bytes()).unwrap();
|
||||
let encoded = encoder.finish().unwrap();
|
||||
let encoded_len = encoded.len();
|
||||
assert!(encoded_len < decoded.len());
|
||||
async {
|
||||
let (router, _) = fixture().await;
|
||||
let body = Body::from_stream(futures::stream::once(async move {
|
||||
tokio::time::sleep(std::time::Duration::from_millis(40)).await;
|
||||
Ok::<_, std::io::Error>(encoded)
|
||||
}));
|
||||
let response = router
|
||||
.oneshot(
|
||||
Request::post("/v1/responses")
|
||||
.header("authorization", "Bearer unused-client-route-key")
|
||||
.header("content-encoding", "gzip")
|
||||
.body(body)
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
|
||||
}
|
||||
.with_subscriber(recorder)
|
||||
.await;
|
||||
let events = events.lock().unwrap();
|
||||
let phases = events
|
||||
.iter()
|
||||
.filter(|event| {
|
||||
event.get("stage").is_some_and(|stage| {
|
||||
stage.starts_with("http.body.") || stage == "http.auth.finished"
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(
|
||||
phases
|
||||
.iter()
|
||||
.map(|event| event["stage"].as_str())
|
||||
.collect::<Vec<_>>(),
|
||||
[
|
||||
"http.body.received",
|
||||
"http.auth.finished",
|
||||
"http.body.decompressed",
|
||||
"http.body.decoded",
|
||||
]
|
||||
);
|
||||
assert!(phases[0]["receive_ms"].parse::<u64>().unwrap() >= 30);
|
||||
assert_eq!(phases[0]["encoded_bytes"], encoded_len.to_string());
|
||||
assert_eq!(phases[0]["content_encoding"], "gzip");
|
||||
assert_eq!(phases[2]["decoded_bytes"], decoded.len().to_string());
|
||||
assert_eq!(phases[2]["accepted"], "true");
|
||||
assert_eq!(phases[3]["accepted"], "false");
|
||||
assert!(events.iter().flat_map(|event| event.values()).all(|value| {
|
||||
!value.contains("SENSITIVE_CONTENT") && !value.contains("unused-client-route-key")
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -91,6 +91,8 @@ impl SystemOperations for VersionSystem {
|
||||
async fn version(&self) -> Result<SystemVersion, SystemOperationError> {
|
||||
Ok(SystemVersion {
|
||||
version: "3.7.0".to_owned(),
|
||||
instance_id: "test-instance".to_owned(),
|
||||
restart_supported: true,
|
||||
git_sha: "internal-revision".to_owned(),
|
||||
build_time: "internal-build-time".to_owned(),
|
||||
deployment_mode: "binary".to_owned(),
|
||||
|
||||
@@ -108,6 +108,7 @@ pub struct RuntimeAccountDirectory {
|
||||
providers_with_accounts: BTreeSet<ProviderKind>,
|
||||
providers_by_group: BTreeMap<AccountGroupId, BTreeSet<ProviderKind>>,
|
||||
group_model_access: BTreeMap<AccountGroupId, AccountModelAccess>,
|
||||
group_fast_modes: BTreeMap<AccountGroupId, FastMode>,
|
||||
}
|
||||
|
||||
impl RuntimeAccountDirectory {
|
||||
@@ -129,6 +130,7 @@ impl RuntimeAccountDirectory {
|
||||
providers_with_accounts,
|
||||
providers_by_group,
|
||||
group_model_access: BTreeMap::new(),
|
||||
group_fast_modes: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -141,6 +143,12 @@ impl RuntimeAccountDirectory {
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn with_group_fast_modes(mut self, policies: BTreeMap<AccountGroupId, FastMode>) -> Self {
|
||||
self.group_fast_modes = policies;
|
||||
self
|
||||
}
|
||||
|
||||
pub(crate) fn accounts_in_group(
|
||||
&self,
|
||||
group: &AccountGroupId,
|
||||
@@ -288,7 +296,7 @@ impl ClientRoutingScope {
|
||||
pub struct FrozenAccountScope {
|
||||
allow_image_generation: bool,
|
||||
allow_subagents: bool,
|
||||
fast_mode: FastMode,
|
||||
fast_mode_override: Option<FastMode>,
|
||||
request_profiles: BTreeMap<ProviderKind, super::OpaqueProviderData>,
|
||||
directory: Arc<RuntimeAccountDirectory>,
|
||||
client_scope: ClientRoutingScope,
|
||||
@@ -355,16 +363,34 @@ impl FrozenAccountScope {
|
||||
self
|
||||
}
|
||||
|
||||
/// Key 绑定分组的冻结 Fast 策略,与账号成员资格无关
|
||||
/// 显式请求覆盖独立于分组策略;None 表示按选中账号的有效分组计算
|
||||
#[must_use]
|
||||
pub const fn with_fast_mode(mut self, fast_mode: FastMode) -> Self {
|
||||
self.fast_mode = fast_mode;
|
||||
pub const fn with_fast_mode_override(mut self, fast_mode: Option<FastMode>) -> Self {
|
||||
self.fast_mode_override = fast_mode;
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn fast_mode(&self) -> FastMode {
|
||||
self.fast_mode
|
||||
pub const fn fast_mode_override(&self) -> Option<FastMode> {
|
||||
self.fast_mode_override
|
||||
}
|
||||
|
||||
/// 只合并当前 Key 授权该账号与模型的启用分组,换号仍使用同一冻结目录
|
||||
#[must_use]
|
||||
pub fn fast_mode_for_account(
|
||||
&self,
|
||||
account_id: &ProviderAccountId,
|
||||
upstream_model: &str,
|
||||
) -> FastMode {
|
||||
if let Some(mode) = self.fast_mode_override {
|
||||
return mode;
|
||||
}
|
||||
let Some(account) = self.directory.account(account_id) else {
|
||||
return FastMode::Default;
|
||||
};
|
||||
self.matching_groups(account, |access| access.allows(upstream_model))
|
||||
.filter_map(|id| self.directory.group_fast_modes.get(id))
|
||||
.fold(FastMode::Default, |mode, other| mode.merge(*other))
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
@@ -376,7 +402,7 @@ impl FrozenAccountScope {
|
||||
Self {
|
||||
allow_image_generation: true,
|
||||
allow_subagents: true,
|
||||
fast_mode: FastMode::Default,
|
||||
fast_mode_override: None,
|
||||
request_profiles: BTreeMap::new(),
|
||||
directory,
|
||||
client_scope,
|
||||
@@ -460,18 +486,31 @@ impl FrozenAccountScope {
|
||||
}
|
||||
match &self.client_scope {
|
||||
ClientRoutingScope::AllAccounts => true,
|
||||
ClientRoutingScope::Restricted { .. } => {
|
||||
self.matching_groups(account, accepts).next().is_some()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn matching_groups<'a>(
|
||||
&'a self,
|
||||
account: &'a RuntimeAccount,
|
||||
accepts: impl Fn(&AccountModelAccess) -> bool + 'a,
|
||||
) -> impl Iterator<Item = &'a AccountGroupId> {
|
||||
let enabled = match &self.client_scope {
|
||||
ClientRoutingScope::AllAccounts => None,
|
||||
ClientRoutingScope::Restricted {
|
||||
enabled_group_ids, ..
|
||||
} => account
|
||||
.group_ids()
|
||||
.intersection(enabled_group_ids)
|
||||
.any(|id| {
|
||||
self.directory
|
||||
.group_model_access
|
||||
.get(id)
|
||||
.is_none_or(&accepts)
|
||||
}),
|
||||
}
|
||||
} => Some(enabled_group_ids),
|
||||
};
|
||||
account.group_ids().iter().filter(move |id| {
|
||||
enabled.is_some_and(|groups| groups.contains(*id))
|
||||
&& self
|
||||
.directory
|
||||
.group_model_access
|
||||
.get(*id)
|
||||
.is_none_or(&accepts)
|
||||
})
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
|
||||
@@ -1200,7 +1200,6 @@ where
|
||||
.with_lease_metadata(Arc::clone(&self.lease_metadata))
|
||||
.with_response_control(self.response_control.clone())
|
||||
.with_request_profile(self.request_profiles.get(candidate.provider()).cloned())
|
||||
.with_fast_mode(self.plan.fast_mode())
|
||||
.with_prompt_rewrite_rules(self.plan.prompt_rewrite_rules(candidate.provider()))
|
||||
.with_pricing(self.plan.pricing())
|
||||
.with_request_location(self.plan.request_location().cloned())
|
||||
|
||||
@@ -48,11 +48,17 @@ pub(super) fn map_routing_error(error: crate::validation::RoutingError) -> Gatew
|
||||
"Mapped model unavailable for this API key. Check the model mapping."
|
||||
},
|
||||
),
|
||||
crate::validation::RoutingError::NoCapableProvider { .. }
|
||||
| crate::validation::RoutingError::NoCapableProviderEndpoint { .. }
|
||||
| crate::validation::RoutingError::EmptyAccountScope => GatewayError::new(
|
||||
crate::validation::RoutingError::NoCapableProvider { .. } => GatewayError::new(
|
||||
GatewayErrorKind::NoAvailableProvider,
|
||||
"The gateway has no eligible provider for this request.",
|
||||
"The gateway cannot select a provider for this model and the requested capabilities.",
|
||||
),
|
||||
crate::validation::RoutingError::NoCapableProviderEndpoint { .. } => GatewayError::new(
|
||||
GatewayErrorKind::NoAvailableProvider,
|
||||
"No eligible provider is available for the requested API endpoint.",
|
||||
),
|
||||
crate::validation::RoutingError::EmptyAccountScope => GatewayError::new(
|
||||
GatewayErrorKind::NoAvailableProvider,
|
||||
"This API key has no accounts in its scope. Add accounts or check its enabled account groups.",
|
||||
),
|
||||
crate::validation::RoutingError::UnsupportedProviderEndpoint { .. } => GatewayError::new(
|
||||
GatewayErrorKind::Unsupported,
|
||||
|
||||
@@ -330,7 +330,6 @@ pub struct RequestAttemptContext {
|
||||
prompt_rewrite_rules: Option<Arc<crate::settings::prompt_rewrite::ProviderPromptRules>>,
|
||||
pricing: Arc<crate::metering::PricingOverrides>,
|
||||
request_profile: Option<crate::account::OpaqueProviderData>,
|
||||
fast_mode: FastMode,
|
||||
openai_websocket_pool: crate::settings::OpenAiWebSocketPoolSettings,
|
||||
openai_request_settings: crate::settings::OpenAiRequestSettings,
|
||||
request_location: Option<crate::account::RequestLocation>,
|
||||
@@ -424,12 +423,6 @@ impl RequestAttemptContext {
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn with_fast_mode(mut self, fast_mode: FastMode) -> Self {
|
||||
self.fast_mode = fast_mode;
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn with_privacy(
|
||||
mut self,
|
||||
@@ -478,7 +471,6 @@ impl RequestAttemptContext {
|
||||
request_profile: None,
|
||||
prompt_rewrite_rules: None,
|
||||
pricing: Arc::default(),
|
||||
fast_mode: FastMode::Default,
|
||||
openai_websocket_pool: Default::default(),
|
||||
openai_request_settings: Default::default(),
|
||||
request_location: None,
|
||||
@@ -743,8 +735,14 @@ impl AttemptContext {
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn fast_mode(&self) -> FastMode {
|
||||
self.request.fast_mode
|
||||
pub fn fast_mode_for_account(
|
||||
&self,
|
||||
account: &ProviderAccountId,
|
||||
upstream_model: &str,
|
||||
) -> FastMode {
|
||||
self.account_scope().map_or(FastMode::Default, |scope| {
|
||||
scope.fast_mode_for_account(account, upstream_model)
|
||||
})
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
|
||||
@@ -1436,14 +1436,14 @@ impl GatewayError {
|
||||
pub(crate) const fn concurrency_queue_full() -> Self {
|
||||
Self::new(
|
||||
GatewayErrorKind::ConcurrencyQueueFull,
|
||||
"The gateway request queue is full.",
|
||||
"The gateway concurrency queue is full.",
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) const fn concurrency_queue_timeout() -> Self {
|
||||
Self::new(
|
||||
GatewayErrorKind::ConcurrencyQueueTimeout,
|
||||
"The request timed out in the gateway queue.",
|
||||
"Timed out waiting for available concurrency in the gateway.",
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1516,20 +1516,25 @@ impl GatewayError {
|
||||
GatewayErrorKind::Unsupported,
|
||||
"Requested capability is unsupported.",
|
||||
),
|
||||
ProviderErrorKind::Unauthorized | ProviderErrorKind::PermissionDenied => Self::new(
|
||||
ProviderErrorKind::Unauthorized => Self::new(
|
||||
GatewayErrorKind::UpstreamUnavailable,
|
||||
"The upstream account cannot access the service.",
|
||||
"Upstream account authentication failed.",
|
||||
),
|
||||
ProviderErrorKind::PermissionDenied => Self::new(
|
||||
GatewayErrorKind::UpstreamUnavailable,
|
||||
"The upstream account does not have permission for this request.",
|
||||
),
|
||||
ProviderErrorKind::RequestPolicyDenied => error.denied_group_feature.map_or_else(
|
||||
|| Self::new(GatewayErrorKind::PolicyDenied, "Request blocked by policy."),
|
||||
Self::from,
|
||||
),
|
||||
ProviderErrorKind::RateLimited => {
|
||||
Self::new(GatewayErrorKind::RateLimited, "Request rate limit reached.")
|
||||
}
|
||||
ProviderErrorKind::RateLimited => Self::new(
|
||||
GatewayErrorKind::RateLimited,
|
||||
"Upstream request rate limit reached.",
|
||||
),
|
||||
ProviderErrorKind::QuotaExhausted => Self::new(
|
||||
GatewayErrorKind::QuotaExhausted,
|
||||
"Account quota is exhausted.",
|
||||
"Upstream account quota is exhausted.",
|
||||
),
|
||||
ProviderErrorKind::AccountPoolQuotaExhausted => Self::new(
|
||||
GatewayErrorKind::AccountPoolQuotaExhausted,
|
||||
@@ -1539,7 +1544,7 @@ impl GatewayError {
|
||||
ProviderErrorKind::ConcurrencyQueueTimeout => Self::concurrency_queue_timeout(),
|
||||
ProviderErrorKind::AccountCapacityUnavailable => Self::new(
|
||||
GatewayErrorKind::AccountCapacityUnavailable,
|
||||
"The gateway account pool is busy.",
|
||||
"No eligible account currently has capacity for this request.",
|
||||
),
|
||||
ProviderErrorKind::NoEligibleAccount => Self::new(
|
||||
GatewayErrorKind::NoAvailableProvider,
|
||||
@@ -1559,11 +1564,23 @@ impl GatewayError {
|
||||
ProviderErrorKind::Cancelled => {
|
||||
Self::new(GatewayErrorKind::Cancelled, "Request was cancelled.")
|
||||
}
|
||||
ProviderErrorKind::Transport
|
||||
| ProviderErrorKind::Protocol
|
||||
| ProviderErrorKind::Unavailable
|
||||
| ProviderErrorKind::UpstreamCapacityUnavailable
|
||||
| ProviderErrorKind::ProcessTerminated => Self::new(
|
||||
ProviderErrorKind::Transport => Self::new(
|
||||
GatewayErrorKind::UpstreamUnavailable,
|
||||
"Communication with the upstream service failed.",
|
||||
),
|
||||
ProviderErrorKind::Protocol => Self::new(
|
||||
GatewayErrorKind::UpstreamUnavailable,
|
||||
"Upstream protocol handling failed.",
|
||||
),
|
||||
ProviderErrorKind::ProcessTerminated => Self::new(
|
||||
GatewayErrorKind::UpstreamUnavailable,
|
||||
"The gateway stopped before the request completed.",
|
||||
),
|
||||
ProviderErrorKind::UpstreamCapacityUnavailable => Self::new(
|
||||
GatewayErrorKind::UpstreamUnavailable,
|
||||
"The upstream service has no capacity for this request.",
|
||||
),
|
||||
ProviderErrorKind::Unavailable => Self::new(
|
||||
GatewayErrorKind::UpstreamUnavailable,
|
||||
"Upstream service is unavailable.",
|
||||
),
|
||||
|
||||
@@ -5,6 +5,7 @@ use std::sync::{Arc, OnceLock};
|
||||
use std::time::{Duration, SystemTime};
|
||||
|
||||
use event_listener::Event;
|
||||
use futures::FutureExt as _;
|
||||
use futures::future::{BoxFuture, pending};
|
||||
use futures_timer::Delay;
|
||||
|
||||
@@ -142,6 +143,14 @@ impl CancellationToken {
|
||||
self.reason().is_some()
|
||||
}
|
||||
|
||||
/// 取消优先于同时就绪的工作,只用于可安全丢弃的 future
|
||||
pub async fn run_until_cancelled<T>(&self, work: impl Future<Output = T>) -> Option<T> {
|
||||
futures::select_biased! {
|
||||
() = self.cancelled().fuse() => None,
|
||||
result = work.fuse() => Some(result),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn cancelled(&self) {
|
||||
if self.is_cancelled() {
|
||||
return;
|
||||
|
||||
@@ -158,7 +158,7 @@ impl RateLimits {
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ClientSettings {
|
||||
pub request_profiles: BTreeMap<ProviderKind, OpaqueProviderData>,
|
||||
pub fast_mode: FastMode,
|
||||
pub fast_mode_override: Option<FastMode>,
|
||||
pub limits: RateLimits,
|
||||
}
|
||||
|
||||
@@ -185,18 +185,18 @@ impl ClientPolicy {
|
||||
pub(crate) fn with_settings(
|
||||
mut self,
|
||||
profiles: &BTreeMap<ProviderKind, OpaqueProviderData>,
|
||||
fast_mode: FastMode,
|
||||
fast_mode_override: Option<FastMode>,
|
||||
limits: RateLimits,
|
||||
) -> Self {
|
||||
if self.account_scope.request_profiles() != profiles
|
||||
|| self.account_scope.fast_mode() != fast_mode
|
||||
|| self.account_scope.fast_mode_override() != fast_mode_override
|
||||
{
|
||||
self.account_scope = Arc::new(
|
||||
self.account_scope
|
||||
.as_ref()
|
||||
.clone()
|
||||
.with_request_profiles(profiles.clone())
|
||||
.with_fast_mode(fast_mode),
|
||||
.with_fast_mode_override(fast_mode_override),
|
||||
);
|
||||
}
|
||||
self.limits = limits;
|
||||
@@ -217,7 +217,7 @@ impl ClientPolicy {
|
||||
name_snapshot: None,
|
||||
defaults: Arc::new(ClientSettings {
|
||||
request_profiles: account_scope.request_profiles().clone(),
|
||||
fast_mode: account_scope.fast_mode(),
|
||||
fast_mode_override: account_scope.fast_mode_override(),
|
||||
limits,
|
||||
}),
|
||||
key_id,
|
||||
|
||||
@@ -23,7 +23,7 @@ use std::fmt;
|
||||
use std::num::{NonZeroU32, NonZeroU64};
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::account::{AccountSelectionPolicy, FastMode};
|
||||
use crate::account::AccountSelectionPolicy;
|
||||
use crate::operation::{CapabilityRequirements, Feature, OperationKind};
|
||||
use crate::validation::{IdentifierError, RoutingError, validate_text};
|
||||
|
||||
@@ -767,11 +767,6 @@ impl RoutingPlan {
|
||||
Arc::clone(&self.pricing)
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn fast_mode(&self) -> FastMode {
|
||||
self.account_scope.fast_mode()
|
||||
}
|
||||
|
||||
/// 本次请求冻结的已编译规则,重试不读取新的全局策略
|
||||
#[must_use]
|
||||
pub fn privacy(&self) -> Option<Arc<dyn crate::settings::privacy::CompiledPrivacyPolicy>> {
|
||||
|
||||
@@ -19,7 +19,8 @@ use crate::settings::{InvalidSettings, SettingsValues};
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct ExecutionSettings {
|
||||
pub runtime: SettingsValues,
|
||||
pub fast_mode: FastMode,
|
||||
/// None 按选中账号的有效分组解析;Some(Default) 显式跟随客户端
|
||||
pub fast_mode: Option<FastMode>,
|
||||
pub client_limits: RateLimits,
|
||||
/// null 表示不限制总时长;显式时限从请求开始计时,改写不重置计时原点
|
||||
pub timeout_ms: Option<u64>,
|
||||
@@ -38,7 +39,7 @@ struct ExecutionOverrides {
|
||||
defaults: Arc<ClientSettings>,
|
||||
client_key_id: String,
|
||||
input: Arc<ExecutionSettings>,
|
||||
fast_mode: Option<SettingOverride<FastMode>>,
|
||||
fast_mode: Option<SettingOverride<Option<FastMode>>>,
|
||||
client_limits: Option<SettingOverride<RateLimits>>,
|
||||
timeout_ms: Option<SettingOverride<Option<u64>>>,
|
||||
}
|
||||
@@ -186,9 +187,10 @@ impl RequestSettings {
|
||||
#[must_use]
|
||||
pub fn apply_policy(&self, policy: ClientPolicy) -> ClientPolicy {
|
||||
let values = self.resolve_execution(policy.key_id().as_str(), policy.defaults(), None);
|
||||
let fast_mode = self.fast_mode_override(policy.key_id().as_str(), policy.defaults());
|
||||
policy.with_settings(
|
||||
values.runtime.request_profiles(),
|
||||
values.fast_mode,
|
||||
fast_mode,
|
||||
values.client_limits,
|
||||
)
|
||||
}
|
||||
@@ -247,9 +249,7 @@ impl RequestSettings {
|
||||
}
|
||||
ExecutionSettings {
|
||||
runtime,
|
||||
fast_mode: overrides
|
||||
.and_then(|scope| scope.fast_mode.as_ref())
|
||||
.map_or(defaults.fast_mode, |change| change.value),
|
||||
fast_mode: self.fast_mode_override(key, defaults),
|
||||
client_limits: overrides
|
||||
.and_then(|scope| scope.client_limits.as_ref())
|
||||
.map_or(defaults.limits, |change| change.value),
|
||||
@@ -259,6 +259,15 @@ impl RequestSettings {
|
||||
}
|
||||
}
|
||||
|
||||
fn fast_mode_override(&self, key: &str, defaults: &ClientSettings) -> Option<FastMode> {
|
||||
self.execution
|
||||
.as_ref()
|
||||
.filter(|scope| scope.client_key_id == key)
|
||||
.and_then(|scope| scope.fast_mode.as_ref())
|
||||
.map(|change| change.value)
|
||||
.unwrap_or(defaults.fast_mode_override)
|
||||
}
|
||||
|
||||
pub(crate) fn execution_deadline(
|
||||
&self,
|
||||
key: &ClientApiKeyId,
|
||||
|
||||
@@ -583,12 +583,19 @@ async fn compile_runtime_snapshot(
|
||||
.map(|group| (group.id.clone(), std::mem::take(&mut group.model_access)))
|
||||
.collect();
|
||||
let account_directory = Arc::new(
|
||||
RuntimeAccountDirectory::new(accounts).with_group_model_access(group_model_access),
|
||||
RuntimeAccountDirectory::new(accounts)
|
||||
.with_group_model_access(group_model_access)
|
||||
.with_group_fast_modes(
|
||||
groups
|
||||
.values()
|
||||
.filter(|group| group.enabled && group.fast_mode != FastMode::Default)
|
||||
.map(|group| (group.id.clone(), group.fast_mode))
|
||||
.collect(),
|
||||
),
|
||||
);
|
||||
|
||||
let mut client_policies = Vec::with_capacity(facts.client_policies.len());
|
||||
for policy in facts.client_policies {
|
||||
let mut fast_mode = FastMode::Default;
|
||||
let mut allow_image_generation = true;
|
||||
let mut allow_subagents = true;
|
||||
let account_scope = if policy.group_ids.is_empty() {
|
||||
@@ -607,8 +614,7 @@ async fn compile_runtime_snapshot(
|
||||
let group = groups
|
||||
.get(&group_id)
|
||||
.ok_or(RuntimeSnapshotCompileError::InvalidData)?;
|
||||
// 停用只影响选号,仍绑定的分组继续贡献请求策略
|
||||
fast_mode = fast_mode.merge(group.fast_mode);
|
||||
// 功能权限仍按 Key 合并,停用分组不解除生图和子代理限制
|
||||
allow_image_generation &= group.allow_image_generation;
|
||||
allow_subagents &= group.allow_subagents;
|
||||
bound_groups.push(RoutingGroupSnapshot::new(
|
||||
@@ -635,7 +641,6 @@ async fn compile_runtime_snapshot(
|
||||
account_scope
|
||||
.with_image_generation(allow_image_generation)
|
||||
.with_subagents(allow_subagents)
|
||||
.with_fast_mode(fast_mode)
|
||||
.with_request_profiles(policy.request_profiles),
|
||||
),
|
||||
true,
|
||||
|
||||
@@ -399,14 +399,13 @@ struct RuntimeSnapshotReconciliationTask {
|
||||
}
|
||||
|
||||
impl ScheduledTask for RuntimeSnapshotReconciliationTask {
|
||||
fn run_cycle(
|
||||
&self,
|
||||
_context: WorkerCycleContext,
|
||||
) -> BoxFuture<'_, Result<(), WorkerTaskError>> {
|
||||
fn run_cycle(&self, context: WorkerCycleContext) -> BoxFuture<'_, Result<(), WorkerTaskError>> {
|
||||
Box::pin(async move {
|
||||
self.publisher
|
||||
.refresh_with_mode(RefreshMode::Reconcile)
|
||||
context
|
||||
.cancellation()
|
||||
.run_until_cancelled(self.publisher.refresh_with_mode(RefreshMode::Reconcile))
|
||||
.await
|
||||
.transpose()
|
||||
.map(|_| ())
|
||||
.map_err(|source| {
|
||||
WorkerTaskError::safe("runtime snapshot reconciliation failed")
|
||||
@@ -430,10 +429,12 @@ impl DaemonTask for RuntimeSnapshotSubscriptionTask {
|
||||
let cancellation = context.cancellation();
|
||||
let mut retry_delay = INITIAL_BACKOFF;
|
||||
loop {
|
||||
if cancellation.is_cancelled() {
|
||||
let Some(subscription) = cancellation
|
||||
.run_until_cancelled(self.subscriptions.subscribe_snapshot_revisions())
|
||||
.await
|
||||
else {
|
||||
return Ok(());
|
||||
}
|
||||
let subscription = self.subscriptions.subscribe_snapshot_revisions().await;
|
||||
};
|
||||
let mut subscription = match subscription {
|
||||
Ok(subscription) => {
|
||||
retry_delay = INITIAL_BACKOFF;
|
||||
@@ -456,7 +457,13 @@ impl DaemonTask for RuntimeSnapshotSubscriptionTask {
|
||||
};
|
||||
match notified {
|
||||
Some(Ok(_)) => {
|
||||
let _ = self.publisher.refresh().await;
|
||||
if cancellation
|
||||
.run_until_cancelled(self.publisher.refresh())
|
||||
.await
|
||||
.is_none()
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
Some(Err(_)) | None => break,
|
||||
}
|
||||
|
||||
@@ -1138,26 +1138,12 @@ fn plan_with_location(
|
||||
operation: &Operation,
|
||||
account_selection_policy: AccountSelectionPolicy,
|
||||
request_location: gateway_core::account::RequestLocation,
|
||||
) -> RoutingPlan {
|
||||
plan_with_location_and_fast_policy(
|
||||
operation,
|
||||
account_selection_policy,
|
||||
request_location,
|
||||
FastMode::Default,
|
||||
)
|
||||
}
|
||||
|
||||
fn plan_with_location_and_fast_policy(
|
||||
operation: &Operation,
|
||||
account_selection_policy: AccountSelectionPolicy,
|
||||
request_location: gateway_core::account::RequestLocation,
|
||||
fast_mode: FastMode,
|
||||
) -> RoutingPlan {
|
||||
plan_with_profiles(
|
||||
operation,
|
||||
account_selection_policy,
|
||||
request_location,
|
||||
fast_mode,
|
||||
FastMode::Default,
|
||||
Default::default(),
|
||||
)
|
||||
}
|
||||
@@ -1255,7 +1241,7 @@ fn plan_with_protection(
|
||||
operation,
|
||||
Arc::new(
|
||||
FrozenAccountScope::new(directory, ClientRoutingScope::all_accounts())
|
||||
.with_fast_mode(fast_mode)
|
||||
.with_fast_mode_override(Some(fast_mode))
|
||||
.with_request_profiles(profiles),
|
||||
),
|
||||
&RoutingContext {
|
||||
@@ -6414,6 +6400,8 @@ fn deadline_before_first_event_is_persisted_as_failed_attempt() {
|
||||
|
||||
#[test]
|
||||
fn global_location_and_group_fast_policy_reach_every_account_retry() {
|
||||
use gateway_core::routing::{AccountGroupId, RoutingGroupSnapshot};
|
||||
|
||||
for mode in [
|
||||
FastMode::Default,
|
||||
FastMode::Enabled,
|
||||
@@ -6425,12 +6413,67 @@ fn global_location_and_group_fast_policy_reach_every_account_retry() {
|
||||
timezone: "Asia/Tokyo".parse().unwrap(),
|
||||
..Default::default()
|
||||
};
|
||||
let route_plan = plan_with_location_and_fast_policy(
|
||||
&operation,
|
||||
plan(&operation).account_selection_policy(),
|
||||
location.clone(),
|
||||
mode,
|
||||
let kind = ProviderKind::new("openai").unwrap();
|
||||
let first_group = AccountGroupId::new(format!("grp_{:032x}", 1)).unwrap();
|
||||
let second_group = AccountGroupId::new(format!("grp_{:032x}", 2)).unwrap();
|
||||
let second_mode = if mode == FastMode::Disabled {
|
||||
FastMode::Default
|
||||
} else {
|
||||
FastMode::Disabled
|
||||
};
|
||||
let directory = Arc::new(
|
||||
RuntimeAccountDirectory::new(
|
||||
[
|
||||
("acct_first", first_group.clone()),
|
||||
("acct_second", second_group.clone()),
|
||||
]
|
||||
.into_iter()
|
||||
.map(|(account, group)| {
|
||||
(
|
||||
ProviderAccountId::new(account).unwrap(),
|
||||
RuntimeAccount::new(kind.clone(), BTreeSet::from([group])),
|
||||
)
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
.with_group_fast_modes(BTreeMap::from([
|
||||
(first_group.clone(), mode),
|
||||
(second_group.clone(), second_mode),
|
||||
])),
|
||||
);
|
||||
let scope = Arc::new(FrozenAccountScope::new(
|
||||
Arc::clone(&directory),
|
||||
ClientRoutingScope::restricted(
|
||||
vec![
|
||||
RoutingGroupSnapshot::new(first_group.clone(), "A".into()),
|
||||
RoutingGroupSnapshot::new(second_group.clone(), "B".into()),
|
||||
],
|
||||
BTreeSet::from([first_group, second_group]),
|
||||
BTreeSet::from([kind.clone()]),
|
||||
)
|
||||
.unwrap(),
|
||||
));
|
||||
let route_plan = RuntimeSnapshot::new(
|
||||
ConfigRevision::new(1).unwrap(),
|
||||
gateway_core::settings::SettingsValues::new(2, "smart", Default::default(), None, None)
|
||||
.with_request_location(location.clone(), true),
|
||||
vec![kind.clone()],
|
||||
vec![ProviderModel::new(
|
||||
kind,
|
||||
UpstreamModelId::new("gpt-5").unwrap(),
|
||||
ModelCapabilities::new(BTreeSet::from([operation.kind()]), Some(32_000)),
|
||||
)],
|
||||
Vec::new(),
|
||||
)
|
||||
.unwrap()
|
||||
.with_account_directory(directory)
|
||||
.plan(
|
||||
&PublicModelId::new("gpt-5").unwrap(),
|
||||
&operation,
|
||||
Arc::clone(&scope),
|
||||
&RoutingContext::default(),
|
||||
)
|
||||
.unwrap();
|
||||
let (coordinator, _, provider) = coordinator(vec![
|
||||
Script::Stream {
|
||||
account_id: "acct_first",
|
||||
@@ -6459,12 +6502,17 @@ fn global_location_and_group_fast_policy_reach_every_account_retry() {
|
||||
block_on(session.commit_downstream(Some(200))).unwrap();
|
||||
let contexts = provider.contexts.lock().unwrap();
|
||||
assert_eq!(contexts.len(), 2);
|
||||
assert!(
|
||||
contexts
|
||||
.iter()
|
||||
.all(|context| context.request_location() == Some(&location)
|
||||
&& context.fast_mode() == mode)
|
||||
);
|
||||
for (context, account, expected) in [
|
||||
(&contexts[0], "acct_first", mode),
|
||||
(&contexts[1], "acct_second", second_mode),
|
||||
] {
|
||||
assert_eq!(context.request_location(), Some(&location));
|
||||
assert!(Arc::ptr_eq(context.account_scope().unwrap(), &scope));
|
||||
assert_eq!(
|
||||
context.fast_mode_for_account(&ProviderAccountId::new(account).unwrap(), "gpt-5"),
|
||||
expected,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -3068,8 +3068,14 @@ impl Provider for ChargedProvider {
|
||||
request: ProviderRequest,
|
||||
context: AttemptContext,
|
||||
) -> Result<ProviderStream, ProviderError> {
|
||||
self.policies.lock().unwrap().push(context.fast_mode());
|
||||
let candidate = request.candidate();
|
||||
self.policies
|
||||
.lock()
|
||||
.unwrap()
|
||||
.push(context.fast_mode_for_account(
|
||||
&ProviderAccountId::new("acct_start").unwrap(),
|
||||
candidate.upstream_model().unwrap().as_str(),
|
||||
));
|
||||
let metadata = ProviderCallMetadata::new(
|
||||
candidate.provider().clone(),
|
||||
candidate.upstream_model().unwrap().clone(),
|
||||
@@ -4792,7 +4798,7 @@ fn start_snapshot_with_image_policy(
|
||||
account_scope(&provider, "acct_start")
|
||||
.as_ref()
|
||||
.clone()
|
||||
.with_fast_mode(fast_mode)
|
||||
.with_fast_mode_override(Some(fast_mode))
|
||||
.with_image_generation(allow_image_generation),
|
||||
),
|
||||
enabled,
|
||||
@@ -5526,7 +5532,7 @@ fn entry_settings_freeze_authentication_and_rebase_only_explicit_overrides() {
|
||||
.execution_values()
|
||||
.unwrap()
|
||||
.fast_mode,
|
||||
FastMode::Disabled
|
||||
Some(FastMode::Disabled)
|
||||
);
|
||||
assert_eq!(
|
||||
prepared
|
||||
@@ -5649,7 +5655,7 @@ fn child_settings_recompute_key_scope_without_inheriting_parent_defaults() {
|
||||
account_scope(&provider, "acct_start")
|
||||
.as_ref()
|
||||
.clone()
|
||||
.with_fast_mode(FastMode::Disabled)
|
||||
.with_fast_mode_override(Some(FastMode::Disabled))
|
||||
.with_request_profiles(profiles(name)),
|
||||
),
|
||||
true,
|
||||
@@ -5688,7 +5694,7 @@ fn child_settings_recompute_key_scope_without_inheriting_parent_defaults() {
|
||||
let configuration = RequestSettings::new(snapshots.acquire().unwrap())
|
||||
.with_execution(parent.client().policy(), previous.timeout_ms);
|
||||
let mut values = previous.clone();
|
||||
values.fast_mode = FastMode::Default;
|
||||
values.fast_mode = Some(FastMode::Default);
|
||||
values.client_limits = RateLimits::unlimited();
|
||||
values.timeout_ms = Some(90_000);
|
||||
let mut runtime = serde_json::to_value(&values.runtime).unwrap();
|
||||
@@ -5722,7 +5728,7 @@ fn child_settings_recompute_key_scope_without_inheriting_parent_defaults() {
|
||||
Some(actual.clone())
|
||||
);
|
||||
assert_eq!(actual.client_limits.max_concurrency, expected_limit);
|
||||
assert_eq!(actual.fast_mode, expected_fast);
|
||||
assert_eq!(actual.fast_mode, Some(expected_fast));
|
||||
assert_eq!(actual.timeout_ms, expected_timeout);
|
||||
let facts = serde_json::to_value(actual.runtime).unwrap();
|
||||
assert_eq!(facts["request_profiles"]["openai"]["identity"], profile);
|
||||
|
||||
@@ -186,7 +186,10 @@ fn gateway_error_should_keep_client_visible_upstream_fields_out_of_safe_diagnost
|
||||
));
|
||||
let gateway = GatewayError::from_provider(&error);
|
||||
|
||||
assert_eq!(gateway.safe_message(), "Account quota is exhausted.");
|
||||
assert_eq!(
|
||||
gateway.safe_message(),
|
||||
"Upstream account quota is exhausted."
|
||||
);
|
||||
assert_eq!(gateway.client_message(), message);
|
||||
assert_eq!(gateway.client_error_code(), Some("quota_exhausted"));
|
||||
assert_eq!(gateway.client_error_type(), Some("rate_limit_error"));
|
||||
|
||||
@@ -53,7 +53,7 @@ fn policy_with_profiles(
|
||||
Arc::new(
|
||||
FrozenAccountScope::new(Arc::default(), ClientRoutingScope::all_accounts())
|
||||
.with_request_profiles(overrides)
|
||||
.with_fast_mode(FastMode::Disabled),
|
||||
.with_fast_mode_override(Some(FastMode::Disabled)),
|
||||
),
|
||||
true,
|
||||
RateLimits {
|
||||
@@ -153,7 +153,7 @@ fn scope_changes_recompute_defaults_and_inherit_only_explicit_overrides() {
|
||||
values.runtime = values
|
||||
.runtime
|
||||
.with_model_mappings(BTreeMap::from([("alias".into(), "model".into())]));
|
||||
values.fast_mode = FastMode::Default;
|
||||
values.fast_mode = Some(FastMode::Default);
|
||||
values.client_limits = RateLimits::unlimited();
|
||||
values.timeout_ms = Some(90_000);
|
||||
let changed = original.replace_execution(&values, "plugin").unwrap();
|
||||
@@ -168,14 +168,14 @@ fn scope_changes_recompute_defaults_and_inherit_only_explicit_overrides() {
|
||||
parent_values.runtime.request_profiles(),
|
||||
&profiles(&[("openai", "parent"), ("xai", "second")])
|
||||
);
|
||||
assert_eq!(parent_values.fast_mode, FastMode::Default);
|
||||
assert_eq!(parent_values.fast_mode, Some(FastMode::Default));
|
||||
let child_settings = rebased.with_execution(&child, Some(60_000));
|
||||
let child_values = child_settings.execution_values().unwrap();
|
||||
assert_eq!(
|
||||
child_values.runtime.request_profiles(),
|
||||
&profiles(&[("openai", "child"), ("xai", "second")])
|
||||
);
|
||||
assert_eq!(child_values.fast_mode, FastMode::Disabled);
|
||||
assert_eq!(child_values.fast_mode, Some(FastMode::Disabled));
|
||||
assert_eq!(child_values.client_limits, child.limits());
|
||||
assert_eq!(child_values.timeout_ms, Some(60_000));
|
||||
assert_eq!(child_settings.snapshot().mapped_model("alias"), "model");
|
||||
@@ -186,6 +186,81 @@ fn scope_changes_recompute_defaults_and_inherit_only_explicit_overrides() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_fast_policy_survives_settings_resolution_until_explicitly_overridden() {
|
||||
use gateway_core::{
|
||||
account::ProviderAccountId,
|
||||
routing::{AccountGroupId, RoutingGroupSnapshot, RuntimeAccount, RuntimeAccountDirectory},
|
||||
};
|
||||
let group = AccountGroupId::new(format!("grp_{:032x}", 1)).unwrap();
|
||||
let account = ProviderAccountId::new("acct_group_fast").unwrap();
|
||||
let provider = ProviderKind::new("openai").unwrap();
|
||||
let scope = Arc::new(FrozenAccountScope::new(
|
||||
Arc::new(
|
||||
RuntimeAccountDirectory::new(BTreeMap::from([(
|
||||
account.clone(),
|
||||
RuntimeAccount::new(provider.clone(), [group.clone()].into()),
|
||||
)]))
|
||||
.with_group_fast_modes([(group.clone(), FastMode::Disabled)].into()),
|
||||
),
|
||||
ClientRoutingScope::restricted(
|
||||
vec![RoutingGroupSnapshot::new(group.clone(), "Standard".into())],
|
||||
[group].into(),
|
||||
[provider].into(),
|
||||
)
|
||||
.unwrap(),
|
||||
));
|
||||
let key = |name: &str| {
|
||||
ClientPolicy::new(
|
||||
ClientApiKeyId::new(name).unwrap(),
|
||||
PlaintextClientApiKey::new(format!("fixture-{name}")).unwrap(),
|
||||
scope.clone(),
|
||||
true,
|
||||
RateLimits::unlimited(),
|
||||
)
|
||||
};
|
||||
let parent = key("parent");
|
||||
let settings = RequestSettings::new(snapshot(1, "host")).with_execution(&parent, None);
|
||||
assert_eq!(settings.execution_values().unwrap().fast_mode, None);
|
||||
let resolved = |settings: &RequestSettings, key| {
|
||||
settings
|
||||
.apply_policy(key)
|
||||
.account_scope()
|
||||
.fast_mode_for_account(&account, "model")
|
||||
};
|
||||
assert_eq!(resolved(&settings, parent.clone()), FastMode::Disabled);
|
||||
let unchanged = settings
|
||||
.replace_execution(&settings.execution_values().unwrap(), "pass-through")
|
||||
.unwrap();
|
||||
assert_eq!(resolved(&unchanged, parent.clone()), FastMode::Disabled);
|
||||
|
||||
let mut values = settings.execution_values().unwrap();
|
||||
values.fast_mode = Some(FastMode::Default);
|
||||
let direct_default = settings
|
||||
.replace_execution(&values, "follow-client")
|
||||
.unwrap();
|
||||
assert_eq!(resolved(&direct_default, parent.clone()), FastMode::Default);
|
||||
values.fast_mode = Some(FastMode::Enabled);
|
||||
let enabled = settings.replace_execution(&values, "force-fast").unwrap();
|
||||
assert_eq!(resolved(&enabled, parent.clone()), FastMode::Enabled);
|
||||
values.fast_mode = Some(FastMode::Default);
|
||||
let default = enabled.replace_execution(&values, "follow-client").unwrap();
|
||||
assert_eq!(resolved(&default, parent.clone()), FastMode::Default);
|
||||
values.fast_mode = None;
|
||||
let cleared = default.replace_execution(&values, "group-policy").unwrap();
|
||||
assert_eq!(resolved(&cleared, parent.clone()), FastMode::Disabled);
|
||||
assert_eq!(
|
||||
cleared.inspect()["execution"]["fast_mode"]["value"],
|
||||
serde_json::Value::Null
|
||||
);
|
||||
let child = key("child");
|
||||
assert_eq!(
|
||||
resolved(&default.with_execution(&child, None), child),
|
||||
FastMode::Disabled
|
||||
);
|
||||
assert_eq!(resolved(&settings, parent), FastMode::Disabled);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicitly_selecting_the_host_profiles_overrides_keys_after_rebase() {
|
||||
let host = snapshot(1, "first");
|
||||
|
||||
@@ -2727,7 +2727,7 @@ fn decompression_setting_should_validate_and_remain_frozen_across_publication()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fast_mode_merges_only_bound_groups_without_changing_account_scope() {
|
||||
fn fast_mode_merges_only_enabled_bound_groups_of_the_selected_account() {
|
||||
use gateway_core::account::ProviderAccountId;
|
||||
use gateway_core::routing::AccountGroupId;
|
||||
for (mode, other_mode, expected) in [
|
||||
@@ -2758,6 +2758,8 @@ fn fast_mode_merges_only_bound_groups_without_changing_account_scope() {
|
||||
let open_group_id =
|
||||
AccountGroupId::new("grp_00000000000000000000000000000002").unwrap();
|
||||
let account_id = ProviderAccountId::new("acct_fast_policy").unwrap();
|
||||
let first_account = ProviderAccountId::new("acct_first_group").unwrap();
|
||||
let second_account = ProviderAccountId::new("acct_second_group").unwrap();
|
||||
let facts = SnapshotFacts::new(
|
||||
revision(1),
|
||||
revision(1),
|
||||
@@ -2786,11 +2788,19 @@ fn fast_mode_merges_only_bound_groups_without_changing_account_scope() {
|
||||
)
|
||||
.with_fast_mode(other_mode),
|
||||
],
|
||||
vec![SnapshotProviderAccountFacts::new(
|
||||
account_id.clone(),
|
||||
"alpha",
|
||||
)],
|
||||
[&account_id, &first_account, &second_account]
|
||||
.into_iter()
|
||||
.map(|id| SnapshotProviderAccountFacts::new(id.clone(), "alpha"))
|
||||
.collect(),
|
||||
vec![
|
||||
SnapshotAccountGroupMemberFacts::new(
|
||||
group_id.clone(),
|
||||
first_account.clone(),
|
||||
),
|
||||
SnapshotAccountGroupMemberFacts::new(
|
||||
open_group_id.clone(),
|
||||
second_account.clone(),
|
||||
),
|
||||
SnapshotAccountGroupMemberFacts::new(group_id, account_id.clone()),
|
||||
SnapshotAccountGroupMemberFacts::new(open_group_id, account_id.clone()),
|
||||
],
|
||||
@@ -2818,16 +2828,99 @@ fn fast_mode_merges_only_bound_groups_without_changing_account_scope() {
|
||||
&Default::default(),
|
||||
)
|
||||
.unwrap();
|
||||
for (account, effective) in [
|
||||
(
|
||||
&account_id,
|
||||
if group_enabled { expected } else { other_mode },
|
||||
),
|
||||
(
|
||||
&first_account,
|
||||
if group_enabled {
|
||||
mode
|
||||
} else {
|
||||
FastMode::Default
|
||||
},
|
||||
),
|
||||
(&second_account, other_mode),
|
||||
] {
|
||||
assert_eq!(
|
||||
plan.account_scope()
|
||||
.fast_mode_for_account(account, "public-model"),
|
||||
if bound { effective } else { FastMode::Default },
|
||||
"account={account}, mode={mode:?}, other={other_mode:?}, enabled={group_enabled}, bound={bound}"
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
plan.fast_mode(),
|
||||
if bound { expected } else { FastMode::Default },
|
||||
"mode={mode:?}, other={other_mode:?}, enabled={group_enabled}, bound={bound}"
|
||||
plan.account_scope().allows(&first_account),
|
||||
!bound || group_enabled
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fast_mode_ignores_unbound_groups_and_groups_that_deny_the_model() {
|
||||
use gateway_core::account::{AccountModelAccess, AccountModelAccessMode, ProviderAccountId};
|
||||
use gateway_core::routing::AccountGroupId;
|
||||
|
||||
let group = |id| AccountGroupId::new(format!("grp_{id:032x}")).unwrap();
|
||||
let account = ProviderAccountId::new("acct_model_fast").unwrap();
|
||||
let facts = SnapshotFacts::new(
|
||||
revision(1),
|
||||
revision(1),
|
||||
SettingsValues::new(3, "smart", BTreeMap::new(), None, None),
|
||||
vec![SnapshotClientPolicyFacts::new(
|
||||
ClientApiKeyId::new("key_model_fast").unwrap(),
|
||||
PlaintextClientApiKey::new("fixture-model-fast").unwrap(),
|
||||
vec![group(1), group(2)],
|
||||
RateLimits::unlimited(),
|
||||
)],
|
||||
vec![
|
||||
SnapshotAccountGroupFacts::new(group(1), "Fast".into(), true)
|
||||
.with_fast_mode(FastMode::Enabled)
|
||||
.with_model_access(
|
||||
AccountModelAccess::new(
|
||||
AccountModelAccessMode::Allowlist,
|
||||
vec!["fast-model".into()],
|
||||
)
|
||||
.unwrap(),
|
||||
),
|
||||
SnapshotAccountGroupFacts::new(group(2), "Standard".into(), true)
|
||||
.with_fast_mode(FastMode::Disabled)
|
||||
.with_model_access(
|
||||
AccountModelAccess::new(
|
||||
AccountModelAccessMode::Denylist,
|
||||
vec!["fast-model".into()],
|
||||
)
|
||||
.unwrap(),
|
||||
),
|
||||
SnapshotAccountGroupFacts::new(group(3), "Unbound".into(), true)
|
||||
.with_fast_mode(FastMode::Disabled),
|
||||
],
|
||||
vec![SnapshotProviderAccountFacts::new(account.clone(), "alpha")],
|
||||
(1..=3)
|
||||
.map(|id| SnapshotAccountGroupMemberFacts::new(group(id), account.clone()))
|
||||
.collect(),
|
||||
);
|
||||
let snapshot = block_on(
|
||||
RuntimeSnapshotCompiler::new(
|
||||
Arc::new(TestSnapshotStore::new(Ok(facts))),
|
||||
Arc::new(TestCatalog::Unavailable),
|
||||
)
|
||||
.compile(),
|
||||
)
|
||||
.unwrap();
|
||||
let scope = snapshot.client_policies().next().unwrap().account_scope();
|
||||
for (model, expected) in [
|
||||
("fast-model", FastMode::Enabled),
|
||||
("standard-model", FastMode::Disabled),
|
||||
] {
|
||||
assert!(scope.allows_model(&account, model));
|
||||
assert_eq!(scope.fast_mode_for_account(&account, model), expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_feature_permissions_merge_independently_with_deny_precedence() {
|
||||
use gateway_core::account::ProviderAccountId;
|
||||
|
||||
@@ -48,6 +48,7 @@ tracing = "0.1.44"
|
||||
tracing-appender = "0.2.5"
|
||||
tracing-subscriber = { version = "0.3.23", features = ["env-filter", "json"] }
|
||||
yaml-rust2 = "0.13.0"
|
||||
uuid = { version = "1.23.3", features = ["v4"] }
|
||||
|
||||
[dev-dependencies]
|
||||
hyper = { version = "=1.11.1", default-features = false, features = ["server"] }
|
||||
|
||||
@@ -37,6 +37,7 @@ const MAX_OFFICIAL_PLUGIN_MANIFEST_SIZE: u64 = 256 * 1024;
|
||||
/// gateway-admin 消费的真实进程/文件系统操作实现
|
||||
#[derive(Clone)]
|
||||
pub struct ProcessSystemOperations {
|
||||
instance_id: String,
|
||||
cancellation: CancellationToken,
|
||||
events: Arc<UpdateEvents>,
|
||||
config: Arc<SystemUpdateConfig>,
|
||||
@@ -62,6 +63,7 @@ impl ProcessSystemOperations {
|
||||
ReleaseFiles::installed(&config)
|
||||
}));
|
||||
Self {
|
||||
instance_id: uuid::Uuid::new_v4().to_string(),
|
||||
cancellation,
|
||||
events: Arc::new(UpdateEvents::default()),
|
||||
config: Arc::new(config),
|
||||
@@ -350,6 +352,8 @@ impl SystemOperations for ProcessSystemOperations {
|
||||
.await;
|
||||
Ok(SystemVersion {
|
||||
version: self.config.version.clone(),
|
||||
instance_id: self.instance_id.clone(),
|
||||
restart_supported: self.config.self_restart_enabled,
|
||||
git_sha: self.config.git_sha.clone(),
|
||||
build_time: self.config.build_time.clone(),
|
||||
deployment_mode: self.config.deployment_mode.clone(),
|
||||
|
||||
@@ -122,11 +122,12 @@ impl WorkerSupervisor {
|
||||
health: &self.health,
|
||||
};
|
||||
let deadline = tokio::time::Instant::now() + timeout;
|
||||
for (_, handle) in &mut shutdown.handles {
|
||||
for (worker, handle) in &mut shutdown.handles {
|
||||
if tokio::time::timeout_at(deadline, &mut *handle)
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
tracing::warn!(target: "gateway_shutdown", %worker, "后台任务收尾超时,强制终止");
|
||||
handle.abort();
|
||||
let _ = handle.await;
|
||||
}
|
||||
@@ -459,6 +460,7 @@ async fn acquire_and_run(
|
||||
let acquisition = AssertUnwindSafe(leader_lease.try_acquire(request)).catch_unwind();
|
||||
tokio::pin!(acquisition);
|
||||
let acquisition = tokio::select! {
|
||||
biased;
|
||||
() = cancellation.cancelled() => return ScheduledOutcome::ShuttingDown,
|
||||
acquisition = &mut acquisition => acquisition,
|
||||
};
|
||||
@@ -490,12 +492,13 @@ async fn run_local_cycle(
|
||||
.catch_unwind();
|
||||
tokio::pin!(cycle);
|
||||
tokio::select! {
|
||||
outcome = &mut cycle => task_result(outcome),
|
||||
biased;
|
||||
() = cancellation.cancelled() => {
|
||||
cycle_cancel.cancel();
|
||||
let _ = cycle.await;
|
||||
ScheduledOutcome::ShuttingDown
|
||||
}
|
||||
outcome = &mut cycle => task_result(outcome),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -527,17 +530,21 @@ async fn run_leased_cycle(
|
||||
|
||||
let outcome = loop {
|
||||
tokio::select! {
|
||||
result = &mut cycle => break task_result(result),
|
||||
biased;
|
||||
() = cancellation.cancelled() => {
|
||||
cycle_cancel.cancel();
|
||||
let _ = cycle.await;
|
||||
break ScheduledOutcome::ShuttingDown;
|
||||
}
|
||||
result = &mut cycle => break task_result(result),
|
||||
() = &mut renewal => {
|
||||
let renewed = renew_guard(
|
||||
let Some(renewed) = cancellation.run_until_cancelled(renew_guard(
|
||||
guard.as_mut(),
|
||||
schedule.leader_lease_renewal_interval(),
|
||||
).await;
|
||||
)).await else {
|
||||
// 返回循环首个取消分支,统一等待正在执行的周期收尾
|
||||
continue;
|
||||
};
|
||||
if let Err(error) = renewed {
|
||||
cycle_cancel.cancel();
|
||||
let _ = cycle.await;
|
||||
|
||||
@@ -142,6 +142,8 @@ async fn restart_should_request_process_restart_inside_docker() {
|
||||
config.deployment_mode = "docker".to_owned();
|
||||
let shutdown = CancellationToken::new();
|
||||
let service = ProcessSystemOperations::new(shutdown.clone(), config);
|
||||
assert!(!service.update_status().await.expect("status").need_restart);
|
||||
assert!(service.version().await.expect("version").restart_supported);
|
||||
service
|
||||
.restart(Arc::new(AllowingUpdatePreflight))
|
||||
.await
|
||||
@@ -152,6 +154,48 @@ async fn restart_should_request_process_restart_inside_docker() {
|
||||
.expect("shutdown requested");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn version_should_distinguish_same_version_service_instances() {
|
||||
let fixture = Fixture::new();
|
||||
let config = fixture.config("http://127.0.0.1:1/repos");
|
||||
let service = ProcessSystemOperations::new(CancellationToken::new(), config.clone());
|
||||
let version = service.version().await.expect("version");
|
||||
assert!(!version.instance_id.is_empty());
|
||||
assert_eq!(
|
||||
service
|
||||
.clone()
|
||||
.version()
|
||||
.await
|
||||
.expect("same instance")
|
||||
.instance_id,
|
||||
version.instance_id
|
||||
);
|
||||
|
||||
let replacement = ProcessSystemOperations::new(CancellationToken::new(), config);
|
||||
let restarted = replacement.version().await.expect("new instance");
|
||||
assert_eq!(restarted.version, version.version);
|
||||
assert_ne!(restarted.instance_id, version.instance_id);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn version_should_report_restart_disabled_when_host_rejects_it() {
|
||||
let fixture = Fixture::new();
|
||||
let mut config = fixture.config("http://127.0.0.1:1/repos");
|
||||
config.self_restart_enabled = false;
|
||||
let shutdown = CancellationToken::new();
|
||||
let service = ProcessSystemOperations::new(shutdown.clone(), config);
|
||||
assert!(!service.version().await.expect("version").restart_supported);
|
||||
assert_eq!(
|
||||
service
|
||||
.restart(Arc::new(AllowingUpdatePreflight))
|
||||
.await
|
||||
.expect_err("restart disabled")
|
||||
.kind(),
|
||||
SystemOperationErrorKind::Conflict
|
||||
);
|
||||
assert!(!shutdown.is_cancelled());
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn accepted_restart_excludes_system_operations_until_service_release() {
|
||||
let fixture = Fixture::new();
|
||||
|
||||
@@ -219,6 +219,7 @@ enum LeaseStep {
|
||||
enum RenewStep {
|
||||
Success,
|
||||
Error,
|
||||
Pending,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
@@ -268,11 +269,12 @@ impl WorkerLeaderLeaseGuard for FakeLeaseGuard {
|
||||
fn renew(&mut self) -> BoxFuture<'_, Result<(), WorkerLeaseError>> {
|
||||
Box::pin(async move {
|
||||
lock_unpoisoned(&self.renewals).push(self.worker.clone());
|
||||
match lock_unpoisoned(&self.renew_scripts)
|
||||
let step = lock_unpoisoned(&self.renew_scripts)
|
||||
.get_mut(&self.worker)
|
||||
.and_then(VecDeque::pop_front)
|
||||
.unwrap_or(RenewStep::Success)
|
||||
{
|
||||
.unwrap_or(RenewStep::Success);
|
||||
match step {
|
||||
RenewStep::Pending => pending().await,
|
||||
RenewStep::Success => Ok(()),
|
||||
RenewStep::Error => Err(WorkerLeaseError::safe("expected renewal failure")),
|
||||
}
|
||||
@@ -510,6 +512,31 @@ async fn long_cycle_renews_leader_lease_before_ttl() {
|
||||
supervisor.shutdown(Duration::from_secs(1)).await;
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn shutdown_signals_the_cycle_while_lease_renewal_is_pending() {
|
||||
let leases = Arc::new(FakeLeasePort::default());
|
||||
leases.renew_script(target_worker(), [RenewStep::Pending]);
|
||||
let task = CancellationTask {
|
||||
entered: Arc::new(AtomicUsize::new(0)),
|
||||
observed: Arc::new(AtomicUsize::new(0)),
|
||||
};
|
||||
let supervisor = supervisor();
|
||||
supervisor
|
||||
.start(
|
||||
target_plan(task.clone(), renewal_schedule()),
|
||||
leases.clone(),
|
||||
Arc::new(RecordingDiagnostics::default()),
|
||||
)
|
||||
.unwrap();
|
||||
yield_until(|| task.entered.load(Ordering::SeqCst) != 0).await;
|
||||
tokio::time::advance(Duration::from_millis(10)).await;
|
||||
yield_until(|| leases.renewal_count(&target_worker()) == 1).await;
|
||||
// 关闭预算短于续租超时,协作取消仍应完成
|
||||
supervisor.shutdown(Duration::from_millis(1)).await;
|
||||
assert_eq!(task.observed.load(Ordering::SeqCst), 1);
|
||||
assert!(lock_unpoisoned(&leases.active_guards).is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn renewal_failure_cancels_old_cycle_before_another_leader_cycle_starts() {
|
||||
let task = ConcurrentCycleTask {
|
||||
|
||||
@@ -248,21 +248,21 @@ impl Execution {
|
||||
request_body_limit,
|
||||
)
|
||||
.map_err(|error| fault_error(error, UpstreamSendState::NotSent))?;
|
||||
let upstream_model = invocation.metadata.upstream_model().ok_or_else(invalid)?;
|
||||
let request = UpstreamAdapterRequest {
|
||||
adapter_id: declaration.id.clone(),
|
||||
provider: declaration.provider,
|
||||
upstream_model: invocation
|
||||
.metadata
|
||||
.upstream_model()
|
||||
.ok_or_else(invalid)?
|
||||
.as_str()
|
||||
.to_owned(),
|
||||
upstream_model: upstream_model.as_str().to_owned(),
|
||||
client_key_id: invocation.context.client_api_key_ref().as_str().to_owned(),
|
||||
account_id: invocation.account.account_id().as_str().to_owned(),
|
||||
credential_revision: invocation.account.credential_revision().get(),
|
||||
protocol: invocation.operation.protocol().to_owned(),
|
||||
client_transport: invocation.context.client_transport().as_str().to_owned(),
|
||||
fast_mode: invocation.context.fast_mode().as_str().to_owned(),
|
||||
fast_mode: invocation
|
||||
.context
|
||||
.fast_mode_for_account(invocation.account.account_id(), upstream_model.as_str())
|
||||
.as_str()
|
||||
.to_owned(),
|
||||
request_elapsed_ms: u64::try_from(
|
||||
invocation.context.timing_started_at().elapsed().as_millis(),
|
||||
)
|
||||
|
||||
@@ -7,13 +7,16 @@ use serde_json::{Value, json};
|
||||
#[tokio::test]
|
||||
async fn middleware_preserves_fast_modes_and_sources() {
|
||||
for (mode, expected) in [
|
||||
(FastMode::Default, FastMode::Default),
|
||||
(FastMode::Enabled, FastMode::Enabled),
|
||||
(FastMode::Disabled, FastMode::Disabled),
|
||||
(FastMode::Enabled, FastMode::Disabled),
|
||||
(FastMode::Ultrafast, FastMode::Ultrafast),
|
||||
(FastMode::Enabled, FastMode::Ultrafast),
|
||||
(FastMode::Disabled, FastMode::Default),
|
||||
(None, None),
|
||||
(None, Some(FastMode::Default)),
|
||||
(Some(FastMode::Default), Some(FastMode::Default)),
|
||||
(Some(FastMode::Enabled), Some(FastMode::Enabled)),
|
||||
(Some(FastMode::Disabled), Some(FastMode::Disabled)),
|
||||
(Some(FastMode::Enabled), Some(FastMode::Disabled)),
|
||||
(Some(FastMode::Ultrafast), Some(FastMode::Ultrafast)),
|
||||
(Some(FastMode::Enabled), Some(FastMode::Ultrafast)),
|
||||
(Some(FastMode::Disabled), Some(FastMode::Default)),
|
||||
(Some(FastMode::Enabled), None),
|
||||
] {
|
||||
let snapshot = gateway_core::routing::RuntimeSnapshot::new(
|
||||
ConfigRevision::new(1).unwrap(),
|
||||
@@ -43,8 +46,7 @@ async fn middleware_preserves_fast_modes_and_sources() {
|
||||
let settings = settings.replace_execution(&seed, "seed").unwrap();
|
||||
let wire = serde_json::to_value(&seed).unwrap();
|
||||
let mut updated = wire.clone();
|
||||
updated["fast_mode"] = json!(expected.as_str());
|
||||
updated["timeout_ms"] = json!(90_000);
|
||||
updated["fast_mode"] = json!(expected);
|
||||
let contribution = crate::support::contribution(
|
||||
Capability::Middleware,
|
||||
vec![Stage::Request],
|
||||
@@ -61,8 +63,8 @@ async fn middleware_preserves_fast_modes_and_sources() {
|
||||
id: "fast-settings",
|
||||
configuration: json!({
|
||||
"mode":"settings", "expected_settings":wire, "settings":updated,
|
||||
"expected_fast_source": if mode == FastMode::Default { Value::Null } else {
|
||||
json!({"instance_id":"seed", "order":1, "value":mode.as_str()})
|
||||
"expected_fast_source": if mode.is_none() { Value::Null } else {
|
||||
json!({"instance_id":"seed", "order":1, "value":mode})
|
||||
},
|
||||
}),
|
||||
bindings: vec![binding(
|
||||
@@ -102,11 +104,11 @@ async fn middleware_preserves_fast_modes_and_sources() {
|
||||
assert_eq!(settings.execution_values().unwrap().fast_mode, expected);
|
||||
assert_eq!(
|
||||
settings.execution_values().unwrap().timeout_ms,
|
||||
Some(90_000)
|
||||
Some(60_000)
|
||||
);
|
||||
let sources = settings.inspect();
|
||||
let fast_source = &sources["execution"]["fast_mode"];
|
||||
if mode == FastMode::Default && expected == FastMode::Default {
|
||||
if mode.is_none() && expected.is_none() {
|
||||
assert!(fast_source.is_null());
|
||||
} else {
|
||||
assert_eq!(
|
||||
@@ -117,12 +119,9 @@ async fn middleware_preserves_fast_modes_and_sources() {
|
||||
"fast-settings"
|
||||
}
|
||||
);
|
||||
assert_eq!(fast_source["value"], expected.as_str());
|
||||
assert_eq!(fast_source["value"], json!(expected));
|
||||
}
|
||||
assert_eq!(
|
||||
sources["execution"]["timeout_ms"]["instance_id"],
|
||||
"fast-settings"
|
||||
);
|
||||
assert!(sources["execution"]["timeout_ms"].is_null());
|
||||
next.run(request).await
|
||||
})
|
||||
}),
|
||||
|
||||
@@ -1277,7 +1277,7 @@ async fn real_request_plugins_rewrite_settings_in_onion_order() {
|
||||
let baseline = ExecutionSettings {
|
||||
runtime: SettingsValues::new(3, "smart", BTreeMap::new(), None, None)
|
||||
.with_request_profiles(profiles("key-default")),
|
||||
fast_mode: FastMode::Disabled,
|
||||
fast_mode: Some(FastMode::Disabled),
|
||||
client_limits: RateLimits {
|
||||
max_concurrency: 2,
|
||||
requests_per_minute: 10,
|
||||
@@ -1314,7 +1314,7 @@ async fn real_request_plugins_rewrite_settings_in_onion_order() {
|
||||
gateway_core::routing::ClientRoutingScope::all_accounts(),
|
||||
)
|
||||
.with_request_profiles(profiles("key-default"))
|
||||
.with_fast_mode(baseline.fast_mode),
|
||||
.with_fast_mode_override(baseline.fast_mode),
|
||||
),
|
||||
true,
|
||||
baseline.client_limits,
|
||||
|
||||
@@ -179,7 +179,6 @@ fn context_with_body_limit(
|
||||
ClientApiKeyId::new(key).unwrap(),
|
||||
)
|
||||
.with_upstream_adapters(runtime.execution_registry().upstream_adapters(generation))
|
||||
.with_fast_mode(mode)
|
||||
.with_request_body_limit(bytes),
|
||||
NonZeroU32::new(1).unwrap(),
|
||||
SystemTime::now() + Duration::from_secs(5),
|
||||
@@ -187,7 +186,13 @@ fn context_with_body_limit(
|
||||
gateway_core::account::RotationStrategy::RoundRobin,
|
||||
std::num::NonZeroU32::new(1).unwrap(),
|
||||
),
|
||||
AccountAttemptContext::new(Default::default(), None, None),
|
||||
AccountAttemptContext::new(Default::default(), None, None).with_account_scope(Arc::new(
|
||||
gateway_core::routing::FrozenAccountScope::new(
|
||||
Arc::default(),
|
||||
gateway_core::routing::ClientRoutingScope::all_accounts(),
|
||||
)
|
||||
.with_fast_mode_override(Some(mode)),
|
||||
)),
|
||||
None,
|
||||
CancellationToken::new(),
|
||||
)
|
||||
|
||||
@@ -588,7 +588,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
);
|
||||
if let Some(expected) = configuration.get("expected_fast_source") {
|
||||
let sources = &call.request.head.settings_sources["execution"];
|
||||
assert_eq!(sources["input"]["fast_mode"], "default");
|
||||
assert!(sources["input"]["fast_mode"].is_null());
|
||||
assert_eq!(&sources["fast_mode"], expected);
|
||||
}
|
||||
if let Some(settings) = configuration.get("settings") {
|
||||
|
||||
@@ -489,7 +489,7 @@ let plugin = PluginBuilder::from_json(manifest_json)?
|
||||
|
||||
#### 模型请求与 attempt
|
||||
|
||||
`RequestCall.request.head` 包含完整 Client Key 与分组归属。request 中间件改写正文后,OpenAI 在进入 attempt 前应用宿主 Fast 策略;
|
||||
`RequestCall.request.head` 包含完整 Client Key 与分组归属。request 中间件改写正文后,OpenAI 按选中账号和上游模型解析宿主 Fast 策略,在进入 attempt 前应用;
|
||||
attempt 中间件在此基线上继续改写,终端不再应用 Fast 策略。
|
||||
request 与 attempt 阶段通过 `append_header` 添加的请求头会进入上游请求,不适合存放插件内部标记或仅供下游读取的信息。
|
||||
OpenAI 与 xAI 的上游 headers 先由账号和画像生成,插件同名字段覆盖基线,同名多值按插件顺序保留;不存在按认证、Cookie 或会话名称划分的保护列表。
|
||||
@@ -498,7 +498,8 @@ CPR 中间件添加的 HTTP 扩展头在发往 Antigravity 时经过该 Provider
|
||||
实际账号租约、凭据版本与计费归属仍记录真实选中事实,不随插件修改 header 名称而伪造
|
||||
|
||||
request 阶段 `request.head.settings` 是本次调用的有效设置对象,包含 `runtime`、`fast_mode`、`client_limits` 和 `timeout_ms`。
|
||||
`fast_mode` 使用 `default`、`enabled`、`ultrafast`、`disabled` 四个值,具体档位语义见[账号分组](../../../../../docs/api.md#6-账号分组)。
|
||||
`fast_mode` 为 `null` 时按选中账号的有效分组解析;显式 `default` 表示跟随客户端,`enabled`、`ultrafast`、`disabled` 覆盖分组策略,具体档位语义见[账号分组](../../../../../docs/api.md#6-账号分组)。
|
||||
保留该字段不建立新覆盖,改写为 `null` 恢复按分组解析;其他改写形成当前 Key 的显式覆盖,优先于分组策略。attempt 中间件仍可直接改写正文档位
|
||||
`runtime` 使用宿主快照的设置字段,画像已合并 Client Key 设置;可以修改映射、画像、调度、位置及计价等执行参数。
|
||||
SDK 仅在对象改变时提交完整替换,`false`、`0`、空映射和合同允许的 `null` 不表示跳过;不做隐式深合并。
|
||||
线协议省略 `next.settings` 才表示保留;显式 `null` 仍按完整替换校验,因不符合设置对象合同而拒绝。
|
||||
|
||||
@@ -41,7 +41,7 @@ Provider、业务协议和传输名称不能写入宿主兼容清单的 capabili
|
||||
`TypedCall<UpstreamAdapterRequest>` 包含只读的 Key、账号、凭据版本、模型、协议、Header 和宿主续接投影;
|
||||
原始请求正文位于 `call.payload`,原始账号凭据不进入插件输入。宿主首次消费冷流才调用插件
|
||||
|
||||
`fast_mode` 是本次模型执行的有效设置,取值为 `default`、`enabled`、`ultrafast` 或 `disabled`。OpenAI 在 attempt 中间件之前将 Fast 设置应用到正文基线,
|
||||
`fast_mode` 是按选中账号及上游模型解析后的有效策略,取值为 `default`、`enabled`、`ultrafast` 或 `disabled`,请求设置的显式覆盖优先于分组策略。OpenAI 在 attempt 中间件之前将 Fast 设置应用到正文基线,
|
||||
适配器收到经过 attempt 中间件处理的正文;attempt 中间件显式改写档位后,宿主不会在发送前再次应用 Fast 策略。
|
||||
其他请求设置与 Key 作用域的覆盖规则见[模型请求与 attempt](capabilities.md#模型请求与-attempt)
|
||||
|
||||
|
||||
@@ -3,7 +3,10 @@
|
||||
use crate::chat_completions::{
|
||||
ChatError, custom_tool_schema,
|
||||
error::{invalid, unsupported},
|
||||
request::string,
|
||||
request::{
|
||||
block_text, empty_history_content, empty_history_part, function_parameters,
|
||||
reasoning_effort, response_format, stop_sequences, string,
|
||||
},
|
||||
validate_request,
|
||||
};
|
||||
use serde_json::{Map, Value, json};
|
||||
@@ -13,7 +16,7 @@ pub fn convert_request(chat: &Map<String, Value>) -> Result<Map<String, Value>,
|
||||
validate_request(chat)?;
|
||||
let mut system = Vec::new();
|
||||
if let Some(instructions) = chat.get("instructions").filter(|v| !v.is_null()) {
|
||||
system.extend(parts(instructions, "instructions", true)?);
|
||||
system.extend(parts(instructions, "instructions", "system")?);
|
||||
}
|
||||
let mut contents = Vec::new();
|
||||
let mut calls = BTreeMap::new();
|
||||
@@ -30,7 +33,7 @@ pub fn convert_request(chat: &Map<String, Value>) -> Result<Map<String, Value>,
|
||||
system.extend(parts(
|
||||
&message["content"],
|
||||
&format!("{path}.content"),
|
||||
true,
|
||||
role,
|
||||
)?);
|
||||
continue;
|
||||
}
|
||||
@@ -48,7 +51,7 @@ pub fn convert_request(chat: &Map<String, Value>) -> Result<Map<String, Value>,
|
||||
}
|
||||
let mut text = Vec::new();
|
||||
let mut media = Vec::new();
|
||||
for part in parts(&message["content"], &format!("{path}.content"), false)? {
|
||||
for part in parts(&message["content"], &format!("{path}.content"), role)? {
|
||||
if let Some(value) = part.get("text").and_then(Value::as_str) {
|
||||
text.push(value.to_owned());
|
||||
} else {
|
||||
@@ -61,12 +64,12 @@ pub fn convert_request(chat: &Map<String, Value>) -> Result<Map<String, Value>,
|
||||
}
|
||||
vec![response]
|
||||
} else {
|
||||
let mut content = if message["content"].is_null() {
|
||||
Vec::new()
|
||||
} else {
|
||||
parts(&message["content"], &format!("{path}.content"), false)?
|
||||
};
|
||||
if let Some(refusal) = message.get("refusal").and_then(Value::as_str) {
|
||||
let mut content = parts(&message["content"], &format!("{path}.content"), role)?;
|
||||
if let Some(refusal) = message
|
||||
.get("refusal")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|v| !v.is_empty())
|
||||
{
|
||||
content.push(json!({"text":refusal}));
|
||||
}
|
||||
for (call_index, call) in message
|
||||
@@ -105,6 +108,9 @@ pub fn convert_request(chat: &Map<String, Value>) -> Result<Map<String, Value>,
|
||||
}
|
||||
content
|
||||
};
|
||||
if role == "assistant" && content.is_empty() {
|
||||
continue;
|
||||
}
|
||||
append(
|
||||
&mut contents,
|
||||
if role == "assistant" { "model" } else { "user" },
|
||||
@@ -134,11 +140,10 @@ pub fn convert_request(chat: &Map<String, Value>) -> Result<Map<String, Value>,
|
||||
generation.insert(to.into(), value.clone());
|
||||
}
|
||||
}
|
||||
if let Some(effort) = chat
|
||||
.get("reasoning_effort")
|
||||
.or_else(|| chat.get("reasoning").and_then(|v| v.get("effort")))
|
||||
.filter(|v| !v.is_null())
|
||||
{
|
||||
if let Some(stops) = stop_sequences(chat)? {
|
||||
generation.insert("stopSequences".into(), stops);
|
||||
}
|
||||
if let Some(effort) = reasoning_effort(chat) {
|
||||
let budget: i64 = match effort.as_str() {
|
||||
Some("none") => 0,
|
||||
Some("minimal" | "low") => 1024,
|
||||
@@ -158,11 +163,7 @@ pub fn convert_request(chat: &Map<String, Value>) -> Result<Map<String, Value>,
|
||||
},
|
||||
);
|
||||
}
|
||||
if let Some(format) = chat
|
||||
.get("response_format")
|
||||
.or_else(|| chat.get("text").and_then(|v| v.get("format")))
|
||||
.filter(|v| !v.is_null())
|
||||
{
|
||||
if let Some(format) = response_format(chat) {
|
||||
match format["type"].as_str() {
|
||||
Some("json_schema") => {
|
||||
generation.insert("responseMimeType".into(), json!("application/json"));
|
||||
@@ -205,7 +206,11 @@ fn append(contents: &mut Vec<Value>, role: &str, parts: Vec<Value>) {
|
||||
}
|
||||
}
|
||||
|
||||
fn parts(value: &Value, path: &str, system: bool) -> Result<Vec<Value>, ChatError> {
|
||||
fn parts(value: &Value, path: &str, role: &str) -> Result<Vec<Value>, ChatError> {
|
||||
if empty_history_content(role, value) {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let system = matches!(role, "system" | "developer");
|
||||
if let Some(text) = value.as_str() {
|
||||
return Ok(vec![json!({"text":text})]);
|
||||
}
|
||||
@@ -214,12 +219,13 @@ fn parts(value: &Value, path: &str, system: bool) -> Result<Vec<Value>, ChatErro
|
||||
.ok_or_else(|| invalid(path))?
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, part)| !empty_history_part(role, part))
|
||||
.map(|(index, part)| {
|
||||
let path = format!("{path}[{index}]");
|
||||
let kind = string(part.get("type"), &format!("{path}.type"), false)?;
|
||||
match kind {
|
||||
"text" | "input_text" | "output_text" => {
|
||||
Ok(json!({"text":string(part.get("text"), &format!("{path}.text"), true)?}))
|
||||
Ok(json!({"text":block_text(part.get("text"), &path)?}))
|
||||
}
|
||||
"refusal" if !system => Ok(
|
||||
json!({"text":string(part.get("refusal"), &format!("{path}.refusal"), true)?}),
|
||||
@@ -314,16 +320,10 @@ fn tools(chat: &Map<String, Value>, result: &mut Map<String, Value>) -> Result<(
|
||||
let parameters = if kind == "custom" {
|
||||
custom_tool_schema(definition.get("format"), &format!("{path}.custom.format"))?
|
||||
} else {
|
||||
definition
|
||||
.get("parameters")
|
||||
.cloned()
|
||||
.unwrap_or_else(|| json!({"type":"object","properties":{}}))
|
||||
function_parameters(definition, &path)?
|
||||
};
|
||||
if !parameters.is_object() {
|
||||
return Err(invalid(&format!("{path}.function.parameters")));
|
||||
}
|
||||
let mut declaration = json!({"name":name,"parametersJsonSchema":parameters});
|
||||
if let Some(value) = definition.get("description") {
|
||||
if let Some(value) = definition.get("description").filter(|v| !v.is_null()) {
|
||||
declaration["description"] = value.clone();
|
||||
}
|
||||
declarations.push(declaration);
|
||||
|
||||
@@ -4,7 +4,10 @@ use crate::anthropic::MessagesModelCapabilities;
|
||||
use crate::chat_completions::{
|
||||
ChatError, custom_tool_schema,
|
||||
error::{invalid, unsupported},
|
||||
request::string,
|
||||
request::{
|
||||
block_text, empty_history_content, empty_history_part, function_parameters,
|
||||
reasoning_effort, response_format, stop_sequences, string,
|
||||
},
|
||||
validate_request,
|
||||
};
|
||||
use serde_json::{Map, Value, json};
|
||||
@@ -37,6 +40,9 @@ pub fn convert_request(
|
||||
result.insert(field.into(), value.clone());
|
||||
}
|
||||
}
|
||||
if let Some(stops) = stop_sequences(chat)? {
|
||||
result.insert("stop_sequences".into(), stops);
|
||||
}
|
||||
if let Some(tier) = chat.get("service_tier").and_then(Value::as_str) {
|
||||
match tier {
|
||||
"priority" => {
|
||||
@@ -53,7 +59,7 @@ pub fn convert_request(
|
||||
}
|
||||
let mut system = Vec::new();
|
||||
if let Some(instructions) = chat.get("instructions").filter(|v| !v.is_null()) {
|
||||
system.extend(content(instructions, "instructions", true)?);
|
||||
system.extend(content(instructions, "instructions", "system")?);
|
||||
}
|
||||
let mut messages = Vec::new();
|
||||
let mut calls = BTreeMap::new();
|
||||
@@ -70,7 +76,7 @@ pub fn convert_request(
|
||||
system.extend(content(
|
||||
&message["content"],
|
||||
&format!("{path}.content"),
|
||||
true,
|
||||
role,
|
||||
)?);
|
||||
continue;
|
||||
}
|
||||
@@ -84,15 +90,15 @@ pub fn convert_request(
|
||||
return Err(invalid(&format!("{path}.tool_call_id")));
|
||||
}
|
||||
vec![
|
||||
json!({"type":"tool_result","tool_use_id":id,"content":content(&message["content"], &format!("{path}.content"), false)?}),
|
||||
json!({"type":"tool_result","tool_use_id":id,"content":content(&message["content"], &format!("{path}.content"), role)?}),
|
||||
]
|
||||
} else {
|
||||
let mut blocks = if message["content"].is_null() {
|
||||
Vec::new()
|
||||
} else {
|
||||
content(&message["content"], &format!("{path}.content"), false)?
|
||||
};
|
||||
if let Some(refusal) = message.get("refusal").and_then(Value::as_str) {
|
||||
let mut blocks = content(&message["content"], &format!("{path}.content"), role)?;
|
||||
if let Some(refusal) = message
|
||||
.get("refusal")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|v| !v.is_empty())
|
||||
{
|
||||
blocks.push(json!({"type":"text","text":refusal}));
|
||||
}
|
||||
for (call_index, call) in message
|
||||
@@ -130,6 +136,9 @@ pub fn convert_request(
|
||||
}
|
||||
blocks
|
||||
};
|
||||
if role == "assistant" && blocks.is_empty() {
|
||||
continue;
|
||||
}
|
||||
append_message(
|
||||
&mut messages,
|
||||
if role == "assistant" {
|
||||
@@ -148,10 +157,7 @@ pub fn convert_request(
|
||||
}
|
||||
result.insert("messages".into(), messages.into());
|
||||
tools(chat, &mut result, capabilities)?;
|
||||
let format = chat
|
||||
.get("response_format")
|
||||
.or_else(|| chat.get("text").and_then(|v| v.get("format")));
|
||||
if let Some(format) = format.filter(|v| !v.is_null()) {
|
||||
if let Some(format) = response_format(chat) {
|
||||
match format["type"].as_str() {
|
||||
Some("json_schema") => {
|
||||
let schema = format
|
||||
@@ -190,7 +196,11 @@ fn append_message(messages: &mut Vec<Value>, role: &str, blocks: Vec<Value>) {
|
||||
}
|
||||
}
|
||||
|
||||
fn content(value: &Value, path: &str, system: bool) -> Result<Vec<Value>, ChatError> {
|
||||
fn content(value: &Value, path: &str, role: &str) -> Result<Vec<Value>, ChatError> {
|
||||
if empty_history_content(role, value) {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let system = matches!(role, "system" | "developer");
|
||||
if let Some(text) = value.as_str() {
|
||||
return Ok(vec![json!({"type":"text","text":text})]);
|
||||
}
|
||||
@@ -200,12 +210,13 @@ fn content(value: &Value, path: &str, system: bool) -> Result<Vec<Value>, ChatEr
|
||||
.ok_or_else(|| invalid(path))?
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, part)| !empty_history_part(role, part))
|
||||
{
|
||||
let path = format!("{path}[{index}]");
|
||||
let kind = string(part.get("type"), &format!("{path}.type"), false)?;
|
||||
let block = match kind {
|
||||
"text" | "input_text" | "output_text" => {
|
||||
json!({"type":"text","text":string(part.get("text"), &format!("{path}.text"), true)?})
|
||||
json!({"type":"text","text":block_text(part.get("text"), &path)?})
|
||||
}
|
||||
"refusal" if !system => {
|
||||
json!({"type":"text","text":string(part.get("refusal"), &format!("{path}.refusal"), true)?})
|
||||
@@ -295,17 +306,11 @@ fn tools(
|
||||
let schema = if kind == "custom" {
|
||||
custom_tool_schema(declaration.get("format"), &format!("{path}.custom.format"))?
|
||||
} else {
|
||||
declaration
|
||||
.get("parameters")
|
||||
.cloned()
|
||||
.unwrap_or_else(|| json!({"type":"object","properties":{}}))
|
||||
function_parameters(declaration, &path)?
|
||||
};
|
||||
if !schema.is_object() {
|
||||
return Err(invalid(&format!("{path}.function.parameters")));
|
||||
}
|
||||
let mut target = json!({"name":name,"input_schema":schema});
|
||||
for field in ["description", "strict", "cache_control"] {
|
||||
if let Some(value) = declaration.get(field) {
|
||||
if let Some(value) = declaration.get(field).filter(|v| !v.is_null()) {
|
||||
target[field] = value.clone();
|
||||
}
|
||||
}
|
||||
@@ -393,11 +398,7 @@ fn reasoning(
|
||||
capabilities: &MessagesModelCapabilities,
|
||||
max_tokens: u64,
|
||||
) -> Result<(), ChatError> {
|
||||
let Some(effort) = chat
|
||||
.get("reasoning_effort")
|
||||
.or_else(|| chat.get("reasoning").and_then(|v| v.get("effort")))
|
||||
.filter(|v| !v.is_null())
|
||||
else {
|
||||
let Some(effort) = reasoning_effort(chat) else {
|
||||
return Ok(());
|
||||
};
|
||||
let effort = effort.as_str().ok_or_else(|| invalid("reasoning_effort"))?;
|
||||
|
||||
@@ -30,11 +30,7 @@ pub fn validate_request(body: &Map<String, Value>) -> Result<(), ChatError> {
|
||||
field: "messages".into(),
|
||||
expected: "an array",
|
||||
})?;
|
||||
if messages.is_empty() {
|
||||
return Err(ChatError::EmptyField {
|
||||
field: "messages".into(),
|
||||
});
|
||||
}
|
||||
let mut has_message = false;
|
||||
for (index, message) in messages.iter().enumerate() {
|
||||
let path = format!("messages[{index}]");
|
||||
let message = message.as_object().ok_or_else(|| invalid(&path))?;
|
||||
@@ -42,43 +38,51 @@ pub fn validate_request(body: &Map<String, Value>) -> Result<(), ChatError> {
|
||||
if !matches!(role, "system" | "developer" | "user" | "assistant" | "tool") {
|
||||
return Err(unsupported(&format!("{path}.role")));
|
||||
}
|
||||
for (field, allowed) in [
|
||||
("tool_calls", "assistant"),
|
||||
("refusal", "assistant"),
|
||||
("tool_call_id", "tool"),
|
||||
] {
|
||||
if role != allowed && message.get(field).is_some_and(|v| !v.is_null()) {
|
||||
return Err(invalid(&format!("{path}.{field}")));
|
||||
let calls = match message.get("tool_calls") {
|
||||
None | Some(Value::Null) => &[][..],
|
||||
Some(Value::Array(calls)) => calls.as_slice(),
|
||||
_ => return Err(invalid(&format!("{path}.tool_calls"))),
|
||||
};
|
||||
if role != "assistant" && !calls.is_empty() {
|
||||
return Err(invalid(&format!("{path}.tool_calls")));
|
||||
}
|
||||
let refusal = message.get("refusal").filter(|v| !v.is_null() && *v != "");
|
||||
if let Some(value) = refusal {
|
||||
if role != "assistant" {
|
||||
return Err(invalid(&format!("{path}.refusal")));
|
||||
}
|
||||
string(Some(value), &format!("{path}.refusal"), true)?;
|
||||
}
|
||||
for field in ["function_call", "audio"] {
|
||||
if message.get(field).is_some_and(|v| !v.is_null()) {
|
||||
return Err(unsupported(&format!("{path}.{field}")));
|
||||
}
|
||||
}
|
||||
for field in ["name", "refusal"] {
|
||||
if let Some(value) = message.get(field).filter(|v| !v.is_null()) {
|
||||
string(Some(value), &format!("{path}.{field}"), true)?;
|
||||
}
|
||||
}
|
||||
if role == "tool" {
|
||||
string(
|
||||
message.get("tool_call_id"),
|
||||
&format!("{path}.tool_call_id"),
|
||||
false,
|
||||
)?;
|
||||
} else if message
|
||||
.get("tool_call_id")
|
||||
.is_some_and(|v| !v.is_null() && v != "")
|
||||
{
|
||||
return Err(invalid(&format!("{path}.tool_call_id")));
|
||||
}
|
||||
if let Some(content) = message.get("content").filter(|v| !v.is_null()) {
|
||||
let content = message.get("content").unwrap_or(&Value::Null);
|
||||
if !empty_history_content(role, content) {
|
||||
if !content.is_string() && !content.is_array() {
|
||||
return Err(invalid(&format!("{path}.content")));
|
||||
}
|
||||
has_message = true;
|
||||
if let Some(parts) = content.as_array() {
|
||||
for (part_index, part) in parts.iter().enumerate() {
|
||||
let part_path = format!("{path}.content[{part_index}]");
|
||||
let kind = string(part.get("type"), &format!("{part_path}.type"), false)?;
|
||||
match kind {
|
||||
"text" | "input_text" | "output_text" => {
|
||||
string(part.get("text"), &format!("{part_path}.text"), true)?;
|
||||
block_text(part.get("text"), &part_path)?;
|
||||
}
|
||||
"image_url" | "file" | "input_audio" | "input_image" | "input_file"
|
||||
if matches!(role, "user" | "tool") => {}
|
||||
@@ -89,45 +93,37 @@ pub fn validate_request(body: &Map<String, Value>) -> Result<(), ChatError> {
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if role != "assistant"
|
||||
|| (!message
|
||||
.get("tool_calls")
|
||||
.is_some_and(|v| v.as_array().is_some_and(|v| !v.is_empty()))
|
||||
&& !message.get("refusal").is_some_and(Value::is_string))
|
||||
{
|
||||
return Err(invalid(&format!("{path}.content")));
|
||||
}
|
||||
if let Some(calls) = message.get("tool_calls").filter(|v| !v.is_null()) {
|
||||
for (call_index, call) in calls
|
||||
.as_array()
|
||||
.ok_or_else(|| invalid(&format!("{path}.tool_calls")))?
|
||||
.iter()
|
||||
.enumerate()
|
||||
{
|
||||
let call_path = format!("{path}.tool_calls[{call_index}]");
|
||||
string(call.get("id"), &format!("{call_path}.id"), false)?;
|
||||
let kind = string(call.get("type"), &format!("{call_path}.type"), false)?;
|
||||
if !matches!(kind, "function" | "custom") {
|
||||
return Err(unsupported(&format!("{call_path}.type")));
|
||||
}
|
||||
string(
|
||||
call.get(kind).and_then(|v| v.get("name")),
|
||||
&format!("{call_path}.{kind}.name"),
|
||||
false,
|
||||
)?;
|
||||
let data_field = if kind == "function" {
|
||||
"arguments"
|
||||
} else {
|
||||
"input"
|
||||
};
|
||||
string(
|
||||
call.get(kind).and_then(|v| v.get(data_field)),
|
||||
&format!("{call_path}.{kind}.{data_field}"),
|
||||
true,
|
||||
)?;
|
||||
has_message |= refusal.is_some() || !calls.is_empty();
|
||||
for (call_index, call) in calls.iter().enumerate() {
|
||||
let call_path = format!("{path}.tool_calls[{call_index}]");
|
||||
string(call.get("id"), &format!("{call_path}.id"), false)?;
|
||||
let kind = string(call.get("type"), &format!("{call_path}.type"), false)?;
|
||||
if !matches!(kind, "function" | "custom") {
|
||||
return Err(unsupported(&format!("{call_path}.type")));
|
||||
}
|
||||
string(
|
||||
call.get(kind).and_then(|v| v.get("name")),
|
||||
&format!("{call_path}.{kind}.name"),
|
||||
false,
|
||||
)?;
|
||||
let data_field = if kind == "function" {
|
||||
"arguments"
|
||||
} else {
|
||||
"input"
|
||||
};
|
||||
string(
|
||||
call.get(kind).and_then(|v| v.get(data_field)),
|
||||
&format!("{call_path}.{kind}.{data_field}"),
|
||||
true,
|
||||
)?;
|
||||
}
|
||||
}
|
||||
if !has_message {
|
||||
return Err(ChatError::EmptyField {
|
||||
field: "messages".into(),
|
||||
});
|
||||
}
|
||||
for (field, value) in body.iter().filter(|(_, v)| !v.is_null()) {
|
||||
let valid = match field.as_str() {
|
||||
"n" => value.as_u64() == Some(1),
|
||||
@@ -150,7 +146,7 @@ pub fn validate_request(body: &Map<String, Value>) -> Result<(), ChatError> {
|
||||
}
|
||||
}
|
||||
if let Some(options) = body.get("stream_options").filter(|v| !v.is_null()) {
|
||||
if body.get("stream") != Some(&Value::Bool(true)) || !options.is_object() {
|
||||
if !options.is_object() {
|
||||
return Err(invalid("stream_options"));
|
||||
}
|
||||
for field in ["include_usage", "include_obfuscation"] {
|
||||
@@ -161,13 +157,99 @@ pub fn validate_request(body: &Map<String, Value>) -> Result<(), ChatError> {
|
||||
return Err(invalid(&format!("stream_options.{field}")));
|
||||
}
|
||||
}
|
||||
if options.get("include_obfuscation") == Some(&Value::Bool(true)) {
|
||||
if body.get("stream") == Some(&Value::Bool(true))
|
||||
&& options.get("include_obfuscation") == Some(&Value::Bool(true))
|
||||
{
|
||||
return Err(unsupported("stream_options.include_obfuscation"));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// 用户输入和工具结果保留原值,空指令或 assistant 正文不生成上游内容块
|
||||
pub(super) fn empty_history_content(role: &str, content: &Value) -> bool {
|
||||
can_omit_empty_text(role)
|
||||
&& (content.is_null()
|
||||
|| content == ""
|
||||
|| content
|
||||
.as_array()
|
||||
.is_some_and(|parts| parts.iter().all(plain_empty_text)))
|
||||
}
|
||||
|
||||
fn can_omit_empty_text(role: &str) -> bool {
|
||||
matches!(role, "system" | "developer" | "assistant")
|
||||
}
|
||||
|
||||
fn plain_empty_text(part: &Value) -> bool {
|
||||
// 只移除纯文本占位,带缓存断点等附加字段的块交给目标转换器
|
||||
part.get("text")
|
||||
.is_some_and(|text| text.is_null() || text == "")
|
||||
&& matches!(
|
||||
part.get("type").and_then(Value::as_str),
|
||||
Some("text" | "input_text" | "output_text")
|
||||
)
|
||||
&& part.as_object().is_some_and(|fields| {
|
||||
fields
|
||||
.iter()
|
||||
.all(|(key, value)| matches!(key.as_str(), "type" | "text") || value.is_null())
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn empty_history_part(role: &str, part: &Value) -> bool {
|
||||
can_omit_empty_text(role) && plain_empty_text(part)
|
||||
}
|
||||
|
||||
// 部分 Chat 客户端用显式 null 表示空文本,缺少 text 或其他类型仍按原字段报错
|
||||
pub(super) fn block_text<'a>(
|
||||
value: Option<&'a Value>,
|
||||
part_path: &str,
|
||||
) -> Result<&'a str, ChatError> {
|
||||
match value {
|
||||
Some(Value::Null) => Ok(""),
|
||||
value => string(value, &format!("{part_path}.text"), true),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn response_format(body: &Map<String, Value>) -> Option<&Value> {
|
||||
body.get("response_format")
|
||||
.filter(|v| !v.is_null())
|
||||
.or_else(|| body.get("text")?.get("format").filter(|v| !v.is_null()))
|
||||
}
|
||||
|
||||
pub(super) fn reasoning_effort(body: &Map<String, Value>) -> Option<&Value> {
|
||||
body.get("reasoning_effort")
|
||||
.filter(|v| !v.is_null())
|
||||
.or_else(|| {
|
||||
body.get("reasoning")?
|
||||
.get("effort")
|
||||
.filter(|v| !v.is_null())
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn stop_sequences(body: &Map<String, Value>) -> Result<Option<Value>, ChatError> {
|
||||
match body.get("stop") {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(Value::String(text)) => Ok(Some(json!([text]))),
|
||||
Some(Value::Array(values)) => {
|
||||
for (index, value) in values.iter().enumerate() {
|
||||
if !value.is_string() {
|
||||
return Err(invalid(&format!("stop[{index}]")));
|
||||
}
|
||||
}
|
||||
Ok((!values.is_empty()).then(|| Value::Array(values.clone())))
|
||||
}
|
||||
_ => Err(invalid("stop")),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn function_parameters(function: &Value, path: &str) -> Result<Value, ChatError> {
|
||||
match function.get("parameters") {
|
||||
None | Some(Value::Null) => Ok(json!({"type":"object","properties":{}})),
|
||||
Some(schema) if schema.is_object() => Ok(schema.clone()),
|
||||
_ => Err(invalid(&format!("{path}.function.parameters"))),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn string<'a>(
|
||||
value: Option<&'a Value>,
|
||||
path: &str,
|
||||
@@ -222,28 +304,16 @@ pub(crate) fn request_facts(body: &Map<String, Value>) -> RequestFacts {
|
||||
.any(|tool| tool.get("type").and_then(Value::as_str) == Some("image_generation")),
|
||||
reasoning: body.get("reasoning_effort").is_some_and(|v| !v.is_null())
|
||||
|| body.get("reasoning").is_some_and(Value::is_object),
|
||||
json_schema: body
|
||||
.get("response_format")
|
||||
json_schema: response_format(body)
|
||||
.and_then(|v| v.get("type"))
|
||||
.and_then(Value::as_str)
|
||||
== Some("json_schema")
|
||||
|| body
|
||||
.get("text")
|
||||
.and_then(|v| v.pointer("/format/type"))
|
||||
.and_then(Value::as_str)
|
||||
== Some("json_schema"),
|
||||
== Some("json_schema"),
|
||||
..RequestFacts::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn request_effort(body: &Map<String, Value>) -> Option<&str> {
|
||||
body.get("reasoning_effort")
|
||||
.and_then(Value::as_str)
|
||||
.or_else(|| {
|
||||
body.get("reasoning")
|
||||
.and_then(|value| value.get("effort"))
|
||||
.and_then(Value::as_str)
|
||||
})
|
||||
reasoning_effort(body).and_then(Value::as_str)
|
||||
}
|
||||
|
||||
/// 将无格式约束的 custom 工具表达为字符串参数,受约束格式必须由目标原生支持
|
||||
|
||||
@@ -4,7 +4,11 @@ use std::collections::HashSet;
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
use crate::chat_completions::{ChatError as RequestDecodeError, validate_request};
|
||||
use crate::chat_completions::{
|
||||
ChatError as RequestDecodeError,
|
||||
request::{block_text, empty_history_content, empty_history_part},
|
||||
validate_request,
|
||||
};
|
||||
|
||||
/// 将已验证的 Chat 正文直接转换为 Responses 请求
|
||||
pub fn convert_request(
|
||||
@@ -161,7 +165,6 @@ fn messages(value: Value) -> Result<Vec<Value>, RequestDecodeError> {
|
||||
let path = format!("messages[{index}]");
|
||||
let mut message = object(value, &path)?;
|
||||
let role = required_string(&mut message, "role", &format!("{path}.role"), false)?;
|
||||
let name = optional(&mut message, "name").filter(|name| name != "");
|
||||
if role == "tool" {
|
||||
let call_id = required_string(
|
||||
&mut message,
|
||||
@@ -182,7 +185,8 @@ fn messages(value: Value) -> Result<Vec<Value>, RequestDecodeError> {
|
||||
"function_call_output"
|
||||
};
|
||||
let mut item = json!({"type": kind, "call_id": call_id, "output": output});
|
||||
if let Some(name) = name {
|
||||
if let Some(name) = optional(&mut message, "name").filter(|name| name != "") {
|
||||
string(&name, &format!("{path}.name"), true)?;
|
||||
item["name"] = name;
|
||||
}
|
||||
input.push(item);
|
||||
@@ -193,8 +197,9 @@ fn messages(value: Value) -> Result<Vec<Value>, RequestDecodeError> {
|
||||
.map(|value| tool_calls(value, &format!("{path}.tool_calls")))
|
||||
.transpose()?
|
||||
.unwrap_or_default();
|
||||
let refusal = optional(&mut message, "refusal");
|
||||
let content = optional(&mut message, "content");
|
||||
let refusal = optional(&mut message, "refusal").filter(|v| v != "");
|
||||
let content =
|
||||
optional(&mut message, "content").filter(|v| !empty_history_content(&role, v));
|
||||
let is_assistant = role == "assistant";
|
||||
let mut parts = content
|
||||
.map(|value| content_parts(value, &role, &format!("{path}.content"), is_assistant))
|
||||
@@ -233,20 +238,23 @@ fn content_parts(
|
||||
is_assistant: bool,
|
||||
) -> Result<Vec<Value>, RequestDecodeError> {
|
||||
let parts = match value {
|
||||
Value::String(text) => return Ok(vec![text_part(text, is_assistant)]),
|
||||
Value::String(text) => return Ok(vec![text_part(&text, is_assistant)]),
|
||||
Value::Array(parts) => parts,
|
||||
_ => return Err(invalid_type(path, "a string or an array")),
|
||||
};
|
||||
let mut result = Vec::with_capacity(parts.len());
|
||||
for (index, value) in parts.into_iter().enumerate() {
|
||||
for (index, value) in parts
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.filter(|(_, part)| !empty_history_part(role, part))
|
||||
{
|
||||
let path = format!("{path}[{index}]");
|
||||
let mut part = object(value, &path)?;
|
||||
let kind = required_string(&mut part, "type", &format!("{path}.type"), false)?;
|
||||
let mut converted = match kind.as_str() {
|
||||
"text" | "input_text" | "output_text" => text_part(
|
||||
required_string(&mut part, "text", &format!("{path}.text"), true)?,
|
||||
is_assistant,
|
||||
),
|
||||
"text" | "input_text" | "output_text" => {
|
||||
text_part(block_text(part.get("text"), &path)?, is_assistant)
|
||||
}
|
||||
"image_url" if matches!(role, "user" | "tool") => image_part(
|
||||
required(&mut part, "image_url", &format!("{path}.image_url"))?,
|
||||
&format!("{path}.image_url"),
|
||||
@@ -278,7 +286,7 @@ fn content_parts(
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
fn text_part(text: String, is_assistant: bool) -> Value {
|
||||
fn text_part(text: &str, is_assistant: bool) -> Value {
|
||||
if is_assistant {
|
||||
json!({"type": "output_text", "text": text, "annotations": []})
|
||||
} else {
|
||||
@@ -376,9 +384,17 @@ fn tools(value: Value) -> Result<Vec<Value>, RequestDecodeError> {
|
||||
if let Some(nested) = optional(&mut tool, &kind) {
|
||||
tool = object(nested, &format!("{path}.{kind}"))?;
|
||||
}
|
||||
if kind == "function" && tool.get("strict").is_none_or(Value::is_null) {
|
||||
// Chat 的缺省是宽松 schema,不能让 Responses 收紧参数合同
|
||||
tool.insert("strict".into(), false.into());
|
||||
if tool.get("description") == Some(&Value::Null) {
|
||||
tool.remove("description");
|
||||
}
|
||||
if kind == "function" {
|
||||
if tool.get("parameters") == Some(&Value::Null) {
|
||||
tool.remove("parameters");
|
||||
}
|
||||
if tool.get("strict").is_none_or(Value::is_null) {
|
||||
// Chat 的缺省是宽松 schema,不能让 Responses 收紧参数合同
|
||||
tool.insert("strict".into(), false.into());
|
||||
}
|
||||
}
|
||||
}
|
||||
// hosted 工具采用原生 Responses 结构,支持范围由选中的 Provider 决定
|
||||
|
||||
@@ -1,4 +1,21 @@
|
||||
//! 跨协议 HTTP 传输、下游环境头分类与重试时间解析
|
||||
//! 跨协议 HTTP 头分类、响应关联与重试时间解析
|
||||
|
||||
/// 响应关联 ID 的头名与优先级沿用官方 Codex
|
||||
pub const RESPONSE_REQUEST_ID_HEADERS: [&str; 4] = [
|
||||
"x-request-id",
|
||||
"x-oai-request-id",
|
||||
"x-openai-request-id",
|
||||
"x-ms-request-id",
|
||||
];
|
||||
|
||||
/// 从各传输容器提供的可读 HTTP 头值中选取关联 ID,空值不阻止别名回退
|
||||
pub fn preferred_response_request_id<'a>(
|
||||
mut header: impl FnMut(&str) -> Option<&'a str>,
|
||||
) -> Option<&'a str> {
|
||||
RESPONSE_REQUEST_ID_HEADERS
|
||||
.iter()
|
||||
.find_map(|name| header(name).filter(|value| !value.trim().is_empty()))
|
||||
}
|
||||
|
||||
/// 上游可交给客户端的秒级与毫秒级重试等待头
|
||||
pub const RETRY_AFTER_HEADERS: [&str; 2] = ["retry-after", "retry-after-ms"];
|
||||
|
||||
@@ -4,7 +4,15 @@ use gateway_protocol::{
|
||||
chat_completions::{CHAT_PROTOCOL, ChatError, genai, messages, parse_request, responses},
|
||||
request::{request_facts, request_observation},
|
||||
};
|
||||
use serde_json::json;
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
fn target_requests(body: &Map<String, Value>) -> [Result<Map<String, Value>, ChatError>; 3] {
|
||||
[
|
||||
responses::convert_request(body),
|
||||
messages::convert_request(body, &Default::default()),
|
||||
genai::convert_request(body),
|
||||
]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parsing_retains_original_protocol_and_usage_preference() {
|
||||
@@ -42,7 +50,7 @@ fn invalid_envelopes_and_chat_controls_keep_safe_field_errors() {
|
||||
("n", json!(2)),
|
||||
("store", json!(true)),
|
||||
("previous_response_id", json!("resp_previous")),
|
||||
("stream_options", json!({"include_usage":true})),
|
||||
("stream_options", json!(true)),
|
||||
] {
|
||||
let mut request = super::request();
|
||||
request.insert(field.into(), value);
|
||||
@@ -104,9 +112,320 @@ fn capability_facts_only_read_protocol_declarations() {
|
||||
assert!(!request_facts(CHAT_PROTOCOL, &body).tools);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_history_is_omitted_only_when_converting() {
|
||||
let mut baseline = super::request();
|
||||
baseline["messages"] = json!([
|
||||
{"role":"developer","content":"Keep replies short."},
|
||||
{"role":"user","content":"hello"}
|
||||
]);
|
||||
let expected = target_requests(&baseline).map(Result::unwrap);
|
||||
for role in ["system", "developer", "assistant"] {
|
||||
for content in [
|
||||
None,
|
||||
Some(Value::Null),
|
||||
Some(json!("")),
|
||||
Some(json!([])),
|
||||
Some(json!([{"type":"text","text":""},{"type":"output_text","text":""}])),
|
||||
Some(json!([{"type":"input_text","text":null}])),
|
||||
Some(json!([{"type":"text","text":"","prompt_cache_breakpoint":null}])),
|
||||
] {
|
||||
let mut placeholder =
|
||||
json!({"role":role,"tool_calls":[],"refusal":"","tool_call_id":""});
|
||||
if let Some(content) = content {
|
||||
placeholder["content"] = content;
|
||||
}
|
||||
let mut body = baseline.clone();
|
||||
body["messages"]
|
||||
.as_array_mut()
|
||||
.unwrap()
|
||||
.insert(1, placeholder.clone());
|
||||
let parsed = parse_request(&serde_json::to_vec(&body).unwrap()).unwrap();
|
||||
assert_eq!(parsed, body);
|
||||
assert_eq!(target_requests(&parsed).map(Result::unwrap), expected);
|
||||
|
||||
body["messages"] = json!([placeholder]);
|
||||
for error in target_requests(&body).map(Result::unwrap_err) {
|
||||
assert_eq!(error.parameter(), Some("messages"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_history_fields_preserve_tool_calls_results_and_refusals() {
|
||||
let mut body = super::request();
|
||||
body["messages"] = json!([
|
||||
{"role":"user","content":"hello"},
|
||||
{"role":"assistant","tool_calls":[{"id":"c","type":"function","function":{"name":"f","arguments":"{}"}}]},
|
||||
{"role":"tool","tool_call_id":"c","content":""},
|
||||
{"role":"assistant","refusal":"declined"}
|
||||
]);
|
||||
let expected = target_requests(&body).map(Result::unwrap);
|
||||
assert_eq!(expected[0]["input"][1]["call_id"], "c");
|
||||
assert_eq!(expected[0]["input"][2]["output"], "");
|
||||
assert_eq!(expected[1]["messages"][1]["content"][0]["type"], "tool_use");
|
||||
assert_eq!(expected[1]["messages"][3]["content"][0]["text"], "declined");
|
||||
assert_eq!(
|
||||
expected[2]["contents"][2]["parts"][0]["functionResponse"]["id"],
|
||||
"c"
|
||||
);
|
||||
assert_eq!(expected[2]["contents"][3]["parts"][0]["text"], "declined");
|
||||
body["messages"][0] = json!({"role":"user","content":"hello","name":17,"refusal":"","tool_calls":[],"tool_call_id":""});
|
||||
for content in [
|
||||
Value::Null,
|
||||
json!(""),
|
||||
json!([]),
|
||||
json!([{"type":"text","text":""}]),
|
||||
json!([{"type":"output_text","text":null}]),
|
||||
] {
|
||||
body["messages"][1]["content"] = content.clone();
|
||||
body["messages"][3]["content"] = content;
|
||||
assert_eq!(target_requests(&body).map(Result::unwrap), expected);
|
||||
}
|
||||
body["messages"][2]["content"] =
|
||||
json!([{"type":"text","text":""},{"type":"text","text":"x"},{"type":"text","text":""}]);
|
||||
let [responses, messages, genai] = target_requests(&body).map(Result::unwrap);
|
||||
assert_eq!(responses["input"][2]["output"].as_array().unwrap().len(), 3);
|
||||
assert_eq!(
|
||||
messages["messages"][2]["content"][0]["content"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.len(),
|
||||
3
|
||||
);
|
||||
assert_eq!(
|
||||
genai["contents"][2]["parts"][0]["functionResponse"]["response"]["output"],
|
||||
"\nx\n"
|
||||
);
|
||||
body["messages"][2]["content"][0]["text"] = Value::Null;
|
||||
assert_eq!(
|
||||
target_requests(&body).map(Result::unwrap),
|
||||
[responses, messages, genai]
|
||||
);
|
||||
body["messages"][2]["content"] = json!("");
|
||||
body["messages"][2]["name"] = json!(17);
|
||||
let parsed = parse_request(&serde_json::to_vec(&body).unwrap()).unwrap();
|
||||
let [responses, messages, genai] = target_requests(&parsed);
|
||||
assert_eq!(responses.unwrap_err().parameter(), Some("messages[2].name"));
|
||||
assert_eq!(messages.unwrap(), expected[1]);
|
||||
assert_eq!(genai.unwrap(), expected[2]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn filters_only_plain_empty_history_parts_and_keeps_source_indices() {
|
||||
let mut body = super::request();
|
||||
let blank = json!({"type":"input_text","text":""});
|
||||
let space = json!({"type":"text","text":" "});
|
||||
for role in ["system", "developer", "assistant", "user"] {
|
||||
body["messages"] = json!([{"role":role,"content":[space]}, {"role":"user","content":"hi"}]);
|
||||
let expected = target_requests(&body).map(Result::unwrap);
|
||||
body["messages"][0]["content"] = json!([blank, space, blank]);
|
||||
let actual = target_requests(&body).map(Result::unwrap);
|
||||
body["messages"][0]["content"][0]["text"] = Value::Null;
|
||||
assert_eq!(target_requests(&body).map(Result::unwrap), actual);
|
||||
if role == "user" {
|
||||
assert_eq!(
|
||||
actual[0]["input"][0]["content"].as_array().unwrap().len(),
|
||||
3
|
||||
);
|
||||
assert_eq!(actual[1]["messages"][0]["content"][1]["text"], " ");
|
||||
assert_eq!(actual[2]["contents"][0]["parts"][1]["text"], " ");
|
||||
} else {
|
||||
assert_eq!(actual, expected);
|
||||
}
|
||||
}
|
||||
let marked = json!({"type":"text","text":null,"prompt_cache_breakpoint":{"mode":"explicit"}});
|
||||
body["messages"][0] = json!({"role":"developer","content":[blank,marked]});
|
||||
let converted = responses::convert_request(&body).unwrap();
|
||||
assert_eq!(
|
||||
converted["input"][0]["content"],
|
||||
json!([{"type":"input_text","text":"","prompt_cache_breakpoint":{"mode":"explicit"}}])
|
||||
);
|
||||
body["messages"][0]["role"] = json!("assistant");
|
||||
assert_eq!(
|
||||
responses::convert_request(&body).unwrap_err().parameter(),
|
||||
Some("messages[0].content[1].prompt_cache_breakpoint")
|
||||
);
|
||||
for (part, code) in [
|
||||
(json!({"type":"text"}), "missing_required_parameter"),
|
||||
(json!({"type":"text","text":17}), "invalid_type"),
|
||||
(json!({"type":"text","text":{}}), "invalid_type"),
|
||||
] {
|
||||
body["messages"][0]["content"] = json!([{"type":"text","text":null},part]);
|
||||
for error in target_requests(&body).map(Result::unwrap_err) {
|
||||
assert_eq!(error.parameter(), Some("messages[0].content[1].text"));
|
||||
assert_eq!(error.code(), code);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn null_chat_controls_fall_back_to_native_format_and_effort() {
|
||||
let mut body = super::request();
|
||||
let schema = json!({"type":"object","properties":{"q":{"type":"string"}}});
|
||||
body.insert(
|
||||
"text".into(),
|
||||
json!({"format":{"type":"json_schema","name":"answer","schema":schema}}),
|
||||
);
|
||||
body.insert("reasoning".into(), json!({"effort":"low"}));
|
||||
let expected = target_requests(&body).map(Result::unwrap);
|
||||
assert_eq!(expected[1]["output_config"]["format"]["schema"], schema);
|
||||
assert_eq!(
|
||||
expected[2]["generationConfig"]["responseJsonSchema"],
|
||||
schema
|
||||
);
|
||||
assert_eq!(expected[1]["thinking"]["budget_tokens"], 1024);
|
||||
assert_eq!(
|
||||
expected[2]["generationConfig"]["thinkingConfig"]["thinkingBudget"],
|
||||
1024
|
||||
);
|
||||
body.insert("response_format".into(), Value::Null);
|
||||
body.insert("reasoning_effort".into(), Value::Null);
|
||||
assert_eq!(target_requests(&body).map(Result::unwrap), expected);
|
||||
assert!(request_facts(CHAT_PROTOCOL, &body).json_schema);
|
||||
|
||||
body["response_format"] = json!({"type":"text"});
|
||||
body["reasoning_effort"] = json!("none");
|
||||
let [responses, messages, genai] = target_requests(&body).map(Result::unwrap);
|
||||
assert!(!request_facts(CHAT_PROTOCOL, &body).json_schema);
|
||||
assert_eq!(responses["text"]["format"]["type"], "text");
|
||||
assert!(messages.get("output_config").is_none());
|
||||
assert!(
|
||||
genai["generationConfig"]
|
||||
.get("responseJsonSchema")
|
||||
.is_none()
|
||||
);
|
||||
assert_eq!(messages["thinking"]["type"], "disabled");
|
||||
assert_eq!(
|
||||
genai["generationConfig"]["thinkingConfig"]["thinkingBudget"],
|
||||
0
|
||||
);
|
||||
body["reasoning_effort"] = json!(5);
|
||||
for error in target_requests(&body).map(Result::unwrap_err) {
|
||||
assert_eq!(error.parameter(), Some("reasoning_effort"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn null_function_parameters_follow_each_targets_default() {
|
||||
let mut body = super::request();
|
||||
body.insert(
|
||||
"tools".into(),
|
||||
json!([{"type":"function","function":{"name":"clock"}}]),
|
||||
);
|
||||
let expected = target_requests(&body).map(Result::unwrap);
|
||||
assert!(expected[0]["tools"][0].get("parameters").is_none());
|
||||
let default_schema = json!({"type":"object","properties":{}});
|
||||
assert_eq!(expected[1]["tools"][0]["input_schema"], default_schema);
|
||||
assert_eq!(
|
||||
expected[2]["tools"][0]["functionDeclarations"][0]["parametersJsonSchema"],
|
||||
default_schema
|
||||
);
|
||||
body["tools"][0]["function"] =
|
||||
json!({"name":"clock","parameters":null,"description":null,"strict":null});
|
||||
assert_eq!(target_requests(&body).map(Result::unwrap), expected);
|
||||
|
||||
let schema =
|
||||
json!({"type":"object","properties":{"q":{"type":["string","null"],"default":null}}});
|
||||
body["tools"][0]["function"]["parameters"] = schema.clone();
|
||||
let [responses, messages, genai] = target_requests(&body).map(Result::unwrap);
|
||||
assert_eq!(responses["tools"][0]["parameters"], schema);
|
||||
assert_eq!(messages["tools"][0]["input_schema"], schema);
|
||||
assert_eq!(
|
||||
genai["tools"][0]["functionDeclarations"][0]["parametersJsonSchema"],
|
||||
schema
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stop_sequences_are_mapped_only_for_targets_that_support_them() {
|
||||
let mut body = super::request();
|
||||
let baseline = target_requests(&body).map(Result::unwrap);
|
||||
for stop in [Value::Null, json!([])] {
|
||||
body.insert("stop".into(), stop);
|
||||
assert_eq!(target_requests(&body).map(Result::unwrap), baseline);
|
||||
}
|
||||
for (stop, expected) in [
|
||||
(json!(" END"), json!([" END"])),
|
||||
(json!([" END", "\n"]), json!([" END", "\n"])),
|
||||
] {
|
||||
body["stop"] = stop;
|
||||
let [responses, messages, genai] = target_requests(&body).map(Result::unwrap);
|
||||
assert_eq!(responses, baseline[0]);
|
||||
assert_eq!(messages["stop_sequences"], expected);
|
||||
assert_eq!(genai["generationConfig"]["stopSequences"], expected);
|
||||
}
|
||||
for (stop, param) in [(json!(5), "stop"), (json!(["end", null]), "stop[1]")] {
|
||||
body["stop"] = stop;
|
||||
let [responses, messages, genai] = target_requests(&body);
|
||||
assert_eq!(responses.unwrap(), baseline[0]);
|
||||
for result in [messages, genai] {
|
||||
assert_eq!(result.unwrap_err().parameter(), Some(param));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stream_options_affect_only_streaming_delivery() {
|
||||
for stream in [None, Some(false), Some(true)] {
|
||||
let mut body = super::request();
|
||||
if let Some(stream) = stream {
|
||||
body.insert("stream".into(), json!(stream));
|
||||
}
|
||||
let expected = target_requests(&body).map(Result::unwrap);
|
||||
body.insert(
|
||||
"stream_options".into(),
|
||||
json!({"include_usage":true, "include_obfuscation":false}),
|
||||
);
|
||||
assert_eq!(target_requests(&body).map(Result::unwrap), expected);
|
||||
body["stream_options"]["include_obfuscation"] = json!(true);
|
||||
if stream == Some(true) {
|
||||
for error in target_requests(&body).map(Result::unwrap_err) {
|
||||
assert_eq!(
|
||||
error.parameter(),
|
||||
Some("stream_options.include_obfuscation")
|
||||
);
|
||||
}
|
||||
} else {
|
||||
assert_eq!(target_requests(&body).map(Result::unwrap), expected);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn all_targets_apply_the_same_common_request_validation() {
|
||||
for (field, value, parameter) in [
|
||||
(
|
||||
"messages",
|
||||
json!([{"role":"system","content":null},{"role":"developer","content":null}]),
|
||||
"messages",
|
||||
),
|
||||
(
|
||||
"messages",
|
||||
json!([{"role":"developer"},{"role":"assistant","audio":{"id":"audio"}}]),
|
||||
"messages[1].audio",
|
||||
),
|
||||
(
|
||||
"messages",
|
||||
json!([{"role":"system","content":42}]),
|
||||
"messages[0].content",
|
||||
),
|
||||
(
|
||||
"messages",
|
||||
json!([{"role":"system","content":null},{"role":"user","content":null}]),
|
||||
"messages[1].content",
|
||||
),
|
||||
(
|
||||
"messages",
|
||||
json!([{"role":"tool","tool_call_id":"c","content":null}]),
|
||||
"messages[0].content",
|
||||
),
|
||||
(
|
||||
"messages",
|
||||
json!([{"role":"system","content":null,"tool_calls":[{}]}]),
|
||||
"messages[0].tool_calls",
|
||||
),
|
||||
(
|
||||
"messages",
|
||||
json!([{"role":"assistant","content":"ok","refusal":17}]),
|
||||
@@ -114,13 +433,18 @@ fn all_targets_apply_the_same_common_request_validation() {
|
||||
),
|
||||
(
|
||||
"messages",
|
||||
json!([{"role":"user","content":"ok","name":17}]),
|
||||
"messages[0].name",
|
||||
json!([{"role":"assistant","tool_calls":{}}]),
|
||||
"messages[0].tool_calls",
|
||||
),
|
||||
(
|
||||
"messages",
|
||||
json!([{"role":"user","content":"ok","tool_calls":[]}]),
|
||||
"messages[0].tool_calls",
|
||||
json!([{"role":"developer","tool_call_id":"c"}]),
|
||||
"messages[0].tool_call_id",
|
||||
),
|
||||
(
|
||||
"messages",
|
||||
json!([{"role":"user","content":"ok","refusal":"declined"}]),
|
||||
"messages[0].refusal",
|
||||
),
|
||||
(
|
||||
"messages",
|
||||
@@ -130,8 +454,8 @@ fn all_targets_apply_the_same_common_request_validation() {
|
||||
("n", json!(2), "n"),
|
||||
(
|
||||
"stream_options",
|
||||
json!({"include_usage":true}),
|
||||
"stream_options",
|
||||
json!({"include_usage":1}),
|
||||
"stream_options.include_usage",
|
||||
),
|
||||
] {
|
||||
let mut body = super::request();
|
||||
@@ -140,11 +464,7 @@ fn all_targets_apply_the_same_common_request_validation() {
|
||||
.err()
|
||||
.unwrap();
|
||||
assert_eq!(expected.parameter(), Some(parameter));
|
||||
for result in [
|
||||
responses::convert_request(&body),
|
||||
messages::convert_request(&body, &Default::default()),
|
||||
genai::convert_request(&body),
|
||||
] {
|
||||
for result in target_requests(&body) {
|
||||
assert_eq!(result.unwrap_err(), expected);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,61 @@
|
||||
//! 验证传输头部分类,以及响应中的连接级和身份字段过滤
|
||||
|
||||
use gateway_protocol::http::{
|
||||
is_transport_managed_request_header, parse_retry_after_seconds, response_header_is_forwardable,
|
||||
is_transport_managed_request_header, parse_retry_after_seconds, preferred_response_request_id,
|
||||
response_header_is_forwardable,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn response_request_ids_follow_official_header_priority() {
|
||||
let names = [
|
||||
"x-request-id",
|
||||
"x-oai-request-id",
|
||||
"x-openai-request-id",
|
||||
"x-ms-request-id",
|
||||
];
|
||||
let mut headers = http::HeaderMap::new();
|
||||
for name in names {
|
||||
headers.insert(name, http::HeaderValue::from_static(name));
|
||||
}
|
||||
headers.insert("cf-ray", http::HeaderValue::from_static("trace-only"));
|
||||
for name in names {
|
||||
assert_eq!(
|
||||
preferred_response_request_id(|name| headers.get(name)?.to_str().ok()),
|
||||
Some(name),
|
||||
);
|
||||
headers.remove(name);
|
||||
}
|
||||
assert_eq!(
|
||||
preferred_response_request_id(|name| headers.get(name)?.to_str().ok()),
|
||||
None,
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn response_request_ids_skip_unusable_first_values_without_rewriting_headers() {
|
||||
let mut headers = http::HeaderMap::new();
|
||||
headers.insert(
|
||||
"x-request-id",
|
||||
http::HeaderValue::from_bytes(b"\xff").unwrap(),
|
||||
);
|
||||
headers.append(
|
||||
"x-request-id",
|
||||
http::HeaderValue::from_static("second-value"),
|
||||
);
|
||||
headers.insert("x-oai-request-id", http::HeaderValue::from_static(" \t "));
|
||||
headers.insert("x-openai-request-id", http::HeaderValue::from_static(""));
|
||||
headers.insert(
|
||||
"x-ms-request-id",
|
||||
http::HeaderValue::from_static(" opaque-id "),
|
||||
);
|
||||
assert_eq!(
|
||||
preferred_response_request_id(|name| headers.get(name)?.to_str().ok()),
|
||||
Some(" opaque-id "),
|
||||
);
|
||||
assert_eq!(headers["x-request-id"].as_bytes(), b"\xff");
|
||||
assert_eq!(headers.get_all("x-request-id").iter().count(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retry_after_should_accept_nonnegative_seconds_and_http_dates() {
|
||||
for (header, expected) in [
|
||||
|
||||
@@ -240,18 +240,21 @@ pub(crate) struct StaleModelRequestRecoveryTask {
|
||||
impl ScheduledTask for StaleModelRequestRecoveryTask {
|
||||
fn run_cycle(
|
||||
&self,
|
||||
_context: WorkerCycleContext,
|
||||
context: WorkerCycleContext,
|
||||
) -> futures::future::BoxFuture<'_, Result<(), WorkerTaskError>> {
|
||||
Box::pin(async move {
|
||||
gateway_core::engine::ExecutionStore::recover_expired(
|
||||
self.execution.as_ref(),
|
||||
SystemTime::now(),
|
||||
)
|
||||
.await
|
||||
.map(|_| ())
|
||||
.map_err(|source| {
|
||||
WorkerTaskError::safe("stale request recovery failed").with_source(source)
|
||||
})
|
||||
context
|
||||
.cancellation()
|
||||
.run_until_cancelled(gateway_core::engine::ExecutionStore::recover_expired(
|
||||
self.execution.as_ref(),
|
||||
SystemTime::now(),
|
||||
))
|
||||
.await
|
||||
.transpose()
|
||||
.map(|_| ())
|
||||
.map_err(|source| {
|
||||
WorkerTaskError::safe("stale request recovery failed").with_source(source)
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,6 +27,7 @@ http-body-util = "0.1.5"
|
||||
reqwest = { version = "=0.12.28", default-features = false, features = ["json", "rustls-tls-native-roots", "socks", "stream"] }
|
||||
serde = { version = "1.0.228", features = ["derive"] }
|
||||
serde_json = { version = "1.0.150", features = ["raw_value"] }
|
||||
sevenz-rust2 = { version = "0.27.0", default-features = false }
|
||||
sha2 = "0.11.0"
|
||||
tar = { version = "0.4.46", default-features = false }
|
||||
tempfile = "3.27.0"
|
||||
@@ -39,6 +40,7 @@ uuid = { version = "1.23.3", features = ["v7"] }
|
||||
zip = { version = "9.8.0", default-features = false, features = ["deflate-flate2"] }
|
||||
|
||||
[dev-dependencies]
|
||||
sevenz-rust2 = { version = "0.27.0", default-features = false, features = ["compress"] }
|
||||
wiremock = "0.6.5"
|
||||
tokio = { version = "=1.53.3", features = ["rt-multi-thread"] }
|
||||
|
||||
|
||||
@@ -308,6 +308,18 @@ impl CatalogService {
|
||||
}
|
||||
}
|
||||
}
|
||||
if !refresh
|
||||
&& matches!(
|
||||
current.account.credential_state(),
|
||||
gateway_core::account::CredentialState::Invalid
|
||||
| gateway_core::account::CredentialState::Banned
|
||||
)
|
||||
{
|
||||
return Ok(ProviderModels {
|
||||
models: Vec::new(),
|
||||
observed_at: None,
|
||||
});
|
||||
}
|
||||
if current.account.authentication_kind() == super::api_key::API_KEY {
|
||||
let material = super::api_key::ApiKeyMaterial::load(¤t)?;
|
||||
let client = crate::transport::GenAiClient::new(
|
||||
@@ -316,7 +328,12 @@ impl CatalogService {
|
||||
)
|
||||
.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| {
|
||||
let result = client.catalog(&material.api_key).await;
|
||||
if let Err(failure) = &result {
|
||||
super::record_account_failure(self.accounts.as_ref(), ¤t.account, failure)
|
||||
.await;
|
||||
}
|
||||
let catalog = result.map_err(|e| {
|
||||
error(AdminKind::Unavailable)
|
||||
.with_public_message("GenAI 模型目录查询失败")
|
||||
.with_source(e)
|
||||
@@ -333,15 +350,16 @@ impl CatalogService {
|
||||
let client = CloudCodeClient::new(&self.origin, current.account.outbound_proxy(), &profile)
|
||||
.map_err(|e| error(AdminKind::Unavailable).with_source(e))?;
|
||||
let observed_at = SystemTime::now();
|
||||
let catalog = client
|
||||
.catalog(&material.access_token)
|
||||
.await
|
||||
.map_err(|e| match e.kind() {
|
||||
Kind::Unauthorized => error(AdminKind::CredentialRefreshRequired).with_source(e),
|
||||
_ => error(AdminKind::Unavailable)
|
||||
.with_public_message("Antigravity 项目或模型目录查询失败")
|
||||
.with_source(e),
|
||||
})?;
|
||||
let result = client.catalog(&material.access_token).await;
|
||||
if let Err(error) = &result {
|
||||
super::record_account_failure(self.accounts.as_ref(), ¤t.account, error).await;
|
||||
}
|
||||
let catalog = result.map_err(|e| match e.kind() {
|
||||
Kind::Unauthorized => error(AdminKind::CredentialRefreshRequired).with_source(e),
|
||||
_ => error(AdminKind::Unavailable)
|
||||
.with_public_message("Antigravity 项目或模型目录查询失败")
|
||||
.with_source(e),
|
||||
})?;
|
||||
self.publish(
|
||||
¤t.account,
|
||||
current.account.plan_type().map(str::to_owned),
|
||||
@@ -452,6 +470,13 @@ impl CatalogService {
|
||||
&self,
|
||||
cancellation: &gateway_core::lifecycle::CancellationToken,
|
||||
) -> Result<(), gateway_core::task::WorkerTaskError> {
|
||||
cancellation
|
||||
.run_until_cancelled(self.refresh_due_accounts())
|
||||
.await
|
||||
.unwrap_or(Ok(()))
|
||||
}
|
||||
|
||||
async fn refresh_due_accounts(&self) -> Result<(), gateway_core::task::WorkerTaskError> {
|
||||
use futures::{StreamExt, stream};
|
||||
use gateway_core::task::WorkerTaskError;
|
||||
let catalogs = self
|
||||
@@ -469,7 +494,11 @@ impl CatalogService {
|
||||
.await
|
||||
.map_err(|e| WorkerTaskError::safe("读取 Antigravity 账号失败").with_source(e))?;
|
||||
due.retain(|account| {
|
||||
matches!(account.authentication_kind(), "oauth" | "api_key")
|
||||
!matches!(
|
||||
account.credential_state(),
|
||||
gateway_core::account::CredentialState::Invalid
|
||||
| gateway_core::account::CredentialState::Banned
|
||||
) && 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()
|
||||
@@ -484,9 +513,9 @@ impl CatalogService {
|
||||
let offset = self.refresh_cursor.fetch_add(32, Ordering::Relaxed) % due.len();
|
||||
due.rotate_left(offset);
|
||||
due.truncate(32);
|
||||
let mut updates=stream::iter(due).map(|account|async move {
|
||||
tokio::select! {biased;_=cancellation.cancelled()=>Ok(()),result=self.account_models(account.id(),true)=>result.map(|_|())}
|
||||
}).buffer_unordered(4);
|
||||
let mut updates = stream::iter(due)
|
||||
.map(|account| async move { self.account_models(account.id(), true).await })
|
||||
.buffer_unordered(4);
|
||||
let mut first_error = None;
|
||||
while let Some(result) = updates.next().await {
|
||||
if let Err(error) = result
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
//! 资源服务的明确拒绝更新账号访问状态,普通授权失败只触发 AT 续期
|
||||
|
||||
use crate::transport::{AccountRejection, account_rejection};
|
||||
use gateway_core::{
|
||||
account::{
|
||||
AccountErrorReason, AccountStateChange, CredentialState, ProviderAccount,
|
||||
ProviderAccountStore,
|
||||
},
|
||||
error::{ProviderError, ProviderErrorKind, StoreError},
|
||||
upstream::UpstreamSendState,
|
||||
};
|
||||
use std::time::{Duration, SystemTime};
|
||||
|
||||
pub(crate) async fn record_account_failure(
|
||||
accounts: &dyn ProviderAccountStore,
|
||||
account: &ProviderAccount,
|
||||
error: &ProviderError,
|
||||
) {
|
||||
if error.send_state() != UpstreamSendState::Sent {
|
||||
return;
|
||||
}
|
||||
let state = match account_rejection(error) {
|
||||
Some(AccountRejection::VerificationRequired) => Some((
|
||||
CredentialState::Invalid,
|
||||
AccountErrorReason::AccountUnverified,
|
||||
"Google 要求验证账号,完成验证后恢复账号状态",
|
||||
)),
|
||||
Some(AccountRejection::Banned) => Some((
|
||||
CredentialState::Banned,
|
||||
AccountErrorReason::AccountBanned,
|
||||
"Google 已停用账号",
|
||||
)),
|
||||
None if error.kind() == ProviderErrorKind::Unauthorized
|
||||
&& account.authentication_kind() == super::api_key::API_KEY =>
|
||||
{
|
||||
Some((
|
||||
CredentialState::Invalid,
|
||||
AccountErrorReason::CredentialInvalid,
|
||||
"上游拒绝 API Key",
|
||||
))
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let feedback = async {
|
||||
if let Some((credential_state, error_reason, message)) = state {
|
||||
accounts
|
||||
.apply_state_change(AccountStateChange {
|
||||
account_id: account.id().clone(),
|
||||
expected_revision: account.revision(),
|
||||
credential_state,
|
||||
observed_at: SystemTime::now(),
|
||||
error_reason: Some(error_reason),
|
||||
message: Some(message.into()),
|
||||
})
|
||||
.await?;
|
||||
} else if error.kind() == ProviderErrorKind::Unauthorized {
|
||||
// 资源服务拒绝 AT 不能证明 RT 失效,续期由 OAuth worker 负责
|
||||
accounts
|
||||
.expire_access_token(account, SystemTime::now())
|
||||
.await?;
|
||||
}
|
||||
Ok::<_, StoreError>(())
|
||||
};
|
||||
if !matches!(
|
||||
tokio::time::timeout(Duration::from_millis(100), feedback).await,
|
||||
Ok(Ok(()))
|
||||
) {
|
||||
tracing::warn!("Antigravity 账号失败反馈未能写入共享状态");
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,8 @@ pub(crate) mod api_key;
|
||||
mod authorization;
|
||||
pub(crate) mod catalog;
|
||||
mod documents;
|
||||
mod failure;
|
||||
pub(crate) use failure::record_account_failure;
|
||||
mod model_groups;
|
||||
pub(crate) mod oauth;
|
||||
pub(crate) mod quota;
|
||||
|
||||
@@ -175,15 +175,20 @@ impl QuotaService {
|
||||
.map_err(upstream)?;
|
||||
// 用查询开始时间隔离交错返回的旧结果,失败不覆盖已有快照
|
||||
let observed_at = SystemTime::now();
|
||||
let info = client
|
||||
.account_info(&material.access_token)
|
||||
.await
|
||||
.map_err(upstream)?;
|
||||
let (catalog, summary) = tokio::try_join!(
|
||||
client.catalog_for_project(&material.access_token, info.project.clone()),
|
||||
client.quota_summary(&material.access_token, &info.project),
|
||||
)
|
||||
.map_err(upstream)?;
|
||||
let result = async {
|
||||
let info = client.account_info(&material.access_token).await?;
|
||||
let (catalog, summary) = tokio::try_join!(
|
||||
client.catalog_for_project(&material.access_token, info.project.clone()),
|
||||
client.quota_summary(&material.access_token, &info.project),
|
||||
)?;
|
||||
Ok::<_, gateway_core::error::ProviderError>((info, catalog, summary))
|
||||
}
|
||||
.await;
|
||||
if let Err(error) = &result {
|
||||
super::super::record_account_failure(self.accounts.as_ref(), ¤t.account, error)
|
||||
.await;
|
||||
}
|
||||
let (info, catalog, summary) = result.map_err(upstream)?;
|
||||
let (tier, plan_description) = match info.paid_tier {
|
||||
Some(paid) => (Some(paid.tier), paid.description),
|
||||
None => (info.current_tier, None),
|
||||
@@ -298,6 +303,13 @@ impl QuotaService {
|
||||
&self,
|
||||
cancel: &CancellationToken,
|
||||
) -> Result<(), WorkerTaskError> {
|
||||
cancel
|
||||
.run_until_cancelled(self.refresh_due_accounts())
|
||||
.await
|
||||
.unwrap_or(Ok(()))
|
||||
}
|
||||
|
||||
async fn refresh_due_accounts(&self) -> Result<(), WorkerTaskError> {
|
||||
let accounts = self
|
||||
.accounts
|
||||
.list_for_provider(&self.kind, false)
|
||||
@@ -317,10 +329,15 @@ impl QuotaService {
|
||||
let stale_before = now - interval;
|
||||
let mut due = Vec::new();
|
||||
let mut stale = Vec::new();
|
||||
for account in accounts
|
||||
.iter()
|
||||
.filter(|a| a.enabled() && a.authentication_kind() == "oauth")
|
||||
{
|
||||
for account in accounts.iter().filter(|a| {
|
||||
a.enabled()
|
||||
&& a.authentication_kind() == "oauth"
|
||||
&& !matches!(
|
||||
a.credential_state(),
|
||||
gateway_core::account::CredentialState::Invalid
|
||||
| gateway_core::account::CredentialState::Banned
|
||||
)
|
||||
}) {
|
||||
let snapshot = observations
|
||||
.remove(account.id())
|
||||
.filter(|s| s.credential_revision == account.revision());
|
||||
@@ -355,13 +372,7 @@ impl QuotaService {
|
||||
due.rotate_left(offset);
|
||||
due.truncate(32);
|
||||
let mut results = stream::iter(due)
|
||||
.map(|id| async move {
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = cancel.cancelled() => Ok(()),
|
||||
result = self.refresh(&id) => result,
|
||||
}
|
||||
})
|
||||
.map(|id| async move { self.refresh(&id).await })
|
||||
.buffer_unordered(4);
|
||||
while let Some(result) = results.next().await {
|
||||
if let Err(e) = result
|
||||
|
||||
@@ -4,8 +4,8 @@ use super::{oauth::error, service::CredentialService};
|
||||
use gateway_admin::ports::provider::{ProviderAdminError, ProviderAdminErrorKind as Kind};
|
||||
use gateway_core::{
|
||||
account::{
|
||||
CredentialCasOutcome, CredentialCasUpdate, CredentialRevision, CredentialState,
|
||||
LoadedCredential, PlaintextCredential, ProviderAccountUpdate, ProviderRefreshQuery,
|
||||
CredentialCasOutcome, CredentialCasUpdate, CredentialRevision, LoadedCredential,
|
||||
PlaintextCredential, ProviderAccountUpdate, ProviderRefreshQuery,
|
||||
},
|
||||
provider_ports::provider_refresh_backoff_at,
|
||||
task::WorkerTaskError,
|
||||
@@ -79,8 +79,8 @@ impl CredentialService {
|
||||
material,
|
||||
facts.access_token_expires_at.map(Into::into),
|
||||
None,
|
||||
)?
|
||||
.with_account_state(CredentialState::Ready, SystemTime::now(), None, None);
|
||||
)?;
|
||||
// AT 续期不证明资源服务已解除验证或封禁,提交时保留当前账号访问状态
|
||||
match self
|
||||
.accounts
|
||||
.compare_and_swap_credential(record)
|
||||
|
||||
@@ -304,6 +304,7 @@ impl CredentialService {
|
||||
Ok(grant) => grant,
|
||||
};
|
||||
self.rotation(¤t.account, grant, guards)
|
||||
.map(PreparedCredentialRotation::preserving_credential_state)
|
||||
}
|
||||
|
||||
pub(super) fn rotation(
|
||||
|
||||
@@ -15,11 +15,12 @@ use std::sync::Arc;
|
||||
#[error("Antigravity Provider 初始化失败")]
|
||||
pub struct ConfigError;
|
||||
|
||||
pub fn initialize(ports: ProviderStorePorts) -> Result<ProviderBundle, ConfigError> {
|
||||
pub async fn initialize(ports: ProviderStorePorts) -> Result<ProviderBundle, ConfigError> {
|
||||
let kind = ProviderKind::new("antigravity").map_err(|_| ConfigError)?;
|
||||
let oauth = Arc::new(credential::GoogleOAuth::for_provider()?);
|
||||
let origin = oauth.resource_origin().clone();
|
||||
let release = Arc::new(profile::ReleaseService::new(ports.artifact_profiles())?);
|
||||
release.restore().await;
|
||||
let credentials = Arc::new(credential::CredentialService::new(
|
||||
kind.clone(),
|
||||
&ports,
|
||||
|
||||
@@ -20,12 +20,12 @@ impl Drop for ParseGuard {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct CancellableFile {
|
||||
file: std::fs::File,
|
||||
pub(crate) struct CancellableFile<R = std::fs::File> {
|
||||
file: R,
|
||||
cancellation: CancellationToken,
|
||||
}
|
||||
impl CancellableFile {
|
||||
pub(crate) fn new(file: std::fs::File) -> (Self, ParseGuard) {
|
||||
impl<R> CancellableFile<R> {
|
||||
pub(crate) fn new(file: R) -> (Self, ParseGuard) {
|
||||
let cancellation = CancellationToken::new();
|
||||
(
|
||||
Self {
|
||||
@@ -36,7 +36,7 @@ impl CancellableFile {
|
||||
)
|
||||
}
|
||||
}
|
||||
impl Read for CancellableFile {
|
||||
impl<R: Read> Read for CancellableFile<R> {
|
||||
fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
|
||||
if self.cancellation.is_cancelled() {
|
||||
return Err(io::Error::other("制品解析已取消"));
|
||||
@@ -44,6 +44,14 @@ impl Read for CancellableFile {
|
||||
self.file.read(buffer)
|
||||
}
|
||||
}
|
||||
impl<R: Seek> Seek for CancellableFile<R> {
|
||||
fn seek(&mut self, from: SeekFrom) -> io::Result<u64> {
|
||||
if self.cancellation.is_cancelled() {
|
||||
return Err(io::Error::other("制品解析已取消"));
|
||||
}
|
||||
self.file.seek(from)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn invalid() -> WorkerTaskError {
|
||||
WorkerTaskError::safe("Antigravity 发布包核验失败")
|
||||
@@ -131,10 +139,6 @@ impl<'a> RemoteArtifact<'a> {
|
||||
}
|
||||
Ok(body.into())
|
||||
}
|
||||
|
||||
pub(crate) async fn prefix(&self, maximum: u64) -> Result<Bytes, WorkerTaskError> {
|
||||
self.read(0, self.size.min(maximum)).await
|
||||
}
|
||||
}
|
||||
|
||||
/// 只缓存目录和所需条目,未下载的区间不能被当作零填充数据读取
|
||||
@@ -189,7 +193,7 @@ impl<'a> RemoteZip<'a> {
|
||||
|
||||
fn archive(
|
||||
&self,
|
||||
member: Option<(u64, Bytes)>,
|
||||
member: Vec<(u64, Bytes)>,
|
||||
) -> Result<zip::ZipArchive<Segments>, WorkerTaskError> {
|
||||
let mut chunks = vec![(
|
||||
self.artifact.size - self.tail.len() as u64,
|
||||
@@ -209,12 +213,22 @@ impl<'a> RemoteZip<'a> {
|
||||
name: &str,
|
||||
maximum: usize,
|
||||
) -> Result<Vec<u8>, WorkerTaskError> {
|
||||
let archive = self.archive(None)?;
|
||||
self.inspect(name, maximum as u64, move |reader| bounded(reader, maximum))
|
||||
.await
|
||||
}
|
||||
|
||||
pub(crate) async fn inspect<T: Send + 'static>(
|
||||
&self,
|
||||
name: &str,
|
||||
maximum: u64,
|
||||
inspect: impl FnOnce(&mut dyn Read) -> Result<T, WorkerTaskError> + Send + 'static,
|
||||
) -> Result<T, WorkerTaskError> {
|
||||
let archive = self.archive(Vec::new())?;
|
||||
let index = archive.index_for_name(name).ok_or_else(invalid)?;
|
||||
let entry = archive
|
||||
.by_index_data(index)
|
||||
.map_err(|e| invalid().with_source(e))?;
|
||||
if entry.size() > maximum as u64 || entry.is_dir() || entry.is_symlink() {
|
||||
if entry.size() > maximum || entry.is_dir() || entry.is_symlink() {
|
||||
return Err(invalid());
|
||||
}
|
||||
let start = entry.header_start();
|
||||
@@ -224,12 +238,25 @@ impl<'a> RemoteZip<'a> {
|
||||
.checked_add(30 + 2 * u64::from(u16::MAX))
|
||||
.ok_or_else(invalid)?
|
||||
.min(self.artifact.size.checked_sub(start).ok_or_else(invalid)?);
|
||||
let member = self.artifact.read(start, length).await?;
|
||||
let mut archive = self.archive(Some((start, member)))?;
|
||||
let file = archive
|
||||
.by_name(name)
|
||||
.map_err(|e| invalid().with_source(e))?;
|
||||
bounded(file, maximum)
|
||||
let mut members = Vec::new();
|
||||
let mut offset = start;
|
||||
while offset < start + length {
|
||||
let length = (start + length - offset).min(MAX_RANGE_BYTES);
|
||||
members.push((offset, self.artifact.read(offset, length).await?));
|
||||
offset += length;
|
||||
}
|
||||
let archive = self.archive(members)?;
|
||||
let (reader, _guard) = CancellableFile::new(archive.into_inner());
|
||||
let name = name.to_owned();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let mut archive = zip::ZipArchive::new(reader).map_err(|e| invalid().with_source(e))?;
|
||||
let mut file = archive
|
||||
.by_name(&name)
|
||||
.map_err(|e| invalid().with_source(e))?;
|
||||
inspect(&mut file)
|
||||
})
|
||||
.await
|
||||
.map_err(|e| invalid().with_source(e))?
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! 从官方发布包核对版本和目标平台,不执行下载的程序或发起模型请求
|
||||
|
||||
use super::archive::{CancellableFile, RemoteArtifact, RemoteZip, bounded, download, invalid};
|
||||
use super::archive::{CancellableFile, RemoteZip, bounded, download, invalid};
|
||||
use super::selection::{Architecture, ClientKind, Platform, ReleaseTarget};
|
||||
use gateway_core::task::WorkerTaskError;
|
||||
use std::io::Read;
|
||||
@@ -14,8 +14,8 @@ pub(crate) struct Release {
|
||||
pub(crate) sha512: Option<String>,
|
||||
}
|
||||
|
||||
const MAX_ASAR_BYTES: usize = 16 * 1024 * 1024;
|
||||
const MAX_BINARY_BYTES: u64 = 512 * 1024 * 1024;
|
||||
pub(super) const MAX_ASAR_BYTES: usize = 16 * 1024 * 1024;
|
||||
pub(super) const MAX_BINARY_BYTES: u64 = 512 * 1024 * 1024;
|
||||
|
||||
pub(crate) async fn verify(
|
||||
client: &reqwest::Client,
|
||||
@@ -23,7 +23,7 @@ pub(crate) async fn verify(
|
||||
version: &str,
|
||||
url: &str,
|
||||
sha512: Option<&str>,
|
||||
) -> Result<(), WorkerTaskError> {
|
||||
) -> Result<u64, WorkerTaskError> {
|
||||
match (target.client, target.platform) {
|
||||
(ClientKind::Desktop, Platform::Macos) => {
|
||||
let url = url.strip_suffix(".dmg").ok_or_else(invalid)?;
|
||||
@@ -40,14 +40,14 @@ pub(crate) async fn verify(
|
||||
let executable = archive
|
||||
.read("Antigravity.app/Contents/MacOS/Antigravity", 1024 * 1024)
|
||||
.await?;
|
||||
architecture(&executable, target)
|
||||
}
|
||||
(ClientKind::Desktop, Platform::Windows) => {
|
||||
let artifact = RemoteArtifact::open(client, url.to_owned()).await?;
|
||||
let header = artifact.prefix(1024 * 1024).await?;
|
||||
let (offset, size) = pe_resources(&header)?;
|
||||
let resources = artifact.read(offset, size).await?;
|
||||
windows_version(&resources, version)
|
||||
architecture(&executable, target)?;
|
||||
archive
|
||||
.inspect(
|
||||
"Antigravity.app/Contents/Resources/bin/language_server",
|
||||
MAX_BINARY_BYTES,
|
||||
move |reader| verify_binary(reader, target, None),
|
||||
)
|
||||
.await
|
||||
}
|
||||
_ => {
|
||||
let file = download(client, url, sha512).await?;
|
||||
@@ -55,8 +55,12 @@ pub(crate) async fn verify(
|
||||
let (file, _guard) = CancellableFile::new(file);
|
||||
let version = version.to_owned();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
if target.client == ClientKind::Cli && target.platform == Platform::Windows {
|
||||
verify_binary(file, target, &version)
|
||||
if target.platform == Platform::Windows {
|
||||
if target.client == ClientKind::Cli {
|
||||
verify_binary(file, target, Some(&version))
|
||||
} else {
|
||||
super::installer::verify(file, target, &version)
|
||||
}
|
||||
} else {
|
||||
verify_tar(file, target, &version)
|
||||
}
|
||||
@@ -124,11 +128,12 @@ pub(crate) fn verify_tar(
|
||||
file: impl Read,
|
||||
target: ReleaseTarget,
|
||||
version: &str,
|
||||
) -> Result<(), WorkerTaskError> {
|
||||
) -> Result<u64, WorkerTaskError> {
|
||||
let decoder = flate2::read::GzDecoder::new(file);
|
||||
let mut archive = tar::Archive::new(decoder.take(2 * 1024 * 1024 * 1024));
|
||||
let mut found_version = false;
|
||||
let mut found_executable = false;
|
||||
let mut changelist = None;
|
||||
for (index, entry) in archive
|
||||
.entries()
|
||||
.map_err(|e| invalid().with_source(e))?
|
||||
@@ -153,7 +158,7 @@ pub(crate) fn verify_tar(
|
||||
if found_executable || entry.size() > MAX_BINARY_BYTES {
|
||||
return Err(invalid());
|
||||
}
|
||||
verify_binary(&mut entry, target, version)?;
|
||||
changelist = Some(verify_binary(&mut entry, target, Some(version))?);
|
||||
found_version = true;
|
||||
found_executable = true;
|
||||
} else if target.client == ClientKind::Desktop {
|
||||
@@ -163,6 +168,11 @@ pub(crate) fn verify_tar(
|
||||
return Err(invalid());
|
||||
}
|
||||
found_version = true;
|
||||
} else if path.ends_with("resources/bin/language_server") {
|
||||
if changelist.is_some() || entry.size() > MAX_BINARY_BYTES {
|
||||
return Err(invalid());
|
||||
}
|
||||
changelist = Some(verify_binary(&mut entry, target, None)?);
|
||||
} else if name == "antigravity" {
|
||||
if found_executable {
|
||||
return Err(invalid());
|
||||
@@ -177,7 +187,7 @@ pub(crate) fn verify_tar(
|
||||
}
|
||||
}
|
||||
if found_version && found_executable {
|
||||
Ok(())
|
||||
changelist.ok_or_else(invalid)
|
||||
} else {
|
||||
Err(invalid())
|
||||
}
|
||||
@@ -186,24 +196,54 @@ pub(crate) fn verify_tar(
|
||||
pub(crate) fn verify_binary(
|
||||
mut reader: impl Read,
|
||||
target: ReleaseTarget,
|
||||
version: &str,
|
||||
) -> Result<(), WorkerTaskError> {
|
||||
version: Option<&str>,
|
||||
) -> Result<u64, WorkerTaskError> {
|
||||
let mut header = [0; 1024];
|
||||
reader
|
||||
.read_exact(&mut header)
|
||||
.map_err(|e| invalid().with_source(e))?;
|
||||
architecture(&header, target)?;
|
||||
// 官方 CLI 把版本文件嵌入 Go 制品,保留其换行与终止字节避免匹配依赖版本
|
||||
let marker = format!("\0{version}\n\0").into_bytes();
|
||||
let marker = version.map(|version| format!("\0{version}\n\0").into_bytes());
|
||||
// Go 制品的源码根目录携带实际 CL;发布目录编号、依赖版本不能代替这个值
|
||||
const PREFIX: &[u8] = b"googlefile:/google_src/files/";
|
||||
const SUFFIX: &[u8] = b"/depot/";
|
||||
let overlap = marker
|
||||
.as_ref()
|
||||
.map_or(0, Vec::len)
|
||||
.max(PREFIX.len() + 20 + SUFFIX.len());
|
||||
let mut tail = header.to_vec();
|
||||
let mut chunk = [0; 64 * 1024];
|
||||
let mut count = 1024u64;
|
||||
let mut found = false;
|
||||
let mut found = marker.is_none();
|
||||
let mut changelist = None;
|
||||
loop {
|
||||
if tail.windows(marker.len()).any(|v| v == marker) {
|
||||
if marker
|
||||
.as_ref()
|
||||
.is_some_and(|marker| tail.windows(marker.len()).any(|v| v == marker))
|
||||
{
|
||||
found = true;
|
||||
}
|
||||
let keep = tail.len().saturating_sub(marker.len());
|
||||
for (offset, candidate) in tail.windows(PREFIX.len()).enumerate() {
|
||||
if candidate != PREFIX {
|
||||
continue;
|
||||
}
|
||||
let rest = &tail[offset + PREFIX.len()..];
|
||||
let digits = rest.iter().take_while(|c| c.is_ascii_digit()).count();
|
||||
if !rest[digits..].starts_with(SUFFIX) {
|
||||
continue;
|
||||
}
|
||||
let value = std::str::from_utf8(&rest[..digits])
|
||||
.ok()
|
||||
.and_then(|s| s.parse::<u64>().ok())
|
||||
.filter(|value| *value > 0)
|
||||
.ok_or_else(invalid)?;
|
||||
if changelist.is_some_and(|previous| previous != value) {
|
||||
return Err(invalid());
|
||||
}
|
||||
changelist = Some(value);
|
||||
}
|
||||
let keep = tail.len().saturating_sub(overlap);
|
||||
tail.drain(..keep);
|
||||
let size = reader
|
||||
.read(&mut chunk)
|
||||
@@ -217,7 +257,11 @@ pub(crate) fn verify_binary(
|
||||
}
|
||||
tail.extend_from_slice(&chunk[..size]);
|
||||
}
|
||||
if found { Ok(()) } else { Err(invalid()) }
|
||||
if found {
|
||||
changelist.ok_or_else(invalid)
|
||||
} else {
|
||||
Err(invalid())
|
||||
}
|
||||
}
|
||||
|
||||
fn pe_offset(body: &[u8]) -> Result<usize, WorkerTaskError> {
|
||||
@@ -231,52 +275,6 @@ fn pe_offset(body: &[u8]) -> Result<usize, WorkerTaskError> {
|
||||
Ok(offset)
|
||||
}
|
||||
|
||||
pub(crate) fn pe_resources(body: &[u8]) -> Result<(u64, u64), WorkerTaskError> {
|
||||
let pe = pe_offset(body)?;
|
||||
let count = u16_at(body, pe + 6)? as usize;
|
||||
let start = pe + 24 + u16_at(body, pe + 20)? as usize;
|
||||
for i in 0..count.min(96) {
|
||||
let section = start + i * 40;
|
||||
if body.get(section..section + 8) == Some(b".rsrc\0\0\0") {
|
||||
return Ok((
|
||||
u64::from(u32_at(body, section + 20)?),
|
||||
u64::from(u32_at(body, section + 16)?),
|
||||
));
|
||||
}
|
||||
}
|
||||
Err(invalid())
|
||||
}
|
||||
|
||||
pub(crate) fn windows_version(body: &[u8], version: &str) -> Result<(), WorkerTaskError> {
|
||||
let parts: Vec<u16> = version
|
||||
.split('.')
|
||||
.map(str::parse)
|
||||
.collect::<Result<_, _>>()
|
||||
.map_err(|_| invalid())?;
|
||||
if parts.len() != 3 {
|
||||
return Err(invalid());
|
||||
}
|
||||
let high = u32::from(parts[0]) << 16 | u32::from(parts[1]);
|
||||
let low = u32::from(parts[2]) << 16;
|
||||
let mut found = false;
|
||||
for (offset, bytes) in body.windows(8).enumerate() {
|
||||
// 官方 Windows 安装器的 dwStrucVersion 为零,也接受标准的 0x00010000
|
||||
if bytes.starts_with(b"\xbd\x04\xef\xfe")
|
||||
&& matches!(u32_at(body, offset + 4)?, 0 | 0x0001_0000)
|
||||
{
|
||||
if u32_at(body, offset + 8)? != high
|
||||
|| u32_at(body, offset + 12)? != low
|
||||
|| u32_at(body, offset + 16)? != high
|
||||
|| u32_at(body, offset + 20)? != low
|
||||
{
|
||||
return Err(invalid());
|
||||
}
|
||||
found = true;
|
||||
}
|
||||
}
|
||||
if found { Ok(()) } else { Err(invalid()) }
|
||||
}
|
||||
|
||||
fn u16_at(body: &[u8], offset: usize) -> Result<u16, WorkerTaskError> {
|
||||
Ok(u16::from_le_bytes(
|
||||
body.get(offset..offset + 2)
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
//! 读取 Windows 安装器内的 7z 应用包,将版本与 language server 的 CL 绑定核验
|
||||
|
||||
use super::archive::{bounded, invalid};
|
||||
use super::artifact::{MAX_ASAR_BYTES, MAX_BINARY_BYTES, asar_version, verify_binary};
|
||||
use super::selection::ReleaseTarget;
|
||||
use gateway_core::task::WorkerTaskError;
|
||||
use std::io::{self, Read, Seek, SeekFrom};
|
||||
|
||||
pub(crate) fn verify(
|
||||
mut file: impl Read + Seek,
|
||||
target: ReleaseTarget,
|
||||
version: &str,
|
||||
) -> Result<u64, WorkerTaskError> {
|
||||
let mut prefix = Vec::new();
|
||||
file.by_ref()
|
||||
.take(2 * 1024 * 1024)
|
||||
.read_to_end(&mut prefix)
|
||||
.map_err(|e| invalid().with_source(e))?;
|
||||
let start = prefix
|
||||
.windows(8)
|
||||
.position(|bytes| bytes == b"7z\xbc\xaf\x27\x1c\0\x04")
|
||||
.ok_or_else(invalid)? as u64;
|
||||
file.seek(SeekFrom::Start(start))
|
||||
.map_err(|e| invalid().with_source(e))?;
|
||||
let source = Payload { file, start };
|
||||
let mut archive = sevenz_rust2::ArchiveReader::new_with_memory_limit(
|
||||
source,
|
||||
sevenz_rust2::Password::empty(),
|
||||
// 官方 NSIS 应用包使用 256 MiB 字典,另预留 1 MiB 解码状态,线程限制为一个
|
||||
257 * 1024,
|
||||
)
|
||||
.map_err(|e| invalid().with_source(e))?;
|
||||
archive.set_thread_count(1);
|
||||
let files = &archive.archive().files;
|
||||
if files.len() > 16_384
|
||||
|| files
|
||||
.iter()
|
||||
.try_fold(0u64, |sum, file| sum.checked_add(file.size))
|
||||
.is_none_or(|size| size > 2 * 1024 * 1024 * 1024)
|
||||
{
|
||||
return Err(invalid());
|
||||
}
|
||||
let mut found_version = false;
|
||||
let mut changelist = None;
|
||||
archive
|
||||
.for_each_entries(|entry, reader| {
|
||||
let result = (|| {
|
||||
if entry.is_directory || entry.is_anti_item {
|
||||
return Ok(());
|
||||
}
|
||||
match entry.name.as_str() {
|
||||
"resources/app.asar" => {
|
||||
if found_version
|
||||
|| entry.size > MAX_ASAR_BYTES as u64
|
||||
|| asar_version(&bounded(reader, MAX_ASAR_BYTES)?)? != version
|
||||
{
|
||||
return Err(invalid());
|
||||
}
|
||||
found_version = true;
|
||||
}
|
||||
"resources/bin/language_server.exe" => {
|
||||
if changelist.is_some() || entry.size > MAX_BINARY_BYTES {
|
||||
return Err(invalid());
|
||||
}
|
||||
changelist = Some(verify_binary(reader, target, None)?);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Ok(())
|
||||
})();
|
||||
result.map_err(|_| {
|
||||
sevenz_rust2::Error::Other("Antigravity Windows 制品内容无效".into())
|
||||
})?;
|
||||
Ok(true)
|
||||
})
|
||||
.map_err(|e| invalid().with_source(e))?;
|
||||
if found_version {
|
||||
changelist.ok_or_else(invalid)
|
||||
} else {
|
||||
Err(invalid())
|
||||
}
|
||||
}
|
||||
|
||||
/// 安装器前缀不属于 7z,解码器的偏移必须以实际签名为零点
|
||||
struct Payload<R> {
|
||||
file: R,
|
||||
start: u64,
|
||||
}
|
||||
impl<R: Read> Read for Payload<R> {
|
||||
fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
|
||||
self.file.read(buffer)
|
||||
}
|
||||
}
|
||||
impl<R: Seek> Seek for Payload<R> {
|
||||
fn seek(&mut self, from: SeekFrom) -> io::Result<u64> {
|
||||
let from = match from {
|
||||
SeekFrom::Start(offset) => SeekFrom::Start(
|
||||
self.start
|
||||
.checked_add(offset)
|
||||
.ok_or(io::ErrorKind::InvalidInput)?,
|
||||
),
|
||||
other => other,
|
||||
};
|
||||
self.file
|
||||
.seek(from)?
|
||||
.checked_sub(self.start)
|
||||
.ok_or_else(|| io::ErrorKind::InvalidInput.into())
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
pub(crate) mod archive;
|
||||
pub(crate) mod artifact;
|
||||
pub(crate) mod installer;
|
||||
pub(crate) mod release;
|
||||
pub(crate) mod selection;
|
||||
pub(crate) mod verification;
|
||||
@@ -17,17 +18,9 @@ pub(crate) fn resolve(
|
||||
releases: &ReleaseService,
|
||||
) -> Result<ClientProfile, ProviderAdminError> {
|
||||
let selection = Selection::parse(configuration)?;
|
||||
Ok(selection.resolve(
|
||||
releases
|
||||
.snapshot(selection.target())
|
||||
.version(selection.client),
|
||||
))
|
||||
Ok(releases.snapshot(selection.target()).profile(&selection))
|
||||
}
|
||||
pub(crate) fn default_profile(releases: &ReleaseService) -> ClientProfile {
|
||||
let selection = Selection::default();
|
||||
selection.resolve(
|
||||
releases
|
||||
.snapshot(selection.target())
|
||||
.version(selection.client),
|
||||
)
|
||||
releases.snapshot(selection.target()).profile(&selection)
|
||||
}
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
//! 按客户端、平台与架构刷新官方发布资料,失败时保留上次成功结果
|
||||
//! 跟踪官方发布资料并整组切换已核验画像,更新失败时保留当前画像
|
||||
|
||||
pub(crate) use super::artifact::Release;
|
||||
use super::selection::{Architecture, ClientKind, Platform, ReleaseTarget, valid_version};
|
||||
use super::selection::{
|
||||
Architecture, ClientKind, ClientProfile, Platform, ReleaseTarget, Selection, valid_version,
|
||||
};
|
||||
use super::verification::{VerificationCache, VerifiedArtifact};
|
||||
use crate::ConfigError;
|
||||
use chrono::{DateTime, Utc};
|
||||
use chrono::{DateTime, TimeDelta, Utc};
|
||||
use futures::{StreamExt, future::BoxFuture, stream};
|
||||
use gateway_core::task::{ScheduledTask, WorkerCycleContext, WorkerTaskError};
|
||||
use gateway_core::{provider_ports::ProviderArtifactProfileCachePort, routing::ProviderKind};
|
||||
@@ -20,32 +22,49 @@ const DESKTOP_PREFIX: &str = "https://storage.googleapis.com/antigravity-public/
|
||||
const CLI_MANIFESTS: &str =
|
||||
"https://antigravity-cli-auto-updater-974169037036.us-central1.run.app/manifests";
|
||||
const MAX_RELEASE_BYTES: usize = 2 * 1024 * 1024;
|
||||
const RELEASE_CHECK_INTERVAL: TimeDelta = TimeDelta::hours(1);
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
pub(crate) struct ReleaseSnapshot {
|
||||
pub(crate) release: Option<Release>,
|
||||
pub(crate) candidate: Option<Release>,
|
||||
pub(crate) checked: Option<DateTime<Utc>>,
|
||||
pub(crate) failed: bool,
|
||||
pub(crate) discovery_failed: bool,
|
||||
pub(crate) verification_failed: bool,
|
||||
verified: Option<VerifiedArtifact>,
|
||||
}
|
||||
impl ReleaseSnapshot {
|
||||
pub(crate) fn profile(&self, selection: &Selection) -> ClientProfile {
|
||||
match &self.verified {
|
||||
Some(verified) => {
|
||||
selection.resolve(&verified.release.version, Some(verified.changelist))
|
||||
}
|
||||
None => selection.resolve(selection.client.baseline(), None),
|
||||
}
|
||||
}
|
||||
pub(crate) fn verified_at(&self, version: &str) -> Option<DateTime<Utc>> {
|
||||
self.verified
|
||||
.as_ref()
|
||||
.filter(|verified| {
|
||||
verified.release.version == version
|
||||
&& self.release.as_ref() == Some(&verified.release)
|
||||
})
|
||||
.filter(|verified| verified.release.version == version)
|
||||
.map(|v| v.verified_at)
|
||||
}
|
||||
pub(crate) fn version(&self, client: ClientKind) -> &str {
|
||||
self.release
|
||||
.as_ref()
|
||||
.map_or(client.baseline().version, |release| {
|
||||
release.version.as_str()
|
||||
})
|
||||
pub(crate) fn pending_verification(&self) -> bool {
|
||||
self.candidate.is_some()
|
||||
&& self.candidate.as_ref() != self.verified.as_ref().map(|artifact| &artifact.release)
|
||||
}
|
||||
}
|
||||
|
||||
fn targets(client: ClientKind) -> impl Iterator<Item = ReleaseTarget> {
|
||||
[Platform::Macos, Platform::Linux, Platform::Windows]
|
||||
.into_iter()
|
||||
.flat_map(move |platform| {
|
||||
[Architecture::Arm64, Architecture::Amd64].map(move |arch| ReleaseTarget {
|
||||
client,
|
||||
platform,
|
||||
arch,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) struct ReleaseService {
|
||||
client: reqwest::Client,
|
||||
state: RwLock<BTreeMap<ReleaseTarget, ReleaseSnapshot>>,
|
||||
@@ -85,16 +104,40 @@ impl ReleaseService {
|
||||
.cloned()
|
||||
.unwrap_or_default()
|
||||
}
|
||||
pub(crate) fn publish(&self, target: ReleaseTarget, result: Option<Release>) {
|
||||
pub(crate) async fn restore(&self) {
|
||||
let mut loads = stream::iter(targets(ClientKind::Desktop).chain(targets(ClientKind::Cli)))
|
||||
.map(|target| async move { (target, self.verification.load(target).await) })
|
||||
.buffer_unordered(3);
|
||||
while let Some((target, result)) = loads.next().await {
|
||||
match result {
|
||||
Ok(Some(verified)) => {
|
||||
self.state
|
||||
.write()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.entry(target)
|
||||
.or_default()
|
||||
.verified = Some(verified);
|
||||
}
|
||||
Ok(None) => {}
|
||||
Err(error) => {
|
||||
tracing::warn!(?target, %error, "Antigravity release cache could not be restored")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
pub(crate) fn observe(&self, target: ReleaseTarget, result: Option<Release>) {
|
||||
let mut state = self
|
||||
.state
|
||||
.write()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let entry = state.entry(target).or_default();
|
||||
entry.checked = Some(Utc::now());
|
||||
entry.failed = result.is_none();
|
||||
entry.discovery_failed = result.is_none();
|
||||
if let Some(release) = result {
|
||||
entry.release = Some(release);
|
||||
if entry.candidate.as_ref() != Some(&release) {
|
||||
entry.verification_failed = false;
|
||||
}
|
||||
entry.candidate = Some(release);
|
||||
}
|
||||
}
|
||||
async fn fetch(&self, url: &str) -> Result<Vec<u8>, WorkerTaskError> {
|
||||
@@ -124,15 +167,16 @@ impl ReleaseService {
|
||||
}
|
||||
pub(crate) async fn update(&self) -> Result<(), WorkerTaskError> {
|
||||
let due = {
|
||||
let now = Utc::now();
|
||||
let state = self
|
||||
.state
|
||||
.read()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
state.is_empty()
|
||||
|| state.values().any(|s| {
|
||||
s.failed
|
||||
s.discovery_failed
|
||||
|| s.checked
|
||||
.is_none_or(|at| (Utc::now() - at).num_seconds() >= 86400)
|
||||
.is_none_or(|at| now - at >= RELEASE_CHECK_INTERVAL)
|
||||
})
|
||||
};
|
||||
let mut first_error = if due {
|
||||
@@ -150,23 +194,31 @@ impl ReleaseService {
|
||||
let mut verification = stream::iter(targets)
|
||||
.map(|target| async move {
|
||||
let snapshot = self.snapshot(target);
|
||||
let Some(release) = snapshot.release.as_ref() else {
|
||||
let Some(release) = snapshot.candidate.as_ref() else {
|
||||
return Ok(());
|
||||
};
|
||||
let verified = self
|
||||
.verification
|
||||
.verify(&self.client, target, release, snapshot.verified.as_ref())
|
||||
.await?;
|
||||
.await;
|
||||
let mut state = self
|
||||
.state
|
||||
.write()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
if let Some(current) = state.get_mut(&target)
|
||||
&& current.release.as_ref() == Some(&verified.release)
|
||||
{
|
||||
current.verified = Some(verified);
|
||||
let Some(current) = state
|
||||
.get_mut(&target)
|
||||
.filter(|current| current.candidate.as_ref() == Some(release))
|
||||
else {
|
||||
return Ok(());
|
||||
};
|
||||
current.verification_failed = verified.is_err();
|
||||
match verified {
|
||||
Ok(verified) => {
|
||||
current.verified = Some(verified);
|
||||
Ok(())
|
||||
}
|
||||
Err(error) => Err(error),
|
||||
}
|
||||
Ok::<_, WorkerTaskError>(())
|
||||
})
|
||||
.buffer_unordered(2);
|
||||
while let Some(result) = verification.next().await {
|
||||
@@ -179,39 +231,23 @@ impl ReleaseService {
|
||||
async fn refresh(&self) -> Result<(), WorkerTaskError> {
|
||||
let page = self.fetch(DOWNLOAD_PAGE).await;
|
||||
let mut first_error = None;
|
||||
for platform in [Platform::Macos, Platform::Linux, Platform::Windows] {
|
||||
for arch in [Architecture::Arm64, Architecture::Amd64] {
|
||||
let target = ReleaseTarget {
|
||||
client: ClientKind::Desktop,
|
||||
platform,
|
||||
arch,
|
||||
};
|
||||
let release = page
|
||||
.as_ref()
|
||||
.ok()
|
||||
.and_then(|page| std::str::from_utf8(page).ok())
|
||||
.and_then(|page| parse_desktop(page, target));
|
||||
if release.is_none() {
|
||||
first_error = Some(WorkerTaskError::safe(
|
||||
"无法解析 Antigravity Desktop 发布资料",
|
||||
));
|
||||
}
|
||||
self.publish(target, release);
|
||||
for target in targets(ClientKind::Desktop) {
|
||||
let release = page
|
||||
.as_ref()
|
||||
.ok()
|
||||
.and_then(|page| std::str::from_utf8(page).ok())
|
||||
.and_then(|page| parse_desktop(page, target));
|
||||
if release.is_none() {
|
||||
first_error = Some(WorkerTaskError::safe(
|
||||
"无法解析 Antigravity Desktop 发布资料",
|
||||
));
|
||||
}
|
||||
self.observe(target, release);
|
||||
}
|
||||
if let Err(error) = page {
|
||||
first_error = Some(error);
|
||||
}
|
||||
let targets = [Platform::Macos, Platform::Linux, Platform::Windows]
|
||||
.into_iter()
|
||||
.flat_map(|platform| {
|
||||
[Architecture::Arm64, Architecture::Amd64].map(move |arch| ReleaseTarget {
|
||||
client: ClientKind::Cli,
|
||||
platform,
|
||||
arch,
|
||||
})
|
||||
});
|
||||
let mut updates = stream::iter(targets)
|
||||
let mut updates = stream::iter(targets(ClientKind::Cli))
|
||||
.map(|target| async move {
|
||||
let url = format!(
|
||||
"{CLI_MANIFESTS}/{}_{}.json",
|
||||
@@ -222,7 +258,7 @@ impl ReleaseService {
|
||||
.fetch(&url)
|
||||
.await
|
||||
.and_then(|body| parse_cli(&body, target));
|
||||
self.publish(target, result.as_ref().ok().cloned());
|
||||
self.observe(target, result.as_ref().ok().cloned());
|
||||
result
|
||||
})
|
||||
.buffer_unordered(3);
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
//! 客户端选择与冻结身份,不读取网络或运行时设置
|
||||
|
||||
use chrono::{DateTime, TimeZone, Utc};
|
||||
use gateway_admin::ports::provider::{ProviderAdminError, ProviderAdminErrorKind};
|
||||
use gateway_core::account::OpaqueProviderData;
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -12,10 +11,6 @@ pub(crate) enum ClientKind {
|
||||
Desktop,
|
||||
Cli,
|
||||
}
|
||||
pub(crate) struct ClientBuild {
|
||||
pub(crate) version: &'static str,
|
||||
changelist: u64,
|
||||
}
|
||||
impl ClientKind {
|
||||
pub(crate) const fn product(self) -> &'static str {
|
||||
match self {
|
||||
@@ -23,17 +18,10 @@ impl ClientKind {
|
||||
Self::Cli => "Antigravity CLI",
|
||||
}
|
||||
}
|
||||
pub(crate) const fn baseline(self) -> ClientBuild {
|
||||
// 版本与 CL 成对取自官方二进制及已认证请求,下载目录的编号不是 CL
|
||||
pub(crate) const fn baseline(self) -> &'static str {
|
||||
match self {
|
||||
Self::Desktop => ClientBuild {
|
||||
version: "2.34.0",
|
||||
changelist: 1_026_637_980,
|
||||
},
|
||||
Self::Cli => ClientBuild {
|
||||
version: "1.5.17",
|
||||
changelist: 1_029_496_841,
|
||||
},
|
||||
Self::Desktop => "2.37.0",
|
||||
Self::Cli => "1.5.23",
|
||||
}
|
||||
}
|
||||
const fn subclient(self) -> &'static str {
|
||||
@@ -142,19 +130,15 @@ impl Selection {
|
||||
arch: self.arch.unwrap_or_else(|| self.platform.default_arch()),
|
||||
}
|
||||
}
|
||||
pub(crate) fn resolve(&self, latest: &str) -> ClientProfile {
|
||||
pub(crate) fn resolve(&self, latest: &str, changelist: Option<u64>) -> ClientProfile {
|
||||
let version = self.client_version.as_deref().unwrap_or(latest);
|
||||
let baseline = self.client.baseline();
|
||||
ClientProfile {
|
||||
client: self.client,
|
||||
platform: self.platform,
|
||||
arch: self.target().arch,
|
||||
client_version: version.into(),
|
||||
// 发布资料只有版本号;未知版本不沿用另一个版本的构建号
|
||||
changelist: match (self.client, version) {
|
||||
(ClientKind::Cli, "1.5.15") => Some(1_027_820_220),
|
||||
_ => (version == baseline.version).then_some(baseline.changelist),
|
||||
},
|
||||
// 固定版本不能借用其他版本制品中的 CL
|
||||
changelist: changelist.filter(|cl| version == latest && *cl > 0),
|
||||
system_prompt: self
|
||||
.system_prompt
|
||||
.as_deref()
|
||||
@@ -195,22 +179,6 @@ impl ClientProfile {
|
||||
pub(crate) fn frozen(&self) -> OpaqueProviderData {
|
||||
object(json!(self))
|
||||
}
|
||||
pub(crate) fn verified_at(&self) -> Option<DateTime<Utc>> {
|
||||
let baseline = self.client.baseline();
|
||||
if self.client_version != baseline.version || self.changelist != Some(baseline.changelist) {
|
||||
return None;
|
||||
}
|
||||
// 对应平台的 OAuth HTTP 请求已实测;此时间不代表 TLS 指纹或发布资料轮询时间
|
||||
match (self.client, self.platform, self.arch) {
|
||||
(ClientKind::Desktop, Platform::Macos, Architecture::Arm64) => {
|
||||
Utc.with_ymd_and_hms(2026, 11, 23, 11, 11, 15).single()
|
||||
}
|
||||
(ClientKind::Cli, Platform::Linux, Architecture::Amd64) => {
|
||||
Utc.with_ymd_and_hms(2026, 11, 26, 16, 1, 16).single()
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
pub(crate) fn client_identifier(&self) -> String {
|
||||
format!(
|
||||
"antigravity/{}/{}",
|
||||
@@ -232,6 +200,7 @@ impl ClientProfile {
|
||||
// CLI 的个人 OAuth 身份携带此字段;Desktop 的已认证请求未携带
|
||||
user_agent.push_str("; auth_method=consumer");
|
||||
}
|
||||
// datacollection_opt_in=false 属于官方管理员强制关闭遥测的策略,不能由普通遥测开关推导
|
||||
user_agent.push(')');
|
||||
user_agent
|
||||
}
|
||||
@@ -251,7 +220,7 @@ fn invalid() -> ProviderAdminError {
|
||||
.with_public_message("Antigravity 客户端配置无效;固定版本须为三段数字")
|
||||
}
|
||||
|
||||
// AGY CLI 1.5.15 内置身份模板的默认交互分支;工具和工作区模板由各客户端管理
|
||||
// AGY CLI 1.5.23 内置身份模板的默认交互分支;工具和工作区模板由各客户端管理
|
||||
pub(crate) const DEFAULT_SYSTEM_PROMPT: &str = "You are Antigravity, a powerful agentic AI coding assistant designed by the Google Deepmind team working on Advanced Agentic Coding.\nYou are pair programming with a USER to solve their coding task. The task may require creating a new codebase, modifying or debugging an existing codebase, or simply answering a question.";
|
||||
|
||||
fn validate_system_prompt(prompt: &str) -> Result<(), ProviderAdminError> {
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
use super::{
|
||||
artifact::{self, Release},
|
||||
selection::ReleaseTarget,
|
||||
selection::{ReleaseTarget, valid_version},
|
||||
};
|
||||
use chrono::{DateTime, Utc};
|
||||
use gateway_core::{
|
||||
@@ -23,8 +23,9 @@ const RENEW_INTERVAL: Duration = Duration::from_secs(86400);
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct VerifiedArtifact {
|
||||
pub(crate) release: Release,
|
||||
pub(crate) changelist: u64,
|
||||
pub(crate) verified_at: DateTime<Utc>,
|
||||
renewed_at: Instant,
|
||||
renewed_at: Option<Instant>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
@@ -32,6 +33,7 @@ pub(crate) struct VerifiedArtifact {
|
||||
struct Payload {
|
||||
target: ReleaseTarget,
|
||||
release: Release,
|
||||
changelist: u64,
|
||||
}
|
||||
|
||||
pub(crate) struct VerificationCache {
|
||||
@@ -46,6 +48,40 @@ impl VerificationCache {
|
||||
Self { provider, cache }
|
||||
}
|
||||
|
||||
pub(crate) async fn load(
|
||||
&self,
|
||||
target: ReleaseTarget,
|
||||
) -> Result<Option<VerifiedArtifact>, WorkerTaskError> {
|
||||
let key = key(target);
|
||||
let Some(cached) = self
|
||||
.cache
|
||||
.read(&self.provider, &key)
|
||||
.await
|
||||
.map_err(|e| error().with_source(e))?
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
let payload: Payload = serde_json::from_value(serde_json::Value::Object(
|
||||
cached.profile().expose_to_provider().clone(),
|
||||
))
|
||||
.map_err(|e| error().with_source(e))?;
|
||||
if cached.provider_kind() != &self.provider
|
||||
|| cached.artifact_key() != key
|
||||
|| payload.target != target
|
||||
|| payload.changelist == 0
|
||||
|| !valid_version(&payload.release.version)
|
||||
|| cached.artifact_sequence() != sequence(&payload.release.version)?
|
||||
{
|
||||
return Err(error());
|
||||
}
|
||||
Ok(Some(VerifiedArtifact {
|
||||
release: payload.release,
|
||||
changelist: payload.changelist,
|
||||
verified_at: cached.verified_at().into(),
|
||||
renewed_at: None,
|
||||
}))
|
||||
}
|
||||
|
||||
pub(crate) async fn verify(
|
||||
&self,
|
||||
client: &reqwest::Client,
|
||||
@@ -54,46 +90,28 @@ impl VerificationCache {
|
||||
previous: Option<&VerifiedArtifact>,
|
||||
) -> Result<VerifiedArtifact, WorkerTaskError> {
|
||||
let sequence = sequence(&release.version)?;
|
||||
if let Some(previous) = previous.filter(|previous| previous.release == *release)
|
||||
&& previous.renewed_at.elapsed() < RENEW_INTERVAL
|
||||
{
|
||||
return Ok(previous.clone());
|
||||
if let Some(previous) = previous {
|
||||
validate_successor(previous, release, sequence)?;
|
||||
if previous.release == *release
|
||||
&& previous
|
||||
.renewed_at
|
||||
.is_some_and(|at| at.elapsed() < RENEW_INTERVAL)
|
||||
{
|
||||
return Ok(previous.clone());
|
||||
}
|
||||
}
|
||||
let key = key(target);
|
||||
let cached = self
|
||||
.cache
|
||||
.read(&self.provider, &key)
|
||||
.await
|
||||
.map_err(|e| error().with_source(e))?;
|
||||
let verified_at = if let Some(cached) = cached {
|
||||
let payload: Payload = serde_json::from_value(serde_json::Value::Object(
|
||||
cached.profile().expose_to_provider().clone(),
|
||||
))
|
||||
.map_err(|e| error().with_source(e))?;
|
||||
if cached.provider_kind() != &self.provider
|
||||
|| cached.artifact_key() != key
|
||||
|| payload.target != target
|
||||
|| cached.artifact_sequence() != self::sequence(&payload.release.version)?
|
||||
{
|
||||
return Err(error());
|
||||
}
|
||||
if cached.artifact_sequence() > sequence
|
||||
|| (cached.artifact_sequence() == sequence && payload.release != *release)
|
||||
{
|
||||
return Err(error());
|
||||
}
|
||||
(payload.release == *release).then(|| DateTime::<Utc>::from(cached.verified_at()))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let verified_at = match verified_at.or_else(|| {
|
||||
previous
|
||||
.filter(|v| v.release == *release)
|
||||
.map(|v| v.verified_at)
|
||||
}) {
|
||||
Some(at) => at,
|
||||
let cached = self.load(target).await?;
|
||||
if let Some(cached) = &cached {
|
||||
validate_successor(cached, release, sequence)?;
|
||||
}
|
||||
let matching = cached
|
||||
.as_ref()
|
||||
.filter(|v| v.release == *release)
|
||||
.or_else(|| previous.filter(|v| v.release == *release));
|
||||
let (verified_at, changelist) = match matching {
|
||||
Some(artifact) => (artifact.verified_at, artifact.changelist),
|
||||
None => {
|
||||
artifact::verify(
|
||||
let changelist = artifact::verify(
|
||||
client,
|
||||
target,
|
||||
&release.version,
|
||||
@@ -101,12 +119,13 @@ impl VerificationCache {
|
||||
release.sha512.as_deref(),
|
||||
)
|
||||
.await?;
|
||||
Utc::now()
|
||||
(Utc::now(), changelist)
|
||||
}
|
||||
};
|
||||
let payload = serde_json::to_value(Payload {
|
||||
target,
|
||||
release: release.clone(),
|
||||
changelist,
|
||||
})
|
||||
.map_err(|e| error().with_source(e))?;
|
||||
let serde_json::Value::Object(payload) = payload else {
|
||||
@@ -114,7 +133,7 @@ impl VerificationCache {
|
||||
};
|
||||
let profile = ProviderArtifactProfile::new(
|
||||
self.provider.clone(),
|
||||
key,
|
||||
key(target),
|
||||
sequence,
|
||||
verified_at.into(),
|
||||
OpaqueProviderData::new(payload),
|
||||
@@ -129,19 +148,36 @@ impl VerificationCache {
|
||||
}
|
||||
Ok(VerifiedArtifact {
|
||||
release: release.clone(),
|
||||
changelist,
|
||||
verified_at,
|
||||
renewed_at: Instant::now(),
|
||||
renewed_at: Some(Instant::now()),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_successor(
|
||||
current: &VerifiedArtifact,
|
||||
next: &Release,
|
||||
next_sequence: u64,
|
||||
) -> Result<(), WorkerTaskError> {
|
||||
let current_sequence = sequence(¤t.release.version)?;
|
||||
if next_sequence < current_sequence
|
||||
|| (next_sequence == current_sequence && current.release != *next)
|
||||
{
|
||||
return Err(WorkerTaskError::safe(
|
||||
"Antigravity 官方发布版本回退或同版本制品不一致",
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn key(target: ReleaseTarget) -> String {
|
||||
let client = match target.client {
|
||||
super::selection::ClientKind::Desktop => "desktop",
|
||||
super::selection::ClientKind::Cli => "cli",
|
||||
};
|
||||
format!(
|
||||
"{client}-{}-{}",
|
||||
"build-v1-{client}-{}-{}",
|
||||
target.platform.os_type(),
|
||||
target.arch.label()
|
||||
)
|
||||
|
||||
@@ -14,33 +14,39 @@ use serde_json::{Value, json};
|
||||
pub(crate) fn options() -> OpaqueProviderData {
|
||||
let presets=[Platform::Macos,Platform::Linux,Platform::Windows].into_iter().flat_map(|platform|[ClientKind::Desktop,ClientKind::Cli].map(move|client|json!({"configuration":Selection {client,platform,..Selection::default()},"automaticAvailable":true,"reason":null}))).collect::<Vec<_>>();
|
||||
object(
|
||||
json!({"defaults":Selection::default(),"presets":presets,"defaultSystemPrompt":super::selection::DEFAULT_SYSTEM_PROMPT,"systemPromptSource":"Antigravity CLI 1.5.15"}),
|
||||
json!({"defaults":Selection::default(),"presets":presets,"defaultSystemPrompt":super::selection::DEFAULT_SYSTEM_PROMPT,"systemPromptSource":"Antigravity CLI 1.5.23"}),
|
||||
)
|
||||
}
|
||||
pub(crate) fn dashboard(selection: &Selection, releases: &ReleaseService) -> DashboardWireProfile {
|
||||
let snapshot = releases.snapshot(selection.target());
|
||||
let profile = selection.resolve(snapshot.version(selection.client));
|
||||
let profile = snapshot.profile(selection);
|
||||
let fixed = selection.version_mode == VersionMode::Fixed;
|
||||
let release = (!fixed).then(|| DashboardDesktopRelease {
|
||||
status: if snapshot.failed {
|
||||
status: if snapshot.discovery_failed || snapshot.verification_failed {
|
||||
DesktopReleaseStatus::Failed
|
||||
} else if snapshot.release.is_none() {
|
||||
} else if snapshot.candidate.is_none() {
|
||||
DesktopReleaseStatus::Unchecked
|
||||
} else if snapshot.pending_verification() {
|
||||
DesktopReleaseStatus::UpdateAvailable
|
||||
} else {
|
||||
DesktopReleaseStatus::Current
|
||||
},
|
||||
checked_at: snapshot.checked,
|
||||
latest_version: snapshot.release.as_ref().map(|r| r.version.clone()),
|
||||
latest_build: snapshot.release.as_ref().and_then(|r| r.build.clone()),
|
||||
download_url: snapshot.release.as_ref().map(|r| r.url.clone()),
|
||||
latest_version: snapshot.candidate.as_ref().map(|r| r.version.clone()),
|
||||
latest_build: snapshot.candidate.as_ref().and_then(|r| r.build.clone()),
|
||||
download_url: snapshot.candidate.as_ref().map(|r| r.url.clone()),
|
||||
published_at: None,
|
||||
minimum_system_version: None,
|
||||
hardware_requirements: None,
|
||||
download_size: None,
|
||||
signature_present: None,
|
||||
error: snapshot
|
||||
.failed
|
||||
.then(|| "无法读取 Google 官方客户端版本".into()),
|
||||
error: if snapshot.discovery_failed {
|
||||
Some("无法读取 Google 官方客户端版本".into())
|
||||
} else if snapshot.verification_failed {
|
||||
Some("无法核验 Google 官方客户端发布包".into())
|
||||
} else {
|
||||
None
|
||||
},
|
||||
});
|
||||
DashboardWireProfile {
|
||||
provider: "antigravity".into(),
|
||||
@@ -65,9 +71,7 @@ pub(crate) fn dashboard(selection: &Selection, releases: &ReleaseService) -> Das
|
||||
],
|
||||
user_agent: profile.user_agent(),
|
||||
release,
|
||||
verified_at: snapshot
|
||||
.verified_at(&profile.client_version)
|
||||
.or_else(|| profile.verified_at()),
|
||||
verified_at: snapshot.verified_at(&profile.client_version),
|
||||
}
|
||||
}
|
||||
pub(crate) fn preview(
|
||||
|
||||
@@ -137,6 +137,7 @@ impl AntigravityProvider {
|
||||
};
|
||||
let body = operation.middleware_body().map_err(|_| unsent(Kind::InvalidRequest))?;
|
||||
let translated_chat = translator.is_some();
|
||||
let native_error = !translated_chat && count_translator.is_none();
|
||||
let events = async_stream::try_stream! {
|
||||
if cancellation.is_cancelled() {
|
||||
Err(unsent(Kind::Cancelled))?;
|
||||
@@ -144,12 +145,12 @@ impl AntigravityProvider {
|
||||
if deadline.is_elapsed() {
|
||||
Err(unsent(Kind::Timeout))?;
|
||||
}
|
||||
let probe_token = (terminal_context.account_eligibility() == AccountEligibilityPolicy::BypassForDiagnostic)
|
||||
.then(|| selected.material.token().to_owned());
|
||||
let error_token = selected.material.token().to_owned();
|
||||
let record_failure = async |error| {
|
||||
let error = match &probe_token {
|
||||
Some(token) => crate::transport::connection_test_error(error, token),
|
||||
None => error,
|
||||
let error = match terminal_context.account_eligibility() {
|
||||
AccountEligibilityPolicy::BypassForDiagnostic => crate::transport::connection_test_error(error, &error_token),
|
||||
AccountEligibilityPolicy::Enforce => crate::transport::client_error(error, &error_token, native_error),
|
||||
_ => error,
|
||||
};
|
||||
feedback.record_failure(&selected.account, &model, records_account_feedback, error).await
|
||||
};
|
||||
|
||||
@@ -18,42 +18,29 @@ impl AntigravityProvider {
|
||||
records_account_feedback: bool,
|
||||
error: ProviderError,
|
||||
) -> ProviderError {
|
||||
if error.send_state() != UpstreamSendState::Sent
|
||||
|| !matches!(error.kind(), Kind::Unauthorized | Kind::RateLimited)
|
||||
{
|
||||
if error.send_state() != UpstreamSendState::Sent {
|
||||
return error;
|
||||
}
|
||||
// 明确拒绝没有生成结果;换号仍受 Core 的交付屏障、范围与预算约束
|
||||
let error = error.with_replay_safe().with_pre_delivery_retry();
|
||||
let error = if !error.retry_is_prohibited()
|
||||
&& matches!(
|
||||
error.kind(),
|
||||
Kind::Unauthorized
|
||||
| Kind::RateLimited
|
||||
| Kind::QuotaExhausted
|
||||
| Kind::UpstreamCapacityUnavailable
|
||||
) {
|
||||
error.with_replay_safe().with_pre_delivery_retry()
|
||||
} else {
|
||||
error
|
||||
};
|
||||
if !records_account_feedback {
|
||||
return error;
|
||||
}
|
||||
crate::credential::record_account_failure(self.accounts.as_ref(), account, &error).await;
|
||||
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())
|
||||
.await
|
||||
.map_err(|_| ())?;
|
||||
}
|
||||
Kind::RateLimited => {
|
||||
Kind::RateLimited | Kind::QuotaExhausted | Kind::UpstreamCapacityUnavailable => {
|
||||
if let Some(until) = error
|
||||
.retry_after()
|
||||
.and_then(|delay| SystemTime::now().checked_add(delay))
|
||||
|
||||
@@ -103,30 +103,43 @@ struct RefreshTask {
|
||||
impl ScheduledTask for RefreshTask {
|
||||
fn run_cycle(&self, context: WorkerCycleContext) -> BoxFuture<'_, Result<(), WorkerTaskError>> {
|
||||
Box::pin(async move {
|
||||
let (candidates, concurrency) = self.credentials.refresh_candidates().await?;
|
||||
if candidates.is_empty() || context.cancellation().is_cancelled() {
|
||||
let cancellation = context.cancellation();
|
||||
let Some(batch) = cancellation
|
||||
.run_until_cancelled(self.credentials.refresh_candidates())
|
||||
.await
|
||||
else {
|
||||
return Ok(());
|
||||
};
|
||||
let (candidates, concurrency) = batch?;
|
||||
if candidates.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let mut catalogs = self
|
||||
.catalog
|
||||
.capture_refresh_catalogs(&candidates)
|
||||
let Some(catalogs) = cancellation
|
||||
.run_until_cancelled(self.catalog.capture_refresh_catalogs(&candidates))
|
||||
.await
|
||||
.unwrap_or_else(|_| {
|
||||
tracing::warn!("Antigravity 目录读取失败,凭据续期后重新查询目录");
|
||||
Default::default()
|
||||
});
|
||||
else {
|
||||
return Ok(());
|
||||
};
|
||||
let mut catalogs = catalogs.unwrap_or_else(|_| {
|
||||
tracing::warn!("Antigravity 目录读取失败,凭据续期后重新查询目录");
|
||||
Default::default()
|
||||
});
|
||||
let mut updates = stream::iter(candidates)
|
||||
.map(|loaded| {
|
||||
let cancellation = context.cancellation();
|
||||
let catalog = catalogs.remove(loaded.account.id());
|
||||
async move {
|
||||
if cancellation.is_cancelled() {
|
||||
return Ok(());
|
||||
}
|
||||
let revision = self.credentials.refresh_due(&loaded).await?;
|
||||
self.catalog
|
||||
.after_credential_refresh(loaded.account.id(), revision, catalog)
|
||||
cancellation
|
||||
.run_until_cancelled(self.catalog.after_credential_refresh(
|
||||
loaded.account.id(),
|
||||
revision,
|
||||
catalog,
|
||||
))
|
||||
.await
|
||||
.unwrap_or(Ok(()))
|
||||
}
|
||||
})
|
||||
.buffer_unordered(concurrency);
|
||||
|
||||
@@ -368,7 +368,16 @@ pub(super) async fn control<T: DeserializeOwned>(
|
||||
}
|
||||
data.extend_from_slice(&chunk);
|
||||
}
|
||||
serde_json::from_slice(&data).map_err(|e| sent(Kind::Protocol).with_source(e))
|
||||
let document: serde_json::Value =
|
||||
serde_json::from_slice(&data).map_err(|e| sent(Kind::Protocol).with_source(e))?;
|
||||
if super::failure::google_error(&document).is_some_and(serde_json::Value::is_object) {
|
||||
return Err(super::failure::body_error(
|
||||
None,
|
||||
&String::from_utf8_lossy(&data),
|
||||
token,
|
||||
));
|
||||
}
|
||||
serde_json::from_value(document).map_err(|e| sent(Kind::Protocol).with_source(e))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
|
||||
@@ -35,6 +35,9 @@ pub(crate) fn count_events(
|
||||
body.extend_from_slice(&chunk);
|
||||
}
|
||||
let value: Value = serde_json::from_slice(&body).map_err(|_| sent(Kind::Protocol))?;
|
||||
if super::failure::google_error(&value).is_some_and(Value::is_object) {
|
||||
Err(super::failure::body_error(None, &String::from_utf8_lossy(&body), &context.token))?;
|
||||
}
|
||||
// Cloud Code 的 protobuf JSON 会省略零值;公开计数接口显式交付 totalTokens
|
||||
if value.as_object().is_some_and(serde_json::Map::is_empty) {
|
||||
body = br#"{"totalTokens":0}"#.to_vec();
|
||||
|
||||
@@ -2,10 +2,10 @@
|
||||
|
||||
use gateway_core::{
|
||||
error::{
|
||||
ClientVisibleUpstreamError, GatewayError, ProviderError, ProviderErrorKind as Kind,
|
||||
RawUpstreamError,
|
||||
ClientVisibleUpstreamError, ClientVisibleUpstreamResponse, GatewayError,
|
||||
OpaqueUpstreamValue, ProviderError, ProviderErrorKind as Kind, RawUpstreamError,
|
||||
},
|
||||
upstream::UpstreamSendState,
|
||||
upstream::{UpstreamFailureFields, UpstreamSendState},
|
||||
};
|
||||
use reqwest::{Response, StatusCode};
|
||||
use serde_json::Value;
|
||||
@@ -44,13 +44,41 @@ fn status_kind(status: StatusCode) -> Kind {
|
||||
}
|
||||
}
|
||||
pub(super) fn body_error(status: Option<u16>, body: &str, token: &str) -> ProviderError {
|
||||
let status = status.and_then(|code| StatusCode::from_u16(code).ok());
|
||||
let error = sent(status.map_or(Kind::Unavailable, status_kind));
|
||||
let error = if let Some(status) = status {
|
||||
error.with_status(status.as_u16())
|
||||
} else {
|
||||
error
|
||||
let document = serde_json::from_str::<Value>(body).ok();
|
||||
let failure = document.as_ref().and_then(google_error);
|
||||
let status = status
|
||||
.filter(|code| (400..=599).contains(code))
|
||||
.or_else(|| failure.and_then(rpc_status));
|
||||
let fields = UpstreamFailureFields {
|
||||
status,
|
||||
code: None,
|
||||
error_type: None,
|
||||
message: None,
|
||||
};
|
||||
let mut kind = status
|
||||
.and_then(|code| StatusCode::from_u16(code).ok())
|
||||
.map_or(Kind::Unavailable, status_kind);
|
||||
if matches!(status, Some(429 | 503)) {
|
||||
match failure
|
||||
.and_then(error_info)
|
||||
.and_then(|info| info["reason"].as_str())
|
||||
{
|
||||
Some("MODEL_CAPACITY_EXHAUSTED") if status == Some(503) => {
|
||||
kind = Kind::UpstreamCapacityUnavailable
|
||||
}
|
||||
Some(
|
||||
"QUOTA_EXHAUSTED"
|
||||
| "QUOTA_ENDPOINT_EXHAUSTED"
|
||||
| "QUOTA_PRODUCT_EXHAUSTED"
|
||||
| "QUOTA_RECIPE_EXHAUSTED",
|
||||
) if status == Some(429) => kind = Kind::QuotaExhausted,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let mut error = sent(kind).with_upstream_failure_fields(fields);
|
||||
if let Some(status) = status {
|
||||
error = error.with_status(status);
|
||||
}
|
||||
attach_body(error, body, token)
|
||||
}
|
||||
fn attach_body(error: ProviderError, body: &str, token: &str) -> ProviderError {
|
||||
@@ -68,6 +96,34 @@ fn attach_body(error: ProviderError, body: &str, token: &str) -> ProviderError {
|
||||
if body.is_empty() {
|
||||
return error;
|
||||
}
|
||||
let mut error = error;
|
||||
if let Ok(document) = serde_json::from_str::<Value>(body)
|
||||
&& let Some(failure) = google_error(&document)
|
||||
{
|
||||
let info = error_info(failure);
|
||||
let code = info
|
||||
.and_then(|info| info["reason"].as_str())
|
||||
.map(str::to_owned)
|
||||
.or_else(|| failure["code"].as_u64().map(|code| code.to_string()));
|
||||
let status = error.upstream_status();
|
||||
error = error.with_upstream_failure_fields(UpstreamFailureFields {
|
||||
status,
|
||||
code: code.clone(),
|
||||
error_type: failure["status"].as_str().map(str::to_owned),
|
||||
message: failure["message"].as_str().map(str::to_owned),
|
||||
});
|
||||
if let Some(code) = code {
|
||||
error = error.with_upstream_code(OpaqueUpstreamValue::new(code));
|
||||
}
|
||||
if account_rejection(&error).is_some()
|
||||
|| (error.upstream_status() == Some(403)
|
||||
&& error
|
||||
.upstream_code()
|
||||
.is_some_and(|code| request_rejection(code.as_str())))
|
||||
{
|
||||
error = error.with_retry_prohibited();
|
||||
}
|
||||
}
|
||||
let end = body.floor_char_boundary(MAX_ERROR_BYTES.min(body.len()));
|
||||
let text = if end < body.len() {
|
||||
format!("{}\n[truncated]", &body[..end])
|
||||
@@ -88,7 +144,7 @@ pub(crate) fn connection_test_error(error: ProviderError, token: &str) -> Provid
|
||||
let Some(failure) = google_error(&document) else {
|
||||
return error;
|
||||
};
|
||||
let info = google_error_detail(failure, "type.googleapis.com/google.rpc.ErrorInfo");
|
||||
let info = error_info(failure);
|
||||
let safe_text = |value: &Value| {
|
||||
value
|
||||
.as_str()
|
||||
@@ -117,12 +173,182 @@ pub(crate) fn connection_test_error(error: ProviderError, token: &str) -> Provid
|
||||
))
|
||||
}
|
||||
|
||||
fn google_error(document: &Value) -> Option<&Value> {
|
||||
pub(super) fn google_error(document: &Value) -> Option<&Value> {
|
||||
document
|
||||
.get("error")
|
||||
.or_else(|| document.pointer("/response/error"))
|
||||
}
|
||||
|
||||
fn error_info(error: &Value) -> Option<&Value> {
|
||||
error
|
||||
.get("details")?
|
||||
.as_array()?
|
||||
.iter()
|
||||
.filter(|detail| {
|
||||
detail["@type"] == "type.googleapis.com/google.rpc.ErrorInfo"
|
||||
&& detail["reason"]
|
||||
.as_str()
|
||||
.is_some_and(|reason| !reason.is_empty())
|
||||
})
|
||||
.max_by_key(|detail| {
|
||||
let reason = detail["reason"].as_str().unwrap_or_default();
|
||||
match account_rejection_reason(reason) {
|
||||
Some(AccountRejection::Banned) => 4,
|
||||
Some(AccountRejection::VerificationRequired) => 3,
|
||||
None if request_rejection(reason) => 2,
|
||||
None => 1,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) enum AccountRejection {
|
||||
VerificationRequired,
|
||||
Banned,
|
||||
}
|
||||
|
||||
pub(crate) fn account_rejection(error: &ProviderError) -> Option<AccountRejection> {
|
||||
if error.send_state() != UpstreamSendState::Sent || error.upstream_status() != Some(403) {
|
||||
return None;
|
||||
}
|
||||
account_rejection_reason(error.upstream_code()?.as_str())
|
||||
}
|
||||
|
||||
fn account_rejection_reason(reason: &str) -> Option<AccountRejection> {
|
||||
match reason {
|
||||
"VALIDATION_REQUIRED" => Some(AccountRejection::VerificationRequired),
|
||||
"TOS_VIOLATION"
|
||||
| "WORKSPACE_TOS_VIOLATION_CONTACT_SUPPORT"
|
||||
| "ACCOUNT_SUSPENDED"
|
||||
| "ACCOUNT_DISABLED"
|
||||
| "USER_SUSPENDED"
|
||||
| "USER_DISABLED" => Some(AccountRejection::Banned),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn request_rejection(reason: &str) -> bool {
|
||||
matches!(
|
||||
reason,
|
||||
"AI_POLICY_REQUIRED"
|
||||
| "AI_POLICY_SOFT_BLOCK_BANNER"
|
||||
| "AI_POLICY_SOFT_BLOCK_CLI"
|
||||
| "UNSUPPORTED_CLIENT"
|
||||
)
|
||||
}
|
||||
|
||||
fn rpc_status(error: &Value) -> Option<u16> {
|
||||
let code = error["code"].as_u64();
|
||||
if let Some(code @ 400..=599) = code {
|
||||
return u16::try_from(code).ok();
|
||||
}
|
||||
match error["status"].as_str() {
|
||||
Some("INVALID_ARGUMENT" | "FAILED_PRECONDITION" | "OUT_OF_RANGE") => Some(400),
|
||||
Some("UNAUTHENTICATED") => Some(401),
|
||||
Some("PERMISSION_DENIED") => Some(403),
|
||||
Some("NOT_FOUND") => Some(404),
|
||||
Some("ALREADY_EXISTS" | "ABORTED") => Some(409),
|
||||
Some("RESOURCE_EXHAUSTED") => Some(429),
|
||||
Some("CANCELLED") => Some(499),
|
||||
Some("UNKNOWN" | "INTERNAL" | "DATA_LOSS") => Some(500),
|
||||
Some("UNIMPLEMENTED") => Some(501),
|
||||
Some("UNAVAILABLE") => Some(503),
|
||||
Some("DEADLINE_EXCEEDED") => Some(504),
|
||||
_ => match code {
|
||||
Some(1) => Some(499),
|
||||
Some(2 | 13 | 15) => Some(500),
|
||||
Some(3 | 9 | 11) => Some(400),
|
||||
Some(4) => Some(504),
|
||||
Some(5) => Some(404),
|
||||
Some(6 | 10) => Some(409),
|
||||
Some(7) => Some(403),
|
||||
Some(8) => Some(429),
|
||||
Some(12) => Some(501),
|
||||
Some(14) => Some(503),
|
||||
Some(16) => Some(401),
|
||||
_ => None,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// 模型客户端只收到协议字段,账号验证链接和其他 metadata 留在受控诊断中
|
||||
pub(crate) fn client_error(error: ProviderError, token: &str, native: bool) -> ProviderError {
|
||||
let error = connection_test_error(error, token);
|
||||
let Some(status) = error
|
||||
.upstream_status()
|
||||
.filter(|status| (400..=599).contains(status))
|
||||
else {
|
||||
return error;
|
||||
};
|
||||
let gateway = GatewayError::from_provider(&error);
|
||||
let detail = error.client_visible_upstream_error();
|
||||
let message = detail.map_or(gateway.safe_message(), ClientVisibleUpstreamError::message);
|
||||
let code = detail.and_then(ClientVisibleUpstreamError::code);
|
||||
let body = if native {
|
||||
let rpc = match status {
|
||||
400 | 413 | 422 => "INVALID_ARGUMENT",
|
||||
401 => "UNAUTHENTICATED",
|
||||
403 => "PERMISSION_DENIED",
|
||||
404 => "NOT_FOUND",
|
||||
408 | 504 => "DEADLINE_EXCEEDED",
|
||||
409 => "ABORTED",
|
||||
429 => "RESOURCE_EXHAUSTED",
|
||||
499 => "CANCELLED",
|
||||
501 => "UNIMPLEMENTED",
|
||||
502 | 503 => "UNAVAILABLE",
|
||||
_ => "INTERNAL",
|
||||
};
|
||||
let mut body = serde_json::json!({"error":{"code":status,"status":rpc,"message":message}});
|
||||
if let Some(kind) = detail.and_then(ClientVisibleUpstreamError::error_type) {
|
||||
body["error"]["status"] = Value::String(kind.into());
|
||||
}
|
||||
if let Some(code) = code {
|
||||
body["error"]["details"] = serde_json::json!([{"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":code}]);
|
||||
}
|
||||
if let Some(delay) = error.retry_after() {
|
||||
let detail = serde_json::json!({"@type":"type.googleapis.com/google.rpc.RetryInfo","retryDelay":format!("{}.{:09}s", delay.as_secs(), delay.subsec_nanos())});
|
||||
let details = body["error"].as_object_mut().and_then(|error| {
|
||||
error
|
||||
.entry("details")
|
||||
.or_insert_with(|| serde_json::json!([]))
|
||||
.as_array_mut()
|
||||
});
|
||||
if let Some(details) = details {
|
||||
details.push(detail);
|
||||
}
|
||||
}
|
||||
body
|
||||
} else {
|
||||
serde_json::json!({"error":{"message":message,"type":detail.and_then(ClientVisibleUpstreamError::error_type).unwrap_or("upstream_error"),"code":code}})
|
||||
};
|
||||
let mut response = ClientVisibleUpstreamResponse::new(
|
||||
status,
|
||||
Some(b"application/json".to_vec()),
|
||||
body.to_string().into(),
|
||||
);
|
||||
if let Some(delay) = error.retry_after() {
|
||||
let seconds = delay
|
||||
.as_secs()
|
||||
.saturating_add(u64::from(delay.subsec_nanos() != 0));
|
||||
response = response.with_headers(vec![gateway_core::event::ProviderResponseHeader::new(
|
||||
"retry-after",
|
||||
seconds.to_string().into(),
|
||||
)]);
|
||||
}
|
||||
let error = error.with_client_visible_upstream_response(response);
|
||||
if native
|
||||
&& let Ok(wire) = gateway_core::event::ProtocolWireEvent::json(
|
||||
gateway_protocol::genai::GENAI_PROTOCOL,
|
||||
None,
|
||||
body,
|
||||
)
|
||||
{
|
||||
return error
|
||||
.with_atomic_client_events(vec![gateway_core::event::ProviderEvent::wire(wire)]);
|
||||
}
|
||||
error
|
||||
}
|
||||
|
||||
fn google_error_detail<'a>(error: &'a Value, kind: &str) -> Option<&'a Value> {
|
||||
error
|
||||
.get("details")?
|
||||
@@ -177,10 +403,6 @@ pub(super) async fn successful(
|
||||
.get(reqwest::header::RETRY_AFTER)
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.and_then(retry_after);
|
||||
let mut error = sent(status_kind(status)).with_status(status.as_u16());
|
||||
if let Some(delay) = retry_after {
|
||||
error = error.with_retry_after(delay);
|
||||
}
|
||||
let mut body = Vec::new();
|
||||
let mut truncated = false;
|
||||
let read = tokio::time::timeout(Duration::from_secs(10), async {
|
||||
@@ -195,14 +417,25 @@ pub(super) async fn successful(
|
||||
Ok::<_, reqwest::Error>(())
|
||||
})
|
||||
.await;
|
||||
let text = String::from_utf8_lossy(&body).into_owned();
|
||||
let mut error = body_error(
|
||||
Some(status.as_u16()),
|
||||
if truncated { "" } else { &text },
|
||||
token,
|
||||
);
|
||||
if let Some(delay) = retry_after {
|
||||
let delay = error
|
||||
.retry_after()
|
||||
.map_or(delay, |current| current.max(delay));
|
||||
error = error.with_retry_after(delay);
|
||||
}
|
||||
match read {
|
||||
Ok(Ok(())) => {}
|
||||
Ok(Err(source)) => error = error.with_source(source.without_url()),
|
||||
Err(source) => error = error.with_source(source),
|
||||
}
|
||||
let text = String::from_utf8_lossy(&body).into_owned();
|
||||
if truncated {
|
||||
return Err(error.redact_sensitive_context(&text));
|
||||
}
|
||||
Err(attach_body(error, &text, token))
|
||||
Err(error)
|
||||
}
|
||||
|
||||
@@ -14,7 +14,9 @@ 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 failure::{
|
||||
AccountRejection, account_rejection, client_error, connection_test_error, sent, unsent,
|
||||
};
|
||||
pub(crate) use headers::request_headers;
|
||||
pub(crate) use pool::ClientPool;
|
||||
pub(crate) use response::{ResponseContext, events, genai_events};
|
||||
|
||||
@@ -23,6 +23,10 @@ pub(super) fn request_body(
|
||||
edit_object(
|
||||
raw,
|
||||
|name, value| {
|
||||
// Gateway 入口的本地状态不能声明成 OAuth 生成请求字段;正文和工具参数不递归改写
|
||||
if matches!(name, "hasFingerprintSet" | "has_fingerprint_set") {
|
||||
return Ok(Edit::Remove);
|
||||
}
|
||||
// 合并到已有的字段处理,避免为签名再解析、复制和校验整个请求
|
||||
if name == "contents" {
|
||||
return super::signatures::prepare_contents(value, model);
|
||||
|
||||
@@ -279,7 +279,7 @@ async fn imported_grants_cannot_inherit_missing_or_reduced_scopes() {
|
||||
async fn import_resolves_scopes_and_freezes_global_profile_until_the_next_refresh() {
|
||||
let (server, credentials, store) = fixture().await;
|
||||
*store.request_profile.lock().unwrap() = Some(crate::profile::object(json!({
|
||||
"client":"cli", "platform":"windows", "versionMode":"fixed", "clientVersion":"1.5.15",
|
||||
"client":"cli", "platform":"windows", "versionMode":"fixed", "clientVersion":"1.5.23",
|
||||
})));
|
||||
let mut response = token_response();
|
||||
response.as_object_mut().unwrap().remove("scope");
|
||||
@@ -325,7 +325,7 @@ async fn import_resolves_scopes_and_freezes_global_profile_until_the_next_refres
|
||||
for request in requests {
|
||||
assert_eq!(
|
||||
request.headers["user-agent"],
|
||||
"antigravity/cli/1.5.15 (aidev_client; os_type=windows; arch=amd64; cl=1027820220; auth_method=consumer)"
|
||||
"antigravity/cli/1.5.23 (aidev_client; os_type=windows; arch=amd64; auth_method=consumer)"
|
||||
);
|
||||
}
|
||||
server.verify().await;
|
||||
|
||||
@@ -10,7 +10,7 @@ use wiremock::{
|
||||
|
||||
pub(crate) async fn refreshed_credential(server: &MockServer) -> (Url, String) {
|
||||
let origin = server.uri();
|
||||
let profile = crate::profile::Selection::default().resolve("2.34.0");
|
||||
let profile = crate::profile::Selection::default().resolve("2.34.0", None);
|
||||
let config:OAuthRegistration=serde_json::from_value(json!({"client_id":"fixture-cpr","client_secret":"fixture-secret","redirect_uri":"http://127.0.0.1:8020/callback","resource_scopes":["fixture-resource"],"resource_origin":origin})).unwrap();
|
||||
config.validate().unwrap();
|
||||
let oauth = GoogleOAuth::with_endpoints(
|
||||
|
||||
@@ -8,12 +8,17 @@ mod api_key_tests;
|
||||
mod authorization;
|
||||
#[path = "../../src/credential/documents.rs"]
|
||||
mod documents;
|
||||
#[path = "../../src/credential/failure.rs"]
|
||||
mod failure;
|
||||
pub(crate) use failure::record_account_failure;
|
||||
#[path = "../../src/credential/model_groups.rs"]
|
||||
mod model_groups;
|
||||
#[path = "../../src/credential/oauth.rs"]
|
||||
pub(crate) mod oauth;
|
||||
#[path = "../../src/credential/refresh.rs"]
|
||||
mod refresh;
|
||||
#[path = "refresh.rs"]
|
||||
mod refresh_tests;
|
||||
#[path = "../../src/credential/service.rs"]
|
||||
mod service;
|
||||
pub(crate) use authorization::AuthorizationService;
|
||||
|
||||
@@ -76,7 +76,7 @@ async fn exchange_and_refresh_preserve_verified_identity_and_offline_grant() {
|
||||
};
|
||||
|
||||
let server = MockServer::start().await;
|
||||
let profile = crate::profile::Selection::default().resolve("2.34.0");
|
||||
let profile = crate::profile::Selection::default().resolve("2.34.0", None);
|
||||
let oauth = GoogleOAuth::with_endpoints(
|
||||
serde_json::from_value(registration()).unwrap(),
|
||||
&format!("{}/token", server.uri()),
|
||||
|
||||
@@ -169,7 +169,7 @@ async fn quota_and_catalog_refresh_use_current_global_identity() {
|
||||
upstream(&server, json!(0.5), Duration::ZERO).await;
|
||||
let f = Fixture::new(&server.uri());
|
||||
let account = f.store.primary().loaded.lock().unwrap().account.clone();
|
||||
for (version, changelist) in [("1.5.14", ""), ("1.5.15", "; cl=1027820220")] {
|
||||
for (version, changelist) in [("9.8.7", ""), ("1.5.23", "")] {
|
||||
*f.store.request_profile.lock().unwrap() = Some(crate::profile::object(
|
||||
json!({"client":"cli","platform":"linux","versionMode":"fixed","clientVersion":version,"arch":null}),
|
||||
));
|
||||
@@ -238,7 +238,7 @@ async fn account_and_request_plans_use_the_desktop_description_for_every_tier()
|
||||
request(false),
|
||||
context(
|
||||
crate::profile::Selection::default()
|
||||
.resolve("2.34.0")
|
||||
.resolve("2.34.0", None)
|
||||
.frozen(),
|
||||
CancellationToken::new(),
|
||||
),
|
||||
@@ -453,7 +453,7 @@ async fn peer_model_facts_keep_membership_quota_and_revision_separate() {
|
||||
crate::support::request(false),
|
||||
crate::support::context(
|
||||
crate::profile::Selection::default()
|
||||
.resolve("2.34.0")
|
||||
.resolve("2.34.0", None)
|
||||
.frozen(),
|
||||
CancellationToken::new(),
|
||||
),
|
||||
@@ -539,7 +539,7 @@ async fn google_one_credits_require_opt_in_and_sufficient_balance() {
|
||||
request(false),
|
||||
context(
|
||||
crate::profile::Selection::default()
|
||||
.resolve("2.34.0")
|
||||
.resolve("2.34.0", None)
|
||||
.frozen(),
|
||||
CancellationToken::new(),
|
||||
),
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
//! OAuth 续期保留资源服务拒绝,旧凭据反馈不能污染新授权
|
||||
|
||||
use super::documents_tests::fixture;
|
||||
use gateway_core::account::{AccountErrorReason, CredentialState, PlaintextCredential};
|
||||
use serde_json::json;
|
||||
use wiremock::{Mock, ResponseTemplate, matchers::path};
|
||||
|
||||
#[tokio::test]
|
||||
async fn token_refresh_preserves_a_denial_recorded_while_refresh_was_in_flight() {
|
||||
let (server, credentials, store) = fixture().await;
|
||||
let loaded = {
|
||||
let mut loaded = store.primary().loaded.lock().unwrap();
|
||||
let mut material = loaded.credential.expose_to_provider().clone();
|
||||
material.insert(
|
||||
"registration".into(),
|
||||
json!(credentials.oauth.registration()),
|
||||
);
|
||||
loaded.credential = PlaintextCredential::new(material);
|
||||
loaded.clone()
|
||||
};
|
||||
Mock::given(path("/token")).respond_with(ResponseTemplate::new(200).set_body_json(json!({
|
||||
"access_token":"fresh-access","token_type":"Bearer","expires_in":3600,"scope":"email fixture-resource"
|
||||
}))).expect(2).mount(&server).await;
|
||||
{
|
||||
let mut current = store.primary().loaded.lock().unwrap();
|
||||
current.account = current.account.clone().with_account_facts(
|
||||
true,
|
||||
CredentialState::Invalid,
|
||||
current.account.quota(),
|
||||
Some(AccountErrorReason::AccountUnverified),
|
||||
Some("需验证".into()),
|
||||
);
|
||||
}
|
||||
let prepared = credentials.refresh_current(&loaded).await.unwrap();
|
||||
assert!(prepared.facts().preserve_credential_state);
|
||||
drop(prepared);
|
||||
let revision = credentials.refresh_due(&loaded).await.unwrap();
|
||||
let stale = gateway_core::error::ProviderError::new(
|
||||
gateway_core::error::ProviderErrorKind::PermissionDenied,
|
||||
gateway_core::upstream::UpstreamSendState::Sent,
|
||||
)
|
||||
.with_status(403)
|
||||
.with_upstream_code(gateway_core::error::OpaqueUpstreamValue::new(
|
||||
"TOS_VIOLATION",
|
||||
));
|
||||
super::record_account_failure(store.as_ref(), &loaded.account, &stale).await;
|
||||
let current = store.primary().loaded.lock().unwrap();
|
||||
assert_eq!(current.account.revision(), revision);
|
||||
assert_eq!(current.account.credential_state(), CredentialState::Invalid);
|
||||
assert_eq!(
|
||||
current.account.last_error_reason(),
|
||||
Some(AccountErrorReason::AccountUnverified)
|
||||
);
|
||||
assert_eq!(
|
||||
current.credential.expose_to_provider()["access_token"],
|
||||
"fresh-access"
|
||||
);
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
use crate::profile::archive::{RemoteZip, download};
|
||||
use sha2::{Digest, Sha512};
|
||||
use std::io::Read;
|
||||
use std::io::{Read, Seek, Write};
|
||||
use wiremock::{Mock, MockServer, Request, ResponseTemplate, matchers::any};
|
||||
|
||||
pub(super) async fn serve(body: Vec<u8>, fault: &'static str) -> MockServer {
|
||||
@@ -121,4 +121,46 @@ fn cancelled_parser_stops_reading_its_temporary_file() {
|
||||
assert_eq!(file.read(&mut [0]).unwrap(), 0);
|
||||
drop(guard);
|
||||
assert!(file.read(&mut [0]).is_err());
|
||||
assert!(file.rewind().is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn large_zip_member_uses_bounded_ranges_and_streaming_inspection() {
|
||||
let size = 16 * 1024 * 1024 + 5;
|
||||
let mut writer = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
writer
|
||||
.start_file(
|
||||
"binary",
|
||||
zip::write::SimpleFileOptions::default()
|
||||
.compression_method(zip::CompressionMethod::Stored),
|
||||
)
|
||||
.unwrap();
|
||||
writer.write_all(&vec![37; size]).unwrap();
|
||||
let server = serve(writer.finish().unwrap().into_inner(), "").await;
|
||||
let client = reqwest::Client::new();
|
||||
let zip = RemoteZip::open(&client, server.uri()).await.unwrap();
|
||||
let count = zip
|
||||
.inspect("binary", size as u64, |reader| {
|
||||
std::io::copy(reader, &mut std::io::sink())
|
||||
.map_err(|e| crate::profile::archive::invalid().with_source(e))
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(count, size as u64);
|
||||
let requests = server.received_requests().await.unwrap();
|
||||
let ranges: Vec<_> = requests
|
||||
.iter()
|
||||
.filter_map(|request| request.headers.get("range"))
|
||||
.collect();
|
||||
assert_eq!(ranges.len(), 3);
|
||||
for range in ranges {
|
||||
let (start, end) = range
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.strip_prefix("bytes=")
|
||||
.unwrap()
|
||||
.split_once('-')
|
||||
.unwrap();
|
||||
assert!(end.parse::<u64>().unwrap() - start.parse::<u64>().unwrap() < 16 * 1024 * 1024);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,6 +22,10 @@ pub(super) fn asar(version: &str) -> Vec<u8> {
|
||||
}
|
||||
|
||||
pub(super) fn executable(target: ReleaseTarget, version: &str) -> Vec<u8> {
|
||||
executable_with_changelist(target, version, 1_234_567_890)
|
||||
}
|
||||
|
||||
fn executable_with_changelist(target: ReleaseTarget, version: &str, changelist: u64) -> Vec<u8> {
|
||||
let mut bytes = vec![0; 65_536];
|
||||
let arm = target.arch == Architecture::Arm64;
|
||||
match target.platform {
|
||||
@@ -45,10 +49,17 @@ pub(super) fn executable(target: ReleaseTarget, version: &str) -> Vec<u8> {
|
||||
}
|
||||
// 把版本放在扫描块边界上,覆盖跨块字符串识别
|
||||
bytes.extend_from_slice(format!("{version}\n\0").as_bytes());
|
||||
bytes.extend_from_slice(
|
||||
format!("googlefile:/google_src/files/{changelist}/depot/google3\0").as_bytes(),
|
||||
);
|
||||
bytes
|
||||
}
|
||||
|
||||
pub(super) fn desktop_zip(version: &str) -> Vec<u8> {
|
||||
desktop_zip_with_changelist(version, 1_234_567_890)
|
||||
}
|
||||
|
||||
pub(super) fn desktop_zip_with_changelist(version: &str, changelist: u64) -> Vec<u8> {
|
||||
let mut zip = zip::ZipWriter::new(Cursor::new(Vec::new()));
|
||||
let options = zip::write::SimpleFileOptions::default()
|
||||
.compression_method(zip::CompressionMethod::Deflated);
|
||||
@@ -62,6 +73,17 @@ pub(super) fn desktop_zip(version: &str) -> Vec<u8> {
|
||||
version,
|
||||
))
|
||||
.unwrap();
|
||||
zip.start_file(
|
||||
"Antigravity.app/Contents/Resources/bin/language_server",
|
||||
options,
|
||||
)
|
||||
.unwrap();
|
||||
zip.write_all(&executable_with_changelist(
|
||||
crate::profile::Selection::default().target(),
|
||||
version,
|
||||
changelist,
|
||||
))
|
||||
.unwrap();
|
||||
zip.finish().unwrap().into_inner()
|
||||
}
|
||||
|
||||
@@ -91,8 +113,8 @@ fn cli_binary_requires_target_architecture_and_exact_embedded_version() {
|
||||
arch,
|
||||
};
|
||||
let binary = executable(target, "1.5.16");
|
||||
assert!(artifact::verify_binary(binary.as_slice(), target, "1.5.16").is_ok());
|
||||
assert!(artifact::verify_binary(binary.as_slice(), target, "1.5.15").is_err());
|
||||
assert!(artifact::verify_binary(binary.as_slice(), target, Some("1.5.16")).is_ok());
|
||||
assert!(artifact::verify_binary(binary.as_slice(), target, Some("1.5.15")).is_err());
|
||||
let other = ReleaseTarget {
|
||||
arch: if arch == Architecture::Arm64 {
|
||||
Architecture::Amd64
|
||||
@@ -101,23 +123,38 @@ fn cli_binary_requires_target_architecture_and_exact_embedded_version() {
|
||||
},
|
||||
..target
|
||||
};
|
||||
assert!(artifact::verify_binary(binary.as_slice(), other, "1.5.16").is_err());
|
||||
assert!(artifact::verify_binary(binary.as_slice(), other, Some("1.5.16")).is_err());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn windows_resource_requires_consistent_file_and_product_versions() {
|
||||
let mut resource = b"\xbd\x04\xef\xfe\0\0\x01\0".to_vec();
|
||||
for word in [2u32 << 16 | 35, 1 << 16, 2 << 16 | 35, 1 << 16] {
|
||||
resource.extend(word.to_le_bytes());
|
||||
fn binary_changelist_requires_one_valid_source_root_and_survives_chunk_boundaries() {
|
||||
let target = crate::profile::Selection::default().target();
|
||||
let mut binary = executable(target, "9.8.7");
|
||||
let marker = b"googlefile:/google_src/files/1234567890/depot/google3\0";
|
||||
binary.truncate(binary.len() - marker.len());
|
||||
assert!(artifact::verify_binary(binary.as_slice(), target, Some("9.8.7")).is_err());
|
||||
for split in 1..marker.len() {
|
||||
let mut bytes = binary.clone();
|
||||
bytes.resize(1024 + 2 * 65536 - split, 0);
|
||||
bytes.extend_from_slice(marker);
|
||||
bytes.extend_from_slice(marker);
|
||||
assert_eq!(
|
||||
artifact::verify_binary(bytes.as_slice(), target, Some("9.8.7")).unwrap(),
|
||||
1_234_567_890
|
||||
);
|
||||
}
|
||||
assert!(artifact::windows_version(&resource, "2.35.1").is_ok());
|
||||
resource[4..8].fill(0);
|
||||
assert!(artifact::windows_version(&resource, "2.35.1").is_ok());
|
||||
assert!(artifact::windows_version(&resource, "2.35.2").is_err());
|
||||
resource[16] ^= 1;
|
||||
assert!(artifact::windows_version(&resource, "2.35.1").is_err());
|
||||
for value in ["0", "18446744073709551616", "", "not-a-number"] {
|
||||
let mut bytes = binary.clone();
|
||||
bytes.extend_from_slice(
|
||||
format!("googlefile:/google_src/files/{value}/depot/google3\0").as_bytes(),
|
||||
);
|
||||
assert!(artifact::verify_binary(bytes.as_slice(), target, Some("9.8.7")).is_err());
|
||||
}
|
||||
binary.extend_from_slice(marker);
|
||||
binary.extend_from_slice(b"googlefile:/google_src/files/9876543210/depot/google3\0");
|
||||
assert!(artifact::verify_binary(binary.as_slice(), target, Some("9.8.7")).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -132,7 +169,13 @@ fn tar_requires_both_package_and_executable_and_rejects_wrong_version() {
|
||||
Vec::new(),
|
||||
flate2::Compression::fast(),
|
||||
));
|
||||
let mut files = vec![("Antigravity/resources/app.asar", asar("2.35.1"))];
|
||||
let mut files = vec![
|
||||
("Antigravity/resources/app.asar", asar("2.35.1")),
|
||||
(
|
||||
"Antigravity/resources/bin/language_server",
|
||||
executable(target, "2.35.1"),
|
||||
),
|
||||
];
|
||||
if include_executable {
|
||||
files.push(("Antigravity/antigravity", executable(target, "2.35.1")));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
//! Windows 安装器内的版本、架构与 CL 必须来自同一应用包
|
||||
|
||||
use crate::profile::{
|
||||
installer,
|
||||
selection::{Architecture, ClientKind, Platform, ReleaseTarget},
|
||||
};
|
||||
use std::io::Cursor;
|
||||
|
||||
fn target() -> ReleaseTarget {
|
||||
ReleaseTarget {
|
||||
client: ClientKind::Desktop,
|
||||
platform: Platform::Windows,
|
||||
arch: Architecture::Amd64,
|
||||
}
|
||||
}
|
||||
|
||||
fn package(files: &[(&str, Vec<u8>)]) -> Vec<u8> {
|
||||
let mut archive = sevenz_rust2::ArchiveWriter::new(Cursor::new(Vec::new())).unwrap();
|
||||
for (name, body) in files {
|
||||
archive
|
||||
.push_archive_entry(
|
||||
sevenz_rust2::ArchiveEntry::new_file(name),
|
||||
Some(body.as_slice()),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
let mut installer = b"MZ fixture installer prefix".to_vec();
|
||||
installer.extend(archive.finish().unwrap().into_inner());
|
||||
installer.extend_from_slice(b"installer trailer");
|
||||
installer
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn embedded_archive_requires_matching_version_architecture_and_unique_runtime() {
|
||||
let files = vec![
|
||||
("resources/app.asar", super::artifact::asar("8.2.1")),
|
||||
(
|
||||
"resources/bin/language_server.exe",
|
||||
super::artifact::executable(target(), "internal-version"),
|
||||
),
|
||||
];
|
||||
let bytes = package(&files);
|
||||
assert_eq!(
|
||||
installer::verify(Cursor::new(&bytes), target(), "8.2.1").unwrap(),
|
||||
1_234_567_890
|
||||
);
|
||||
assert!(installer::verify(Cursor::new(&bytes), target(), "8.2.2").is_err());
|
||||
let arm = ReleaseTarget {
|
||||
arch: Architecture::Arm64,
|
||||
..target()
|
||||
};
|
||||
assert!(installer::verify(Cursor::new(&bytes), arm, "8.2.1").is_err());
|
||||
for files in [
|
||||
vec![files[0].clone()],
|
||||
vec![files[1].clone()],
|
||||
vec![files[0].clone(), files[1].clone(), files[1].clone()],
|
||||
] {
|
||||
assert!(installer::verify(Cursor::new(package(&files)), target(), "8.2.1").is_err());
|
||||
}
|
||||
assert!(installer::verify(Cursor::new(&bytes[..40]), target(), "8.2.1").is_err());
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
mod archive;
|
||||
mod artifact;
|
||||
mod installer;
|
||||
mod release;
|
||||
mod selection;
|
||||
mod verification;
|
||||
|
||||
@@ -10,30 +10,35 @@ fn client_presets_resolve_platform_and_frozen_version() {
|
||||
("linux", "linux", "amd64"),
|
||||
("windows", "windows", "amd64"),
|
||||
] {
|
||||
for (client, subclient, auth) in [
|
||||
("desktop", "hub", ""),
|
||||
("cli", "cli", "; auth_method=consumer"),
|
||||
for (client, subclient, version, cl, auth) in [
|
||||
("desktop", "hub", "2.37.0", "1033035865", ""),
|
||||
(
|
||||
"cli",
|
||||
"cli",
|
||||
"1.5.23",
|
||||
"1035033525",
|
||||
"; auth_method=consumer",
|
||||
),
|
||||
] {
|
||||
let selection = Selection::parse(&object(json!({"client":client,"platform":platform,"versionMode":"latest","clientVersion":null,"arch":null}))).unwrap();
|
||||
let initial = selection
|
||||
.resolve(selection.client.baseline().version)
|
||||
.resolve(selection.client.baseline(), Some(cl.parse().unwrap()))
|
||||
.frozen();
|
||||
let frozen = selection.resolve("2.35.0").frozen();
|
||||
let frozen = selection.resolve("9.8.7", None).frozen();
|
||||
let profile = ClientProfile::from_frozen(&frozen).unwrap();
|
||||
// 发布版本变化后不混入旧 CL,也不把未知版本标记为实测画像
|
||||
assert!(profile.verified_at().is_none());
|
||||
// 发布版本变化后不混入另一个版本的 CL
|
||||
assert_eq!(
|
||||
profile.user_agent(),
|
||||
format!(
|
||||
"antigravity/{subclient}/2.35.0 (aidev_client; os_type={os}; arch={arch}{auth})"
|
||||
"antigravity/{subclient}/9.8.7 (aidev_client; os_type={os}; arch={arch}{auth})"
|
||||
)
|
||||
);
|
||||
let original = ClientProfile::from_frozen(&initial).unwrap();
|
||||
assert!(original.user_agent().contains("; cl="));
|
||||
assert_eq!(
|
||||
original.verified_at().is_some(),
|
||||
(client == "desktop" && platform == "macos")
|
||||
|| (client == "cli" && platform == "linux")
|
||||
original.user_agent(),
|
||||
format!(
|
||||
"antigravity/{subclient}/{version} (aidev_client; os_type={os}; arch={arch}; cl={cl}{auth})"
|
||||
)
|
||||
);
|
||||
assert_ne!(original.user_agent(), profile.user_agent());
|
||||
}
|
||||
@@ -49,20 +54,39 @@ fn fixed_version_rejects_header_injection_and_incomplete_selection() {
|
||||
] {
|
||||
assert!(Selection::parse(&object(value)).is_err());
|
||||
}
|
||||
let selected = Selection::parse(&object(json!({"client":"cli","platform":"linux","versionMode":"fixed","clientVersion":"1.5.17","arch":"arm64"}))).unwrap();
|
||||
let selected = Selection::parse(&object(json!({"client":"cli","platform":"linux","versionMode":"fixed","clientVersion":"1.5.23","arch":"arm64"}))).unwrap();
|
||||
assert_eq!(
|
||||
selected.resolve("9.9.9").user_agent(),
|
||||
"antigravity/cli/1.5.17 (aidev_client; os_type=linux; arch=arm64; cl=1029496841; auth_method=consumer)"
|
||||
selected.resolve("9.9.9", Some(987654321)).user_agent(),
|
||||
"antigravity/cli/1.5.23 (aidev_client; os_type=linux; arch=arm64; auth_method=consumer)"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arbitrary_verified_build_is_frozen_without_a_static_version_map() {
|
||||
let selection = Selection::default();
|
||||
let frozen = selection.resolve("41.8.12", Some(9_876_543_210)).frozen();
|
||||
let newer = selection.resolve("41.8.13", Some(9_876_543_211));
|
||||
let profile = ClientProfile::from_frozen(&frozen).unwrap();
|
||||
assert!(profile.user_agent().contains("/41.8.12 "));
|
||||
assert!(profile.user_agent().contains("cl=9876543210"));
|
||||
assert!(newer.user_agent().contains("cl=9876543211"));
|
||||
for version in [selection.client.baseline(), "41.8.12"] {
|
||||
assert!(
|
||||
!selection
|
||||
.resolve(version, None)
|
||||
.user_agent()
|
||||
.contains("cl=")
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn system_prompt_defaults_and_customization_are_frozen_with_the_profile() {
|
||||
let mut selection = Selection::default();
|
||||
let default = selection.resolve("1.5.15");
|
||||
let default = selection.resolve("2.37.0", None);
|
||||
assert!(default.system_prompt.starts_with("You are Antigravity,"));
|
||||
selection.system_prompt = Some("Use the fixture instruction.".into());
|
||||
let frozen = selection.resolve("1.5.15").frozen();
|
||||
let frozen = selection.resolve("2.37.0", None).frozen();
|
||||
selection.system_prompt = Some("New configuration.".into());
|
||||
assert_eq!(
|
||||
ClientProfile::from_frozen(&frozen).unwrap().system_prompt,
|
||||
@@ -70,7 +94,10 @@ fn system_prompt_defaults_and_customization_are_frozen_with_the_profile() {
|
||||
);
|
||||
selection.system_prompt = Some(" \n".into());
|
||||
let reset = Selection::parse(&selection.configuration()).unwrap();
|
||||
assert_eq!(reset.resolve("1.5.15").system_prompt, default.system_prompt);
|
||||
assert_eq!(
|
||||
reset.resolve("2.37.0", None).system_prompt,
|
||||
default.system_prompt
|
||||
);
|
||||
for prompt in ["x".repeat(16 * 1024 + 1), "\0".into()] {
|
||||
selection.system_prompt = Some(prompt);
|
||||
assert!(Selection::parse(&selection.configuration()).is_err());
|
||||
|
||||
@@ -1,16 +1,20 @@
|
||||
//! 缓存恢复保留事实时间,制品、目标或缓存变化不能借用旧核验结果
|
||||
|
||||
use crate::{
|
||||
profile::{ReleaseService, Selection, artifact::Release, verification::VerificationCache},
|
||||
profile::{
|
||||
ClientProfile, ReleaseService, Selection, artifact::Release, dashboard, default_profile,
|
||||
verification::VerificationCache,
|
||||
},
|
||||
support::profile::cache,
|
||||
};
|
||||
use gateway_admin::model::observability::DesktopReleaseStatus;
|
||||
use gateway_core::{provider_ports::ProviderArtifactProfile, routing::ProviderKind};
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
fn provider() -> ProviderKind {
|
||||
ProviderKind::new("antigravity").unwrap()
|
||||
}
|
||||
fn release(server: &wiremock::MockServer, version: &str) -> Release {
|
||||
fn fixture_release(server: &wiremock::MockServer, version: &str) -> Release {
|
||||
Release {
|
||||
version: version.into(),
|
||||
build: Some("123".into()),
|
||||
@@ -26,7 +30,7 @@ async fn cache_restore_and_renewal_preserve_verification_without_downloading_aga
|
||||
let service = VerificationCache::new(provider(), cache.clone());
|
||||
let client = reqwest::Client::new();
|
||||
let target = Selection::default().target();
|
||||
let release = release(&server, "2.35.1");
|
||||
let release = fixture_release(&server, "2.35.1");
|
||||
let first = service
|
||||
.verify(&client, target, &release, None)
|
||||
.await
|
||||
@@ -39,31 +43,87 @@ async fn cache_restore_and_renewal_preserve_verification_without_downloading_aga
|
||||
assert_eq!(same.verified_at, first.verified_at);
|
||||
assert_eq!(cache.writes.load(Ordering::SeqCst), 1);
|
||||
let restarted = VerificationCache::new(provider(), cache.clone());
|
||||
let restored = restarted
|
||||
.verify(&client, target, &release, None)
|
||||
.await
|
||||
.unwrap();
|
||||
let restored = restarted.load(target).await.unwrap().unwrap();
|
||||
assert_eq!(restored.verified_at, first.verified_at);
|
||||
assert_eq!(cache.writes.load(Ordering::SeqCst), 2);
|
||||
assert_eq!(first.changelist, 1_234_567_890);
|
||||
assert_eq!(restored.changelist, first.changelist);
|
||||
assert_eq!(cache.writes.load(Ordering::SeqCst), 1);
|
||||
assert_eq!(server.received_requests().await.unwrap().len(), requests);
|
||||
|
||||
let releases = ReleaseService::new(cache).unwrap();
|
||||
releases.publish(target, Some(release.clone()));
|
||||
releases.update().await.unwrap();
|
||||
let releases = ReleaseService::new(cache.clone()).unwrap();
|
||||
releases.restore().await;
|
||||
let restored = dashboard(&Selection::default(), &releases);
|
||||
assert_eq!(restored.version, release.version);
|
||||
assert!(restored.user_agent.contains("cl=1234567890"));
|
||||
assert_eq!(restored.verified_at, Some(first.verified_at));
|
||||
assert_eq!(
|
||||
crate::profile::dashboard(&Selection::default(), &releases).verified_at,
|
||||
restored.release.unwrap().status,
|
||||
DesktopReleaseStatus::Unchecked
|
||||
);
|
||||
releases.observe(target, Some(release));
|
||||
releases.update().await.unwrap();
|
||||
assert_eq!(cache.writes.load(Ordering::SeqCst), 2);
|
||||
assert_eq!(server.received_requests().await.unwrap().len(), requests);
|
||||
assert_eq!(
|
||||
dashboard(&Selection::default(), &releases).verified_at,
|
||||
Some(first.verified_at)
|
||||
);
|
||||
let new_release = Release {
|
||||
version: "2.36.0".into(),
|
||||
..release
|
||||
};
|
||||
releases.publish(target, Some(new_release));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn latest_profile_switches_version_and_changelist_only_after_verified_publication() {
|
||||
let old_server = super::archive::serve(super::artifact::desktop_zip("2.35.1"), "").await;
|
||||
let new_server = super::archive::serve(
|
||||
super::artifact::desktop_zip_with_changelist("2.36.0", 2_345_678_901),
|
||||
"",
|
||||
)
|
||||
.await;
|
||||
let cache = cache();
|
||||
let service = VerificationCache::new(provider(), cache.clone());
|
||||
let target = Selection::default().target();
|
||||
let client = reqwest::Client::new();
|
||||
let old = service
|
||||
.verify(
|
||||
&client,
|
||||
target,
|
||||
&fixture_release(&old_server, "2.35.1"),
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let new_release = fixture_release(&new_server, "2.36.0");
|
||||
let releases = ReleaseService::new(cache.clone()).unwrap();
|
||||
releases.restore().await;
|
||||
let before = dashboard(&Selection::default(), &releases);
|
||||
let frozen = default_profile(&releases).frozen();
|
||||
releases.observe(target, Some(new_release.clone()));
|
||||
let pending = dashboard(&Selection::default(), &releases);
|
||||
assert_eq!(pending.user_agent, before.user_agent);
|
||||
let observation = pending.release.unwrap();
|
||||
assert_eq!(observation.status, DesktopReleaseStatus::UpdateAvailable);
|
||||
assert_eq!(observation.latest_version.as_deref(), Some("2.36.0"));
|
||||
|
||||
cache.fail.store(true, Ordering::SeqCst);
|
||||
assert!(releases.update().await.is_err());
|
||||
assert!(
|
||||
crate::profile::dashboard(&Selection::default(), &releases)
|
||||
.verified_at
|
||||
.is_none()
|
||||
let failed = dashboard(&Selection::default(), &releases);
|
||||
assert_eq!(failed.user_agent, before.user_agent);
|
||||
assert_eq!(failed.verified_at, Some(old.verified_at));
|
||||
assert_eq!(failed.release.unwrap().status, DesktopReleaseStatus::Failed);
|
||||
|
||||
cache.fail.store(false, Ordering::SeqCst);
|
||||
let new = service
|
||||
.verify(&client, target, &new_release, Some(&old))
|
||||
.await
|
||||
.unwrap();
|
||||
releases.update().await.unwrap();
|
||||
let after = dashboard(&Selection::default(), &releases);
|
||||
assert_eq!(after.version, new_release.version);
|
||||
assert!(after.user_agent.contains("cl=2345678901"));
|
||||
assert_eq!(after.verified_at, Some(new.verified_at));
|
||||
assert_eq!(after.release.unwrap().status, DesktopReleaseStatus::Current);
|
||||
assert_eq!(
|
||||
ClientProfile::from_frozen(&frozen).unwrap().user_agent(),
|
||||
before.user_agent
|
||||
);
|
||||
}
|
||||
|
||||
@@ -74,7 +134,7 @@ async fn changed_artifact_or_target_and_failed_cache_do_not_publish_verification
|
||||
let service = VerificationCache::new(provider(), cache.clone());
|
||||
let client = reqwest::Client::new();
|
||||
let target = Selection::default().target();
|
||||
let release = release(&server, "2.35.1");
|
||||
let release = fixture_release(&server, "2.35.1");
|
||||
service
|
||||
.verify(&client, target, &release, None)
|
||||
.await
|
||||
@@ -132,7 +192,7 @@ async fn version_disagreement_leaves_the_previous_cache_intact() {
|
||||
let service = VerificationCache::new(provider(), cache.clone());
|
||||
let client = reqwest::Client::new();
|
||||
let target = Selection::default().target();
|
||||
let release = release(&server, "2.35.1");
|
||||
let release = fixture_release(&server, "2.35.1");
|
||||
let first = service
|
||||
.verify(&client, target, &release, None)
|
||||
.await
|
||||
|
||||
@@ -31,7 +31,7 @@ use wiremock::{
|
||||
};
|
||||
|
||||
fn frozen_profile() -> OpaqueProviderData {
|
||||
Selection::parse(&object(json!({"client":"cli","platform":"linux","versionMode":"fixed","clientVersion":"1.5.14","arch":null}))).unwrap().resolve("9.9.9").frozen()
|
||||
Selection::parse(&object(json!({"client":"cli","platform":"linux","versionMode":"fixed","clientVersion":"1.5.14","arch":null}))).unwrap().resolve("9.9.9", None).frozen()
|
||||
}
|
||||
|
||||
async fn released(fixture: &Fixture) {
|
||||
@@ -528,13 +528,14 @@ async fn connection_probe_reports_google_rejection_without_verification_links()
|
||||
async fn recovery_probe_does_not_mutate_credentials_cooldowns_or_scheduling_feedback() {
|
||||
for (status, kind) in [
|
||||
(401, ProviderErrorKind::Unauthorized),
|
||||
(403, ProviderErrorKind::PermissionDenied),
|
||||
(429, ProviderErrorKind::RateLimited),
|
||||
] {
|
||||
let upstream = MockServer::start().await;
|
||||
mock_project(&upstream).await;
|
||||
Mock::given(path("/v1internal:generateContent"))
|
||||
.and(body_partial_json(json!({"project":"probe-project"})))
|
||||
.respond_with(ResponseTemplate::new(status).insert_header("retry-after", "30"))
|
||||
.respond_with(ResponseTemplate::new(status).insert_header("retry-after", "30").set_body_json(if status == 403 {json!({"error":{"code":403,"status":"PERMISSION_DENIED","details":[{"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":"VALIDATION_REQUIRED"}]}})} else {json!({})}))
|
||||
.expect(1)
|
||||
.mount(&upstream)
|
||||
.await;
|
||||
@@ -560,6 +561,17 @@ async fn recovery_probe_does_not_mutate_credentials_cooldowns_or_scheduling_feed
|
||||
assert_eq!(error.upstream_status(), Some(status));
|
||||
assert!(!fixture.store.expired.load(Ordering::SeqCst));
|
||||
assert!(fixture.store.cooldowns.lock().unwrap().is_empty());
|
||||
assert_eq!(
|
||||
fixture
|
||||
.store
|
||||
.primary()
|
||||
.loaded
|
||||
.lock()
|
||||
.unwrap()
|
||||
.account
|
||||
.credential_state(),
|
||||
CredentialState::Ready
|
||||
);
|
||||
assert_eq!(
|
||||
fixture
|
||||
.feedback
|
||||
@@ -775,6 +787,7 @@ async fn chat_direct_genai_keeps_json_sse_usage_and_releases_the_native_lease()
|
||||
for streaming in [false, true] {
|
||||
let fixture = Fixture::new(&upstream.uri());
|
||||
let mut body = json!({"model":"fixture-model","stream":streaming,"messages":[{"role":"user","content":"hello"}],"max_completion_tokens":100,"reasoning_effort":"high","temperature":0.3,"top_p":0.8,"tools":[{"type":"function","function":{"name":"pwd","parameters":{"type":"object"}}}],"tool_choice":"required","response_format":{"type":"json_schema","json_schema":{"name":"result","schema":{"type":"object"}}}});
|
||||
body["stop"] = json!(["END", " STOP"]);
|
||||
body["messages"].as_array_mut().unwrap().insert(
|
||||
0,
|
||||
json!({"role":"system","content":"Preserve the caller's project rules."}),
|
||||
@@ -877,6 +890,10 @@ async fn chat_direct_genai_keeps_json_sse_usage_and_releases_the_native_lease()
|
||||
json!([{"text": if streaming { "Apply the caller's project rules." } else { "Preserve the caller's project rules." }}])
|
||||
);
|
||||
assert_eq!(body["request"]["generationConfig"]["maxOutputTokens"], 100);
|
||||
assert_eq!(
|
||||
body["request"]["generationConfig"]["stopSequences"],
|
||||
json!(["END", " STOP"])
|
||||
);
|
||||
assert_eq!(
|
||||
body["request"]["generationConfig"]["thinkingConfig"]["thinkingBudget"],
|
||||
24576
|
||||
|
||||
@@ -0,0 +1,522 @@
|
||||
//! Google 拒绝的协议交付、账号范围与查询反馈合同
|
||||
|
||||
use crate::support::{Fixture, context, request};
|
||||
use futures::TryStreamExt;
|
||||
use gateway_core::{
|
||||
account::{AccountErrorReason, CredentialState, ProviderAccountId, ProviderAccountStore},
|
||||
engine::provider::Provider,
|
||||
error::ProviderErrorKind as Kind,
|
||||
lifecycle::CancellationToken,
|
||||
};
|
||||
use serde_json::json;
|
||||
use wiremock::{Mock, MockServer, ResponseTemplate, matchers::path};
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_late_stream_denial_finishes_with_an_error_frame_and_disables_the_account() {
|
||||
let server = MockServer::start().await;
|
||||
let rejection = json!({"error":{"code":7,"status":"PERMISSION_DENIED","message":"Verify account.","details":[{"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":"VALIDATION_REQUIRED"}]}});
|
||||
let body = format!(
|
||||
"data: {}\n\ndata: {rejection}\n\n",
|
||||
json!({"response":{"candidates":[{"content":{"parts":[{"text":"partial"}]}}]}})
|
||||
);
|
||||
Mock::given(path("/v1internal:streamGenerateContent"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_raw(body, "text/event-stream"))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let fixture = Fixture::new(&server.uri());
|
||||
let mut stream = fixture
|
||||
.provider
|
||||
.clone()
|
||||
.execute(
|
||||
request(true),
|
||||
context(
|
||||
crate::profile::Selection::default()
|
||||
.resolve("2.34.0", None)
|
||||
.frozen(),
|
||||
CancellationToken::new(),
|
||||
),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let first = stream.try_next().await.unwrap().unwrap();
|
||||
assert!(
|
||||
first
|
||||
.wire_event()
|
||||
.unwrap()
|
||||
.data()
|
||||
.to_string()
|
||||
.contains("partial")
|
||||
);
|
||||
let mut error = stream.try_next().await.unwrap_err();
|
||||
assert!(error.retry_is_prohibited());
|
||||
let events = error.take_atomic_client_events();
|
||||
assert_eq!(events.len(), 1);
|
||||
assert_eq!(
|
||||
events[0].wire_event().unwrap().data()["error"]["details"][0]["reason"],
|
||||
"VALIDATION_REQUIRED"
|
||||
);
|
||||
assert!(stream.try_next().await.unwrap().is_none());
|
||||
assert_eq!(
|
||||
fixture
|
||||
.store
|
||||
.primary()
|
||||
.loaded
|
||||
.lock()
|
||||
.unwrap()
|
||||
.account
|
||||
.credential_state(),
|
||||
CredentialState::Invalid
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn count_tokens_recognizes_a_success_status_containing_an_rpc_denial() {
|
||||
use gateway_core::{
|
||||
engine::provider::ProviderRequest,
|
||||
operation::{Operation, RawJsonPayload, TokenCountRequest},
|
||||
};
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(path("/v1internal:countTokens")).respond_with(ResponseTemplate::new(200).set_body_json(json!({"error":{"code":7,"status":"PERMISSION_DENIED","details":[{"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":"VALIDATION_REQUIRED"}]}}))).expect(1).mount(&server).await;
|
||||
let fixture = Fixture::new(&server.uri());
|
||||
let input = ProviderRequest::new(
|
||||
Operation::CountTokens(TokenCountRequest::from_raw_json(
|
||||
RawJsonPayload::new("genai", br#"{"contents":[]}"#.as_slice().into()).unwrap(),
|
||||
)),
|
||||
request(false).candidate().clone(),
|
||||
);
|
||||
let error = fixture
|
||||
.provider
|
||||
.clone()
|
||||
.execute(
|
||||
input,
|
||||
context(
|
||||
crate::profile::Selection::default()
|
||||
.resolve("2.34.0", None)
|
||||
.frozen(),
|
||||
CancellationToken::new(),
|
||||
),
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
.try_collect::<Vec<_>>()
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(error.kind(), Kind::PermissionDenied);
|
||||
assert_eq!(
|
||||
error.client_visible_upstream_response().unwrap().status(),
|
||||
403
|
||||
);
|
||||
assert_eq!(
|
||||
fixture
|
||||
.store
|
||||
.primary()
|
||||
.loaded
|
||||
.lock()
|
||||
.unwrap()
|
||||
.account
|
||||
.last_error_reason(),
|
||||
Some(AccountErrorReason::AccountUnverified)
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn structured_denials_preserve_protocol_and_only_suspend_the_confirmed_account() {
|
||||
for (status, reason, state, error_reason) in [
|
||||
(
|
||||
403,
|
||||
"VALIDATION_REQUIRED",
|
||||
CredentialState::Invalid,
|
||||
Some(AccountErrorReason::AccountUnverified),
|
||||
),
|
||||
(
|
||||
403,
|
||||
"TOS_VIOLATION",
|
||||
CredentialState::Banned,
|
||||
Some(AccountErrorReason::AccountBanned),
|
||||
),
|
||||
(
|
||||
403,
|
||||
"WORKSPACE_TOS_VIOLATION_CONTACT_SUPPORT",
|
||||
CredentialState::Banned,
|
||||
Some(AccountErrorReason::AccountBanned),
|
||||
),
|
||||
(
|
||||
200,
|
||||
"WORKSPACE_TOS_VIOLATION_CONTACT_SUPPORT",
|
||||
CredentialState::Banned,
|
||||
Some(AccountErrorReason::AccountBanned),
|
||||
),
|
||||
(
|
||||
403,
|
||||
"ACCESS_TOKEN_SCOPE_INSUFFICIENT",
|
||||
CredentialState::Ready,
|
||||
None,
|
||||
),
|
||||
(403, "PROJECT_DISABLED", CredentialState::Ready, None),
|
||||
(403, "AI_POLICY_REQUIRED", CredentialState::Ready, None),
|
||||
(
|
||||
200,
|
||||
"VALIDATION_REQUIRED",
|
||||
CredentialState::Invalid,
|
||||
Some(AccountErrorReason::AccountUnverified),
|
||||
),
|
||||
] {
|
||||
let server = MockServer::start().await;
|
||||
let metadata = json!({
|
||||
"validation_url":"https://accounts.example.test/verify?nonce=private",
|
||||
"appeal_url":"https://accounts.example.test/appeal?nonce=private",
|
||||
"appeal_url_link_text":"Submit Appeal",
|
||||
"uiMessage":"Account action required."
|
||||
});
|
||||
let mut body = json!({"error":{"code": if status == 200 {7} else {403},"status":"PERMISSION_DENIED","message":"Verify your account to continue.","details":[
|
||||
{"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":"ACCESS_TOKEN_SCOPE_INSUFFICIENT"},
|
||||
{"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":reason,"metadata":metadata}
|
||||
]}});
|
||||
if state == CredentialState::Banned {
|
||||
body["error"]["details"].as_array_mut().unwrap().push(json!({"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":"VALIDATION_REQUIRED"}));
|
||||
} else if reason == "AI_POLICY_REQUIRED" {
|
||||
body["error"]["details"].as_array_mut().unwrap().push(json!({"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":"PROJECT_DISABLED"}));
|
||||
}
|
||||
Mock::given(path("/v1internal:generateContent"))
|
||||
.respond_with(ResponseTemplate::new(status).set_body_json(body))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let fixture = Fixture::with_two_accounts(&server.uri());
|
||||
let mut error = fixture
|
||||
.provider
|
||||
.clone()
|
||||
.execute(
|
||||
request(false),
|
||||
context(
|
||||
crate::profile::Selection::default()
|
||||
.resolve("2.34.0", None)
|
||||
.frozen(),
|
||||
CancellationToken::new(),
|
||||
),
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
.try_collect::<Vec<_>>()
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(error.kind(), Kind::PermissionDenied);
|
||||
assert_eq!(error.upstream_status(), Some(403));
|
||||
assert_eq!(
|
||||
error.retry_is_prohibited(),
|
||||
error_reason.is_some() || reason == "AI_POLICY_REQUIRED"
|
||||
);
|
||||
let fields = error.upstream_failure_fields().unwrap();
|
||||
assert_eq!(fields.code.as_deref(), Some(reason));
|
||||
let response = error.client_visible_upstream_response().unwrap();
|
||||
assert_eq!(response.status(), 403);
|
||||
let response: serde_json::Value = serde_json::from_slice(response.body()).unwrap();
|
||||
assert_eq!(response["error"]["code"], 403);
|
||||
assert_eq!(response["error"]["status"], "PERMISSION_DENIED");
|
||||
assert_eq!(response["error"]["details"][0]["reason"], reason);
|
||||
assert_eq!(
|
||||
response["error"]["message"],
|
||||
"Verify your account to continue."
|
||||
);
|
||||
assert!(response["error"]["details"][0].get("metadata").is_none());
|
||||
assert!(!response.to_string().contains("nonce=private"));
|
||||
let raw: serde_json::Value =
|
||||
serde_json::from_str(error.raw_upstream_error().unwrap().as_str()).unwrap();
|
||||
assert_eq!(raw["error"]["details"][1]["metadata"], metadata);
|
||||
let events = error.take_atomic_client_events();
|
||||
assert_eq!(events.len(), 1);
|
||||
assert_eq!(events[0].wire_event().unwrap().data(), &response);
|
||||
{
|
||||
let loaded = fixture.store.primary().loaded.lock().unwrap();
|
||||
assert_eq!(loaded.account.credential_state(), state);
|
||||
assert_eq!(loaded.account.last_error_reason(), error_reason);
|
||||
}
|
||||
let standby = fixture
|
||||
.store
|
||||
.get_account(&ProviderAccountId::new("acct_standby").unwrap())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(standby.credential_state(), CredentialState::Ready);
|
||||
if error_reason.is_some() {
|
||||
assert_eq!(
|
||||
fixture
|
||||
.provider
|
||||
.clone()
|
||||
.execute(
|
||||
request(false),
|
||||
context(
|
||||
crate::profile::Selection::default()
|
||||
.resolve("2.34.0", None)
|
||||
.frozen(),
|
||||
CancellationToken::new()
|
||||
)
|
||||
)
|
||||
.await
|
||||
.err()
|
||||
.unwrap()
|
||||
.kind(),
|
||||
Kind::NoEligibleAccount
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn not_found_preserves_the_upstream_error_without_penalizing_the_account() {
|
||||
for stream in [false, true] {
|
||||
let server = MockServer::start().await;
|
||||
let body = json!({"error":{"code":404,"status":"NOT_FOUND","message":"Requested entity was not found."}});
|
||||
Mock::given(path(if stream {
|
||||
"/v1internal:streamGenerateContent"
|
||||
} else {
|
||||
"/v1internal:generateContent"
|
||||
}))
|
||||
.respond_with(ResponseTemplate::new(404).set_body_json(&body))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let fixture = Fixture::new(&server.uri());
|
||||
let error = fixture
|
||||
.provider
|
||||
.clone()
|
||||
.execute(
|
||||
request(stream),
|
||||
context(
|
||||
crate::profile::Selection::default()
|
||||
.resolve("2.37.0", None)
|
||||
.frozen(),
|
||||
CancellationToken::new(),
|
||||
),
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
.try_collect::<Vec<_>>()
|
||||
.await
|
||||
.unwrap_err();
|
||||
let response = error.client_visible_upstream_response().unwrap();
|
||||
assert_eq!(response.status(), 404);
|
||||
assert_eq!(
|
||||
serde_json::from_slice::<serde_json::Value>(response.body()).unwrap(),
|
||||
body
|
||||
);
|
||||
assert_eq!(
|
||||
error.upstream_failure_fields().unwrap().code.as_deref(),
|
||||
Some("404")
|
||||
);
|
||||
let loaded = fixture.store.primary().loaded.lock().unwrap();
|
||||
assert_eq!(loaded.account.credential_state(), CredentialState::Ready);
|
||||
assert_eq!(loaded.account.last_error_reason(), None);
|
||||
assert!(fixture.store.cooldowns.lock().unwrap().is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn untyped_and_sensitive_denials_cannot_change_account_state_or_escape_diagnostics() {
|
||||
for (typed, message) in [(false, "VALIDATION_REQUIRED"), (true, "fixture-access")] {
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(path("/v1internal:generateContent"))
|
||||
.respond_with(ResponseTemplate::new(403).set_body_json(json!({"error":{"status":"PERMISSION_DENIED","message":message,"details":[{"@type":if typed {"type.googleapis.com/google.rpc.ErrorInfo"} else {"unknown"},"reason":"VALIDATION_REQUIRED"}]}})))
|
||||
.expect(1).mount(&server).await;
|
||||
let fixture = Fixture::new(&server.uri());
|
||||
let error = fixture
|
||||
.provider
|
||||
.clone()
|
||||
.execute(
|
||||
request(false),
|
||||
context(
|
||||
crate::profile::Selection::default()
|
||||
.resolve("2.34.0", None)
|
||||
.frozen(),
|
||||
CancellationToken::new(),
|
||||
),
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
.try_collect::<Vec<_>>()
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(
|
||||
fixture
|
||||
.store
|
||||
.primary()
|
||||
.loaded
|
||||
.lock()
|
||||
.unwrap()
|
||||
.account
|
||||
.credential_state(),
|
||||
CredentialState::Ready
|
||||
);
|
||||
assert!(error.upstream_code().is_none());
|
||||
assert!(
|
||||
!String::from_utf8_lossy(error.client_visible_upstream_response().unwrap().body())
|
||||
.contains("fixture-access")
|
||||
);
|
||||
assert_eq!(error.raw_upstream_error().is_some(), !typed);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn resource_queries_share_denial_state_and_background_queries_stop() {
|
||||
for (quota, api_key) in [(false, false), (true, false), (false, true)] {
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(path(if api_key {"/v1beta/models"} else {"/v1internal:loadCodeAssist"}))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({"error":{"code":7,"status":"PERMISSION_DENIED","details":[{"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":"VALIDATION_REQUIRED"}]}})))
|
||||
.expect(1).mount(&server).await;
|
||||
let fixture = Fixture::new(&server.uri());
|
||||
if api_key {
|
||||
fixture
|
||||
.store
|
||||
.use_api_key(&format!("{}/v1beta", server.uri()));
|
||||
}
|
||||
let account = fixture
|
||||
.store
|
||||
.primary()
|
||||
.loaded
|
||||
.lock()
|
||||
.unwrap()
|
||||
.account
|
||||
.clone();
|
||||
if quota {
|
||||
assert!(fixture.quota.refresh(account.id()).await.is_err());
|
||||
} else {
|
||||
assert!(
|
||||
fixture
|
||||
.catalog
|
||||
.account_models(account.id(), true)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
fixture
|
||||
.store
|
||||
.primary()
|
||||
.loaded
|
||||
.lock()
|
||||
.unwrap()
|
||||
.account
|
||||
.last_error_reason(),
|
||||
Some(AccountErrorReason::AccountUnverified)
|
||||
);
|
||||
*fixture.store.primary().catalog.lock().unwrap() = None;
|
||||
if !api_key {
|
||||
fixture
|
||||
.quota
|
||||
.reconcile(&CancellationToken::new())
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
fixture
|
||||
.catalog
|
||||
.reconcile(&CancellationToken::new())
|
||||
.await
|
||||
.unwrap();
|
||||
fixture
|
||||
.catalog
|
||||
.account_models(account.id(), false)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(server.received_requests().await.unwrap().len(), 1);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn quota_capacity_and_symbolic_rpc_errors_keep_distinct_facts() {
|
||||
for (status, code, rpc, reason, kind, mapped) in [
|
||||
(
|
||||
429,
|
||||
Some(429),
|
||||
"RESOURCE_EXHAUSTED",
|
||||
"QUOTA_EXHAUSTED",
|
||||
Kind::QuotaExhausted,
|
||||
429,
|
||||
),
|
||||
(
|
||||
429,
|
||||
Some(429),
|
||||
"RESOURCE_EXHAUSTED",
|
||||
"MODEL_CAPACITY_EXHAUSTED",
|
||||
Kind::RateLimited,
|
||||
429,
|
||||
),
|
||||
(
|
||||
503,
|
||||
Some(503),
|
||||
"UNAVAILABLE",
|
||||
"MODEL_CAPACITY_EXHAUSTED",
|
||||
Kind::UpstreamCapacityUnavailable,
|
||||
503,
|
||||
),
|
||||
(
|
||||
200,
|
||||
Some(8),
|
||||
"RESOURCE_EXHAUSTED",
|
||||
"RATE_LIMIT_EXCEEDED",
|
||||
Kind::RateLimited,
|
||||
429,
|
||||
),
|
||||
(
|
||||
200,
|
||||
None,
|
||||
"PERMISSION_DENIED",
|
||||
"ACCESS_TOKEN_SCOPE_INSUFFICIENT",
|
||||
Kind::PermissionDenied,
|
||||
403,
|
||||
),
|
||||
] {
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(path("/v1internal:generateContent"))
|
||||
.respond_with(ResponseTemplate::new(status).set_body_json(json!({"error":{"code":code,"status":rpc,"message":"Rejected.","details":[{"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":reason},{"@type":"type.googleapis.com/google.rpc.RetryInfo","retryDelay":"30s"}]}})))
|
||||
.expect(1).mount(&server).await;
|
||||
let fixture = Fixture::new(&server.uri());
|
||||
let error = fixture
|
||||
.provider
|
||||
.clone()
|
||||
.execute(
|
||||
request(false),
|
||||
context(
|
||||
crate::profile::Selection::default()
|
||||
.resolve("2.34.0", None)
|
||||
.frozen(),
|
||||
CancellationToken::new(),
|
||||
),
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
.try_collect::<Vec<_>>()
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(error.kind(), kind);
|
||||
assert_eq!(error.upstream_status(), Some(mapped));
|
||||
let response = error.client_visible_upstream_response().unwrap();
|
||||
let body: serde_json::Value = serde_json::from_slice(response.body()).unwrap();
|
||||
assert_eq!(body["error"]["details"][1]["retryDelay"], "30.000000000s");
|
||||
assert!(
|
||||
response
|
||||
.headers()
|
||||
.iter()
|
||||
.any(|header| header.name() == "retry-after" && header.value().as_ref() == b"30")
|
||||
);
|
||||
assert_eq!(
|
||||
error.upstream_failure_fields().unwrap().code.as_deref(),
|
||||
Some(reason)
|
||||
);
|
||||
assert_eq!(
|
||||
fixture
|
||||
.store
|
||||
.primary()
|
||||
.loaded
|
||||
.lock()
|
||||
.unwrap()
|
||||
.account
|
||||
.credential_state(),
|
||||
CredentialState::Ready
|
||||
);
|
||||
assert_eq!(
|
||||
fixture.store.cooldowns.lock().unwrap().len(),
|
||||
usize::from(mapped != 403)
|
||||
);
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user