Compare commits

..
Author SHA1 Message Date
ZyyandCodex f43e1f95c3 chore: bump version to 3.61.1-rc.5
Co-authored-by: Codex <noreply@openai.com>
2026-12-04 17:57:14 +08:00
21cf139c96 fix(openai): keep slow model catalog refreshes alive (#846)
Use a 30-second idle timeout for account retries and manual refreshes while keeping ordinary discovery bounded. Let the admin UI wait for these refreshes until completion or cancellation.

Co-authored-by: Zyy <zyycn@users.noreply.github.com>
Co-authored-by: Codex <noreply@openai.com>
2026-12-04 17:49:30 +08:00
ZyyandCodex 7d6e4cc4e7 fix(openai): limit model retry hints to scoped rate limits
Keep ordinary account cooldowns on their existing selection path, including peer accounts after quota synchronization.

Co-authored-by: Codex <noreply@openai.com>
2026-12-04 17:40:15 +08:00
ZyyandCodex 2ddcd7c936 feat(openai): track turn rate limits per account and model
Preserve session scheduling and retry hints while a model cools down. Show active model limits and their recovery times in the account list.

Co-authored-by: Codex <noreply@openai.com>
2026-12-04 17:17:10 +08:00
ZyyandCodex c71e6176c5 fix(web): add a subtle surface to client import options
Give the tool row a persistent muted background and light shadow, and
increase the inset around the GitHub link.

Co-authored-by: Codex <noreply@openai.com>
2026-12-04 14:54:47 +08:00
ZyyandCodex 28d3e3c2cb fix(web): centralize page sizing and preserve PWA bottom spacing
Keep long pages naturally sized and share the available page height across
viewport-bound panels. Let list cards fill the remaining space while
preserving internal scrolling and pagination in short windows.

Co-authored-by: Codex <noreply@openai.com>
2026-12-04 14:54:46 +08:00
dd793a84ab fix(protocol): preserve tool semantics across Chat and Codex (#844)
Support named independent tool outputs and flatten custom grammar formats.
Adapt Codex search aliases, long call IDs and tool names while preserving
history pairing and restoring client-visible names in JSON and SSE.

Refs #843

Co-authored-by: Zyy <zyycn@users.noreply.github.com>
Co-authored-by: Codex <noreply@openai.com>
2026-12-04 14:13:31 +08:00
ZyyandCodex 5ed8b626d7 docs(skills): ground safeguards in expected behavior
Co-authored-by: Codex <noreply@openai.com>
2026-12-04 13:33:50 +08:00
ZyyandCodex 96d8b25d0b fix(store): skip nested requests in key recovery and accept large limits
Co-authored-by: Codex <noreply@openai.com>
2026-12-04 13:25:44 +08:00
Zyy a193de4eba fix(providers): align SSE history reuse with Codex and use disk for Antigravity artifacts 2026-12-04 13:07:26 +08:00
github-actions[bot] e296bef65e chore(release): update release channels to 3.61.1-rc.4 2026-12-04 04:09:54 +00:00
ZyyandCodex 89092272a1 docs(readme): add the Telegram community invite
Co-authored-by: Codex <noreply@openai.com>
2026-12-04 11:49:02 +08:00
ZyyandCodex 09f3b39bbc chore: bump version to 3.61.1-rc.4
Co-authored-by: Codex <noreply@openai.com>
2026-12-04 11:37:01 +08:00
7591845f74 fix(openai): honor chat session affinity during account selection (#842)
Co-authored-by: Zyy <zyycn@users.noreply.github.com>
Co-authored-by: Codex <noreply@openai.com>
2026-12-04 11:27:41 +08:00
ZyyandCodex 67ac8fd067 fix(deps): update DOMPurify to 3.5.1
Co-authored-by: Codex <noreply@openai.com>
2026-12-04 11:14:27 +08:00
b232e367fc fix(openai): defer failed account catalog refresh with per-scope backoff (#839)
* fix(openai): defer failed account catalog refresh with per-scope backoff

* style: cargo fmt refresh.rs

* fix(openai): keep stale-catalog accounts probeable during refresh backoff

* fix(openai): schedule account catalog retries independently

Co-authored-by: Codex <noreply@openai.com>

---------

Co-authored-by: Zyy <zyycn@users.noreply.github.com>
Co-authored-by: Codex <noreply@openai.com>
2026-12-04 11:02:02 +08:00
ZyyandCodex 0bdaa29907 fix(ui): clarify update actions and align dashboard empty state
Co-authored-by: Codex <noreply@openai.com>
2026-12-03 21:13:07 +08:00
github-actions[bot] cc798e33a1 chore(release): update release channels to 3.61.1-rc.3 2026-12-03 18:48:31 +08:00
ZyyandCodex 6eabda047c chore: bump version to 3.61.1-rc.3
Co-authored-by: Codex <noreply@openai.com>
2026-12-03 18:48:31 +08:00
ZyyandCodex 3c560b9276 fix(ui): unify account subscription badges
Use compact badges in the dashboard and switch account rows to a stacked layout when the card is narrow.

Co-authored-by: Codex <noreply@openai.com>
2026-12-03 17:59:10 +08:00
ZyyandCodex 77c42cea98 fix(antigravity): publish verified client profiles
Derive changelists from official client artifacts and publish them with the
matching version only after verification. Restore profiles from the shared
cache at startup and check release metadata hourly.

Filter gateway fingerprint status from OAuth requests and recognize structured
workspace policy denials without changing unrelated request data.

Co-authored-by: Codex <noreply@openai.com>
2026-12-03 17:44:09 +08:00
ZyyandCodex dd234c3619 fix(antigravity): preserve structured Google denials
Preserve RPC status, ErrorInfo reasons and retry hints across generation,
token counting and resource queries. Isolate confirmed account denials,
keep verification links in diagnostics, and preserve access state during
token refresh.

Cover in-band and streaming failures, background query suppression and
stale credential feedback with regression tests.

Refs #836

Co-authored-by: Codex <noreply@openai.com>
2026-12-03 16:07:12 +08:00
ZyyandCodex b5e691c63d fix(dashboard): animate incremental data updates
Preserve chart state across updates and animate capacity, status distribution, and account reordering. Keep metric transition values synchronized when reduced motion is enabled.

Co-authored-by: Codex <noreply@openai.com>
2026-12-03 14:50:05 +08:00
Zyy 2d0a52096a fix(workers): prioritize shutdown during background tasks 2026-12-03 13:56:18 +08:00
github-actions[bot] 47620e217a chore(release): update release channels to 3.61.1-rc.2 2026-12-03 05:16:01 +00:00
178 changed files with 5250 additions and 1341 deletions

No files matched your search

+3 -1
View File
@@ -16,6 +16,8 @@ description: Codex Proxy RS 的需求评估、排障、开发、代码审查与
评估功能建议、排障、开发和审查时,先按[问题与方案依据](../../../CONTRIBUTING.md#问题与方案依据)核实使用者要完成什么、当前行为造成了什么影响。反馈直接给出改法时,先弄清提出这个改法的原因
先确定正常使用时应得到的结果。设计校验、回退或故障恢复时,同时看它防住的具体风险和它可能挡住的正常用法。按协议、隔离要求和实际部署条件选择对正常路径影响最小的做法。只在假设的部署场景下才需要的处理,留到有相应需求时再做
排查故障时,从症状沿实际调用链回溯,定位行为最早偏离预期的环节,用源码、诊断或对照复现说明触发条件如何导致结果。原因尚未确定时,区分已知事实与假设,指出哪项证据能区分可能原因。确认根因后,在负责该行为的模块修复,用原触发场景验证
涉及 Codex 时,以对应版本的官方源码核实客户端行为,默认透明转发,只做必要适配。建议宿主接管已有决定时,指出需要它介入的网关职责或实际约束。若只是个别部署希望采用不同策略,说明不建议内置的原因。实现可行性不能证明宿主应当承担这项需求
@@ -56,7 +58,7 @@ description: Codex Proxy RS 的需求评估、排障、开发、代码审查与
- 移动或重命名测试时,核对受影响的场景覆盖是否保留;涉及子进程调用或名称过滤时,同步更新调用入口并实际运行,确认目标用例确实执行且行为断言通过
- 清理只证明旧字段、旧路由或旧实现已经消失的用例与附带断言;未知字段校验使用合法请求基线加无业务含义的未知字段,避免因缺少必填项等其他错误而误通过
- 同一层对同一行为的重复覆盖合并为清晰的场景矩阵,复用相邻测试夹具;跨层测试确有不同职责或失败路径时保留,不为统一而扩大测试辅助抽象
- 断言可观察的行为与业务不变量,避免复述结构体赋值、罗列表列或字段清单、匹配 SQL 文本与源码布局
- 断言可观察的行为与业务不变量,避免复述实现细节。验收上游兼容行为时,先从对应版本的上游实现确定预期,再核对网关对同一输入的处理。例如历史应增量续接时,要看出站请求是否只含预期的增量,因为回退全量也可能返回成功
- 维护项目明确要求的架构边界检查;发现漏检时,对照规则核实扫描范围、排除项与被检查的依赖关系,优先补齐现有检查中能稳定判定的缺口
- 当前协议兼容、数据读取兼容、安全边界、并发和资源生命周期仍需覆盖,不按 `old`、`legacy` 等名称机械删除,也不能用改名代替无效用例清理
- 不在仓库中新增或保留迁移 SQL 专项测试,包括迁移文本、schema 演变与指定版本升级用例;需要验证迁移执行、数据保留或回滚时,在临时目录编写一次性验证并使用隔离数据库,测试通过即可,临时脚本不纳入维护测试集
+13 -7
View File
@@ -12,7 +12,7 @@
[![GHCR](https://img.shields.io/badge/GHCR-codex--proxy--rs-2496ED?logo=docker&logoColor=white&style=flat-square)](https://github.com/zyycn/codex-proxy-rs/pkgs/container/codex-proxy-rs)
[![License: Apache 2.0](https://img.shields.io/badge/License-Apache%202.0-blue.svg?style=flat-square)](LICENSE)
[快速预览](#快速预览) · [快速开始](#快速开始) · [文档](#文档) · [社区](#社区) · [贡献者](#贡献者) · [Star History](#star-history) · [支持项目](#支持项目) · [许可证](#许可证)
[快速预览](#快速预览) · [快速开始](#快速开始) · [文档](#文档) · [贡献者](#贡献者) · [Star History](#star-history) · [社区](#社区) · [支持项目](#支持项目) · [许可证](#许可证)
</div>
@@ -49,12 +49,6 @@ curl -fsSL https://raw.githubusercontent.com/zyycn/codex-proxy-rs/main/deploy/in
| 开发宿主 | [开发与源码联调](docs/development.md) · [系统架构](docs/architecture.md) · [管理端主题](docs/theme.md) · [数据库迁移](backend/migrations/README.md) |
| 参与协作 | [贡献、审查与验证](CONTRIBUTING.md) |
## 社区
问题反馈与功能建议请使用 [GitHub Issues](https://github.com/zyycn/codex-proxy-rs/issues),填写要求见 [贡献说明](CONTRIBUTING.md#提交-issue)
感谢 [LINUX DO](https://linux.do) 社区提供开放、友善的技术交流平台
## 贡献者
[<img src="https://contrib.rocks/image?repo=zyycn/codex-proxy-rs&amp;columns=10" alt="查看 GitHub 贡献者列表" width="480">](https://github.com/zyycn/codex-proxy-rs/graphs/contributors)
@@ -68,6 +62,18 @@ curl -fsSL https://raw.githubusercontent.com/zyycn/codex-proxy-rs/main/deploy/in
</picture>
</a>
## 社区
点击或扫码加入 Telegram 群 [小酒馆][telegram-group]
[<img src="docs/community/telegram-qr.png" alt="扫码加入小酒馆 Telegram 群" width="138">][telegram-group]
[telegram-group]: https://t.me/+9tk761zbNAMyNWY9
问题反馈与功能建议请使用 [GitHub Issues](https://github.com/zyycn/codex-proxy-rs/issues),填写要求见 [贡献说明](CONTRIBUTING.md#提交-issue)
感谢 [LINUX DO](https://linux.do) 社区提供开放、友善的技术交流平台
## 支持项目
如果 Codex Proxy RS 帮助到你了,欢迎请我喝杯咖啡 ☕
+19
View File
@@ -2708,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"
@@ -3405,6 +3411,7 @@ dependencies = [
"reqwest",
"serde",
"serde_json",
"sevenz-rust2",
"sha2",
"tar",
"tempfile",
@@ -4186,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,11 @@ impl Providers {
)
.await?;
environment.host.report_startup_ready("OpenAI Provider");
let antigravity = provider_antigravity::initialize(ports.clone())?;
let antigravity = provider_antigravity::initialize(
ports.clone(),
environment.host.runtime_data_dir().join("antigravity"),
)
.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(())
})
}
@@ -92,6 +92,9 @@ pub struct AccountListQuery {
/// Admin query service 从运行态存储取得的当前账号冷却快照
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct AccountRuntimeSnapshot {
/// 模型维度冷却独立于整账号冷却,不能据此阻断其他模型
pub model_cooldowns:
BTreeMap<String, Vec<gateway_core::provider_ports::ProviderScopedCooldown>>,
pub protection_rules: BTreeMap<String, Vec<gateway_core::account::AccountProtectionMatch>>,
pub cooldown: BTreeMap<String, gateway_core::account::AccountCooldown>,
/// `None` 表示实时 lease 存储不可用;`Some` 中未出现的账号当前使用量为零
@@ -223,6 +226,7 @@ pub struct AccountPage {
/// 同一状态快照下的账号事实与唯一状态投影
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AccountPageItem {
pub model_cooldowns: Vec<gateway_core::provider_ports::ProviderScopedCooldown>,
pub platform_icon: Option<String>,
pub protection_rules: Vec<gateway_core::account::AccountProtectionMatch>,
pub account: AccountRecord,
@@ -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;
@@ -1319,6 +1319,7 @@ impl fmt::Debug for ProviderExport {
/// 统一账号目录的一行完整结果
#[derive(Debug, Clone, PartialEq)]
pub struct AccountDirectoryItem {
pub model_cooldowns: Vec<gateway_core::provider_ports::ProviderScopedCooldown>,
pub platform_icon: Option<String>,
pub protection_rules: Vec<gateway_core::account::AccountProtectionMatch>,
pub account: AccountRecord,
@@ -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(())
}
}
@@ -513,6 +513,7 @@ impl DefaultAccountsService {
lookback,
);
Ok(AccountDirectoryItem {
model_cooldowns: stored.model_cooldowns,
platform_icon: stored.platform_icon,
protection_rules: stored.protection_rules,
capacity: super::peer_link::upstream::account_capacity(
@@ -648,6 +649,7 @@ impl AccountsService for DefaultAccountsService {
lookback,
);
Ok(AccountDirectoryItem {
model_cooldowns: item.model_cooldowns,
platform_icon: item.platform_icon,
protection_rules: item.protection_rules,
capacity: crate::model::accounts::AccountCapacity {
@@ -315,6 +315,7 @@ impl AccountRuntimeStore for FakeRuntimeStore {
) -> AdminStoreResult<AccountRuntimeSnapshot> {
*self.requested_accounts.lock().expect("requested accounts") = account_ids.to_vec();
Ok(AccountRuntimeSnapshot {
model_cooldowns: BTreeMap::new(),
protection_rules: std::collections::BTreeMap::new(),
cooldown: BTreeMap::from([(
"acct_limited".to_owned(),
@@ -740,6 +740,7 @@ impl FakeAccountStore {
last_error_message: account.last_error_message.clone(),
};
AccountPageItem {
model_cooldowns: Vec::new(),
platform_icon: None,
protection_rules: Vec::new(),
capacity: gateway_admin::model::accounts::AccountCapacity {
@@ -67,6 +67,7 @@ pub(super) fn account_view(
time: crate::time::TimePresenter,
) -> AccountView {
let AccountDirectoryItem {
model_cooldowns,
platform_icon,
account,
capacity,
@@ -111,6 +112,17 @@ pub(super) fn account_view(
.map(|value| super::upstream_info::view(value, now, time));
let (mut quota, refresh_token_expires_at) = account_quota_view(quota, cooldown, now, time);
quota.protection_rules = protection_rules;
quota.model_rate_limits = model_cooldowns
.into_iter()
.map(|cooldown| {
let until: DateTime<Utc> = cooldown.until().into();
AccountModelRateLimitView {
model: cooldown.scope().value().to_owned(),
until: time.rfc3339(&until),
until_display: time.datetime(&until),
}
})
.collect();
AccountView {
platform_icon,
quota_settings: account.quota_settings,
@@ -271,6 +283,7 @@ pub(super) fn account_quota_view(
let recovery_probe_required = cooldown.is_some_and(|value| value.kind.requires_probe());
(
AccountQuotaView {
model_rate_limits: Vec::new(),
paused_windows: quota.paused_windows,
refreshed_at: quota.observed_at.map(|value| time.rfc3339(&value)),
refreshed_at_relative: quota
@@ -382,6 +382,7 @@ pub use crate::admin::account_groups::AccountGroupRefView;
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AccountQuotaView {
pub model_rate_limits: Vec<AccountModelRateLimitView>,
pub paused_windows: Vec<String>,
pub refreshed_at: Option<String>,
pub refreshed_at_relative: Option<crate::time::RelativeTimeView>,
@@ -397,6 +398,14 @@ pub struct AccountQuotaView {
pub credits: Option<AccountQuotaCreditsView>,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AccountModelRateLimitView {
pub model: String,
pub until: String,
pub until_display: String,
}
/// 上游点数安全视图,不透出额度响应中的其他 Provider 字段
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
+12 -10
View File
@@ -119,22 +119,24 @@ pub fn gateway_error_response(error: &GatewayError) -> Response {
}
let mut response = (status, Json(body)).into_response();
response.extensions_mut().insert(error.clone());
if let Some(delay) = error.retry_after()
&& let Ok(value) = HeaderValue::from_str(
&delay
.as_secs()
.saturating_add(u64::from(delay.subsec_nanos() > 0))
.max(1)
.to_string(),
)
{
if let Some(seconds) = retry_after_seconds(error) {
response
.headers_mut()
.insert(axum::http::header::RETRY_AFTER, value);
.insert(axum::http::header::RETRY_AFTER, HeaderValue::from(seconds));
}
response
}
/// HTTP 和 WS 的等待秒数均向上取整,避免客户端在冷却到期前重新发起请求
pub(crate) fn retry_after_seconds(error: &GatewayError) -> Option<u64> {
error.retry_after().map(|delay| {
delay
.as_secs()
.saturating_add(u64::from(delay.subsec_nanos() > 0))
.max(1)
})
}
/// Gateway 错误稳定映射,供 HTTP、SSE 和 WebSocket 共用
#[must_use]
pub const fn gateway_error_contract(
@@ -185,6 +185,9 @@ pub(super) fn initial_engine_error_event(
response_event_headers(response_headers)
};
if upstream.is_none() {
if let Some(seconds) = crate::client_error::retry_after_seconds(&gateway) {
headers.insert("retry-after".to_owned(), Value::String(seconds.to_string()));
}
// 会话 opening 身份不证明当前失败属于该请求;仅保留其他允许的会话头
for name in RESPONSE_REQUEST_ID_HEADERS {
headers.remove(name);
@@ -255,6 +255,18 @@ async fn account_cooldown_returns_an_instant_and_server_formatted_recovery() {
last_error_message: None,
};
let mut item = account_page_item(facts, now, "oauth");
let model_until = now + Duration::seconds(8);
item.model_cooldowns = vec![gateway_core::provider_ports::ProviderScopedCooldown::new(
gateway_core::account::ProviderAccountId::new(item.account.id.clone()).unwrap(),
gateway_core::account::CredentialRevision::new(
item.account.credential_revision.get(),
)
.unwrap(),
gateway_core::provider_ports::ProviderCooldownScope::upstream_model(
gateway_core::routing::UpstreamModelId::new("gpt-5.4").unwrap(),
),
model_until.into(),
)];
if kind.is_error_protection() {
item.protection_rules = vec![gateway_core::account::AccountProtectionMatch {
id: "removed-rule".to_owned(),
@@ -278,6 +290,14 @@ async fn account_cooldown_returns_an_instant_and_server_formatted_recovery() {
let body = to_bytes(response.into_body(), 32768).await.unwrap();
let value: serde_json::Value = serde_json::from_slice(&body).unwrap();
let quota = &value["data"]["items"][0]["quota"];
assert_eq!(
quota["modelRateLimits"],
serde_json::json!([{
"model": "gpt-5.4",
"until": zone.local(model_until).to_rfc3339(),
"untilDisplay": zone.local(model_until).format("%Y-%m-%d %H:%M:%S").to_string(),
}])
);
if kind.is_error_protection() {
assert_eq!(quota["rateLimitReason"], "error_protection");
assert_eq!(
@@ -411,6 +431,7 @@ fn account_page_item(
use gateway_core::account::resolve_account_status;
AccountPageItem {
model_cooldowns: Vec::new(),
platform_icon: None,
protection_rules: Vec::new(),
account: AccountRecord {
@@ -564,6 +564,7 @@ mod provider {
last_error_message: None,
};
AccountPageItem {
model_cooldowns: Vec::new(),
platform_icon: None,
protection_rules: Vec::new(),
capacity: gateway_admin::model::accounts::AccountCapacity {
@@ -1484,6 +1484,7 @@ impl AccountRuntimeStore for UnusedStore {
async fn active_rate_limits(&self) -> AdminStoreResult<AccountRuntimeSnapshot> {
Ok(AccountRuntimeSnapshot {
model_cooldowns: BTreeMap::new(),
cooldown: BTreeMap::new(),
protection_rules: BTreeMap::new(),
in_flight: Some(BTreeMap::new()),
@@ -1492,6 +1493,7 @@ impl AccountRuntimeStore for UnusedStore {
async fn account_runtime(&self, _: &[String]) -> AdminStoreResult<AccountRuntimeSnapshot> {
Ok(AccountRuntimeSnapshot {
model_cooldowns: BTreeMap::new(),
cooldown: BTreeMap::new(),
protection_rules: BTreeMap::new(),
in_flight: Some(BTreeMap::new()),
@@ -262,7 +262,8 @@ async fn request_middleware_sees_original_chat_and_preserves_the_endpoint() {
{"role":"developer","content":"brief"},
{"role":"system","content":null},
{"role":"assistant","tool_calls":[]},
{"role":"user","content":[{"type":"text","text":null},{"type":"text","text":"hello"}]}
{"role":"user","content":[{"type":"text","text":null},{"type":"text","text":"hello"}]},
{"role":"tool","name":"notifications","namespace":"agent","content":"notice"}
]);
let response = fixture.post(request.clone()).await;
assert_eq!(response.status(), StatusCode::OK);
@@ -384,10 +384,14 @@ fn engine_provider_error_should_preserve_retry_classification() {
#[test]
fn local_provider_capacity_exhaustion_should_map_to_service_unavailable() {
let error = EngineError::Provider(ProviderError::new(
ProviderErrorKind::AccountCapacityUnavailable,
UpstreamSendState::NotSent,
));
let error = EngineError::Provider(
ProviderError::new(
ProviderErrorKind::AccountCapacityUnavailable,
UpstreamSendState::NotSent,
)
.with_retry_after(std::time::Duration::from_millis(7100)),
);
assert_eq!(engine_error_response(&error).headers()["retry-after"], "8");
let projected = gateway_error_from_engine(&error);
assert_eq!(
@@ -91,6 +91,7 @@ async fn fixture(sharing: ClientPeerSharing, plaintext: &str) -> (AdminTestFixtu
last_error_message: None,
};
*fixture.account.lock().unwrap() = Some(AccountPageItem {
model_cooldowns: Vec::new(),
platform_icon: None,
protection_rules: Vec::new(),
capacity: AccountCapacity {
@@ -1586,6 +1586,11 @@ impl GatewayError {
),
};
let mut gateway = gateway;
if gateway.kind() == GatewayErrorKind::AccountCapacityUnavailable
&& let Some(delay) = error.retry_after()
{
gateway = gateway.with_retry_after(delay);
}
if gateway.kind() == GatewayErrorKind::InvalidRequest
&& let Some(details) = error
.failure_observation
@@ -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;
@@ -113,6 +113,7 @@ pub struct ProviderScopedCooldown {
credential_revision: CredentialRevision,
scope: ProviderCooldownScope,
until: SystemTime,
rate_limited_until: Option<SystemTime>,
}
impl ProviderScopedCooldown {
@@ -128,6 +129,7 @@ impl ProviderScopedCooldown {
credential_revision,
scope,
until,
rate_limited_until: None,
}
}
@@ -141,6 +143,18 @@ impl ProviderScopedCooldown {
self.credential_revision
}
/// 选号冷却可能还包含模型拒绝;目录只展示实际限流期限
#[must_use]
pub fn with_rate_limited_until(mut self, until: Option<SystemTime>) -> Self {
self.rate_limited_until = until.map(|until| until.min(self.until));
self
}
#[must_use]
pub const fn rate_limited_until(&self) -> Option<SystemTime> {
self.rate_limited_until
}
#[must_use]
pub const fn scope(&self) -> &ProviderCooldownScope {
&self.scope
@@ -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,
}
+5
View File
@@ -117,6 +117,11 @@ pub async fn initialize_command_line(mut config: HostConfig) -> Result<HostBundl
}
impl HostBundle {
/// 宿主配置解析后的运行数据目录,供需要磁盘空间的内置服务使用。
pub fn runtime_data_dir(&self) -> &std::path::Path {
self.config.runtime_data_dir()
}
/// 向启动控制台报告一个组装阶段已就绪
pub fn report_startup_ready(&self, service: &'static str) {
tracing::info!(target: "gateway_startup", service, "服务启动正常");
+12 -5
View File
@@ -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;
+30 -3
View File
@@ -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 {
@@ -59,11 +59,13 @@ pub fn validate_request(body: &Map<String, Value>) -> Result<(), ChatError> {
}
}
if role == "tool" {
string(
message.get("tool_call_id"),
&format!("{path}.tool_call_id"),
false,
)?;
// Responses 的独立工具输出通过名称标识,不依赖前序调用
let field = if message.get("tool_call_id").is_none_or(Value::is_null) {
"name"
} else {
"tool_call_id"
};
string(message.get(field), &format!("{path}.{field}"), false)?;
} else if message
.get("tool_call_id")
.is_some_and(|v| !v.is_null() && v != "")
@@ -166,12 +166,7 @@ fn messages(value: Value) -> Result<Vec<Value>, RequestDecodeError> {
let mut message = object(value, &path)?;
let role = required_string(&mut message, "role", &format!("{path}.role"), false)?;
if role == "tool" {
let call_id = required_string(
&mut message,
"tool_call_id",
&format!("{path}.tool_call_id"),
false,
)?;
let call_id = optional(&mut message, "tool_call_id");
let content_path = format!("{path}.content");
let content = required(&mut message, "content", &content_path)?;
let output = if content.is_string() {
@@ -179,15 +174,24 @@ fn messages(value: Value) -> Result<Vec<Value>, RequestDecodeError> {
} else {
content_parts(content, &role, &content_path, false)?.into()
};
let kind = if custom_calls.contains(&call_id) {
let kind = if call_id
.as_ref()
.and_then(Value::as_str)
.is_some_and(|id| custom_calls.contains(id))
{
"custom_tool_call_output"
} else {
"function_call_output"
};
let mut item = json!({"type": kind, "call_id": call_id, "output": output});
if let Some(name) = optional(&mut message, "name").filter(|name| name != "") {
string(&name, &format!("{path}.name"), true)?;
item["name"] = name;
let mut item = json!({"type": kind, "output": output});
if let Some(call_id) = call_id {
item["call_id"] = call_id;
}
for field in ["name", "namespace"] {
if let Some(value) = optional(&mut message, field).filter(|value| value != "") {
string(&value, &format!("{path}.{field}"), true)?;
item[field] = value;
}
}
input.push(item);
continue;
@@ -377,12 +381,13 @@ fn tools(value: Value) -> Result<Vec<Value>, RequestDecodeError> {
.into_iter()
.enumerate()
.map(|(index, value)| {
let path = format!("tools[{index}]");
let mut path = format!("tools[{index}]");
let mut tool = object(value, &path)?;
let kind = required_string(&mut tool, "type", &format!("{path}.type"), false)?;
if matches!(kind.as_str(), "function" | "custom") {
if let Some(nested) = optional(&mut tool, &kind) {
tool = object(nested, &format!("{path}.{kind}"))?;
path = format!("{path}.{kind}");
tool = object(nested, &path)?;
}
if tool.get("description") == Some(&Value::Null) {
tool.remove("description");
@@ -395,6 +400,14 @@ fn tools(value: Value) -> Result<Vec<Value>, RequestDecodeError> {
// Chat 的缺省是宽松 schema,不能让 Responses 收紧参数合同
tool.insert("strict".into(), false.into());
}
} else if let Some(format) = tool.get_mut("format").and_then(Value::as_object_mut)
&& format.get("type").and_then(Value::as_str) == Some("grammar")
&& let Some(grammar) = optional(format, "grammar")
{
// Chat 将语法嵌套在 grammar,Responses 使用同层的 syntax 和 definition
let grammar = object(grammar, &format!("{path}.format.grammar"))?;
format.extend(grammar);
format.insert("type".into(), "grammar".into());
}
}
// hosted 工具采用原生 Responses 结构,支持范围由选中的 Provider 决定
@@ -63,14 +63,48 @@ fn invalid_envelopes_and_chat_controls_keep_safe_field_errors() {
#[test]
fn invalid_tool_history_reports_source_path() {
let request = json!({"model":"m","messages":[{"role":"tool","content":"ok"}]});
assert_eq!(
parse_request(&serde_json::to_vec(&request).unwrap())
.err()
for (identity, parameter) in [
(json!({}), "messages[0].name"),
(json!({"name":null}), "messages[0].name"),
(json!({"name":" "}), "messages[0].name"),
(json!({"name":17}), "messages[0].name"),
(
json!({"name":"notifications","tool_call_id":""}),
"messages[0].tool_call_id",
),
(
json!({"name":"notifications","tool_call_id":17}),
"messages[0].tool_call_id",
),
] {
let mut message = json!({"role":"tool","content":"ok"});
message
.as_object_mut()
.unwrap()
.parameter(),
Some("messages[0].tool_call_id")
);
.extend(identity.as_object().unwrap().clone());
let request = json!({"model":"m","messages":[message]});
let error = parse_request(&serde_json::to_vec(&request).unwrap()).unwrap_err();
assert_eq!(error.parameter(), Some(parameter));
}
}
#[test]
fn named_tool_outputs_preserve_the_original_request_and_target_requirements() {
let request = json!({"model":"m","messages":[
{"role":"tool","name":"notifications","namespace":"agent","content":"notice"}
]});
let parsed = parse_request(&serde_json::to_vec(&request).unwrap()).unwrap();
assert_eq!(&parsed, request.as_object().unwrap());
assert!(responses::convert_request(&parsed).is_ok());
for result in [
messages::convert_request(&parsed, &Default::default()),
genai::convert_request(&parsed),
] {
assert_eq!(
result.unwrap_err().parameter(),
Some("messages[0].tool_call_id")
);
}
}
#[test]
@@ -472,11 +506,14 @@ fn all_targets_apply_the_same_common_request_validation() {
#[test]
fn custom_format_constraints_are_preserved_or_rejected_by_the_target() {
for format in [
json!(null),
json!({"type":"text"}),
json!({"type":"grammar","grammar":{"syntax":"lark","definition":"PRIVATE_GRAMMAR"}}),
json!(17),
for (format, expected) in [
(json!(null), json!(null)),
(json!({"type":"text"}), json!({"type":"text"})),
(
json!({"type":"grammar","grammar":{"syntax":"lark","definition":"PRIVATE_GRAMMAR"}}),
json!({"type":"grammar","syntax":"lark","definition":"PRIVATE_GRAMMAR"}),
),
(json!(17), json!(17)),
] {
let mut body = super::request();
body.insert(
@@ -484,7 +521,7 @@ fn custom_format_constraints_are_preserved_or_rejected_by_the_target() {
json!([{"type":"custom","custom":{"name":"run","format":format}}]),
);
let responses = responses::convert_request(&body).unwrap();
assert_eq!(responses["tools"][0]["format"], format);
assert_eq!(responses["tools"][0]["format"], expected);
for result in [
messages::convert_request(&body, &Default::default()),
genai::convert_request(&body),
@@ -53,6 +53,31 @@ fn preserves_ordered_roles_images_and_modern_tool_round_trip() {
assert!(converted.get("previous_response_id").is_none());
}
#[test]
fn named_tool_outputs_preserve_unpaired_identity_and_order() {
for call_id in [None, Some(Value::Null)] {
let mut notice = json!({"role":"tool","name":"lookup","namespace":"agent","content":[{"type":"text","text":"independent notice"}]});
if let Some(call_id) = call_id {
notice["tool_call_id"] = call_id;
}
let converted = convert(json!({"model":"model-a","messages":[
{"role":"assistant","tool_calls":[{"id":"call_lookup","type":"custom","custom":{"name":"lookup","input":"query"}}]},
notice,
{"role":"tool","tool_call_id":"call_lookup","content":"matched result"},
{"role":"tool","name":"notifications","content":"another notice"}
]}));
assert_eq!(
converted["input"],
json!([
{"type":"custom_tool_call","call_id":"call_lookup","name":"lookup","input":"query"},
{"type":"function_call_output","name":"lookup","namespace":"agent","output":[{"type":"input_text","text":"independent notice"}]},
{"type":"custom_tool_call_output","call_id":"call_lookup","output":"matched result"},
{"type":"function_call_output","name":"notifications","output":"another notice"}
])
);
}
}
#[test]
fn web_search_options_require_a_hosted_search_and_flatten_location() {
for (options, expected) in [
@@ -278,7 +303,7 @@ fn custom_tools_keep_native_input_and_mixed_call_families_through_history() {
]}));
assert_eq!(
converted["tools"][0],
json!({"type":"custom", "name":"patch", "format":schema})
json!({"type":"custom", "name":"patch", "format":{"type":"grammar","syntax":"lark","definition":"start: /.+/"}})
);
assert_eq!(
converted["tool_choice"],
@@ -293,6 +318,40 @@ fn custom_tools_keep_native_input_and_mixed_call_families_through_history() {
assert_eq!(converted["input"][5]["type"], "function_call_output");
}
#[test]
fn custom_grammar_formats_keep_their_constraints_and_source_paths() {
for nested in [false, true] {
for syntax in ["lark", "regex"] {
let format =
json!({"type":"grammar","syntax":syntax,"definition":"OK","future_field":true});
let definition = json!({"name":"probe","format":format});
let tool = if nested {
json!({"type":"custom","custom":definition})
} else {
json!({"type":"custom","name":"probe","format":format})
};
let mut body =
json!({"model":"m","messages":[{"role":"user","content":"hello"}],"tools":[tool]});
assert_eq!(convert(body.clone())["tools"][0]["format"], format);
let declaration = if nested {
&mut body["tools"][0]["custom"]
} else {
&mut body["tools"][0]
};
declaration["format"] = json!({"type":"grammar","grammar":false});
let error = convert_request(body.as_object().unwrap()).unwrap_err();
assert_eq!(
error.parameter(),
Some(if nested {
"tools[0].custom.format.grammar"
} else {
"tools[0].format.grammar"
})
);
}
}
}
#[test]
fn files_and_audio_are_preserved_as_inputs_instead_of_losing_the_user_turn() {
for file in [
@@ -69,7 +69,9 @@ impl ClientAdmissionRecoveryRepository for PgClientAdmissionRecoveryRepository {
lease.lease_expires_at, request.outcome
from model_requests request
left join model_request_leases lease on lease.request_id = request.id
where request.started_at >= $1 or request.outcome = 'running'
where (request.started_at >= $1 or request.outcome = 'running')
and (request.client_transport, request.request_kind)
is distinct from ('internal_plugin', 'plugin_child_model')
order by request.client_api_key_ref, request.started_at, request.id",
)
.bind(window_started_at)
@@ -325,19 +325,36 @@ impl AccountStore for PgAdminAccountStore {
));
}
let now = Utc::now();
let cooldown = runtime.cooldown;
let now_system_time = std::time::SystemTime::from(now);
let active_rate_limited_ids = cooldown
let active_rate_limited_ids = runtime
.cooldown
.iter()
.filter(|(_, cooldown)| cooldown.is_active(now_system_time))
.map(|(account_id, _)| account_id.clone())
.collect::<Vec<_>>();
let active_model_revisions = runtime
.model_cooldowns
.iter()
.flat_map(|(account, models)| {
models
.iter()
.filter(|model| model.until() > now_system_time)
.filter_map(|model| {
i64::try_from(model.credential_revision().get())
.ok()
.map(|revision| (account.clone(), revision))
})
})
.collect::<std::collections::BTreeSet<_>>()
.into_iter()
.collect();
let page = load_admin_account_page(
&self.pool,
&self.query_budget,
&query,
now,
active_rate_limited_ids,
active_model_revisions,
)
.await?;
let item_ids = page
@@ -351,14 +368,12 @@ impl AccountStore for PgAdminAccountStore {
.into_iter()
.map(|(summary, platform_icon)| {
let account_id = summary.id.clone();
let projection = account_status_projection(
&summary,
now.into(),
cooldown.get(&account_id).copied(),
);
let (projection, model_cooldowns) =
super::runtime::account_directory_projection(&summary, now.into(), &runtime);
let mut account = admin_account_record(summary)?;
account.groups = groups_by_account.remove(&account_id).unwrap_or_default();
Ok(AccountPageItem {
model_cooldowns,
platform_icon,
protection_rules: runtime
.protection_rules
@@ -397,8 +412,8 @@ impl AccountStore for PgAdminAccountStore {
return Ok(None);
};
let now = Utc::now();
let cooldown = runtime.cooldown.get(account_id).copied();
let projection = account_status_projection(&record.summary, now.into(), cooldown);
let (projection, model_cooldowns) =
super::runtime::account_directory_projection(&record.summary, now.into(), &runtime);
let account_id = record.summary.id.clone();
let mut groups = self
.account_groups_by_account(std::slice::from_ref(&account_id))
@@ -424,6 +439,7 @@ impl AccountStore for PgAdminAccountStore {
)
})?;
Ok(Some(AccountPageItem {
model_cooldowns,
platform_icon,
protection_rules: runtime
.protection_rules
@@ -16,7 +16,10 @@ pub(crate) async fn load_admin_account_page(
query: &AdminAccountListQuery,
now: DateTime<Utc>,
active_rate_limited_ids: Vec<String>,
active_model_revisions: Vec<(String, i64)>,
) -> AdminStoreResult<AdminAccountPageRows> {
let (model_account_ids, model_revisions): (Vec<_>, Vec<_>) =
active_model_revisions.into_iter().unzip();
validate_group_filter(pool, query.group_filter.as_ref()).await?;
let provider_kind = query
@@ -56,7 +59,10 @@ pub(crate) async fn load_admin_account_page(
when a.credential_state <> 'ready'
or a.access_token_expires_at <= $2 then 'error'
when a.quota_access_state = 'exhausted' then 'quota_exhausted'
when a.id = any($1::text[]) then 'rate_limited'
when a.id = any($1::text[]) or exists (
select 1 from unnest($13::text[], $14::bigint[]) as limits(account_id, revision)
where limits.account_id = a.id and limits.revision = a.credential_revision
) then 'rate_limited'
when a.quota_paused then 'quota_paused'
else 'normal'
end as admin_status
@@ -165,6 +171,8 @@ pub(crate) async fn load_admin_account_page(
.bind(usage_ids)
.bind(usage_tokens)
.bind(usage_latest)
.bind(model_account_ids)
.bind(model_revisions)
.fetch_all(&mut *snapshot.tx)
.await
.map_err(|source| postgres_unavailable("load admin account page", source))?;
@@ -12,6 +12,40 @@ use gateway_core::{
use super::ProviderAccountSummary;
pub(crate) fn account_directory_projection(
account: &ProviderAccountSummary,
now: SystemTime,
runtime: &gateway_admin::model::accounts::AccountRuntimeSnapshot,
) -> (
AccountStatusProjection,
Vec<gateway_core::provider_ports::ProviderScopedCooldown>,
) {
let models = runtime
.model_cooldowns
.get(&account.id)
.into_iter()
.flatten()
.filter(|cooldown| {
cooldown.credential_revision().get() == account.credential_revision.get()
&& cooldown.until() > now
})
.cloned()
.collect::<Vec<_>>();
let mut projection =
account_status_projection(account, now, runtime.cooldown.get(&account.id).copied());
// 目录汇总展示部分模型受限,不将其写入整账号 cooldown 或用于其他模型的调度
if !models.is_empty()
&& matches!(
projection.status,
gateway_core::account::AccountStatus::Normal
| gateway_core::account::AccountStatus::QuotaPaused
)
{
projection.status = gateway_core::account::AccountStatus::RateLimited;
}
(projection, models)
}
#[must_use]
pub(crate) fn account_status_projection(
account: &ProviderAccountSummary,
@@ -155,8 +155,6 @@ impl ClientAdmissionRequest {
return Err(invalid("lease TTL must be positive"));
}
redis_duration_millis(self.lease_ttl)?;
redis_integer(self.limits.max_concurrency, "maximum concurrency")?;
redis_integer(self.limits.requests_per_minute, "requests per minute")?;
Ok(())
}
}
@@ -287,6 +285,7 @@ impl ClientAdmissionRepository for RedisClientAdmissionRepository {
.key(&keys[1])
.arg(&request.model_request_id)
.arg(lease_ttl_ms)
// ZCARD 的取值都能精确表示,超过 Lua 精确范围的限额始终大于实际计数
.arg(request.limits.max_concurrency)
.arg(request.limits.requests_per_minute)
.arg(MAX_REDIS_EXACT_INTEGER)
@@ -11,7 +11,7 @@ use gateway_core::{
},
};
use redis::{Script, aio::ConnectionManager};
use std::{collections::BTreeMap, sync::LazyLock};
use std::{collections::BTreeMap, sync::LazyLock, time::SystemTime};
use crate::{Revision, StoreError, StoreResult, redis_unavailable, require_nonempty};
@@ -55,6 +55,42 @@ static WRITE_ACCOUNT: LazyLock<Script> = LazyLock::new(|| {
)
});
// 模型事实与目录索引同次写入;普通成功只清整账号冷却,不触碰这里的期限
const WRITE_SCOPED: &str = r#"
local current = tonumber(redis.call('HGET', KEYS[1], 'revision') or '0')
local incoming = tonumber(ARGV[1])
local until_ms = tonumber(ARGV[2])
local limited_ms = tonumber(ARGV[4])
local clock = redis.call('TIME')
local now_ms = tonumber(clock[1]) * 1000 + math.floor(tonumber(clock[2]) / 1000)
if current > incoming or until_ms <= now_ms then return 0 end
if current == incoming then
local previous = tonumber(redis.call('HGET', KEYS[1], 'until_ms') or '0')
local limited = tonumber(redis.call('HGET', KEYS[1], 'rate_limited_until_ms') or '0')
if previous >= until_ms and limited >= limited_ms then return 0 end
until_ms = math.max(previous, until_ms)
limited_ms = math.max(limited, limited_ms)
end
redis.call('HSET', KEYS[1], 'revision', incoming, 'until_ms', until_ms, 'rate_limited_until_ms', limited_ms)
redis.call('PEXPIREAT', KEYS[1], until_ms + 60000)
if limited_ms > now_ms then
redis.call('ZADD', KEYS[2], limited_ms, ARGV[3])
local latest = redis.call('ZRANGE', KEYS[2], -1, -1, 'WITHSCORES')
redis.call('PEXPIREAT', KEYS[2], tonumber(latest[2]) + 60000)
redis.call('ZADD', KEYS[3], 'GT', latest[2], ARGV[5])
else
redis.call('ZREM', KEYS[2], ARGV[3])
end
return 1
"#;
const ACTIVE_SCOPES: &str = r#"
local clock = redis.call('TIME')
local now_ms = tonumber(clock[1]) * 1000 + math.floor(tonumber(clock[2]) / 1000)
redis.call('ZREMRANGEBYSCORE', KEYS[1], '-inf', now_ms)
return redis.call('ZRANGE', KEYS[1], 0, -1)
"#;
const READ_SCOPED: &str = r#"
local revision = redis.call('HGET', KEYS[1], 'revision')
local until_ms = redis.call('HGET', KEYS[1], 'until_ms')
@@ -62,9 +98,9 @@ local clock = redis.call('TIME')
local now_ms = (tonumber(clock[1]) * 1000) + math.floor(tonumber(clock[2]) / 1000)
if not revision or not until_ms or tonumber(until_ms) <= now_ms then
redis.call('DEL', KEYS[1])
return {0, '0', '0'}
return {0, '0', '0', '0'}
end
return {1, revision, until_ms}
return {1, revision, until_ms, redis.call('HGET', KEYS[1], 'rate_limited_until_ms') or '0'}
"#;
const INVALIDATE_SCRIPT: &str = r#"
@@ -132,6 +168,73 @@ impl RedisCredentialCooldownRepository {
format!("{}:account:active-cooldowns", self.namespace)
}
fn model_index_key(&self, account: &str) -> StoreResult<String> {
Ok(format!("{}:models", self.key(account)?))
}
fn active_model_index_key(&self) -> String {
format!("{}:account:active-model-cooldowns", self.namespace)
}
async fn read_model_cooldowns(
&self,
account: &str,
) -> StoreResult<Vec<ProviderScopedCooldown>> {
let models: Vec<String> = Script::new(ACTIVE_SCOPES)
.key(self.model_index_key(account)?)
.invoke_async(&mut self.connection.clone())
.await
.map_err(|source| redis_unavailable("list account model cooldowns", source))?;
let account =
ProviderAccountId::new(account).map_err(|_| invalid("invalid cooldown account"))?;
let scopes = models
.into_iter()
.map(|model| {
gateway_core::routing::UpstreamModelId::new(model)
.map(ProviderCooldownScope::upstream_model)
.map_err(|_| invalid("invalid cooldown model"))
})
.collect::<StoreResult<Vec<_>>>()?;
let mut cooldowns = Vec::new();
for scopes in scopes.chunks(COOLDOWN_READ_BATCH_SIZE) {
let script = Script::new(READ_SCOPED);
let commands = scopes
.iter()
.map(|scope| {
let mut command = redis::cmd("EVALSHA");
command
.arg(script.get_hash())
.arg(1)
.arg(self.scoped_key(account.as_str(), scope)?);
Ok(command)
})
.collect();
for (scope, value) in scopes
.iter()
.zip(self.read_script_batch(&script, commands).await)
{
let value = redis::from_redis_value(value?)
.map_err(|source| redis_unavailable("decode model cooldown", source))?;
if let Some(cooldown) = parse_scoped_cooldown(value, &account, scope)?
&& let Some(until) = cooldown
.rate_limited_until()
.filter(|until| *until > SystemTime::now())
{
cooldowns.push(
ProviderScopedCooldown::new(
account.clone(),
cooldown.credential_revision(),
scope.clone(),
until,
)
.with_rate_limited_until(Some(until)),
);
}
}
}
Ok(cooldowns)
}
fn capacity_failures_key(&self, provider_account_id: &str) -> StoreResult<String> {
let fingerprint = resource_fingerprint("credential cooldown", provider_account_id)?;
Ok(format!(
@@ -168,49 +271,27 @@ impl RedisCredentialCooldownRepository {
credential_revision: Revision,
cooldown_until: DateTime<Utc>,
kind: ProviderCooldownKind,
index_member: Option<&str>,
index_member: &str,
) -> StoreResult<bool> {
let until_ms = cooldown_until.timestamp_millis();
if until_ms <= 0 {
return Err(invalid("cooldown expiry must be positive"));
}
let mut connection = self.connection.clone();
let written = if let Some(index_member) = index_member {
WRITE_ACCOUNT
.key(key)
.key(self.active_index_key())
.key(self.protection_key(index_member)?)
.key(self.protection_index_key())
.arg(credential_revision.get())
.arg(until_ms)
.arg(index_member)
.arg(kind.as_str())
.arg(uuid::Uuid::new_v4().to_string())
.invoke_async::<i64>(&mut connection)
.await
} else {
Script::new(WRITE_SCRIPT)
.key(key)
.arg(credential_revision.get())
.arg(until_ms)
.arg("")
.arg(kind.as_str())
.arg(uuid::Uuid::new_v4().to_string())
.invoke_async::<i64>(&mut connection)
.await
}
.map_err(|source| redis_unavailable("cache credential cooldown", source))?;
Ok(written == 1)
}
async fn read_scoped_key(&self, key: String) -> StoreResult<Option<(Revision, DateTime<Utc>)>> {
let result = Script::new(READ_SCOPED)
let written = WRITE_ACCOUNT
.key(key)
.invoke_async(&mut self.connection.clone())
.await;
parse_scoped_cooldown(
result.map_err(|source| redis_unavailable("read credential cooldown", source))?,
)
.key(self.active_index_key())
.key(self.protection_key(index_member)?)
.key(self.protection_index_key())
.arg(credential_revision.get())
.arg(until_ms)
.arg(index_member)
.arg(kind.as_str())
.arg(uuid::Uuid::new_v4().to_string())
.invoke_async::<i64>(&mut connection)
.await
.map_err(|source| redis_unavailable("cache credential cooldown", source))?;
Ok(written == 1)
}
/// 保留每条命令的错误,脚本失效时只补发尚未执行的 NOSCRIPT 项
@@ -294,26 +375,18 @@ impl RedisCredentialCooldownRepository {
&self,
key: String,
through_revision: Revision,
index_member: Option<&str>,
index_key: String,
index_member: &str,
) -> StoreResult<bool> {
let mut connection = self.connection.clone();
let removed = if let Some(index_member) = index_member {
Script::new(INVALIDATE_SCRIPT)
.key(key)
.key(self.active_index_key())
.arg(through_revision.get())
.arg(index_member)
.invoke_async::<i64>(&mut connection)
.await
} else {
Script::new(INVALIDATE_SCRIPT)
.key(key)
.arg(through_revision.get())
.arg("")
.invoke_async::<i64>(&mut connection)
.await
}
.map_err(|source| redis_unavailable("invalidate credential cooldown", source))?;
let removed = Script::new(INVALIDATE_SCRIPT)
.key(key)
.key(index_key)
.arg(through_revision.get())
.arg(index_member)
.invoke_async::<i64>(&mut connection)
.await
.map_err(|source| redis_unavailable("invalidate credential cooldown", source))?;
Ok(removed == 1)
}
@@ -337,8 +410,16 @@ impl RedisCredentialCooldownRepository {
}
pub(crate) async fn active_cooldowns(&self) -> StoreResult<AccountRuntimeSnapshot> {
self.read_cooldown_accounts(self.all_cooldown_accounts().await?)
let mut accounts = self.all_cooldown_accounts().await?;
let model_accounts: Vec<String> = Script::new(ACTIVE_SCOPES)
.key(self.active_model_index_key())
.invoke_async(&mut self.connection.clone())
.await
.map_err(|source| redis_unavailable("list model cooldown accounts", source))?;
accounts.extend(model_accounts);
accounts.sort_unstable();
accounts.dedup();
self.read_cooldown_accounts(accounts).await
}
pub(crate) async fn account_cooldowns(
@@ -349,13 +430,16 @@ impl RedisCredentialCooldownRepository {
return Ok(AccountRuntimeSnapshot::default());
}
// 索引与冷却事实由 Lua 原子维护,只读取范围内实际有状态的账号
let (cooldowns, protections): (Vec<Option<f64>>, Vec<Option<f64>>) = redis::pipe()
let [cooldowns, protections, models]: [Vec<Option<f64>>; 3] = redis::pipe()
.cmd("ZMSCORE")
.arg(self.active_index_key())
.arg(accounts)
.cmd("ZMSCORE")
.arg(self.protection_index_key())
.arg(accounts)
.cmd("ZMSCORE")
.arg(self.active_model_index_key())
.arg(accounts)
.query_async(&mut self.connection.clone())
.await
.map_err(|error| redis_unavailable("read scoped account cooldown index", error))?;
@@ -363,8 +447,11 @@ impl RedisCredentialCooldownRepository {
.iter()
.zip(cooldowns)
.zip(protections)
.filter(|((_, cooldown), protection)| cooldown.is_some() || protection.is_some())
.map(|((account, _), _)| account.clone())
.zip(models)
.filter(|(((_, cooldown), protection), model)| {
cooldown.is_some() || protection.is_some() || model.is_some()
})
.map(|(((account, _), _), _)| account.clone())
.collect();
self.read_cooldown_accounts(active).await
}
@@ -376,15 +463,20 @@ impl RedisCredentialCooldownRepository {
use futures::{StreamExt as _, TryStreamExt as _};
let reads = futures::stream::iter(accounts)
.map(|account| async move {
self.read_account_runtime(&account)
.await
.map(|runtime| (account, runtime))
let (runtime, models) = tokio::try_join!(
self.read_account_runtime(&account),
self.read_model_cooldowns(&account),
)?;
Ok((account, runtime, models))
})
.buffer_unordered(32)
.try_collect::<Vec<_>>()
.await?;
let mut snapshot = AccountRuntimeSnapshot::default();
for (account, (cooldown, freeze)) in reads {
for (account, (cooldown, freeze), models) in reads {
if !models.is_empty() {
snapshot.model_cooldowns.insert(account.clone(), models);
}
if let Some(cooldown) = cooldown {
snapshot.cooldown.insert(
account.clone(),
@@ -446,7 +538,7 @@ impl CredentialCooldownRepository for RedisCredentialCooldownRepository {
cooldown.credential_revision,
cooldown.cooldown_until,
cooldown.kind,
Some(&cooldown.provider_account_id),
&cooldown.provider_account_id,
)
.await
}
@@ -480,7 +572,8 @@ impl CredentialCooldownRepository for RedisCredentialCooldownRepository {
.invalidate_at_key(
self.key(provider_account_id)?,
through_revision,
Some(provider_account_id),
self.active_index_key(),
provider_account_id,
)
.await?;
Ok(protection_cleared || cooldown_cleared)
@@ -530,6 +623,7 @@ impl CredentialCooldownRepository for RedisCredentialCooldownRepository {
local removed = 0
for i = 2, #KEYS do removed = removed + redis.call('DEL', KEYS[i]) end
redis.call('ZREM', ARGV[2], ARGV[1])
redis.call('ZREM', ARGV[3], ARGV[1])
return removed + redis.call('ZREM', KEYS[1], ARGV[1])
"#,
)
@@ -537,6 +631,7 @@ impl CredentialCooldownRepository for RedisCredentialCooldownRepository {
.key(keys)
.arg(provider_account_id)
.arg(self.protection_index_key())
.arg(self.active_model_index_key())
.invoke_async(&mut connection)
.await
.map_err(|source| redis_unavailable("delete account cooldowns and index", source))?;
@@ -686,18 +781,37 @@ impl ProviderCooldownPort for RedisCredentialCooldownRepository {
Box::pin(async move {
let revision = Revision::new(cooldown.credential_revision().get())
.map_err(|_| provider_invalid("encode scoped credential cooldown"))?;
self.cache_at_key(
self.scoped_key(cooldown.account_id().as_str(), cooldown.scope())
.map_err(|_| provider_invalid("encode scoped credential cooldown"))?,
revision,
cooldown.until().into(),
ProviderCooldownKind::RateLimit,
None,
)
.await
.map_err(|source| {
crate::provider_unavailable("cache scoped credential cooldown", source)
})
let account = cooldown.account_id().as_str();
let key = self
.scoped_key(account, cooldown.scope())
.map_err(|_| provider_invalid("encode scoped credential cooldown"))?;
let index = self
.model_index_key(account)
.map_err(|_| provider_invalid("encode model cooldown index"))?;
let until: DateTime<Utc> = cooldown.until().into();
let written: i64 = Script::new(WRITE_SCOPED)
.key(key)
.key(index)
.key(self.active_model_index_key())
.arg(revision.get())
.arg(until.timestamp_millis())
.arg(cooldown.scope().value())
.arg(
cooldown
.rate_limited_until()
.map(DateTime::<Utc>::from)
.map_or(0, |time| time.timestamp_millis()),
)
.arg(account)
.invoke_async(&mut self.connection.clone())
.await
.map_err(|source| {
crate::provider_unavailable(
"cache scoped credential cooldown",
redis_unavailable("write model cooldown", source),
)
})?;
Ok(written == 1)
})
}
@@ -708,24 +822,18 @@ impl ProviderCooldownPort for RedisCredentialCooldownRepository {
) -> futures::future::BoxFuture<'a, Result<Option<ProviderScopedCooldown>, ProviderStoreError>>
{
Box::pin(async move {
self.read_scoped_key(
self.scoped_key(account_id.as_str(), scope)
.map_err(|_| provider_invalid("encode scoped credential cooldown"))?,
)
.await
.map_err(|source| {
let key = self
.scoped_key(account_id.as_str(), scope)
.map_err(|_| provider_invalid("encode scoped credential cooldown"))?;
let value = Script::new(READ_SCOPED)
.key(key)
.invoke_async(&mut self.connection.clone())
.await
.map_err(|source| redis_unavailable("read scoped cooldown", source))
.and_then(|value| parse_scoped_cooldown(value, account_id, scope));
value.map_err(|source| {
crate::provider_unavailable("read scoped credential cooldown", source)
})?
.map(|(revision, until)| {
Ok(ProviderScopedCooldown::new(
account_id.clone(),
CredentialRevision::new(revision.get())
.map_err(|_| provider_invalid("decode scoped credential cooldown"))?,
scope.clone(),
until.into(),
))
})
.transpose()
})
}
@@ -754,28 +862,16 @@ impl ProviderCooldownPort for RedisCredentialCooldownRepository {
.collect();
let values = self.read_script_batch(&script, commands).await;
results.extend(batch.iter().zip(values).map(|(account, value)| {
let value = value
value
.and_then(|value| {
redis::from_redis_value(value).map_err(|source| {
redis_unavailable("decode scoped cooldown", source)
})
})
.and_then(parse_scoped_cooldown)
.and_then(|value| parse_scoped_cooldown(value, account, scope))
.map_err(|source| {
crate::provider_unavailable("read scoped credential cooldown", source)
})?;
value
.map(|(revision, until)| {
Ok(ProviderScopedCooldown::new(
account.clone(),
CredentialRevision::new(revision.get()).map_err(|_| {
provider_invalid("decode scoped credential cooldown")
})?,
scope.clone(),
until.into(),
))
})
.transpose()
}));
}
results
@@ -795,7 +891,9 @@ impl ProviderCooldownPort for RedisCredentialCooldownRepository {
self.scoped_key(account_id.as_str(), scope)
.map_err(|_| provider_invalid("encode scoped credential cooldown"))?,
revision,
None,
self.model_index_key(account_id.as_str())
.map_err(|_| provider_invalid("encode model cooldown index"))?,
scope.value(),
)
.await
.map_err(|source| {
@@ -858,21 +956,35 @@ pub(super) fn invalid(message: &str) -> StoreError {
}
}
type ScopedCooldownReply = (i64, String, i64, i64);
fn parse_scoped_cooldown(
(present, revision, until_ms): (i64, String, String),
) -> StoreResult<Option<(Revision, DateTime<Utc>)>> {
(present, revision, until_ms, limited_ms): ScopedCooldownReply,
account: &ProviderAccountId,
scope: &ProviderCooldownScope,
) -> StoreResult<Option<ProviderScopedCooldown>> {
if present == 0 {
return Ok(None);
}
let revision = revision
.parse::<u64>()
.map_err(|source| invalid("cached cooldown revision is invalid").with_source(source))?;
let until_ms = until_ms
.parse::<i64>()
.map_err(|source| invalid("cached cooldown expiry is invalid").with_source(source))?;
let cooldown_until = DateTime::from_timestamp_millis(until_ms)
.ok_or_else(|| invalid("cached cooldown expiry is invalid"))?;
Ok(Some((Revision::new(revision)?, cooldown_until)))
let revision =
CredentialRevision::new(revision).map_err(|_| invalid("invalid cooldown revision"))?;
let deadline = |ms| {
DateTime::from_timestamp_millis(ms)
.map(SystemTime::from)
.ok_or_else(|| invalid("cached cooldown expiry is invalid"))
};
Ok(Some(
ProviderScopedCooldown::new(
account.clone(),
revision,
scope.clone(),
deadline(until_ms)?,
)
.with_rate_limited_until((limited_ms > 0).then(|| deadline(limited_ms)).transpose()?),
))
}
fn provider_cooldown(record: CredentialCooldown) -> Result<ProviderCooldown, ProviderStoreError> {
+13 -10
View File
@@ -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)
})
})
}
}
@@ -62,6 +62,23 @@ async fn recovery_loads_precise_window_and_running_request_facts() {
.await
.expect("remove missing lease fixture");
seed_request(
&database.pool,
"nested-child",
now - Duration::seconds(8),
now + Duration::seconds(30),
"running",
)
.await;
sqlx::query(
"update model_requests set client_transport = 'internal_plugin',
request_kind = case id when 'recent-running' then 'plugin_bound_model' else 'plugin_child_model' end
where id in ('nested-child', 'recent-running')",
)
.execute(&database.pool)
.await
.unwrap();
let repository = PgClientAdmissionRecoveryRepository::new(database.pool.clone());
let actual = repository
.load_client_admission_recovery(window_started_at)
@@ -2,6 +2,76 @@
use super::*;
#[tokio::test]
async fn model_cooldown_status_filter_and_details_share_revision_and_expiry_rules() {
use gateway_core::provider_ports::{ProviderCooldownScope, ProviderScopedCooldown};
let Some(database) = TestDatabase::create("account_model_cooldown").await else {
return;
};
let repository = PgProviderAccountRepository::new(database.pool.clone());
let ids = ["acct_active", "acct_stale", "acct_expired", "acct_disabled"];
for id in ids {
let mut record = account(id, id);
record.enabled = id != "acct_disabled";
repository.insert_provider_account(record).await.unwrap();
}
let mut runtime = AccountRuntimeSnapshot::default();
for id in ids {
let stored = repository.load_provider_account(id).await.unwrap().unwrap();
let revision = stored.summary.credential_revision.get();
let revision = if id == "acct_stale" {
revision + 1
} else {
revision
};
let until = Utc::now() + TimeDelta::seconds(if id == "acct_expired" { -1 } else { 60 });
runtime.model_cooldowns.insert(
id.into(),
vec![ProviderScopedCooldown::new(
ProviderAccountId::new(id).unwrap(),
gateway_core::account::CredentialRevision::new(revision).unwrap(),
ProviderCooldownScope::upstream_model(
gateway_core::routing::UpstreamModelId::new("gpt-5.4").unwrap(),
),
until.into(),
)],
);
}
let store = admin_account_store(&database.pool);
let page = store
.list_accounts(
AccountListQuery {
page: 1,
page_size: PageSize::new(20).unwrap(),
provider_kind: None,
group_filter: None,
search: None,
status: Some(AccountStatus::RateLimited),
sort: None,
},
runtime.clone(),
)
.await
.unwrap();
assert_eq!(page.total, 1);
assert_eq!(page.summary.rate_limited, 1);
assert_eq!(page.summary.normal, 2);
assert_eq!(page.summary.disabled, 1);
let item = &page.items[0];
assert_eq!(item.account.id, "acct_active");
assert_eq!(item.projection.status, AccountStatus::RateLimited);
assert!(item.projection.cooldown.is_none());
assert_eq!(item.model_cooldowns.len(), 1);
let detail = store
.load_account("acct_active", runtime)
.await
.unwrap()
.unwrap();
assert_eq!(detail.projection, item.projection);
assert_eq!(detail.model_cooldowns, item.model_cooldowns);
database.close().await;
}
#[tokio::test]
async fn import_name_only_overrides_a_single_account_and_keeps_batch_names() {
use gateway_admin::model::accounts::AccountImportSettings;
@@ -940,6 +940,7 @@ async fn terminal_admin_list_filters_and_sorts_before_pagination_with_retained_u
sort: None,
},
AccountRuntimeSnapshot {
model_cooldowns: BTreeMap::new(),
protection_rules: std::collections::BTreeMap::new(),
cooldown: BTreeMap::from([(
"acct_alpha".to_owned(),
@@ -18,11 +18,19 @@ fn client_admission_rejects_zero_ttl() {
assert!(request.validate().is_err());
}
#[test]
fn client_admission_rejects_values_outside_redis_exact_integer_range() {
let mut request = admission_request("request-1", "key-1", Duration::from_secs(30));
#[tokio::test]
async fn configured_limits_above_lua_integer_precision_allow_requests() {
let Some((repository, mut connection, namespace)) = repository().await else {
return;
};
let mut request = admission_request("req_large_limits", "key-1", Duration::from_secs(30));
request.limits.max_concurrency = 1_u64 << 53;
assert!(request.validate().is_err());
request.limits.requests_per_minute = i64::MAX as u64;
assert_eq!(
repository.admit_client_request(&request).await.unwrap(),
ClientAdmissionDecision::Granted
);
delete_namespace_keys(&mut connection, &namespace).await;
}
#[test]
@@ -313,7 +313,12 @@ async fn scoped_cooldown_isolated_by_model_and_revision_fenced() {
.is_some()
);
let keys = namespace_keys(&mut connection, &namespace).await;
assert_eq!(keys.len(), 1);
assert_eq!(
keys.iter()
.filter(|key| key.contains(":cooldown:model:"))
.count(),
1
);
assert!(!keys[0].contains(account_id.as_str()));
assert!(!keys[0].contains(model_b.value()));
}
@@ -516,6 +521,142 @@ fn runtime_store(
)
}
#[tokio::test]
async fn model_cooldowns_are_visible_in_runtime_without_blocking_the_entire_account() {
use gateway_admin::ports::store::AccountRuntimeStore as _;
let Some((repository, connection, namespace)) = repository().await else {
return;
};
let runtime = runtime_store(&repository, connection, &namespace);
let id = ProviderAccountId::new("acct_model_limit").unwrap();
let revision = CredentialRevision::new(1).unwrap();
let models = ["gpt-5.4", "gpt-5.5"].map(|model| {
ProviderCooldownScope::upstream_model(
gateway_core::routing::UpstreamModelId::new(model).unwrap(),
)
});
let until: SystemTime = millisecond_precision(Utc::now() + Duration::seconds(60)).into();
// 不支持的模型仍影响选号,但不能让目录误报限流;两种期限可重叠
let unsupported_until = until + std::time::Duration::from_secs(1800);
repository
.put_scoped_if_later(ProviderScopedCooldown::new(
id.clone(),
revision,
models[0].clone(),
unsupported_until,
))
.await
.unwrap();
assert!(
runtime
.active_rate_limits()
.await
.unwrap()
.model_cooldowns
.is_empty()
);
for scope in &models {
repository
.put_scoped_if_later(
ProviderScopedCooldown::new(id.clone(), revision, scope.clone(), until)
.with_rate_limited_until(Some(until)),
)
.await
.unwrap();
}
repository.clear_after_success(&id, revision).await.unwrap();
let snapshot = runtime.active_rate_limits().await.unwrap();
assert!(snapshot.cooldown.is_empty());
assert_eq!(snapshot.model_cooldowns[id.as_str()].len(), 2);
assert!(
snapshot.model_cooldowns[id.as_str()]
.iter()
.all(|model| model.until() == until)
);
assert_eq!(
repository
.read_scoped(&id, &models[0])
.await
.unwrap()
.unwrap()
.until(),
unsupported_until
);
let scoped = runtime
.account_rate_limits(&[id.to_string()])
.await
.unwrap();
assert_eq!(scoped.model_cooldowns, snapshot.model_cooldowns);
repository
.clear_scoped(&id, &models[0], revision)
.await
.unwrap();
let snapshot = runtime.active_rate_limits().await.unwrap();
assert_eq!(snapshot.model_cooldowns[id.as_str()].len(), 1);
assert_eq!(snapshot.model_cooldowns[id.as_str()][0].scope(), &models[1]);
repository
.delete_account_cooldowns(id.as_str())
.await
.unwrap();
assert!(
runtime
.active_rate_limits()
.await
.unwrap()
.model_cooldowns
.is_empty()
);
}
#[tokio::test]
async fn expired_model_cooldown_disappears_from_the_directory_even_during_redis_grace() {
use gateway_admin::ports::store::AccountRuntimeStore as _;
let Some((repository, mut connection, namespace)) = repository().await else {
return;
};
let runtime = runtime_store(&repository, connection.clone(), &namespace);
let id = ProviderAccountId::new("acct_model_expired").unwrap();
let until = (Utc::now() + Duration::minutes(1)).into();
repository
.put_scoped_if_later(
ProviderScopedCooldown::new(
id.clone(),
CredentialRevision::new(1).unwrap(),
ProviderCooldownScope::upstream_model(
gateway_core::routing::UpstreamModelId::new("gpt-5.4").unwrap(),
),
until,
)
.with_rate_limited_until(Some(until)),
)
.await
.unwrap();
let key = namespace_keys(&mut connection, &namespace)
.await
.into_iter()
.find(|key| key.contains(":cooldown:model:"))
.unwrap();
redis::cmd("HSET")
.arg(key)
.arg("until_ms")
.arg(Utc::now().timestamp_millis() - 1000)
.query_async::<i64>(&mut connection)
.await
.unwrap();
assert!(
runtime
.active_rate_limits()
.await
.unwrap()
.model_cooldowns
.is_empty()
);
repository
.delete_account_cooldowns(id.as_str())
.await
.unwrap();
}
#[tokio::test]
async fn capacity_freeze_survives_due_time_and_runtime_restart_until_probe_succeeds() {
use gateway_admin::ports::store::AccountRuntimeStore as _;
@@ -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(&current)?;
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(), &current.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(), &current.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(
&current.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(), &current.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(&current.account, grant, guards)
.map(PreparedCredentialRotation::preserving_credential_state)
}
pub(super) fn rotation(
@@ -9,17 +9,24 @@ mod transport;
use gateway_admin::ports::provider::ProviderBundle;
use gateway_core::{provider_ports::ProviderStorePorts, routing::ProviderKind};
use std::sync::Arc;
use std::{path::PathBuf, sync::Arc};
#[derive(Debug, thiserror::Error)]
#[error("Antigravity Provider 初始化失败")]
pub struct ConfigError;
pub fn initialize(ports: ProviderStorePorts) -> Result<ProviderBundle, ConfigError> {
pub async fn initialize(
ports: ProviderStorePorts,
artifact_dir: PathBuf,
) -> 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())?);
let release = Arc::new(profile::ReleaseService::new(
ports.artifact_profiles(),
artifact_dir,
)?);
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))?
}
}
@@ -281,6 +308,7 @@ pub(crate) async fn download(
client: &Client,
url: &str,
sha512: Option<&str>,
artifact_dir: &std::path::Path,
) -> Result<std::fs::File, WorkerTaskError> {
let mut response = client
.get(url)
@@ -296,7 +324,11 @@ pub(crate) async fn download(
{
return Err(invalid());
}
let file = tempfile::tempfile().map_err(|e| invalid().with_source(e))?;
// 官方包可能大于容器的 /tmp;匿名文件随句柄释放,失败和取消也不会留下半包。
tokio::fs::create_dir_all(artifact_dir)
.await
.map_err(|e| invalid().with_source(e))?;
let file = tempfile::tempfile_in(artifact_dir).map_err(|e| invalid().with_source(e))?;
let mut file = tokio::fs::File::from_std(file);
let mut count = 0u64;
let mut digest = Sha512::new();
@@ -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,8 @@ pub(crate) async fn verify(
version: &str,
url: &str,
sha512: Option<&str>,
) -> Result<(), WorkerTaskError> {
artifact_dir: &std::path::Path,
) -> Result<u64, WorkerTaskError> {
match (target.client, target.platform) {
(ClientKind::Desktop, Platform::Macos) => {
let url = url.strip_suffix(".dmg").ok_or_else(invalid)?;
@@ -40,23 +41,27 @@ 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?;
let file = download(client, url, sha512, artifact_dir).await?;
// 取消 worker 时同步中止阻塞解包,临时文件由解析任务退出时关闭
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 +129,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 +159,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 +169,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 +188,7 @@ pub(crate) fn verify_tar(
}
}
if found_version && found_executable {
Ok(())
changelist.ok_or_else(invalid)
} else {
Err(invalid())
}
@@ -186,24 +197,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 +258,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 +276,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,16 +1,19 @@
//! 按客户端、平台与架构刷新官方发布资料,失败时保留上次成功结果
//! 跟踪官方发布资料并整组切换已核验画像,更新失败时保留当前画像
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};
use serde::Deserialize;
use std::{
collections::{BTreeMap, BTreeSet},
path::PathBuf,
sync::{Arc, Mutex, RwLock},
time::Duration,
};
@@ -20,32 +23,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>>,
@@ -55,6 +75,7 @@ pub(crate) struct ReleaseService {
impl ReleaseService {
pub(crate) fn new(
cache: Arc<dyn ProviderArtifactProfileCachePort>,
artifact_dir: PathBuf,
) -> Result<Self, ConfigError> {
let client = gateway_egress::http_client(None)
.map_err(|_| ConfigError)?
@@ -70,6 +91,7 @@ impl ReleaseService {
verification: VerificationCache::new(
ProviderKind::new("antigravity").map_err(|_| ConfigError)?,
cache,
artifact_dir,
),
})
}
@@ -85,16 +107,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 +170,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 +197,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 +234,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 +261,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::{
@@ -13,6 +13,7 @@ use gateway_core::{
};
use serde::{Deserialize, Serialize};
use std::{
path::PathBuf,
sync::Arc,
time::{Duration, Instant},
};
@@ -23,8 +24,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,18 +34,59 @@ pub(crate) struct VerifiedArtifact {
struct Payload {
target: ReleaseTarget,
release: Release,
changelist: u64,
}
pub(crate) struct VerificationCache {
provider: ProviderKind,
cache: Arc<dyn ProviderArtifactProfileCachePort>,
artifact_dir: PathBuf,
}
impl VerificationCache {
pub(crate) fn new(
provider: ProviderKind,
cache: Arc<dyn ProviderArtifactProfileCachePort>,
artifact_dir: PathBuf,
) -> Self {
Self { provider, cache }
Self {
provider,
cache,
artifact_dir,
}
}
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(
@@ -54,59 +97,43 @@ 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,
&release.url,
release.sha512.as_deref(),
&self.artifact_dir,
)
.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 +141,7 @@ impl VerificationCache {
};
let profile = ProviderArtifactProfile::new(
self.provider.clone(),
key,
key(target),
sequence,
verified_at.into(),
OpaqueProviderData::new(payload),
@@ -129,19 +156,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(&current.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);
@@ -46,7 +46,11 @@ pub(super) async fn fixture() -> (MockServer, CredentialService, Arc<MemoryPorts
runtime_policy: store.clone(),
credential_state: store.clone(),
release: Arc::new(
crate::profile::ReleaseService::new(crate::support::profile::cache()).unwrap(),
crate::profile::ReleaseService::new(
crate::support::profile::cache(),
std::env::temp_dir(),
)
.unwrap(),
),
oauth: Arc::new(GoogleOAuth::with_endpoints(
config,
@@ -279,7 +283,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 +329,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 {
@@ -103,15 +103,31 @@ async fn complete_download_requires_the_manifest_digest() {
let server = serve(body.to_vec(), "").await;
let client = reqwest::Client::new();
let digest = hex::encode(Sha512::digest(body));
let file = download(&client, &server.uri(), Some(&digest))
let root = tempfile::tempdir().unwrap();
let artifact_dir = root.path().join("antigravity");
let file = download(&client, &server.uri(), Some(&digest), &artifact_dir)
.await
.unwrap();
assert_eq!(file.metadata().unwrap().len(), body.len() as u64);
drop(file);
assert_eq!(std::fs::read_dir(&artifact_dir).unwrap().count(), 0);
let blocked = root.path().join("file");
std::fs::write(&blocked, b"").unwrap();
assert!(
download(&client, &server.uri(), Some(&"0".repeat(128)))
download(&client, &server.uri(), Some(&digest), &blocked)
.await
.is_err()
);
assert!(
download(
&client,
&server.uri(),
Some(&"0".repeat(128)),
&artifact_dir
)
.await
.is_err()
);
}
#[test]
@@ -121,4 +137,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()),
@@ -23,10 +27,10 @@ fn release(server: &wiremock::MockServer, version: &str) -> Release {
async fn cache_restore_and_renewal_preserve_verification_without_downloading_again() {
let server = super::archive::serve(super::artifact::desktop_zip("2.35.1"), "").await;
let cache = cache();
let service = VerificationCache::new(provider(), cache.clone());
let service = VerificationCache::new(provider(), cache.clone(), std::env::temp_dir());
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
@@ -38,32 +42,88 @@ async fn cache_restore_and_renewal_preserve_verification_without_downloading_aga
.unwrap();
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 restarted = VerificationCache::new(provider(), cache.clone(), std::env::temp_dir());
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(), std::env::temp_dir()).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(), std::env::temp_dir());
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(), std::env::temp_dir()).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
);
}
@@ -71,10 +131,10 @@ async fn cache_restore_and_renewal_preserve_verification_without_downloading_aga
async fn changed_artifact_or_target_and_failed_cache_do_not_publish_verification() {
let server = super::archive::serve(super::artifact::desktop_zip("2.35.1"), "").await;
let cache = cache();
let service = VerificationCache::new(provider(), cache.clone());
let service = VerificationCache::new(provider(), cache.clone(), std::env::temp_dir());
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
@@ -129,10 +189,10 @@ async fn changed_artifact_or_target_and_failed_cache_do_not_publish_verification
async fn version_disagreement_leaves_the_previous_cache_intact() {
let server = super::archive::serve(super::artifact::desktop_zip("2.35.1"), "").await;
let cache = cache();
let service = VerificationCache::new(provider(), cache.clone());
let service = VerificationCache::new(provider(), cache.clone(), std::env::temp_dir());
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
@@ -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)
);
}
}
@@ -16,10 +16,10 @@ async fn native_and_translated_requests_forward_business_headers_with_account_id
let server = MockServer::start().await;
let fixture = Fixture::new(&server.uri());
let profile = crate::profile::Selection::parse(&crate::profile::object(json!({
"client":"cli", "platform":"linux", "versionMode":"fixed", "clientVersion":"1.5.17"
"client":"cli", "platform":"linux", "versionMode":"fixed", "clientVersion":"1.5.23"
})))
.unwrap()
.resolve("1.5.17")
.resolve("1.5.23", Some(1200034567))
.frozen();
let ctx = || {
context(
@@ -50,7 +50,6 @@ async fn native_and_translated_requests_forward_business_headers_with_account_id
"authorization",
"cookie",
"cookie2",
"user-agent",
"x-goog-api-key",
"x-goog-user-project",
"x-goog-api-client",
@@ -67,6 +66,12 @@ async fn native_and_translated_requests_forward_business_headers_with_account_id
.map(|name| json!([name, STANDARD.encode("forbidden")]))
.collect();
headers.extend([
// 下游客户端的管理员策略和认证类型不能覆盖当前账号的个人 OAuth 画像
json!([
"user-agent",
STANDARD
.encode("antigravity/cli/9.9.9 (auth_method=gateway; datacollection_opt_in=false)")
]),
json!(["x-business-extension", STANDARD.encode(b"first\x80")]),
json!(["x-business-extension", STANDARD.encode("second")]),
json!(["traceparent", STANDARD.encode("original-trace")]),
@@ -75,7 +80,7 @@ async fn native_and_translated_requests_forward_business_headers_with_account_id
for (protocol, body) in [
(
gateway_protocol::genai::GENAI_PROTOCOL,
json!({"contents":[]}),
json!({"contents":[], "hasFingerprintSet":true, "has_fingerprint_set":true}),
),
(
gateway_protocol::chat_completions::CHAT_PROTOCOL,
@@ -97,7 +102,7 @@ async fn native_and_translated_requests_forward_business_headers_with_account_id
Operation::CountTokens(TokenCountRequest::from_raw_json(
RawJsonPayload::new(
gateway_protocol::genai::GENAI_PROTOCOL,
br#"{"contents":[]}"#.as_slice().into(),
br#"{"contents":[],"hasFingerprintSet":true}"#.as_slice().into(),
)
.unwrap()
.with_context(metadata.as_object().unwrap().clone()),
@@ -116,6 +121,9 @@ async fn native_and_translated_requests_forward_business_headers_with_account_id
let requests = server.received_requests().await.unwrap();
assert_eq!(requests.len(), 3);
for request in requests {
let body: serde_json::Value = serde_json::from_slice(&request.body).unwrap();
assert!(body["request"].get("hasFingerprintSet").is_none());
assert!(body["request"].get("has_fingerprint_set").is_none());
let values: Vec<_> = request
.headers
.get_all("x-business-extension")
@@ -128,10 +136,10 @@ async fn native_and_translated_requests_forward_business_headers_with_account_id
assert_eq!(request.headers["content-type"], "application/json");
assert_eq!(
request.headers["user-agent"],
"antigravity/cli/1.5.17 (aidev_client; os_type=linux; arch=amd64; cl=1029496841; auth_method=consumer)"
"antigravity/cli/1.5.23 (aidev_client; os_type=linux; arch=amd64; cl=1200034567; auth_method=consumer)"
);
for name in forbidden {
if !matches!(name, "authorization" | "user-agent" | "content-length") {
if !matches!(name, "authorization" | "content-length") {
assert!(!request.headers.contains_key(name), "unexpected {name}");
}
}
@@ -67,7 +67,7 @@ async fn middleware_business_headers_survive_without_overriding_frozen_authentic
let fixture = Fixture::new(&upstream.uri());
let profile = profile::resolve(
&Selection::default().configuration(),
&ReleaseService::new(crate::support::profile::cache()).unwrap(),
&ReleaseService::new(crate::support::profile::cache(), std::env::temp_dir()).unwrap(),
)
.unwrap();
Mock::given(path("/v1internal:generateContent"))
@@ -3,6 +3,7 @@
mod affinity;
mod api_key;
mod execution;
mod feedback;
mod headers;
mod middleware;
mod round_robin;
@@ -247,7 +247,9 @@ impl Fixture {
store.clone(),
store.clone(),
);
let release = Arc::new(ReleaseService::new(crate::support::profile::cache()).unwrap());
let release = Arc::new(
ReleaseService::new(crate::support::profile::cache(), std::env::temp_dir()).unwrap(),
);
let credentials = Arc::new(CredentialService::new(
kind.clone(),
&ports,
@@ -144,7 +144,7 @@ impl ProviderCredentialStatePort for MemoryPorts {
&'a self,
_account_id: &'a ProviderAccountId,
) -> BoxFuture<'a, Result<(), ProviderStoreError>> {
unreachable!("unused fixture port: ProviderCredentialStatePort::clear_refresh_backoff")
Box::pin(async { Ok(()) })
}
}
@@ -548,9 +548,43 @@ impl ProviderAccountStore for MemoryPorts {
}
async fn compare_and_swap_credential(
&self,
_update: CredentialCasUpdate,
update: CredentialCasUpdate,
) -> Result<CredentialCasOutcome, StoreError> {
unreachable!("unused fixture port: ProviderAccountStore::compare_and_swap_credential")
let update = update.into_parts();
let entry = &self.accounts[&update.account_id];
let mut loaded = entry.loaded.lock().unwrap();
if loaded.account.revision() != update.expected_revision {
return Ok(CredentialCasOutcome::Conflict);
}
let revision = CredentialRevision::new(update.expected_revision.get() + 1).unwrap();
let previous = &loaded.account;
let (state, reason, message) = update.account_state.map_or_else(
|| {
(
previous.credential_state(),
previous.last_error_reason(),
previous.last_error_message().map(str::to_owned),
)
},
|state| (state.credential_state, state.error_reason, state.message),
);
loaded.account = ProviderAccount::new(
previous.id().clone(),
previous.provider().clone(),
previous.name().into(),
previous.upstream_user_id().map(str::to_owned),
previous.authentication_kind().into(),
revision,
if update.preserve_access_token_expiry {
previous.access_token_expires_at()
} else {
update.access_token_expires_at
},
)
.with_account_facts(previous.enabled(), state, previous.quota(), reason, message)
.with_refresh_schedule(update.has_refresh_token, update.next_refresh_at);
loaded.credential = update.credential;
Ok(CredentialCasOutcome::Updated(revision))
}
async fn get_quotas(
&self,
@@ -21,11 +21,10 @@ use wiremock::{
async fn oauth_refresh_and_native_generate_preserve_grant_profile_and_wire_payload() {
let server = MockServer::start().await;
let (origin, access_token) = refreshed_credential(&server).await;
let profile =
profile::default_profile(&ReleaseService::new(crate::support::profile::cache()).unwrap());
// 官方 macOS arm64 Desktop 2.34.0 在默认参数下实际发送的已认证请求头
let user_agent =
"antigravity/hub/2.34.0 (aidev_client; os_type=darwin; arch=arm64; cl=1026637980)";
let profile = profile::default_profile(
&ReleaseService::new(crate::support::profile::cache(), std::env::temp_dir()).unwrap(),
);
let user_agent = "antigravity/hub/2.37.0 (aidev_client; os_type=darwin; arch=arm64)";
let client = CloudCodeClient::new(&origin, None, &profile).unwrap();
let post = |p| {
Mock::given(method("POST"))
@@ -173,8 +172,9 @@ async fn oauth_refresh_and_native_generate_preserve_grant_profile_and_wire_paylo
#[tokio::test]
async fn streamed_text_is_projected_once_across_native_frames() {
let server = MockServer::start().await;
let profile =
profile::default_profile(&ReleaseService::new(crate::support::profile::cache()).unwrap());
let profile = profile::default_profile(
&ReleaseService::new(crate::support::profile::cache(), std::env::temp_dir()).unwrap(),
);
let client = CloudCodeClient::new(&server.uri().parse().unwrap(), None, &profile).unwrap();
let frames = [
json!({"candidates":[{"content":{"parts":[{"text":""}]}}]}),
@@ -251,8 +251,9 @@ async fn streamed_text_is_projected_once_across_native_frames() {
#[tokio::test]
async fn incomplete_native_stream_and_redirect_are_rejected() {
let server = MockServer::start().await;
let profile =
profile::default_profile(&ReleaseService::new(crate::support::profile::cache()).unwrap());
let profile = profile::default_profile(
&ReleaseService::new(crate::support::profile::cache(), std::env::temp_dir()).unwrap(),
);
let client = CloudCodeClient::new(&server.uri().parse().unwrap(), None, &profile).unwrap();
Mock::given(path("/v1internal:streamGenerateContent")).respond_with(ResponseTemplate::new(200).set_body_raw("data: {\"response\":{\"candidates\":[{\"content\":{\"parts\":[{\"text\":\"partial\"}]}}]}}\n\n","text/event-stream")).mount(&server).await;
let res = client
@@ -352,8 +353,9 @@ async fn compressed_response(status: u16, body: &[u8], media: &str) -> ResponseT
async fn compressed_control_responses_keep_errors_and_decoded_size_limits() {
use gateway_core::error::ProviderErrorKind;
let server = MockServer::start().await;
let profile =
profile::default_profile(&ReleaseService::new(crate::support::profile::cache()).unwrap());
let profile = profile::default_profile(
&ReleaseService::new(crate::support::profile::cache(), std::env::temp_dir()).unwrap(),
);
let client = CloudCodeClient::new(&server.uri().parse().unwrap(), None, &profile).unwrap();
Mock::given(path("/v1internal:loadCodeAssist"))
.respond_with(
@@ -22,7 +22,7 @@ use wiremock::{
};
fn profile() -> OpaqueProviderData {
Selection::parse(&object(json!({"client":"cli","platform":"linux","versionMode":"fixed","clientVersion":"1.5.14","arch":null,"systemPrompt":"count identity"}))).unwrap().resolve("9.9.9").frozen()
Selection::parse(&object(json!({"client":"cli","platform":"linux","versionMode":"fixed","clientVersion":"1.5.14","arch":null,"systemPrompt":"count identity"}))).unwrap().resolve("9.9.9", None).frozen()
}
fn counted(protocol: &str, body: Value) -> gateway_core::engine::provider::ProviderRequest {
@@ -165,7 +165,7 @@ async fn repeated_account_reuses_tcp_without_caching_token_project_or_prompt() {
let peer = KeepAlivePeer::start().await;
let pool = ClientPool::default();
let account = account("acct_one", 1);
let mut profile = Selection::default().resolve("2.34.0");
let mut profile = Selection::default().resolve("2.34.0", None);
for index in 0..5 {
profile.system_prompt = format!("fixture prompt {index}");
generate(
@@ -202,8 +202,8 @@ async fn repeated_account_reuses_tcp_without_caching_token_project_or_prompt() {
async fn account_revision_and_user_agent_isolate_connection_pools() {
let peer = KeepAlivePeer::start().await;
let pool = ClientPool::default();
let profile = Selection::default().resolve("2.34.0");
let changed_profile = Selection::default().resolve("2.35.0");
let profile = Selection::default().resolve("2.34.0", None);
let changed_profile = Selection::default().resolve("2.35.0", None);
for (id, revision, profile) in [
("acct_one", 1, &profile),
("acct_two", 1, &profile),
@@ -233,7 +233,7 @@ async fn proxy_routes_keep_independent_pools_and_preserve_the_direct_pool() {
let first_proxy = KeepAlivePeer::start().await;
let second_proxy = KeepAlivePeer::start().await;
let pool = ClientPool::default();
let profile = Selection::default().resolve("2.34.0");
let profile = Selection::default().resolve("2.34.0", None);
for proxy in [
None,
Some(&first_proxy.origin),
@@ -264,7 +264,7 @@ async fn proxy_routes_keep_independent_pools_and_preserve_the_direct_pool() {
async fn cache_evicts_the_least_recently_used_client_after_sixty_four_identities() {
let peer = KeepAlivePeer::start().await;
let pool = ClientPool::default();
let profile = Selection::default().resolve("2.34.0");
let profile = Selection::default().resolve("2.34.0", None);
for index in (0..64).chain([0, 64, 0, 1]) {
generate(
&pool,
@@ -18,7 +18,7 @@ async fn oauth_identity_edits_preserve_remaining_json_bytes_and_duplicate_busine
let client = CloudCodeClient::new(
&server.uri().parse().unwrap(),
None,
&selection.resolve("2.34.0"),
&selection.resolve("2.34.0", None),
)
.unwrap();
let instruction = r#""systemInstruction":{"parts":[{"text":"OAuth fixture"}]}"#;
@@ -102,7 +102,7 @@ async fn generation_and_count_preserve_client_rules_and_instruction_metadata() {
let client = CloudCodeClient::new(
&server.uri().parse().unwrap(),
None,
&selection.resolve("2.34.0"),
&selection.resolve("2.34.0", None),
)
.unwrap();
// CLI 1.5.18 Gateway 请求把全局和项目规则放在系统指令中
@@ -146,3 +146,65 @@ async fn generation_and_count_preserve_client_rules_and_instruction_metadata() {
}
}
}
#[tokio::test]
async fn oauth_filters_local_fingerprint_state_without_changing_business_data_or_key_upstreams() {
let server = MockServer::start().await;
Mock::given(wiremock::matchers::any())
.respond_with(
ResponseTemplate::new(200).set_body_json(json!({"response":{},"totalTokens":1})),
)
.mount(&server)
.await;
let profile = profile::Selection::default().resolve("8.4.2", Some(1_234_567_890));
let oauth = CloudCodeClient::new(&server.uri().parse().unwrap(), None, &profile).unwrap();
let api_key = crate::transport::GenAiClient::new(server.uri().parse().unwrap(), None).unwrap();
for state in [
r#""hasFingerprintSet":true,"has_fingerprint_set":false,"hasFingerprintSet":false,"#,
r#""has_fingerprint_set":true,"hasFingerprintSet":false,"#,
"",
] {
let body = format!(
r#"{{{state}"contents":[{{"parts":[{{"functionCall":{{"name":"tool","args":{{"hasFingerprintSet":true,"has_fingerprint_set":false}}}}}}]}}],"tools":[{{"functionDeclarations":[{{"name":"tool","parameters":{{"type":"OBJECT","properties":{{"hasFingerprintSet":{{"type":"BOOLEAN"}}}}}}}}]}}]}}"#
);
oauth
.generate(
"project",
"model",
"oauth-token",
body.as_bytes(),
false.into(),
&[],
)
.await
.unwrap();
oauth
.count_tokens("oauth-token", body.as_bytes(), &[])
.await
.unwrap();
api_key
.execute(
"model",
"upstream-key",
body.as_bytes(),
"generateContent",
&[],
)
.await
.unwrap();
let requests = server.received_requests().await.unwrap();
let key_request = requests.last().unwrap();
assert_eq!(key_request.body, body.as_bytes());
assert_eq!(key_request.headers["x-goog-api-key"], "upstream-key");
let original: serde_json::Value = serde_json::from_str(&body).unwrap();
for request in requests.iter().rev().skip(1).take(2) {
let envelope: serde_json::Value = serde_json::from_slice(&request.body).unwrap();
let request_body = &envelope["request"];
assert!(request_body.get("hasFingerprintSet").is_none());
assert!(request_body.get("has_fingerprint_set").is_none());
assert_eq!(request_body["contents"], original["contents"]);
assert_eq!(request_body["tools"], original["tools"]);
assert_eq!(request.headers["authorization"], "Bearer oauth-token");
}
}
}
@@ -74,7 +74,7 @@ async fn fixture(reply: &str) -> (MockServer, CloudCodeClient) {
let client = CloudCodeClient::new(
&server.uri().parse().unwrap(),
None,
&profile::Selection::default().resolve("2.34.0"),
&profile::Selection::default().resolve("2.34.0", None),
)
.unwrap();
(server, client)
@@ -27,7 +27,7 @@ async fn client() -> (MockServer, CloudCodeClient) {
let client = CloudCodeClient::new(
&server.uri().parse().unwrap(),
None,
&profile::Selection::default().resolve("2.34.0"),
&profile::Selection::default().resolve("2.34.0", None),
)
.unwrap();
(server, client)
@@ -341,6 +341,11 @@ pub(super) fn map_catalog_error(error: CodexCredentialCatalogError) -> ProviderA
.with_public_message(message)
.with_source(source);
}
Error::Store(source) => {
return provider_admin_error(Kind::Unavailable)
.with_public_message("模型目录存储暂不可用")
.with_source(source);
}
Error::InvalidEtag => (Kind::Invalid, "模型目录版本无效,请重新查询"),
Error::NoEligibleCredential => (Kind::NotFound, "没有可查询模型的账号"),
Error::ConcurrentUpdate => (Kind::Conflict, "模型目录正在更新,请稍后重试"),
@@ -1,9 +1,147 @@
//! Chat 转换的目标档位与 fast 协议头适配
//! Chat 转换的目标档位、工具标识与 fast 协议头适配
use std::collections::{HashMap, HashSet};
use bytes::Bytes;
use gateway_core::engine::middleware::MiddlewareHeader;
use reqwest::header::HeaderMap;
use serde_json::{Map, Value};
use sha2::{Digest as _, Sha256};
/// 名称映射只属于本次 Chat 响应,历史调用 ID 在出站副本中保持成对关联
pub(crate) fn normalize_translated_codex_tools(
body: &mut Map<String, Value>,
) -> HashMap<String, String> {
let mut fields = Vec::new();
for (field, value) in body.iter_mut() {
match field.as_str() {
"tools" | "input" => {
if let Some(items) = value.as_array_mut() {
for item in items {
collect_tool_names(item, &mut fields);
}
}
}
"tool_choice" => collect_tool_names(value, &mut fields),
_ => {}
}
}
// 先预留所有原名,避免别名抢占后面声明的合法名称
let mut used = fields
.iter()
.filter_map(|value| value.as_str())
.map(str::to_owned)
.collect();
let mut names = HashMap::new();
for field in fields {
let Some(name) = field.as_str() else { continue };
if name.is_empty()
|| name
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-'))
{
continue;
}
let alias = names.entry(name.to_owned()).or_insert_with(|| {
let base: String = name
.chars()
.map(|ch| {
if ch.is_ascii_alphanumeric() || matches!(ch, '_' | '-') {
ch
} else {
'_'
}
})
.collect();
unique_tool_alias(&base, &mut used)
});
*field = Value::String(alias.clone());
}
if let Some(input) = body.get_mut("input").and_then(Value::as_array_mut) {
let mut used = input
.iter()
.filter_map(|item| item.get("call_id").and_then(Value::as_str))
.map(str::to_owned)
.collect();
let mut ids = HashMap::new();
for item in input.iter().filter(|item| {
matches!(
item.get("type").and_then(Value::as_str),
Some("function_call" | "custom_tool_call")
)
}) {
let Some(id) = item
.get("call_id")
.and_then(Value::as_str)
.filter(|id| id.chars().count() > 64)
else {
continue;
};
ids.entry(id.to_owned()).or_insert_with(|| {
let digest = hex::encode(Sha256::digest(id.as_bytes()));
unique_tool_alias(&format!("call_{digest}"), &mut used)
});
}
for item in input {
if matches!(
item.get("type").and_then(Value::as_str),
Some(
"function_call"
| "custom_tool_call"
| "function_call_output"
| "custom_tool_call_output"
)
) && let Some(alias) = item
.get("call_id")
.and_then(Value::as_str)
.and_then(|id| ids.get(id))
{
item["call_id"] = alias.clone().into();
}
}
}
names
.into_iter()
.map(|(name, alias)| (alias, name))
.collect()
}
fn collect_tool_names<'a>(tool: &'a mut Value, names: &mut Vec<&'a mut Value>) {
match tool.get("type").and_then(Value::as_str) {
Some(
"function"
| "custom"
| "function_call"
| "custom_tool_call"
| "function_call_output"
| "custom_tool_call_output",
) => {
if let Some(name) = tool.get_mut("name") {
names.push(name);
}
}
Some("namespace" | "allowed_tools" | "additional_tools" | "tool_search_output") => {
if let Some(tools) = tool.get_mut("tools").and_then(Value::as_array_mut) {
for tool in tools {
collect_tool_names(tool, names);
}
}
}
_ => {}
}
}
fn unique_tool_alias(base: &str, used: &mut HashSet<String>) -> String {
// 调用方只传入 ASCII 名称或十六进制摘要,可按字节截取 Codex 标识上限
let mut candidate = base[..base.len().min(64)].to_owned();
let mut index = 0;
while !used.insert(candidate.clone()) {
index += 1;
let suffix = format!("_{index}");
candidate = format!("{}{suffix}", &base[..base.len().min(64 - suffix.len())]);
}
candidate
}
pub(crate) fn normalize_translated_codex_service_tier(body: &mut Map<String, Value>) {
// 转换生成的默认档位沿用 Codex 客户端的省略表达,原生 Responses 保留调用方声明
@@ -10,7 +10,10 @@ mod search_tools;
use gateway_core::engine::middleware::MiddlewareHeader;
use serde_json::{Map, Value};
pub(crate) use chat::{add_translated_fast_beta, normalize_translated_codex_service_tier};
pub(crate) use chat::{
add_translated_fast_beta, normalize_translated_codex_service_tier,
normalize_translated_codex_tools,
};
pub(crate) use headers::is_non_codex_request_header;
pub(crate) use request::normalize_codex_request_body;
pub(crate) use search_tools::declares_hosted_search;
@@ -8,6 +8,7 @@ use serde_json::{Map, Value, json};
/// 只处理已验证被拒绝的字段,不根据客户端品牌推断整份历史是否合法
pub(super) fn normalize_non_codex_request_body(body: &mut Map<String, Value>) {
normalize_codex_oauth_options(body);
super::search_tools::normalize_search_tool_aliases(body);
let Some(input) = body.get_mut("input").and_then(Value::as_array_mut) else {
return;
};
@@ -1,7 +1,39 @@
//! 识别普通与 Responses Lite 请求中的托管搜索声明,不改写工具配置
//! 识别托管搜索声明并适配 Codex 的搜索工具名称
use serde_json::{Map, Value};
pub(super) fn normalize_search_tool_aliases(body: &mut Map<String, Value>) {
for (field, value) in body {
match field.as_str() {
"tools" | "input" => {
if let Some(items) = value.as_array_mut() {
for item in items {
normalize_search_tool(item);
}
}
}
"tool_choice" => normalize_search_tool(value),
_ => {}
}
}
}
fn normalize_search_tool(tool: &mut Value) {
match tool.get("type").and_then(Value::as_str) {
Some("web_search_preview" | "web_search_preview_2025_03_11") => {
tool["type"] = "web_search".into();
}
Some("allowed_tools" | "additional_tools" | "tool_search_output" | "namespace") => {
if let Some(tools) = tool.get_mut("tools").and_then(Value::as_array_mut) {
for tool in tools {
normalize_search_tool(tool);
}
}
}
_ => {}
}
}
pub(crate) fn declares_hosted_search(body: &Map<String, Value>) -> bool {
body.get("tools")
.and_then(Value::as_array)
@@ -256,20 +256,7 @@ pub(crate) fn derive_endpoint_affinity_with_headers(
if let Some(session) = body.get(body_session_field).cloned() {
body.entry("session_id").or_insert(session);
}
let session_id = account_session_with_headers(&body, payload.context(), headers)?;
session_affinity(
"root-session",
&session_id,
Some(&session_id),
client_api_key_id,
)
.map(|affinity| {
affinity.with_follow_only(follows_session_with_headers(
&body,
payload.context(),
headers,
))
})
session_affinity_with_headers(&body, payload.context(), headers, client_api_key_id)
}
pub(crate) fn derive_live_session_affinity(
@@ -292,19 +279,18 @@ pub(crate) fn derive_live_session_affinity(
}),
);
// x-session-id 是实时通话身份,不代表根对话;只消费官方发送的 session-id
let session_id = account_session_with_headers(&Map::new(), &Map::new(), &effective)?;
session_affinity(
"root-session",
&session_id,
Some(&session_id),
client_api_key_id,
)
.map(|affinity| {
affinity.with_follow_only(follows_session_with_headers(
&Map::new(),
&Map::new(),
&effective,
))
session_affinity_with_headers(&Map::new(), &Map::new(), &effective, client_api_key_id)
}
pub(crate) fn session_affinity_with_headers(
body: &Map<String, Value>,
context: &Map<String, Value>,
headers: &[gateway_core::engine::middleware::MiddlewareHeader],
client_api_key_id: &ClientApiKeyId,
) -> Option<CodexSessionAffinity> {
let session = account_session_with_headers(body, context, headers)?;
root_session_affinity(Some(&session), client_api_key_id).map(|affinity| {
affinity.with_follow_only(follows_session_with_headers(body, context, headers))
})
}
@@ -13,6 +13,7 @@ use gateway_core::account::AccountCatalogObservation;
use gateway_core::account::{
CredentialRevision, CredentialState, OpaqueProviderData, ProviderAccount, ProviderAccountId,
};
use gateway_core::error::{StoreError, StoreErrorKind};
use gateway_core::provider_ports::{
ProviderCatalogCacheKey, ProviderCatalogCachePort, ProviderCatalogScope,
ProviderRuntimePolicyPort,
@@ -39,6 +40,8 @@ const CATALOG_REFRESH_AFTER: Duration = Duration::from_hours(1);
const MAX_ACCOUNT_CATALOG_MODELS: usize = 2_048;
const MODEL_CATALOG_TIMEOUT: Duration = Duration::from_secs(15);
const CATALOG_FAILURE_BACKOFF_BASE: Duration = Duration::from_secs(60);
const CATALOG_FAILURE_BACKOFF_MAX: Duration = Duration::from_hours(1);
const REFRESH_CONCURRENCY: usize = 32;
// 同时到期或导入大量账号时也限制起始速率,不能把连接并发上限当作请求速率上限
const REFRESH_SPACING: Duration = Duration::from_millis(10);
@@ -272,6 +275,8 @@ pub enum CodexCredentialCatalogError {
Credential(#[from] CredentialRepositoryError),
#[error("Codex model catalog upstream query failed: {detail}")]
Upstream { detail: String },
#[error("Codex model catalog storage is unavailable")]
Store(#[from] StoreError),
#[error("Codex model catalog cache is unavailable")]
Cache,
#[error("Codex model catalog ETag is invalid")]
@@ -282,13 +287,40 @@ pub enum CodexCredentialCatalogError {
Profile(#[source] gateway_core::error::ErrorSource),
}
impl CodexCredentialCatalogError {
fn is_account_failure(&self) -> bool {
matches!(
self,
Self::Upstream { .. }
| Self::Credential(CredentialRepositoryError::InvalidCredentialData(_))
)
}
}
#[derive(Default)]
struct AccountCatalogRefresh {
etag: Option<String>,
retry: Option<CatalogRetry>,
}
struct CatalogRetry {
at: tokio::time::Instant,
delay: Duration,
}
#[derive(Clone, Copy)]
enum CatalogFetchMode {
Discovery,
Recovery,
}
#[derive(Default)]
struct CatalogCacheState {
restored: bool,
revision: u64,
generation: u64,
snapshot: Option<Arc<CodexCredentialCatalogSnapshot>>,
pending: BTreeMap<CodexCatalogScope, String>,
refreshes: BTreeMap<CodexCatalogScope, AccountCatalogRefresh>,
}
#[derive(Clone)]
@@ -301,6 +333,7 @@ pub struct CodexCredentialCatalogService {
runtime_policy: Arc<dyn ProviderRuntimePolicyPort>,
cache: Arc<RwLock<CatalogCacheState>>,
refresh_notification: Arc<Notify>,
retry_changed: Arc<Notify>,
refresh_lock: Arc<tokio::sync::Mutex<()>>,
publication: Arc<std::sync::Mutex<()>>,
}
@@ -323,6 +356,7 @@ impl CodexCredentialCatalogService {
runtime_policy,
cache: Arc::new(RwLock::new(CatalogCacheState::default())),
refresh_notification: Arc::new(Notify::new()),
retry_changed: Arc::new(Notify::new()),
refresh_lock: Arc::new(tokio::sync::Mutex::new(())),
publication: Default::default(),
}
@@ -548,13 +582,23 @@ impl CodexCredentialCatalogService {
if let Some(catalog) = self.read_account_catalog(account).await? {
return Ok(catalog);
}
self.refresh_account_catalog(account.id()).await
self.query_account_catalog(account.id(), CatalogFetchMode::Discovery)
.await
}
/// 实时刷新指定账号的模型集合,包括管理员显式查询的停用账号
pub async fn refresh_account_catalog(
&self,
account_id: &ProviderAccountId,
) -> Result<CodexAccountCatalog, CodexCredentialCatalogError> {
self.query_account_catalog(account_id, CatalogFetchMode::Recovery)
.await
}
async fn query_account_catalog(
&self,
account_id: &ProviderAccountId,
mode: CatalogFetchMode,
) -> Result<CodexAccountCatalog, CodexCredentialCatalogError> {
let account = self
.repository
@@ -568,7 +612,7 @@ impl CodexCredentialCatalogService {
let client = self.discovery_client().await?;
let revision = self.state_revision()?;
let (catalog, entry) = self
.fetch_observation(&client, &account, &scope, None)
.fetch_observation(&client, &account, &scope, None, mode)
.await?;
if eligible_catalog_account(&account, SystemTime::now())
&& let Err(error) = self.merge_observations(revision, vec![(scope, entry)])
@@ -587,9 +631,10 @@ impl CodexCredentialCatalogService {
account: &ProviderAccount,
scope: &CodexCatalogScope,
etag: Option<String>,
mode: CatalogFetchMode,
) -> Result<(CodexAccountCatalog, AccountEntry), CodexCredentialCatalogError> {
let observed_at = SystemTime::now();
let mut fetched = self.fetch_account_models(client, account).await?;
let mut fetched = self.fetch_account_models(client, account, mode).await?;
let observed = AccountCatalogObservation {
account_id: account.id().clone(),
revision: account.revision(),
@@ -601,8 +646,7 @@ impl CodexCredentialCatalogService {
.repository
.store()
.save_account_catalog(&observed, &fetched.document)
.await
.map_err(|_| CodexCredentialCatalogError::Cache)?
.await?
{
return Err(CodexCredentialCatalogError::ConcurrentUpdate);
}
@@ -637,7 +681,9 @@ impl CodexCredentialCatalogService {
account: &ProviderAccount,
) -> Result<(Vec<CodexCatalogModel>, SystemTime), CodexCredentialCatalogError> {
let client = self.discovery_client().await?;
let fetched = self.fetch_account_models(&client, account).await?;
let fetched = self
.fetch_account_models(&client, account, CatalogFetchMode::Discovery)
.await?;
if fetched.models.is_empty() {
return Err(CodexCredentialCatalogError::NoEligibleCredential);
}
@@ -701,44 +747,56 @@ impl CodexCredentialCatalogService {
&self,
client: &CodexBackendClient,
account: &ProviderAccount,
mode: CatalogFetchMode,
) -> Result<CodexModelCatalogSnapshot, CodexCredentialCatalogError> {
tokio::time::timeout(MODEL_CATALOG_TIMEOUT, async {
let credential = self.repository.load_runtime_credential(account).await?;
let request_id = format!("catalog_{}", Uuid::now_v7().simple());
let authorization = credential
.authentication
.authorization_header()
.map_err(CredentialRepositoryError::from)?;
let mut client = credential
.authentication
.model_client_for_account(client, account)
.map_err(|error| CodexCredentialCatalogError::Upstream {
detail: error.to_string(),
})?;
if let super::CodexRuntimeAuthentication::ApiKey(auth) = &credential.authentication
&& auth.configuration.protocol == super::ApiKeyProtocol::Messages
{
client = client.with_messages_api_base_url(&auth.configuration.base_url);
}
let result = client
.fetch_models_with_context(
CodexRequestContext::auxiliary(
authorization.expose_secret(),
account.upstream_account_id(),
&request_id,
None,
),
None,
)
.await;
result.map_err(|error| CodexCredentialCatalogError::Upstream {
let deadline = tokio::time::Instant::now() + MODEL_CATALOG_TIMEOUT;
let credential =
tokio::time::timeout_at(deadline, self.repository.load_runtime_credential(account))
.await
.map_err(|error| {
CredentialRepositoryError::Store(StoreError::caused_by(
StoreErrorKind::Unavailable,
error,
))
})??;
let request_id = format!("catalog_{}", Uuid::now_v7().simple());
let authorization = credential
.authentication
.authorization_header()
.map_err(CredentialRepositoryError::from)?;
let mut client = credential
.authentication
.model_client_for_account(client, account)
.map_err(|error| CodexCredentialCatalogError::Upstream {
detail: error.to_string(),
})
})?;
if let super::CodexRuntimeAuthentication::ApiKey(auth) = &credential.authentication
&& auth.configuration.protocol == super::ApiKeyProtocol::Messages
{
client = client.with_messages_api_base_url(&auth.configuration.base_url);
}
let fetch = client.fetch_models_with_context(
CodexRequestContext::auxiliary(
authorization.expose_secret(),
account.upstream_account_id(),
&request_id,
None,
),
None,
);
match mode {
CatalogFetchMode::Discovery => {
tokio::time::timeout_at(deadline, fetch)
.await
.map_err(|_| CodexCredentialCatalogError::Upstream {
detail: "model catalog timed out".to_owned(),
})?
}
CatalogFetchMode::Recovery => fetch.await,
}
.map_err(|error| CodexCredentialCatalogError::Upstream {
detail: error.to_string(),
})
.await
.map_err(|_| CodexCredentialCatalogError::Upstream {
detail: "model catalog timed out".to_owned(),
})?
}
}
Loaded 100 of 178 files, more files were not shown because too many files have changed in this diff. Show more