Compare commits

..
37 Commits
Author SHA1 Message Date
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
ZyyandCodex 48aeccd0e0 chore: bump version to 3.61.1-rc.2
Co-authored-by: Codex <noreply@openai.com>
2026-12-03 12:54:43 +08:00
bdc618701b feat(system): add confirmed manual service restart (#832)
* feat(system): add confirmed manual service restart

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

* fix(system): preserve restart for legacy update responses

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

* fix(system): require explicit restart support

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

* docs(deploy): drop legacy restart notes

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-03 12:48:52 +08:00
ZyyandCodex acd76a09dc fix(ui): keep loading feedback with the active action
Co-authored-by: Codex <noreply@openai.com>
2026-12-03 12:35:57 +08:00
ZyyandCodex 808387442b docs: strengthen frontend interaction verification
Co-authored-by: Codex <noreply@openai.com>
2026-12-03 12:35:57 +08:00
5bc4e3e5c8 fix(routing): scope Fast policy to the selected account (#829)
* fix(gateway): resolve fast policy from the account's hit group

Bound-group fast policies were merged once per API key at snapshot
compile time, so a disabled or forced group on the same key leaked its
policy onto accounts that only belong to other enabled groups. Keep the
per-group policies frozen on the account scope, skip disabled groups
when merging, and resolve the effective fast mode from the account the
request actually hit, falling back to the key-level merged value only
when the account matches no enabled bound group.

* ci: retrigger checks

* style(gateway): rustfmt the account-scoped fast mode helper

* fix(routing): scope Fast policy to selected eligible groups

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

* fix(routing): preserve explicit default Fast overrides

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-03 11:39:33 +08:00
7e98130cac fix(openai): re-anchor bucket warmup after early quota reset (#830)
* fix(openai): re-anchor bucket warmup after upstream early quota reset

* fix(openai): record initial usage for early reset warmup

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

* fix(openai): preserve precise bucket reset boundaries

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-03 11:36:44 +08:00
2821a5e3bd fix(protocol): handle empty Chat history and nullable fields (#831)
* fix(protocol): accept null-content system/developer chat messages

Codex 客户端偶尔会发送 content 为 null 的 system 消息,公共校验按空内容拒绝并报
Parameter messages[N].content has an invalid value。允许 system/developer 消息
内容为空,genai 与 messages 转换跳过空内容,responses 目标已自然忽略。

fixes #824

* fix(protocol): normalize empty Chat history and nullable fields

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-03 11:36:44 +08:00
ZyyandCodex 6a6a167d41 perf(openai): trim SSE history after privacy processing
Match privacy-processed SSE requests against the existing WebSocket history prefix. Keep full input on a mismatch and resume trimming after a matching completed turn.

Record body receipt, authentication, decompression, decoding and execution preparation timings to distinguish ingress delays from upstream latency.

Cover metadata, body and header privacy across reuse, mismatch and resumed reuse.

Co-authored-by: Codex <noreply@openai.com>
2026-12-03 11:36:44 +08:00
ZyyandCodex cffb6b35d2 fix(protocol): handle empty Chat history and nullable request fields
Treat explicit null text as empty in Chat content blocks and preserve user input, tool results, and cache breakpoints during conversion. Resolve nullable format and reasoning controls consistently with routing, and forward stop sequences to Messages and GenAI.

Co-authored-by: Codex <noreply@openai.com>
2026-12-03 10:28:00 +08:00
ZyyandCodex 17e50df06f fix(accounts): hide zero token usage in the account list
Co-authored-by: Codex <noreply@openai.com>
2026-12-03 10:28:00 +08:00
ZyyandCodex f2d95cc3fa fix(errors): clarify account selection and upstream failures
Report WebSocket transport constraints separately from exhausted account quota, including mixed account pools. Clarify routing, concurrency, authentication, permission, transport and protocol failure messages while preserving upstream error details.

Update HTTP and WebSocket regression coverage and document the client error contract. Validate 2,620 tests, workspace Clippy, formatting and architecture checks.

Co-authored-by: Codex <noreply@openai.com>
2026-12-03 10:28:00 +08:00
ZyyandCodex e4f6e1d4e3 fix(protocol): align response request IDs with Codex
Share the four Codex request ID headers across HTTP, WebSocket, diagnostics, and continuation failures. Preserve current-failure IDs and the model execution ID fallback, and remove unsupported aliases.

Update regression coverage and the public API contract.

Co-authored-by: Codex <noreply@openai.com>
2026-12-03 10:28:00 +08:00
github-actions[bot] 66f650f097 chore(release): update release channels to 3.61.1-rc.1 2026-12-02 13:47:28 +00:00
ZyyandCodex ca4d02068a chore: bump version to 3.61.1-rc.1
Co-authored-by: Codex <noreply@openai.com>
2026-12-02 21:33:34 +08:00
Zyy d185a639a9 perf(openai): send incremental SSE history over pooled WebSockets 2026-12-02 21:09:28 +08:00
github-actions[bot] 3078dd9993 chore(release): update release channels to 3.61.0 2026-12-01 13:39:52 +00:00
212 changed files with 6727 additions and 1765 deletions
+3 -1
View File
@@ -16,6 +16,8 @@ description: Codex Proxy RS 的需求评估、排障、开发、代码审查与
评估功能建议、排障、开发和审查时,先按[问题与方案依据](../../../CONTRIBUTING.md#问题与方案依据)核实使用者要完成什么、当前行为造成了什么影响。反馈直接给出改法时,先弄清提出这个改法的原因 评估功能建议、排障、开发和审查时,先按[问题与方案依据](../../../CONTRIBUTING.md#问题与方案依据)核实使用者要完成什么、当前行为造成了什么影响。反馈直接给出改法时,先弄清提出这个改法的原因
先确定正常使用时应得到的结果。设计校验、回退或故障恢复时,同时看它防住的具体风险和它可能挡住的正常用法。按协议、隔离要求和实际部署条件选择对正常路径影响最小的做法。只在假设的部署场景下才需要的处理,留到有相应需求时再做
排查故障时,从症状沿实际调用链回溯,定位行为最早偏离预期的环节,用源码、诊断或对照复现说明触发条件如何导致结果。原因尚未确定时,区分已知事实与假设,指出哪项证据能区分可能原因。确认根因后,在负责该行为的模块修复,用原触发场景验证 排查故障时,从症状沿实际调用链回溯,定位行为最早偏离预期的环节,用源码、诊断或对照复现说明触发条件如何导致结果。原因尚未确定时,区分已知事实与假设,指出哪项证据能区分可能原因。确认根因后,在负责该行为的模块修复,用原触发场景验证
涉及 Codex 时,以对应版本的官方源码核实客户端行为,默认透明转发,只做必要适配。建议宿主接管已有决定时,指出需要它介入的网关职责或实际约束。若只是个别部署希望采用不同策略,说明不建议内置的原因。实现可行性不能证明宿主应当承担这项需求 涉及 Codex 时,以对应版本的官方源码核实客户端行为,默认透明转发,只做必要适配。建议宿主接管已有决定时,指出需要它介入的网关职责或实际约束。若只是个别部署希望采用不同策略,说明不建议内置的原因。实现可行性不能证明宿主应当承担这项需求
@@ -56,7 +58,7 @@ description: Codex Proxy RS 的需求评估、排障、开发、代码审查与
- 移动或重命名测试时,核对受影响的场景覆盖是否保留;涉及子进程调用或名称过滤时,同步更新调用入口并实际运行,确认目标用例确实执行且行为断言通过 - 移动或重命名测试时,核对受影响的场景覆盖是否保留;涉及子进程调用或名称过滤时,同步更新调用入口并实际运行,确认目标用例确实执行且行为断言通过
- 清理只证明旧字段、旧路由或旧实现已经消失的用例与附带断言;未知字段校验使用合法请求基线加无业务含义的未知字段,避免因缺少必填项等其他错误而误通过 - 清理只证明旧字段、旧路由或旧实现已经消失的用例与附带断言;未知字段校验使用合法请求基线加无业务含义的未知字段,避免因缺少必填项等其他错误而误通过
- 同一层对同一行为的重复覆盖合并为清晰的场景矩阵,复用相邻测试夹具;跨层测试确有不同职责或失败路径时保留,不为统一而扩大测试辅助抽象 - 同一层对同一行为的重复覆盖合并为清晰的场景矩阵,复用相邻测试夹具;跨层测试确有不同职责或失败路径时保留,不为统一而扩大测试辅助抽象
- 断言可观察的行为与业务不变量,避免复述结构体赋值、罗列表列或字段清单、匹配 SQL 文本与源码布局 - 断言可观察的行为与业务不变量,避免复述实现细节。验收上游兼容行为时,先从对应版本的上游实现确定预期,再核对网关对同一输入的处理。例如历史应增量续接时,要看出站请求是否只含预期的增量,因为回退全量也可能返回成功
- 维护项目明确要求的架构边界检查;发现漏检时,对照规则核实扫描范围、排除项与被检查的依赖关系,优先补齐现有检查中能稳定判定的缺口 - 维护项目明确要求的架构边界检查;发现漏检时,对照规则核实扫描范围、排除项与被检查的依赖关系,优先补齐现有检查中能稳定判定的缺口
- 当前协议兼容、数据读取兼容、安全边界、并发和资源生命周期仍需覆盖,不按 `old`、`legacy` 等名称机械删除,也不能用改名代替无效用例清理 - 当前协议兼容、数据读取兼容、安全边界、并发和资源生命周期仍需覆盖,不按 `old`、`legacy` 等名称机械删除,也不能用改名代替无效用例清理
- 不在仓库中新增或保留迁移 SQL 专项测试,包括迁移文本、schema 演变与指定版本升级用例;需要验证迁移执行、数据保留或回滚时,在临时目录编写一次性验证并使用隔离数据库,测试通过即可,临时脚本不纳入维护测试集 - 不在仓库中新增或保留迁移 SQL 专项测试,包括迁移文本、schema 演变与指定版本升级用例;需要验证迁移执行、数据保留或回滚时,在临时目录编写一次性验证并使用隔离数据库,测试通过即可,临时脚本不纳入维护测试集
@@ -30,6 +30,8 @@
验证前按[界面验证](../../../../CONTRIBUTING.md#界面验证)明确本次受影响的用户路径、状态和通过条件。局部修改围绕受影响区域及相关操作验收;主题、窗口尺寸和空/加载/错误状态仅在受影响时补充,共用主题或基础组件变更按主题规范扩大范围 验证前按[界面验证](../../../../CONTRIBUTING.md#界面验证)明确本次受影响的用户路径、状态和通过条件。局部修改围绕受影响区域及相关操作验收;主题、窗口尺寸和空/加载/错误状态仅在受影响时补充,共用主题或基础组件变更按主题规范扩大范围
沿实际操作验证待确认、执行中、完成、失败与取消等受影响阶段,同时检查当前弹层和背景区域,核对应该出现的反馈与不应出现的状态。必要时延迟模拟响应以观察过渡状态,不能仅凭请求成功或截图齐全判定交互通过
通过后按[验证停止条件](../../../../CONTRIBUTING.md#验证)收尾;只有新改动、失败或未解疑点时补验相关部分。补交截图或 PR 材料时复用仍有效的运行证据 通过后按[验证停止条件](../../../../CONTRIBUTING.md#验证)收尾;只有新改动、失败或未解疑点时补验相关部分。补交截图或 PR 材料时复用仍有效的运行证据
## 交付前 ## 交付前
@@ -42,7 +44,7 @@
- **样式与状态**:是否使用对应 Token 与 utility,局部样式是否符合适用边界,受影响的主题、窄屏及交互状态是否正确 - **样式与状态**:是否使用对应 Token 与 utility,局部样式是否符合适用边界,受影响的主题、窄屏及交互状态是否正确
- **模块归属**从调用方核对公开入口。页面或多文件组件通过 `index.vue` 提供界面,其他页面复用整页时引用所属模块的布局入口,独立复用的业务组件按领域放置 - **模块归属**从调用方核对公开入口。页面或多文件组件通过 `index.vue` 提供界面,其他页面复用整页时引用所属模块的布局入口,独立复用的业务组件按领域放置
- **Provider 边界**涉及账号操作、身份配置或定价时,沿接口响应、控件和提交载荷追踪同一条规则。服务端决定的能力使用接口字段,Provider 专属表单解释自己的字段,多个页面共用的编辑流程只维护一份。按[前端职责](../../../../docs/architecture.md#34-前端模块职责)核对归属 - **Provider 边界**涉及账号操作、身份配置或定价时,沿接口响应、控件和提交载荷追踪同一条规则。服务端决定的能力使用接口字段,Provider 专属表单解释自己的字段,多个页面共用的编辑流程只维护一份。按[前端职责](../../../../docs/architecture.md#34-前端模块职责)核对归属
- **查询与动作**:区分首次加载、刷新、分页、单行与批量操作,核对 loading、禁用状态的影响范围;沿用请求层错误处理,不在页面叠加同一错误的提示 - **查询与动作**:区分首次加载、刷新、分页、单行与批量操作,明确当前动作的反馈归属及其他控件的禁用范围,避免同一动作在前后景重复显示执行反馈。待确认不等于已提交,复用交互时重新核对 loading、进度与结果的显示条件是否适用于当前动作;沿用请求层错误处理,不在页面叠加同一错误的提示
- **运行证据**:按界面验证核对截图与实际交互,证据对应当前实现;页面 PR 的可访问图片和 Draft 条件按该节执行 - **运行证据**:按界面验证核对截图与实际交互,证据对应当前实现;页面 PR 的可访问图片和 Draft 条件按该节执行
交付简述所复用的页面或组件、实际验证范围及缺口;环境不足时如实说明,不能仅凭构建、源码或截图推断未验证的行为 交付简述所复用的页面或组件、实际验证范围及缺口;环境不足时如实说明,不能仅凭构建、源码或截图推断未验证的行为
+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) [![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) [![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> </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) | | 开发宿主 | [开发与源码联调](docs/development.md) · [系统架构](docs/architecture.md) · [管理端主题](docs/theme.md) · [数据库迁移](backend/migrations/README.md) |
| 参与协作 | [贡献、审查与验证](CONTRIBUTING.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) [<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> </picture>
</a> </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 帮助到你了,欢迎请我喝杯咖啡 ☕ 如果 Codex Proxy RS 帮助到你了,欢迎请我喝杯咖啡 ☕
+20
View File
@@ -1887,6 +1887,7 @@ dependencies = [
"tracing", "tracing",
"tracing-appender", "tracing-appender",
"tracing-subscriber", "tracing-subscriber",
"uuid",
"wiremock", "wiremock",
"yaml-rust2 0.13.2", "yaml-rust2 0.13.2",
] ]
@@ -2707,6 +2708,12 @@ version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154" checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154"
[[package]]
name = "lzma-rust2"
version = "0.26.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4c7861572250348d13073a9035c6a83f3e583ec9a76a65ce92f338fe1107d8f5"
[[package]] [[package]]
name = "lzma-sys" name = "lzma-sys"
version = "0.1.20" version = "0.1.20"
@@ -3404,6 +3411,7 @@ dependencies = [
"reqwest", "reqwest",
"serde", "serde",
"serde_json", "serde_json",
"sevenz-rust2",
"sha2", "sha2",
"tar", "tar",
"tempfile", "tempfile",
@@ -4185,6 +4193,18 @@ dependencies = [
"stable_deref_trait", "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]] [[package]]
name = "sha1" name = "sha1"
version = "0.10.7" version = "0.10.7"
@@ -79,7 +79,11 @@ impl Providers {
) )
.await?; .await?;
environment.host.report_startup_ready("OpenAI Provider"); 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 environment
.host .host
.report_startup_ready("Antigravity Provider"); .report_startup_ready("Antigravity Provider");
@@ -263,10 +263,11 @@ impl ScheduledTask for FreezeRecoveryTask {
context: WorkerCycleContext, context: WorkerCycleContext,
) -> futures::future::BoxFuture<'_, Result<(), WorkerTaskError>> { ) -> futures::future::BoxFuture<'_, Result<(), WorkerTaskError>> {
Box::pin(async move { Box::pin(async move {
if context.cancellation().is_cancelled() { // 中止在途探测,避免把停机当成探测失败而延长冻结
return Ok(()); context
} .cancellation()
self.run_cycle_inner().await; .run_until_cancelled(self.run_cycle_inner())
.await;
Ok(()) Ok(())
}) })
} }
@@ -698,7 +698,7 @@ pub struct PreparedCredentialRotationFacts {
pub plan_type: Option<String>, pub plan_type: Option<String>,
/// Token 刷新保留提交时的资料,不以准备阶段的副本覆盖新套餐 /// Token 刷新保留提交时的资料,不以准备阶段的副本覆盖新套餐
pub preserve_profile: bool, pub preserve_profile: bool,
/// 连接配置变更保留当前凭据健康状态与错误事实 /// 凭据或连接配置更新保留提交时的健康状态与错误事实
pub preserve_credential_state: bool, pub preserve_credential_state: bool,
pub preserve_access_token_expiry: bool, pub preserve_access_token_expiry: bool,
pub provider_material: ProviderDocument, pub provider_material: ProviderDocument,
@@ -722,7 +722,7 @@ impl PreparedCredentialRotation {
Self { facts, guard } Self { facts, guard }
} }
/// 仅修改连接配置时,不把配置更新视为凭据恢复成功 /// 更新本身不能证明账号已恢复时,保留提交时的状态
#[must_use] #[must_use]
pub fn preserving_credential_state(mut self) -> Self { pub fn preserving_credential_state(mut self) -> Self {
self.facts.preserve_credential_state = true; self.facts.preserve_credential_state = true;
@@ -50,6 +50,8 @@ pub struct SystemUpdatePolicy {
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub struct SystemVersion { pub struct SystemVersion {
pub version: String, pub version: String,
pub instance_id: String,
pub restart_supported: bool,
pub git_sha: String, pub git_sha: String,
pub build_time: String, pub build_time: String,
pub deployment_mode: String, pub deployment_mode: String,
@@ -55,37 +55,44 @@ impl ScheduledTask for ResetCreditAutomationTask {
context: WorkerCycleContext, context: WorkerCycleContext,
) -> futures::future::BoxFuture<'_, Result<(), WorkerTaskError>> { ) -> futures::future::BoxFuture<'_, Result<(), WorkerTaskError>> {
Box::pin(async move { Box::pin(async move {
let settings = self context
.settings .cancellation()
.load_runtime_settings() .run_until_cancelled(self.run_due())
.await .await
.map_err(|_| WorkerTaskError::safe("重置卡设置读取失败"))?; .unwrap_or(Ok(()))
// 单轮有界,积压沿到期顺序继续;并发复用已有账号刷新配置
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(())
}) })
} }
} }
impl ResetCreditAutomationTask {
async fn run_due(&self) -> Result<(), WorkerTaskError> {
let settings = self
.settings
.load_runtime_settings()
.await
.map_err(|_| WorkerTaskError::safe("重置卡设置读取失败"))?;
// 单轮有界,积压沿到期顺序继续;并发复用已有账号刷新配置
let due = self
.store
.due_reset_credit_automations(Utc::now(), 100)
.await
.map_err(|_| WorkerTaskError::safe("重置卡计划读取失败"))?;
let work = futures::stream::iter(due)
.map(|account_id| async move {
let id = ProviderAccountId::new(account_id.clone())
.map_err(|_| WorkerTaskError::safe("重置卡账号 ID 不合法"))?;
if let Err(error) = self.accounts.reconcile_reset_credit_automation(id).await {
tracing::warn!(
account_id,
error_kind = error.kind().as_str(),
"自动重置卡任务失败"
);
}
Ok::<_, WorkerTaskError>(())
})
.buffer_unordered(settings.values.refresh_concurrency.max(1) as usize)
.collect::<Vec<_>>();
let _ = tokio::time::timeout(Duration::from_secs(30), work).await;
Ok(())
}
}
@@ -27,6 +27,8 @@ impl SystemOperations for RecordingSystemOperations {
} }
Ok(SystemVersion { Ok(SystemVersion {
version: "1.0.0".to_owned(), version: "1.0.0".to_owned(),
instance_id: "test-instance".to_owned(),
restart_supported: false,
git_sha: "unknown".to_owned(), git_sha: "unknown".to_owned(),
build_time: "unknown".to_owned(), build_time: "unknown".to_owned(),
deployment_mode: "source".to_owned(), deployment_mode: "source".to_owned(),
@@ -81,6 +81,8 @@ impl UpdateRequest {
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
struct SystemVersionView { struct SystemVersionView {
version: String, version: String,
instance_id: String,
restart_supported: bool,
git_sha: String, git_sha: String,
build_time: String, build_time: String,
deployment_mode: String, deployment_mode: String,
@@ -97,6 +99,8 @@ impl From<SystemVersion> for SystemVersionView {
Self { Self {
deployment_mode_label: deployment_mode_label(&version.deployment_mode).to_owned(), deployment_mode_label: deployment_mode_label(&version.deployment_mode).to_owned(),
version: version.version, version: version.version,
instance_id: version.instance_id,
restart_supported: version.restart_supported,
git_sha: version.git_sha, git_sha: version.git_sha,
build_time: version.build_time, build_time: version.build_time,
deployment_mode: version.deployment_mode, deployment_mode: version.deployment_mode,
@@ -11,6 +11,7 @@ use gateway_core::{
error::ProviderErrorKind, error::ProviderErrorKind,
policy::{ClientVersionRejection, CodexClientKind}, policy::{ClientVersionRejection, CodexClientKind},
}; };
use gateway_protocol::http::preferred_response_request_id;
use serde_json::{Value, json}; use serde_json::{Value, json};
pub use gateway_core::engine::execution::gateway_error_from_engine; pub use gateway_core::engine::execution::gateway_error_from_engine;
@@ -170,8 +171,8 @@ pub fn engine_error_response(error: &EngineError) -> Response {
}; };
response.headers_mut().append(name, value); response.headers_mut().append(name, value);
} }
if !response.headers().contains_key("x-request-id") if preferred_response_request_id(|name| response.headers().get(name)?.to_str().ok())
&& !response.headers().contains_key("x-oai-request-id") .is_none()
&& let Some(request_id) = error.upstream_request_id() && let Some(request_id) = error.upstream_request_id()
&& let Ok(value) = HeaderValue::from_str(request_id.as_str()) && let Ok(value) = HeaderValue::from_str(request_id.as_str())
{ {
@@ -665,7 +665,7 @@ fn engine_error_response_with_headers(
response_headers: &[ProviderResponseHeader], response_headers: &[ProviderResponseHeader],
) -> Response { ) -> Response {
let response = engine_error_response(error); let response = engine_error_response(error);
let failure_request_ids = ["x-request-id", "x-oai-request-id"] let failure_request_ids = gateway_protocol::http::RESPONSE_REQUEST_ID_HEADERS
.into_iter() .into_iter()
.flat_map(|name| { .flat_map(|name| {
response response
@@ -678,8 +678,9 @@ fn engine_error_response_with_headers(
.collect::<Vec<_>>(); .collect::<Vec<_>>();
// 失败后仍须交付已采集的 turn state;只隔离 opening 身份,不丢弃会话状态 // 失败后仍须交付已采集的 turn state;只隔离 opening 身份,不丢弃会话状态
let mut response = apply_provider_response_headers(response, response_headers); let mut response = apply_provider_response_headers(response, response_headers);
response.headers_mut().remove("x-request-id"); for name in gateway_protocol::http::RESPONSE_REQUEST_ID_HEADERS {
response.headers_mut().remove("x-oai-request-id"); response.headers_mut().remove(name);
}
for (name, value) in failure_request_ids { for (name, value) in failure_request_ids {
response.headers_mut().append(name, value); response.headers_mut().append(name, value);
} }
@@ -37,11 +37,11 @@ pub(crate) fn with_model_request_id(
let usable = |value: &HeaderValue| value.to_str().is_ok_and(|id| !id.trim().is_empty()); let usable = |value: &HeaderValue| value.to_str().is_ok_and(|id| !id.trim().is_empty());
if !headers.get("x-request-id").is_some_and(usable) { if !headers.get("x-request-id").is_some_and(usable) {
// 只有别名时沿用同一个上游值,避免外层 middleware 再填入入口 ID // 只有别名时沿用同一个上游值,避免外层 middleware 再填入入口 ID
let client_id = headers let client_id = gateway_protocol::http::preferred_response_request_id(|name| {
.get("x-oai-request-id") headers.get(name)?.to_str().ok()
.filter(|value| usable(value)) })
.unwrap_or(&gateway_id) .and_then(|value| HeaderValue::from_str(value).ok())
.clone(); .unwrap_or_else(|| gateway_id.clone());
headers.insert("x-request-id", client_id); headers.insert("x-request-id", client_id);
} }
headers.insert("x-gateway-request-id", gateway_id); headers.insert("x-gateway-request-id", gateway_id);
@@ -7,6 +7,7 @@ use crate::{
auth::{ClientKeyHeaders, authenticate_client, client_access_error_response}, auth::{ClientKeyHeaders, authenticate_client, client_access_error_response},
error::gateway_error_response, error::gateway_error_response,
generation::{GenerationEndpoint, GenerationHttpRequest, execute_prepared_generation}, generation::{GenerationEndpoint, GenerationHttpRequest, execute_prepared_generation},
router::IngressStarted,
}, },
}; };
use axum::{ use axum::{
@@ -15,18 +16,43 @@ use axum::{
http::{HeaderMap, StatusCode}, http::{HeaderMap, StatusCode},
response::Response, response::Response,
}; };
use std::net::SocketAddr; use std::{net::SocketAddr, time::Instant};
/// `POST /v1/responses` /// `POST /v1/responses`
pub(crate) async fn responses( pub(crate) async fn responses(
State(state): State<ApiState>, State(state): State<ApiState>,
connect_info: Option<Extension<ConnectInfo<SocketAddr>>>, connect_info: Option<Extension<ConnectInfo<SocketAddr>>>,
ingress_id: Option<Extension<tower_http::request_id::RequestId>>, ingress_id: Option<Extension<tower_http::request_id::RequestId>>,
ingress_started: Option<Extension<IngressStarted>>,
headers: HeaderMap, headers: HeaderMap,
body: Bytes, body: Bytes,
) -> Response { ) -> Response {
// Bytes extractor 已读完传输正文;此时尚未认证、解压或解析 JSON
let mut encodings = headers.get_all(axum::http::header::CONTENT_ENCODING).iter();
let encoding = match (encodings.next(), encodings.next()) {
(None, _) => "identity",
(Some(value), None) => value
.to_str()
.ok()
.and_then(|value| {
["identity", "gzip", "deflate", "zstd"]
.into_iter()
.find(|known| known.eq_ignore_ascii_case(value.trim()))
})
.unwrap_or("other"),
_ => "other",
};
tracing::info!(target: "request_trace", stage = "http.body.received",
receive_ms = ingress_started.map(|Extension(start)| start.0.elapsed().as_millis()),
encoded_bytes = body.len(), content_encoding = encoding,
"HTTP request body received");
let service = state.data_plane().clone(); let service = state.data_plane().clone();
let client = match authenticate_client(&service, &headers, ClientKeyHeaders::Bearer).await { let started = Instant::now();
let authentication = authenticate_client(&service, &headers, ClientKeyHeaders::Bearer).await;
tracing::info!(target: "request_trace", stage = "http.auth.finished",
auth_ms = started.elapsed().as_millis(), accepted = authentication.is_ok(),
"HTTP request authentication finished");
let client = match authentication {
Ok(client) => client, Ok(client) => client,
Err(error) => return client_access_error_response(error), Err(error) => return client_access_error_response(error),
}; };
@@ -42,7 +68,12 @@ pub(crate) async fn responses(
} }
}; };
let execution = service.execution(); let execution = service.execution();
let prepared = match execution.prepare_execution(client).await { let started = Instant::now();
let preparation = execution.prepare_execution(client).await;
tracing::info!(target: "request_trace", stage = "http.execution.prepared",
prepare_ms = started.elapsed().as_millis(), accepted = preparation.is_ok(),
"HTTP execution preparation finished");
let prepared = match preparation {
Ok(prepared) => prepared, Ok(prepared) => prepared,
Err(error) => return gateway_error_response(&error), Err(error) => return gateway_error_response(&error),
}; };
@@ -143,9 +143,20 @@ pub(crate) fn decode_request_with_body(
headers: &HeaderMap, headers: &HeaderMap,
max_decompressed_bytes: usize, max_decompressed_bytes: usize,
) -> Result<(DecodedGenerationRequest, Bytes), RequestDecodeError> { ) -> Result<(DecodedGenerationRequest, Bytes), RequestDecodeError> {
let body = decompress_request_body(body, headers, max_decompressed_bytes)?; let started = std::time::Instant::now();
let decoded = decode_request_inner(&body, &OpenAiRequestHeaders::from_headers(headers))?; let decompressed = decompress_request_body(body, headers, max_decompressed_bytes);
Ok((decoded, Bytes::copy_from_slice(&body))) tracing::info!(target: "request_trace", stage = "http.body.decompressed",
decompress_ms = started.elapsed().as_millis(),
decoded_bytes = decompressed.as_ref().ok().map(|body| body.len()),
accepted = decompressed.is_ok(), "HTTP request body decompressed");
let body = decompressed?;
let started = std::time::Instant::now();
let decoded = decode_request_inner(&body, &OpenAiRequestHeaders::from_headers(headers))
.map(|decoded| (decoded, Bytes::copy_from_slice(&body)));
tracing::info!(target: "request_trace", stage = "http.body.decoded",
decode_ms = started.elapsed().as_millis(), accepted = decoded.is_ok(),
"HTTP request body decoded");
decoded
} }
pub(super) fn decode_request_inner( pub(super) fn decode_request_inner(
@@ -8,6 +8,7 @@ use axum::http::{HeaderName, HeaderValue, StatusCode};
use gateway_core::engine::EngineError; use gateway_core::engine::EngineError;
use gateway_core::error::ProviderErrorKind; use gateway_core::error::ProviderErrorKind;
use gateway_core::event::ProviderResponseHeader; use gateway_core::event::ProviderResponseHeader;
use gateway_protocol::http::{RESPONSE_REQUEST_ID_HEADERS, preferred_response_request_id};
use serde_json::{Map, Value, json}; use serde_json::{Map, Value, json};
use thiserror::Error; use thiserror::Error;
@@ -119,9 +120,12 @@ pub(super) fn response_metadata_event(
response_headers: &[ProviderResponseHeader], response_headers: &[ProviderResponseHeader],
) -> String { ) -> String {
let mut headers = response_event_headers(response_headers); let mut headers = response_event_headers(response_headers);
let client_request_id = preferred_response_request_id(|name| headers.get(name)?.as_str())
.unwrap_or(request_id)
.to_owned();
headers headers
.entry("x-request-id".to_owned()) .entry("x-request-id".to_owned())
.or_insert_with(|| Value::String(request_id.to_owned())); .or_insert(Value::String(client_request_id));
json!({ json!({
"type": "response.metadata", "type": "response.metadata",
"headers": headers, "headers": headers,
@@ -149,7 +153,7 @@ fn response_event_headers(response_headers: &[ProviderResponseHeader]) -> Map<St
let Ok(value) = std::str::from_utf8(header.value()) else { let Ok(value) = std::str::from_utf8(header.value()) else {
continue; continue;
}; };
if matches!(name.as_str(), "x-request-id" | "x-oai-request-id") if RESPONSE_REQUEST_ID_HEADERS.contains(&name.as_str())
&& (value.trim().is_empty() || http_value.to_str().is_err()) && (value.trim().is_empty() || http_value.to_str().is_err())
{ {
continue; continue;
@@ -182,8 +186,9 @@ pub(super) fn initial_engine_error_event(
}; };
if upstream.is_none() { if upstream.is_none() {
// 会话 opening 身份不证明当前失败属于该请求;仅保留其他允许的会话头 // 会话 opening 身份不证明当前失败属于该请求;仅保留其他允许的会话头
headers.remove("x-request-id"); for name in RESPONSE_REQUEST_ID_HEADERS {
headers.remove("x-oai-request-id"); headers.remove(name);
}
} }
let status = if provider let status = if provider
.is_some_and(|error| error.kind() == ProviderErrorKind::UpstreamCapacityUnavailable) .is_some_and(|error| error.kind() == ProviderErrorKind::UpstreamCapacityUnavailable)
@@ -221,7 +226,7 @@ pub(super) fn initial_engine_error_event(
} }
fn has_request_id(headers: &Map<String, Value>) -> bool { fn has_request_id(headers: &Map<String, Value>) -> bool {
headers.contains_key("x-request-id") || headers.contains_key("x-oai-request-id") preferred_response_request_id(|name| headers.get(name)?.as_str()).is_some()
} }
pub(super) fn error_event( pub(super) fn error_event(
@@ -46,6 +46,10 @@ pub(crate) fn router() -> Router<ApiState> {
.merge(super::provider_endpoints::router()) .merge(super::provider_endpoints::router())
} }
/// 在读取正文前保存入口时刻,交给端点区分接收与执行耗时
#[derive(Clone, Copy)]
pub(crate) struct IngressStarted(pub(crate) std::time::Instant);
#[derive(Clone, Copy)] #[derive(Clone, Copy)]
pub(crate) enum DataPlaneNamespace { pub(crate) enum DataPlaneNamespace {
V1, V1,
@@ -19,7 +19,7 @@ use serde_json::json;
use tower_http::request_id::RequestId; use tower_http::request_id::RequestId;
use crate::client_error::{AccessRejection, ProtocolErrorBody}; use crate::client_error::{AccessRejection, ProtocolErrorBody};
use crate::data_plane::router::DataPlaneNamespace; use crate::data_plane::router::{DataPlaneNamespace, IngressStarted};
pub(crate) async fn record_ingress( pub(crate) async fn record_ingress(
State(diagnostics): State<Arc<dyn OperationalDiagnostics>>, State(diagnostics): State<Arc<dyn OperationalDiagnostics>>,
@@ -29,6 +29,9 @@ pub(crate) async fn record_ingress(
let Some(namespace) = DataPlaneNamespace::for_path(request.uri().path()) else { let Some(namespace) = DataPlaneNamespace::for_path(request.uri().path()) else {
return next.run(request).await; return next.run(request).await;
}; };
request
.extensions_mut()
.insert(IngressStarted(std::time::Instant::now()));
let correlation_id = request let correlation_id = request
.extensions() .extensions()
.get::<RequestId>() .get::<RequestId>()
@@ -24,6 +24,27 @@ use tower::ServiceExt as _;
use super::{AdminTestFixture, AdminTestState, unavailable_system}; use super::{AdminTestFixture, AdminTestState, unavailable_system};
#[tokio::test]
async fn version_should_expose_runtime_identity_and_restart_capability() {
let fixture = crate::support::key_fixture().await;
fixture.auth.insert_session("valid-session");
let response = app(fixture.state())
.oneshot(
Request::builder()
.uri("/api/admin/system/version")
.header(header::COOKIE, "cpr_session=valid-session")
.header("x-request-id", "req_system_version")
.body(Body::empty())
.expect("version request"),
)
.await
.expect("version response");
assert_eq!(response.status(), StatusCode::OK);
let body = crate::support::response_json(response).await;
assert_eq!(body["data"]["instanceId"], "test-instance");
assert_eq!(body["data"]["restartSupported"], true);
}
#[test] #[test]
fn update_detail_query_should_default_to_no_refresh_and_reject_unknown_fields() { fn update_detail_query_should_default_to_no_refresh_and_reject_unknown_fields() {
let query: UpdateDetailQuery = serde_json::from_str("{}").expect("empty query object"); let query: UpdateDetailQuery = serde_json::from_str("{}").expect("empty query object");
@@ -256,12 +256,21 @@ async fn request_middleware_sees_original_chat_and_preserves_the_endpoint() {
let mut execution = Execution::new(Session::new(vec![created(), completed("ok")])); let mut execution = Execution::new(Session::new(vec![created(), completed("ok")]));
execution.middleware = Some(middleware.frozen()); execution.middleware = Some(middleware.frozen());
let fixture = Fixture::with_execution(execution).await; let fixture = Fixture::with_execution(execution).await;
let response = fixture.post(chat_request(false)).await; let mut request = chat_request(false);
request["stream_options"] = json!({"include_usage":true});
request["messages"] = json!([
{"role":"developer","content":"brief"},
{"role":"system","content":null},
{"role":"assistant","tool_calls":[]},
{"role":"user","content":[{"type":"text","text":null},{"type":"text","text":"hello"}]},
{"role":"tool","name":"notifications","namespace":"agent","content":"notice"}
]);
let response = fixture.post(request.clone()).await;
assert_eq!(response.status(), StatusCode::OK); assert_eq!(response.status(), StatusCode::OK);
let downstream = json_body(response).await; let downstream = json_body(response).await;
assert_eq!(downstream["object"], "chat.completion"); assert_eq!(downstream["object"], "chat.completion");
let observed = middleware.requests.lock().unwrap(); let observed = middleware.requests.lock().unwrap();
assert_eq!(observed.as_slice(), [chat_request(false)]); assert_eq!(observed.as_slice(), [request]);
assert_eq!( assert_eq!(
middleware.inner.endpoints.lock().unwrap().as_slice(), middleware.inner.endpoints.lock().unwrap().as_slice(),
[PATH] [PATH]
@@ -396,16 +396,16 @@ fn local_provider_capacity_exhaustion_should_map_to_service_unavailable() {
); );
assert_eq!( assert_eq!(
projected.safe_message(), projected.safe_message(),
"The gateway account pool is busy." "No eligible account currently has capacity for this request."
); );
} }
#[test] #[tokio::test]
fn no_eligible_provider_account_should_preserve_safe_provider_detail() { async fn no_eligible_provider_account_should_preserve_safe_provider_detail() {
let detail = ClientVisibleUpstreamError::new( let detail = ClientVisibleUpstreamError::new(
"no account is eligible for the requested model", "This request requires an upstream WebSocket.",
Some("no_eligible_account".to_owned()), Some("websocket_account_unavailable".to_owned()),
Some("account_unavailable_error".to_owned()), None,
); );
let error = EngineError::Provider( let error = EngineError::Provider(
ProviderError::new( ProviderError::new(
@@ -419,17 +419,24 @@ fn no_eligible_provider_account_should_preserve_safe_provider_detail() {
assert_eq!(gateway.kind(), GatewayErrorKind::NoAvailableProvider); assert_eq!(gateway.kind(), GatewayErrorKind::NoAvailableProvider);
assert_eq!( assert_eq!(
gateway.client_message(), gateway.client_message(),
"no account is eligible for the requested model" "This request requires an upstream WebSocket."
); );
assert_eq!(gateway.client_error_code(), Some("no_eligible_account"));
assert_eq!( assert_eq!(
gateway.client_error_type(), gateway.client_error_code(),
Some("account_unavailable_error") Some("websocket_account_unavailable")
); );
assert_eq!(gateway.client_error_type(), None);
assert_eq!( assert_eq!(
gateway.safe_message(), gateway.safe_message(),
"The gateway found no eligible account for this request." "The gateway found no eligible account for this request."
); );
let response = engine_error_response(&error);
assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
let body: serde_json::Value =
serde_json::from_slice(&to_bytes(response.into_body(), usize::MAX).await.unwrap()).unwrap();
assert_eq!(body["error"]["type"], "server_error");
assert_eq!(body["error"]["code"], "websocket_account_unavailable");
assert_eq!(body["error"]["message"], gateway.client_message());
} }
#[test] #[test]
@@ -508,6 +515,7 @@ fn engine_provider_unsupported_capability_should_remain_unsupported() {
#[test] #[test]
fn engine_provider_credential_failures_should_not_impersonate_client_auth_failures() { fn engine_provider_credential_failures_should_not_impersonate_client_auth_failures() {
let mut messages = std::collections::HashSet::new();
for kind in [ for kind in [
ProviderErrorKind::Unauthorized, ProviderErrorKind::Unauthorized,
ProviderErrorKind::PermissionDenied, ProviderErrorKind::PermissionDenied,
@@ -516,11 +524,19 @@ fn engine_provider_credential_failures_should_not_impersonate_client_auth_failur
let mapped = gateway_error_from_engine(&error); let mapped = gateway_error_from_engine(&error);
assert_eq!(mapped.kind(), GatewayErrorKind::UpstreamUnavailable); assert_eq!(mapped.kind(), GatewayErrorKind::UpstreamUnavailable);
assert_eq!( assert!(
mapped.safe_message(), mapped
"The upstream account cannot access the service." .safe_message()
.to_lowercase()
.contains("upstream account")
); );
messages.insert(mapped.safe_message().to_owned());
} }
assert_eq!(
messages.len(),
2,
"authentication and permission failures must be distinguishable"
);
} }
#[test] #[test]
@@ -577,19 +593,29 @@ fn engine_provider_timeout_and_cancellation_should_remain_distinct() {
} }
#[test] #[test]
fn engine_provider_runtime_failures_should_collapse_to_safe_unavailability() { fn engine_provider_runtime_failures_preserve_the_cause_without_exposing_internal_details() {
let mut messages = std::collections::HashSet::new();
for kind in [ for kind in [
ProviderErrorKind::Transport, ProviderErrorKind::Transport,
ProviderErrorKind::Protocol, ProviderErrorKind::Protocol,
ProviderErrorKind::Unavailable, ProviderErrorKind::Unavailable,
ProviderErrorKind::ProcessTerminated, ProviderErrorKind::ProcessTerminated,
] { ] {
let error = EngineError::Provider(ProviderError::new(kind, UpstreamSendState::Ambiguous)); let error = EngineError::Provider(
ProviderError::new(kind, UpstreamSendState::Ambiguous)
.with_source(std::io::Error::other("PRIVATE_ENDPOINT_AND_CREDENTIAL")),
);
let projected = gateway_error_from_engine(&error); let projected = gateway_error_from_engine(&error);
assert_eq!(projected.kind(), GatewayErrorKind::UpstreamUnavailable); assert_eq!(projected.kind(), GatewayErrorKind::UpstreamUnavailable);
assert_eq!(projected.safe_message(), "Upstream service is unavailable."); assert!(!projected.client_message().contains("PRIVATE_"));
messages.insert(projected.client_message().to_owned());
} }
assert_eq!(
messages.len(),
4,
"different failure causes must remain distinguishable"
);
} }
#[test] #[test]
@@ -334,7 +334,7 @@ async fn request_settings_reach_query_terminal_without_mutating_authenticated_ba
runtime["account_queue_timeout_seconds"] = serde_json::json!(30); runtime["account_queue_timeout_seconds"] = serde_json::json!(30);
runtime["switch_account_on_queue_failure"] = serde_json::json!(false); runtime["switch_account_on_queue_failure"] = serde_json::json!(false);
settings.runtime = serde_json::from_value(runtime).unwrap(); settings.runtime = serde_json::from_value(runtime).unwrap();
settings.fast_mode = FastMode::Disabled; settings.fast_mode = Some(FastMode::Disabled);
}), }),
..Default::default() ..Default::default()
})); }));
@@ -355,8 +355,12 @@ async fn request_settings_reach_query_terminal_without_mutating_authenticated_ba
"model-a" "model-a"
); );
assert_ne!( assert_ne!(
execution.client.policy().account_scope().fast_mode(), execution
FastMode::Disabled .client
.policy()
.account_scope()
.fast_mode_override(),
Some(FastMode::Disabled)
); );
} }
} }
@@ -3300,6 +3300,12 @@ async fn response_ids_are_provider_and_client_independent() {
(&[], MODEL_REQUEST_ID), (&[], MODEL_REQUEST_ID),
(&[("x-request-id", "upstream-primary")], "upstream-primary"), (&[("x-request-id", "upstream-primary")], "upstream-primary"),
(&[("x-oai-request-id", "upstream-alias")], "upstream-alias"), (&[("x-oai-request-id", "upstream-alias")], "upstream-alias"),
(
&[("x-openai-request-id", "upstream-openai")],
"upstream-openai",
),
(&[("x-ms-request-id", "upstream-ms")], "upstream-ms"),
(&[("cf-ray", "trace-only")], MODEL_REQUEST_ID),
( (
&[ &[
("x-request-id", "upstream-primary"), ("x-request-id", "upstream-primary"),
@@ -3315,6 +3321,22 @@ async fn response_ids_are_provider_and_client_independent() {
"upstream-alias", "upstream-alias",
), ),
(&[("x-request-id", "")], MODEL_REQUEST_ID), (&[("x-request-id", "")], MODEL_REQUEST_ID),
(
&[
("x-request-id", "é"),
("x-oai-request-id", " "),
("x-openai-request-id", ""),
("x-ms-request-id", "upstream-ms"),
],
"upstream-ms",
),
(
&[
("x-openai-request-id", "upstream-openai"),
("x-ms-request-id", "upstream-ms"),
],
"upstream-openai",
),
]; ];
for provider in ["openai", "xai"] { for provider in ["openai", "xai"] {
for streaming in [false, true] { for streaming in [false, true] {
@@ -3343,6 +3365,11 @@ async fn response_ids_are_provider_and_client_independent() {
assert_eq!(response.status(), StatusCode::OK); assert_eq!(response.status(), StatusCode::OK);
assert_eq!(response.headers()["x-request-id"], *expected); assert_eq!(response.headers()["x-request-id"], *expected);
assert_eq!(response.headers()["x-gateway-request-id"], MODEL_REQUEST_ID); assert_eq!(response.headers()["x-gateway-request-id"], MODEL_REQUEST_ID);
for (name, value) in *upstream_headers {
if *name != "x-request-id" {
assert_eq!(response.headers()[*name].as_bytes(), value.as_bytes());
}
}
assert!( assert!(
!to_bytes(response.into_body(), 64 * 1024) !to_bytes(response.into_body(), 64 * 1024)
.await .await
@@ -3359,7 +3386,12 @@ async fn failure_ids_prefer_the_actual_error_over_session_headers() {
let admin = crate::admin::AdminTestFixture::new().await.services; let admin = crate::admin::AdminTestFixture::new().await.services;
for provider in ["openai", "xai"] { for provider in ["openai", "xai"] {
for streaming in [false, true] { for streaming in [false, true] {
for upstream_headers in [vec![], headers(&[("x-oai-request-id", "actual-error")])] { for upstream_headers in [
vec![],
headers(&[("x-oai-request-id", "actual-error")]),
headers(&[("x-openai-request-id", "actual-error")]),
headers(&[("x-ms-request-id", "actual-error")]),
] {
let expected = if upstream_headers.is_empty() { let expected = if upstream_headers.is_empty() {
MODEL_REQUEST_ID MODEL_REQUEST_ID
} else { } else {
@@ -3367,7 +3399,7 @@ async fn failure_ids_prefer_the_actual_error_over_session_headers() {
}; };
let raw = let raw =
Bytes::from_static(br#"{"error":{"message":"synthetic upstream detail"}}"#); Bytes::from_static(br#"{"error":{"message":"synthetic upstream detail"}}"#);
let error = let mut error =
ProviderError::new(ProviderErrorKind::InvalidRequest, UpstreamSendState::Sent) ProviderError::new(ProviderErrorKind::InvalidRequest, UpstreamSendState::Sent)
.with_client_visible_upstream_response( .with_client_visible_upstream_response(
ClientVisibleUpstreamResponse::new( ClientVisibleUpstreamResponse::new(
@@ -3377,12 +3409,25 @@ async fn failure_ids_prefer_the_actual_error_over_session_headers() {
) )
.with_headers(upstream_headers), .with_headers(upstream_headers),
); );
if expected == "actual-error" {
// 最终响应头优先于错误对象中残留的旧观测 ID
error = error.with_upstream_request_id(OpaqueUpstreamValue::new("stale-fact"));
}
let session = failed_session(streaming, EngineError::Provider(error)) let session = failed_session(streaming, EngineError::Provider(error))
.with_response_headers(headers(&[("x-request-id", "earlier-session")])); .with_response_headers(headers(&[
("x-request-id", "earlier-session"),
("x-openai-request-id", "earlier-openai"),
("x-ms-request-id", "earlier-ms"),
]));
let response = response(&admin, provider, session, streaming).await; let response = response(&admin, provider, session, streaming).await;
assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY); assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
assert_eq!(response.headers()["x-request-id"], expected); assert_eq!(response.headers()["x-request-id"], expected);
assert_eq!(response.headers()["x-gateway-request-id"], MODEL_REQUEST_ID); assert_eq!(response.headers()["x-gateway-request-id"], MODEL_REQUEST_ID);
for name in ["x-openai-request-id", "x-ms-request-id"] {
if let Some(value) = response.headers().get(name) {
assert_eq!(value, "actual-error");
}
}
assert_eq!(to_bytes(response.into_body(), 4096).await.unwrap(), raw); assert_eq!(to_bytes(response.into_body(), 4096).await.unwrap(), raw);
} }
@@ -3394,12 +3439,16 @@ async fn failure_ids_prefer_the_actual_error_over_session_headers() {
.with_response_headers(headers(&[ .with_response_headers(headers(&[
("x-request-id", "earlier-session"), ("x-request-id", "earlier-session"),
("x-oai-request-id", "earlier-alias"), ("x-oai-request-id", "earlier-alias"),
("x-openai-request-id", "earlier-openai"),
("x-ms-request-id", "earlier-ms"),
])); ]));
let response = response(&admin, provider, session, streaming).await; let response = response(&admin, provider, session, streaming).await;
assert_eq!(response.status(), StatusCode::BAD_GATEWAY); assert_eq!(response.status(), StatusCode::BAD_GATEWAY);
assert_eq!(response.headers()["x-request-id"], "body-read-error"); assert_eq!(response.headers()["x-request-id"], "body-read-error");
assert_eq!(response.headers().get_all("x-request-id").iter().count(), 1); assert_eq!(response.headers().get_all("x-request-id").iter().count(), 1);
assert!(response.headers().get("x-oai-request-id").is_none()); assert!(response.headers().get("x-oai-request-id").is_none());
assert!(response.headers().get("x-openai-request-id").is_none());
assert!(response.headers().get("x-ms-request-id").is_none());
assert_eq!(response.headers()["x-gateway-request-id"], MODEL_REQUEST_ID); assert_eq!(response.headers()["x-gateway-request-id"], MODEL_REQUEST_ID);
} }
} }
@@ -3414,12 +3463,16 @@ async fn local_execution_failure_uses_the_existing_model_id() {
failed_session(streaming, EngineError::Deadline).with_response_headers(headers(&[ failed_session(streaming, EngineError::Deadline).with_response_headers(headers(&[
("x-request-id", "opening-primary"), ("x-request-id", "opening-primary"),
("x-oai-request-id", "opening-alias"), ("x-oai-request-id", "opening-alias"),
("x-openai-request-id", "opening-openai"),
("x-ms-request-id", "opening-ms"),
("x-codex-turn-state", "retained-turn-state"), ("x-codex-turn-state", "retained-turn-state"),
])); ]));
let response = response(&admin, provider, session, streaming).await; let response = response(&admin, provider, session, streaming).await;
assert_eq!(response.headers()["x-request-id"], MODEL_REQUEST_ID); assert_eq!(response.headers()["x-request-id"], MODEL_REQUEST_ID);
assert_eq!(response.headers()["x-gateway-request-id"], MODEL_REQUEST_ID); assert_eq!(response.headers()["x-gateway-request-id"], MODEL_REQUEST_ID);
assert!(response.headers().get("x-oai-request-id").is_none()); assert!(response.headers().get("x-oai-request-id").is_none());
assert!(response.headers().get("x-openai-request-id").is_none());
assert!(response.headers().get("x-ms-request-id").is_none());
assert_eq!( assert_eq!(
response.headers()["x-codex-turn-state"], response.headers()["x-codex-turn-state"],
"retained-turn-state" "retained-turn-state"
@@ -369,23 +369,25 @@ async fn classified_capacity_error_without_special_code_returns_retryable_websoc
#[tokio::test] #[tokio::test]
async fn final_failure_headers_take_precedence_over_observed_opening_headers() { async fn final_failure_headers_take_precedence_over_observed_opening_headers() {
let provider = upstream_failure(403, b"", vec![header("x-oai-request-id", b"req_final")]) for name in ["x-oai-request-id", "x-openai-request-id", "x-ms-request-id"] {
.with_status(502) let provider = upstream_failure(403, b"", vec![header(name, b"req_final")])
.with_upstream_request_id(OpaqueUpstreamValue::new("req_stale_fact")); .with_status(502)
let error = initial_error( .with_upstream_request_id(OpaqueUpstreamValue::new("req_stale_fact"));
EngineError::Provider(provider), let error = initial_error(
vec![ EngineError::Provider(provider),
header("x-request-id", b"req_old_opening"), vec![
header("x-codex-turn-state", b"old-turn-state"), header("x-request-id", b"req_old_opening"),
], header("x-codex-turn-state", b"old-turn-state"),
) ],
.await; )
assert_eq!(error["status"], 403); .await;
assert_eq!(error["headers"]["x-oai-request-id"], "req_final"); assert_eq!(error["status"], 403);
assert!(error["headers"].get("x-request-id").is_none()); assert_eq!(error["headers"][name], "req_final");
assert!(!error.to_string().contains("req_old_opening")); assert!(error["headers"].get("x-request-id").is_none());
assert!(!error.to_string().contains("req_stale_fact")); assert!(!error.to_string().contains("req_old_opening"));
assert!(!error.to_string().contains("old-turn-state")); assert!(!error.to_string().contains("req_stale_fact"));
assert!(!error.to_string().contains("old-turn-state"));
}
} }
#[tokio::test] #[tokio::test]
@@ -398,6 +400,8 @@ async fn provider_failure_facts_survive_without_a_complete_http_response() {
vec![ vec![
header("x-request-id", b"req_old"), header("x-request-id", b"req_old"),
header("x-oai-request-id", b"req_old_alias"), header("x-oai-request-id", b"req_old_alias"),
header("x-openai-request-id", b"req_old_openai"),
header("x-ms-request-id", b"req_old_ms"),
header("x-codex-turn-state", b"observed-turn-state"), header("x-codex-turn-state", b"observed-turn-state"),
], ],
) )
@@ -409,9 +413,11 @@ async fn provider_failure_facts_survive_without_a_complete_http_response() {
"observed-turn-state" "observed-turn-state"
); );
assert!(error["headers"].get("x-oai-request-id").is_none()); assert!(error["headers"].get("x-oai-request-id").is_none());
assert!(error["headers"].get("x-openai-request-id").is_none());
assert!(error["headers"].get("x-ms-request-id").is_none());
assert_eq!( assert_eq!(
error["error"]["message"], error["error"]["message"],
"Upstream service is unavailable." "Communication with the upstream service failed."
); );
} }
@@ -511,6 +517,8 @@ async fn opening_ids_stay_in_metadata_but_do_not_identify_initial_failures() {
vec![ vec![
header("x-request-id", b"req_old_opening"), header("x-request-id", b"req_old_opening"),
header("x-oai-request-id", b"req_observed"), header("x-oai-request-id", b"req_observed"),
header("x-openai-request-id", b"req_observed_openai"),
header("x-ms-request-id", b"req_observed_ms"),
header("x-codex-turn-state", b"observed-turn-state"), header("x-codex-turn-state", b"observed-turn-state"),
header("x-future-header", b"future-value"), header("x-future-header", b"future-value"),
], ],
@@ -525,6 +533,8 @@ async fn opening_ids_stay_in_metadata_but_do_not_identify_initial_failures() {
"headers": { "headers": {
"x-request-id": "req_old_opening", "x-request-id": "req_old_opening",
"x-oai-request-id": "req_observed", "x-oai-request-id": "req_observed",
"x-openai-request-id": "req_observed_openai",
"x-ms-request-id": "req_observed_ms",
"x-codex-turn-state": "observed-turn-state", "x-codex-turn-state": "observed-turn-state",
"x-future-header": "future-value", "x-future-header": "future-value",
}, },
@@ -548,6 +558,46 @@ async fn opening_ids_stay_in_metadata_but_do_not_identify_initial_failures() {
} }
} }
#[tokio::test]
async fn metadata_prefers_readable_upstream_aliases_before_the_model_id() {
let cases: &[(&str, &[u8], Option<&str>)] = &[
("x-oai-request-id", b"req_oai", Some("req_oai")),
("X-OpenAI-Request-ID", b"req_openai", Some("req_openai")),
("x-ms-request-id", b"req_ms", Some("req_ms")),
("x-ms-request-id", b" \t ", None),
("x-ms-request-id", b"\xc3\xa9", None),
];
for (name, value, expected) in cases {
let trace = Arc::new(AtomicFailureTrace {
initial_errors: Mutex::new(VecDeque::from([EngineError::Deadline])),
..AtomicFailureTrace::default()
});
let (mut socket, _server) = connect(
Arc::clone(&trace),
vec![header("x-request-id", b"\xff"), header(name, value)],
)
.await;
send_request(&mut socket).await;
let metadata = next_event(&mut socket).await;
assert_eq!(metadata["type"], "response.metadata");
let model_id = trace.prepared_request_id.lock().unwrap().clone().unwrap();
assert_eq!(
metadata["headers"]["x-request-id"],
expected.unwrap_or(&model_id)
);
assert_eq!(
metadata["headers"][name.to_ascii_lowercase()].as_str(),
*expected
);
let error = next_event(&mut socket).await;
assert_eq!(error["type"], "error");
assert_eq!(error["headers"]["x-request-id"], "req_ws_atomic");
assert_eq!(error["headers"]["x-gateway-request-id"], "req_ws_atomic");
assert!(error["headers"].get(name.to_ascii_lowercase()).is_none());
socket.close(None).await.unwrap();
}
}
#[tokio::test] #[tokio::test]
async fn header_only_request_middleware_updates_websocket_turn_context() { async fn header_only_request_middleware_updates_websocket_turn_context() {
let middleware = Arc::new(crate::data_plane::middleware::RequestMiddleware { let middleware = Arc::new(crate::data_plane::middleware::RequestMiddleware {
@@ -746,13 +796,38 @@ async fn initial_continuation_recovery_delivers_the_official_client_replay_signa
} }
#[tokio::test] #[tokio::test]
async fn locally_exhausted_account_pool_sends_one_official_usage_limit_error() { async fn account_selection_errors_distinguish_quota_from_websocket_requirements() {
let provider = ProviderError::new( let exhausted = ProviderError::new(
ProviderErrorKind::AccountPoolQuotaExhausted, ProviderErrorKind::AccountPoolQuotaExhausted,
UpstreamSendState::NotSent, UpstreamSendState::NotSent,
); );
let error = initial_error(EngineError::Provider(provider), Vec::new()).await; let incompatible = ProviderError::new(
assert_eq!(error["status"], 429); ProviderErrorKind::NoEligibleAccount,
assert_eq!(error["error"]["type"], "usage_limit_reached"); UpstreamSendState::NotSent,
assert_eq!(error["error"]["code"], "usage_limit_reached"); )
.with_client_visible_upstream_error(ClientVisibleUpstreamError::new(
"This request requires an upstream WebSocket.",
Some("websocket_account_unavailable".to_owned()),
None,
));
for (provider, status, kind, code) in [
(exhausted, 429, "usage_limit_reached", "usage_limit_reached"),
(
incompatible,
503,
"server_error",
"websocket_account_unavailable",
),
] {
let error = initial_error(EngineError::Provider(provider), Vec::new()).await;
assert_eq!(error["status"], status);
assert_eq!(error["error"]["type"], kind);
assert_eq!(error["error"]["code"], code);
if status == 503 {
assert_eq!(
error["error"]["message"],
"This request requires an upstream WebSocket."
);
}
}
} }
@@ -313,6 +313,7 @@ fn response_create_should_reject_non_boolean_stream_without_disclosing_body_valu
#[derive(Default)] #[derive(Default)]
struct AtomicFailureTrace { struct AtomicFailureTrace {
prepared_request_id: Mutex<Option<String>>,
starts: AtomicUsize, starts: AtomicUsize,
next_calls: AtomicUsize, next_calls: AtomicUsize,
committed: AtomicBool, committed: AtomicBool,
@@ -414,8 +415,9 @@ struct AtomicFailureExecution {
impl ExecutionService for AtomicFailureExecution { impl ExecutionService for AtomicFailureExecution {
fn middleware_plan( fn middleware_plan(
&self, &self,
_: &gateway_core::engine::execution::PreparedRootExecution, prepared: &gateway_core::engine::execution::PreparedRootExecution,
) -> Option<gateway_core::engine::middleware::FrozenMiddlewarePlan> { ) -> Option<gateway_core::engine::middleware::FrozenMiddlewarePlan> {
*self.trace.prepared_request_id.lock().unwrap() = Some(prepared.request_id().to_string());
self.trace.middleware.clone() self.trace.middleware.clone()
} }
@@ -255,3 +255,71 @@ async fn original_rejected_request_is_dumped_only_when_explicitly_enabled() {
} }
} }
} }
#[tokio::test]
async fn responses_ingress_separates_body_receipt_from_decompression_and_decoding() {
use std::io::Write as _;
use tracing::instrument::WithSubscriber as _;
let recorder = Recorder {
dump_enabled: false,
events: Arc::default(),
};
let events = recorder.events.clone();
let decoded = json!({"model":42,"input":"SENSITIVE_CONTENT".repeat(1024)}).to_string();
let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast());
encoder.write_all(decoded.as_bytes()).unwrap();
let encoded = encoder.finish().unwrap();
let encoded_len = encoded.len();
assert!(encoded_len < decoded.len());
async {
let (router, _) = fixture().await;
let body = Body::from_stream(futures::stream::once(async move {
tokio::time::sleep(std::time::Duration::from_millis(40)).await;
Ok::<_, std::io::Error>(encoded)
}));
let response = router
.oneshot(
Request::post("/v1/responses")
.header("authorization", "Bearer unused-client-route-key")
.header("content-encoding", "gzip")
.body(body)
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
}
.with_subscriber(recorder)
.await;
let events = events.lock().unwrap();
let phases = events
.iter()
.filter(|event| {
event.get("stage").is_some_and(|stage| {
stage.starts_with("http.body.") || stage == "http.auth.finished"
})
})
.collect::<Vec<_>>();
assert_eq!(
phases
.iter()
.map(|event| event["stage"].as_str())
.collect::<Vec<_>>(),
[
"http.body.received",
"http.auth.finished",
"http.body.decompressed",
"http.body.decoded",
]
);
assert!(phases[0]["receive_ms"].parse::<u64>().unwrap() >= 30);
assert_eq!(phases[0]["encoded_bytes"], encoded_len.to_string());
assert_eq!(phases[0]["content_encoding"], "gzip");
assert_eq!(phases[2]["decoded_bytes"], decoded.len().to_string());
assert_eq!(phases[2]["accepted"], "true");
assert_eq!(phases[3]["accepted"], "false");
assert!(events.iter().flat_map(|event| event.values()).all(|value| {
!value.contains("SENSITIVE_CONTENT") && !value.contains("unused-client-route-key")
}));
}
@@ -91,6 +91,8 @@ impl SystemOperations for VersionSystem {
async fn version(&self) -> Result<SystemVersion, SystemOperationError> { async fn version(&self) -> Result<SystemVersion, SystemOperationError> {
Ok(SystemVersion { Ok(SystemVersion {
version: "3.7.0".to_owned(), version: "3.7.0".to_owned(),
instance_id: "test-instance".to_owned(),
restart_supported: true,
git_sha: "internal-revision".to_owned(), git_sha: "internal-revision".to_owned(),
build_time: "internal-build-time".to_owned(), build_time: "internal-build-time".to_owned(),
deployment_mode: "binary".to_owned(), deployment_mode: "binary".to_owned(),
@@ -108,6 +108,7 @@ pub struct RuntimeAccountDirectory {
providers_with_accounts: BTreeSet<ProviderKind>, providers_with_accounts: BTreeSet<ProviderKind>,
providers_by_group: BTreeMap<AccountGroupId, BTreeSet<ProviderKind>>, providers_by_group: BTreeMap<AccountGroupId, BTreeSet<ProviderKind>>,
group_model_access: BTreeMap<AccountGroupId, AccountModelAccess>, group_model_access: BTreeMap<AccountGroupId, AccountModelAccess>,
group_fast_modes: BTreeMap<AccountGroupId, FastMode>,
} }
impl RuntimeAccountDirectory { impl RuntimeAccountDirectory {
@@ -129,6 +130,7 @@ impl RuntimeAccountDirectory {
providers_with_accounts, providers_with_accounts,
providers_by_group, providers_by_group,
group_model_access: BTreeMap::new(), group_model_access: BTreeMap::new(),
group_fast_modes: BTreeMap::new(),
} }
} }
@@ -141,6 +143,12 @@ impl RuntimeAccountDirectory {
self self
} }
#[must_use]
pub fn with_group_fast_modes(mut self, policies: BTreeMap<AccountGroupId, FastMode>) -> Self {
self.group_fast_modes = policies;
self
}
pub(crate) fn accounts_in_group( pub(crate) fn accounts_in_group(
&self, &self,
group: &AccountGroupId, group: &AccountGroupId,
@@ -288,7 +296,7 @@ impl ClientRoutingScope {
pub struct FrozenAccountScope { pub struct FrozenAccountScope {
allow_image_generation: bool, allow_image_generation: bool,
allow_subagents: bool, allow_subagents: bool,
fast_mode: FastMode, fast_mode_override: Option<FastMode>,
request_profiles: BTreeMap<ProviderKind, super::OpaqueProviderData>, request_profiles: BTreeMap<ProviderKind, super::OpaqueProviderData>,
directory: Arc<RuntimeAccountDirectory>, directory: Arc<RuntimeAccountDirectory>,
client_scope: ClientRoutingScope, client_scope: ClientRoutingScope,
@@ -355,16 +363,34 @@ impl FrozenAccountScope {
self self
} }
/// Key 绑定分组的冻结 Fast 策略,与账号成员资格无关 /// 显式请求覆盖独立于分组策略;None 表示按选中账号的有效分组计算
#[must_use] #[must_use]
pub const fn with_fast_mode(mut self, fast_mode: FastMode) -> Self { pub const fn with_fast_mode_override(mut self, fast_mode: Option<FastMode>) -> Self {
self.fast_mode = fast_mode; self.fast_mode_override = fast_mode;
self self
} }
#[must_use] #[must_use]
pub const fn fast_mode(&self) -> FastMode { pub const fn fast_mode_override(&self) -> Option<FastMode> {
self.fast_mode self.fast_mode_override
}
/// 只合并当前 Key 授权该账号与模型的启用分组,换号仍使用同一冻结目录
#[must_use]
pub fn fast_mode_for_account(
&self,
account_id: &ProviderAccountId,
upstream_model: &str,
) -> FastMode {
if let Some(mode) = self.fast_mode_override {
return mode;
}
let Some(account) = self.directory.account(account_id) else {
return FastMode::Default;
};
self.matching_groups(account, |access| access.allows(upstream_model))
.filter_map(|id| self.directory.group_fast_modes.get(id))
.fold(FastMode::Default, |mode, other| mode.merge(*other))
} }
#[must_use] #[must_use]
@@ -376,7 +402,7 @@ impl FrozenAccountScope {
Self { Self {
allow_image_generation: true, allow_image_generation: true,
allow_subagents: true, allow_subagents: true,
fast_mode: FastMode::Default, fast_mode_override: None,
request_profiles: BTreeMap::new(), request_profiles: BTreeMap::new(),
directory, directory,
client_scope, client_scope,
@@ -460,18 +486,31 @@ impl FrozenAccountScope {
} }
match &self.client_scope { match &self.client_scope {
ClientRoutingScope::AllAccounts => true, ClientRoutingScope::AllAccounts => true,
ClientRoutingScope::Restricted { .. } => {
self.matching_groups(account, accepts).next().is_some()
}
}
}
fn matching_groups<'a>(
&'a self,
account: &'a RuntimeAccount,
accepts: impl Fn(&AccountModelAccess) -> bool + 'a,
) -> impl Iterator<Item = &'a AccountGroupId> {
let enabled = match &self.client_scope {
ClientRoutingScope::AllAccounts => None,
ClientRoutingScope::Restricted { ClientRoutingScope::Restricted {
enabled_group_ids, .. enabled_group_ids, ..
} => account } => Some(enabled_group_ids),
.group_ids() };
.intersection(enabled_group_ids) account.group_ids().iter().filter(move |id| {
.any(|id| { enabled.is_some_and(|groups| groups.contains(*id))
self.directory && self
.group_model_access .directory
.get(id) .group_model_access
.is_none_or(&accepts) .get(*id)
}), .is_none_or(&accepts)
} })
} }
#[must_use] #[must_use]
@@ -1200,7 +1200,6 @@ where
.with_lease_metadata(Arc::clone(&self.lease_metadata)) .with_lease_metadata(Arc::clone(&self.lease_metadata))
.with_response_control(self.response_control.clone()) .with_response_control(self.response_control.clone())
.with_request_profile(self.request_profiles.get(candidate.provider()).cloned()) .with_request_profile(self.request_profiles.get(candidate.provider()).cloned())
.with_fast_mode(self.plan.fast_mode())
.with_prompt_rewrite_rules(self.plan.prompt_rewrite_rules(candidate.provider())) .with_prompt_rewrite_rules(self.plan.prompt_rewrite_rules(candidate.provider()))
.with_pricing(self.plan.pricing()) .with_pricing(self.plan.pricing())
.with_request_location(self.plan.request_location().cloned()) .with_request_location(self.plan.request_location().cloned())
@@ -48,11 +48,17 @@ pub(super) fn map_routing_error(error: crate::validation::RoutingError) -> Gatew
"Mapped model unavailable for this API key. Check the model mapping." "Mapped model unavailable for this API key. Check the model mapping."
}, },
), ),
crate::validation::RoutingError::NoCapableProvider { .. } crate::validation::RoutingError::NoCapableProvider { .. } => GatewayError::new(
| crate::validation::RoutingError::NoCapableProviderEndpoint { .. }
| crate::validation::RoutingError::EmptyAccountScope => GatewayError::new(
GatewayErrorKind::NoAvailableProvider, GatewayErrorKind::NoAvailableProvider,
"The gateway has no eligible provider for this request.", "The gateway cannot select a provider for this model and the requested capabilities.",
),
crate::validation::RoutingError::NoCapableProviderEndpoint { .. } => GatewayError::new(
GatewayErrorKind::NoAvailableProvider,
"No eligible provider is available for the requested API endpoint.",
),
crate::validation::RoutingError::EmptyAccountScope => GatewayError::new(
GatewayErrorKind::NoAvailableProvider,
"This API key has no accounts in its scope. Add accounts or check its enabled account groups.",
), ),
crate::validation::RoutingError::UnsupportedProviderEndpoint { .. } => GatewayError::new( crate::validation::RoutingError::UnsupportedProviderEndpoint { .. } => GatewayError::new(
GatewayErrorKind::Unsupported, GatewayErrorKind::Unsupported,
+8 -10
View File
@@ -330,7 +330,6 @@ pub struct RequestAttemptContext {
prompt_rewrite_rules: Option<Arc<crate::settings::prompt_rewrite::ProviderPromptRules>>, prompt_rewrite_rules: Option<Arc<crate::settings::prompt_rewrite::ProviderPromptRules>>,
pricing: Arc<crate::metering::PricingOverrides>, pricing: Arc<crate::metering::PricingOverrides>,
request_profile: Option<crate::account::OpaqueProviderData>, request_profile: Option<crate::account::OpaqueProviderData>,
fast_mode: FastMode,
openai_websocket_pool: crate::settings::OpenAiWebSocketPoolSettings, openai_websocket_pool: crate::settings::OpenAiWebSocketPoolSettings,
openai_request_settings: crate::settings::OpenAiRequestSettings, openai_request_settings: crate::settings::OpenAiRequestSettings,
request_location: Option<crate::account::RequestLocation>, request_location: Option<crate::account::RequestLocation>,
@@ -424,12 +423,6 @@ impl RequestAttemptContext {
self self
} }
#[must_use]
pub const fn with_fast_mode(mut self, fast_mode: FastMode) -> Self {
self.fast_mode = fast_mode;
self
}
#[must_use] #[must_use]
pub fn with_privacy( pub fn with_privacy(
mut self, mut self,
@@ -478,7 +471,6 @@ impl RequestAttemptContext {
request_profile: None, request_profile: None,
prompt_rewrite_rules: None, prompt_rewrite_rules: None,
pricing: Arc::default(), pricing: Arc::default(),
fast_mode: FastMode::Default,
openai_websocket_pool: Default::default(), openai_websocket_pool: Default::default(),
openai_request_settings: Default::default(), openai_request_settings: Default::default(),
request_location: None, request_location: None,
@@ -743,8 +735,14 @@ impl AttemptContext {
} }
#[must_use] #[must_use]
pub const fn fast_mode(&self) -> FastMode { pub fn fast_mode_for_account(
self.request.fast_mode &self,
account: &ProviderAccountId,
upstream_model: &str,
) -> FastMode {
self.account_scope().map_or(FastMode::Default, |scope| {
scope.fast_mode_for_account(account, upstream_model)
})
} }
#[must_use] #[must_use]
+31 -14
View File
@@ -1436,14 +1436,14 @@ impl GatewayError {
pub(crate) const fn concurrency_queue_full() -> Self { pub(crate) const fn concurrency_queue_full() -> Self {
Self::new( Self::new(
GatewayErrorKind::ConcurrencyQueueFull, GatewayErrorKind::ConcurrencyQueueFull,
"The gateway request queue is full.", "The gateway concurrency queue is full.",
) )
} }
pub(crate) const fn concurrency_queue_timeout() -> Self { pub(crate) const fn concurrency_queue_timeout() -> Self {
Self::new( Self::new(
GatewayErrorKind::ConcurrencyQueueTimeout, GatewayErrorKind::ConcurrencyQueueTimeout,
"The request timed out in the gateway queue.", "Timed out waiting for available concurrency in the gateway.",
) )
} }
@@ -1516,20 +1516,25 @@ impl GatewayError {
GatewayErrorKind::Unsupported, GatewayErrorKind::Unsupported,
"Requested capability is unsupported.", "Requested capability is unsupported.",
), ),
ProviderErrorKind::Unauthorized | ProviderErrorKind::PermissionDenied => Self::new( ProviderErrorKind::Unauthorized => Self::new(
GatewayErrorKind::UpstreamUnavailable, GatewayErrorKind::UpstreamUnavailable,
"The upstream account cannot access the service.", "Upstream account authentication failed.",
),
ProviderErrorKind::PermissionDenied => Self::new(
GatewayErrorKind::UpstreamUnavailable,
"The upstream account does not have permission for this request.",
), ),
ProviderErrorKind::RequestPolicyDenied => error.denied_group_feature.map_or_else( ProviderErrorKind::RequestPolicyDenied => error.denied_group_feature.map_or_else(
|| Self::new(GatewayErrorKind::PolicyDenied, "Request blocked by policy."), || Self::new(GatewayErrorKind::PolicyDenied, "Request blocked by policy."),
Self::from, Self::from,
), ),
ProviderErrorKind::RateLimited => { ProviderErrorKind::RateLimited => Self::new(
Self::new(GatewayErrorKind::RateLimited, "Request rate limit reached.") GatewayErrorKind::RateLimited,
} "Upstream request rate limit reached.",
),
ProviderErrorKind::QuotaExhausted => Self::new( ProviderErrorKind::QuotaExhausted => Self::new(
GatewayErrorKind::QuotaExhausted, GatewayErrorKind::QuotaExhausted,
"Account quota is exhausted.", "Upstream account quota is exhausted.",
), ),
ProviderErrorKind::AccountPoolQuotaExhausted => Self::new( ProviderErrorKind::AccountPoolQuotaExhausted => Self::new(
GatewayErrorKind::AccountPoolQuotaExhausted, GatewayErrorKind::AccountPoolQuotaExhausted,
@@ -1539,7 +1544,7 @@ impl GatewayError {
ProviderErrorKind::ConcurrencyQueueTimeout => Self::concurrency_queue_timeout(), ProviderErrorKind::ConcurrencyQueueTimeout => Self::concurrency_queue_timeout(),
ProviderErrorKind::AccountCapacityUnavailable => Self::new( ProviderErrorKind::AccountCapacityUnavailable => Self::new(
GatewayErrorKind::AccountCapacityUnavailable, GatewayErrorKind::AccountCapacityUnavailable,
"The gateway account pool is busy.", "No eligible account currently has capacity for this request.",
), ),
ProviderErrorKind::NoEligibleAccount => Self::new( ProviderErrorKind::NoEligibleAccount => Self::new(
GatewayErrorKind::NoAvailableProvider, GatewayErrorKind::NoAvailableProvider,
@@ -1559,11 +1564,23 @@ impl GatewayError {
ProviderErrorKind::Cancelled => { ProviderErrorKind::Cancelled => {
Self::new(GatewayErrorKind::Cancelled, "Request was cancelled.") Self::new(GatewayErrorKind::Cancelled, "Request was cancelled.")
} }
ProviderErrorKind::Transport ProviderErrorKind::Transport => Self::new(
| ProviderErrorKind::Protocol GatewayErrorKind::UpstreamUnavailable,
| ProviderErrorKind::Unavailable "Communication with the upstream service failed.",
| ProviderErrorKind::UpstreamCapacityUnavailable ),
| ProviderErrorKind::ProcessTerminated => Self::new( ProviderErrorKind::Protocol => Self::new(
GatewayErrorKind::UpstreamUnavailable,
"Upstream protocol handling failed.",
),
ProviderErrorKind::ProcessTerminated => Self::new(
GatewayErrorKind::UpstreamUnavailable,
"The gateway stopped before the request completed.",
),
ProviderErrorKind::UpstreamCapacityUnavailable => Self::new(
GatewayErrorKind::UpstreamUnavailable,
"The upstream service has no capacity for this request.",
),
ProviderErrorKind::Unavailable => Self::new(
GatewayErrorKind::UpstreamUnavailable, GatewayErrorKind::UpstreamUnavailable,
"Upstream service is unavailable.", "Upstream service is unavailable.",
), ),
@@ -5,6 +5,7 @@ use std::sync::{Arc, OnceLock};
use std::time::{Duration, SystemTime}; use std::time::{Duration, SystemTime};
use event_listener::Event; use event_listener::Event;
use futures::FutureExt as _;
use futures::future::{BoxFuture, pending}; use futures::future::{BoxFuture, pending};
use futures_timer::Delay; use futures_timer::Delay;
@@ -142,6 +143,14 @@ impl CancellationToken {
self.reason().is_some() 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) { pub async fn cancelled(&self) {
if self.is_cancelled() { if self.is_cancelled() {
return; return;
@@ -158,7 +158,7 @@ impl RateLimits {
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub struct ClientSettings { pub struct ClientSettings {
pub request_profiles: BTreeMap<ProviderKind, OpaqueProviderData>, pub request_profiles: BTreeMap<ProviderKind, OpaqueProviderData>,
pub fast_mode: FastMode, pub fast_mode_override: Option<FastMode>,
pub limits: RateLimits, pub limits: RateLimits,
} }
@@ -185,18 +185,18 @@ impl ClientPolicy {
pub(crate) fn with_settings( pub(crate) fn with_settings(
mut self, mut self,
profiles: &BTreeMap<ProviderKind, OpaqueProviderData>, profiles: &BTreeMap<ProviderKind, OpaqueProviderData>,
fast_mode: FastMode, fast_mode_override: Option<FastMode>,
limits: RateLimits, limits: RateLimits,
) -> Self { ) -> Self {
if self.account_scope.request_profiles() != profiles if self.account_scope.request_profiles() != profiles
|| self.account_scope.fast_mode() != fast_mode || self.account_scope.fast_mode_override() != fast_mode_override
{ {
self.account_scope = Arc::new( self.account_scope = Arc::new(
self.account_scope self.account_scope
.as_ref() .as_ref()
.clone() .clone()
.with_request_profiles(profiles.clone()) .with_request_profiles(profiles.clone())
.with_fast_mode(fast_mode), .with_fast_mode_override(fast_mode_override),
); );
} }
self.limits = limits; self.limits = limits;
@@ -217,7 +217,7 @@ impl ClientPolicy {
name_snapshot: None, name_snapshot: None,
defaults: Arc::new(ClientSettings { defaults: Arc::new(ClientSettings {
request_profiles: account_scope.request_profiles().clone(), request_profiles: account_scope.request_profiles().clone(),
fast_mode: account_scope.fast_mode(), fast_mode_override: account_scope.fast_mode_override(),
limits, limits,
}), }),
key_id, key_id,
@@ -23,7 +23,7 @@ use std::fmt;
use std::num::{NonZeroU32, NonZeroU64}; use std::num::{NonZeroU32, NonZeroU64};
use std::sync::Arc; use std::sync::Arc;
use crate::account::{AccountSelectionPolicy, FastMode}; use crate::account::AccountSelectionPolicy;
use crate::operation::{CapabilityRequirements, Feature, OperationKind}; use crate::operation::{CapabilityRequirements, Feature, OperationKind};
use crate::validation::{IdentifierError, RoutingError, validate_text}; use crate::validation::{IdentifierError, RoutingError, validate_text};
@@ -767,11 +767,6 @@ impl RoutingPlan {
Arc::clone(&self.pricing) Arc::clone(&self.pricing)
} }
#[must_use]
pub fn fast_mode(&self) -> FastMode {
self.account_scope.fast_mode()
}
/// 本次请求冻结的已编译规则,重试不读取新的全局策略 /// 本次请求冻结的已编译规则,重试不读取新的全局策略
#[must_use] #[must_use]
pub fn privacy(&self) -> Option<Arc<dyn crate::settings::privacy::CompiledPrivacyPolicy>> { pub fn privacy(&self) -> Option<Arc<dyn crate::settings::privacy::CompiledPrivacyPolicy>> {
@@ -19,7 +19,8 @@ use crate::settings::{InvalidSettings, SettingsValues};
#[serde(deny_unknown_fields)] #[serde(deny_unknown_fields)]
pub struct ExecutionSettings { pub struct ExecutionSettings {
pub runtime: SettingsValues, pub runtime: SettingsValues,
pub fast_mode: FastMode, /// None 按选中账号的有效分组解析;Some(Default) 显式跟随客户端
pub fast_mode: Option<FastMode>,
pub client_limits: RateLimits, pub client_limits: RateLimits,
/// null 表示不限制总时长;显式时限从请求开始计时,改写不重置计时原点 /// null 表示不限制总时长;显式时限从请求开始计时,改写不重置计时原点
pub timeout_ms: Option<u64>, pub timeout_ms: Option<u64>,
@@ -38,7 +39,7 @@ struct ExecutionOverrides {
defaults: Arc<ClientSettings>, defaults: Arc<ClientSettings>,
client_key_id: String, client_key_id: String,
input: Arc<ExecutionSettings>, input: Arc<ExecutionSettings>,
fast_mode: Option<SettingOverride<FastMode>>, fast_mode: Option<SettingOverride<Option<FastMode>>>,
client_limits: Option<SettingOverride<RateLimits>>, client_limits: Option<SettingOverride<RateLimits>>,
timeout_ms: Option<SettingOverride<Option<u64>>>, timeout_ms: Option<SettingOverride<Option<u64>>>,
} }
@@ -186,9 +187,10 @@ impl RequestSettings {
#[must_use] #[must_use]
pub fn apply_policy(&self, policy: ClientPolicy) -> ClientPolicy { pub fn apply_policy(&self, policy: ClientPolicy) -> ClientPolicy {
let values = self.resolve_execution(policy.key_id().as_str(), policy.defaults(), None); let values = self.resolve_execution(policy.key_id().as_str(), policy.defaults(), None);
let fast_mode = self.fast_mode_override(policy.key_id().as_str(), policy.defaults());
policy.with_settings( policy.with_settings(
values.runtime.request_profiles(), values.runtime.request_profiles(),
values.fast_mode, fast_mode,
values.client_limits, values.client_limits,
) )
} }
@@ -247,9 +249,7 @@ impl RequestSettings {
} }
ExecutionSettings { ExecutionSettings {
runtime, runtime,
fast_mode: overrides fast_mode: self.fast_mode_override(key, defaults),
.and_then(|scope| scope.fast_mode.as_ref())
.map_or(defaults.fast_mode, |change| change.value),
client_limits: overrides client_limits: overrides
.and_then(|scope| scope.client_limits.as_ref()) .and_then(|scope| scope.client_limits.as_ref())
.map_or(defaults.limits, |change| change.value), .map_or(defaults.limits, |change| change.value),
@@ -259,6 +259,15 @@ impl RequestSettings {
} }
} }
fn fast_mode_override(&self, key: &str, defaults: &ClientSettings) -> Option<FastMode> {
self.execution
.as_ref()
.filter(|scope| scope.client_key_id == key)
.and_then(|scope| scope.fast_mode.as_ref())
.map(|change| change.value)
.unwrap_or(defaults.fast_mode_override)
}
pub(crate) fn execution_deadline( pub(crate) fn execution_deadline(
&self, &self,
key: &ClientApiKeyId, key: &ClientApiKeyId,
@@ -583,12 +583,19 @@ async fn compile_runtime_snapshot(
.map(|group| (group.id.clone(), std::mem::take(&mut group.model_access))) .map(|group| (group.id.clone(), std::mem::take(&mut group.model_access)))
.collect(); .collect();
let account_directory = Arc::new( let account_directory = Arc::new(
RuntimeAccountDirectory::new(accounts).with_group_model_access(group_model_access), RuntimeAccountDirectory::new(accounts)
.with_group_model_access(group_model_access)
.with_group_fast_modes(
groups
.values()
.filter(|group| group.enabled && group.fast_mode != FastMode::Default)
.map(|group| (group.id.clone(), group.fast_mode))
.collect(),
),
); );
let mut client_policies = Vec::with_capacity(facts.client_policies.len()); let mut client_policies = Vec::with_capacity(facts.client_policies.len());
for policy in facts.client_policies { for policy in facts.client_policies {
let mut fast_mode = FastMode::Default;
let mut allow_image_generation = true; let mut allow_image_generation = true;
let mut allow_subagents = true; let mut allow_subagents = true;
let account_scope = if policy.group_ids.is_empty() { let account_scope = if policy.group_ids.is_empty() {
@@ -607,8 +614,7 @@ async fn compile_runtime_snapshot(
let group = groups let group = groups
.get(&group_id) .get(&group_id)
.ok_or(RuntimeSnapshotCompileError::InvalidData)?; .ok_or(RuntimeSnapshotCompileError::InvalidData)?;
// 停用只影响选号,仍绑定的分组继续贡献请求策略 // 功能权限仍按 Key 合并,停用分组不解除生图和子代理限制
fast_mode = fast_mode.merge(group.fast_mode);
allow_image_generation &= group.allow_image_generation; allow_image_generation &= group.allow_image_generation;
allow_subagents &= group.allow_subagents; allow_subagents &= group.allow_subagents;
bound_groups.push(RoutingGroupSnapshot::new( bound_groups.push(RoutingGroupSnapshot::new(
@@ -635,7 +641,6 @@ async fn compile_runtime_snapshot(
account_scope account_scope
.with_image_generation(allow_image_generation) .with_image_generation(allow_image_generation)
.with_subagents(allow_subagents) .with_subagents(allow_subagents)
.with_fast_mode(fast_mode)
.with_request_profiles(policy.request_profiles), .with_request_profiles(policy.request_profiles),
), ),
true, true,
@@ -399,14 +399,13 @@ struct RuntimeSnapshotReconciliationTask {
} }
impl ScheduledTask for RuntimeSnapshotReconciliationTask { impl ScheduledTask for RuntimeSnapshotReconciliationTask {
fn run_cycle( fn run_cycle(&self, context: WorkerCycleContext) -> BoxFuture<'_, Result<(), WorkerTaskError>> {
&self,
_context: WorkerCycleContext,
) -> BoxFuture<'_, Result<(), WorkerTaskError>> {
Box::pin(async move { Box::pin(async move {
self.publisher context
.refresh_with_mode(RefreshMode::Reconcile) .cancellation()
.run_until_cancelled(self.publisher.refresh_with_mode(RefreshMode::Reconcile))
.await .await
.transpose()
.map(|_| ()) .map(|_| ())
.map_err(|source| { .map_err(|source| {
WorkerTaskError::safe("runtime snapshot reconciliation failed") WorkerTaskError::safe("runtime snapshot reconciliation failed")
@@ -430,10 +429,12 @@ impl DaemonTask for RuntimeSnapshotSubscriptionTask {
let cancellation = context.cancellation(); let cancellation = context.cancellation();
let mut retry_delay = INITIAL_BACKOFF; let mut retry_delay = INITIAL_BACKOFF;
loop { loop {
if cancellation.is_cancelled() { let Some(subscription) = cancellation
.run_until_cancelled(self.subscriptions.subscribe_snapshot_revisions())
.await
else {
return Ok(()); return Ok(());
} };
let subscription = self.subscriptions.subscribe_snapshot_revisions().await;
let mut subscription = match subscription { let mut subscription = match subscription {
Ok(subscription) => { Ok(subscription) => {
retry_delay = INITIAL_BACKOFF; retry_delay = INITIAL_BACKOFF;
@@ -456,7 +457,13 @@ impl DaemonTask for RuntimeSnapshotSubscriptionTask {
}; };
match notified { match notified {
Some(Ok(_)) => { Some(Ok(_)) => {
let _ = self.publisher.refresh().await; if cancellation
.run_until_cancelled(self.publisher.refresh())
.await
.is_none()
{
return Ok(());
}
} }
Some(Err(_)) | None => break, Some(Err(_)) | None => break,
} }
@@ -1138,26 +1138,12 @@ fn plan_with_location(
operation: &Operation, operation: &Operation,
account_selection_policy: AccountSelectionPolicy, account_selection_policy: AccountSelectionPolicy,
request_location: gateway_core::account::RequestLocation, request_location: gateway_core::account::RequestLocation,
) -> RoutingPlan {
plan_with_location_and_fast_policy(
operation,
account_selection_policy,
request_location,
FastMode::Default,
)
}
fn plan_with_location_and_fast_policy(
operation: &Operation,
account_selection_policy: AccountSelectionPolicy,
request_location: gateway_core::account::RequestLocation,
fast_mode: FastMode,
) -> RoutingPlan { ) -> RoutingPlan {
plan_with_profiles( plan_with_profiles(
operation, operation,
account_selection_policy, account_selection_policy,
request_location, request_location,
fast_mode, FastMode::Default,
Default::default(), Default::default(),
) )
} }
@@ -1255,7 +1241,7 @@ fn plan_with_protection(
operation, operation,
Arc::new( Arc::new(
FrozenAccountScope::new(directory, ClientRoutingScope::all_accounts()) FrozenAccountScope::new(directory, ClientRoutingScope::all_accounts())
.with_fast_mode(fast_mode) .with_fast_mode_override(Some(fast_mode))
.with_request_profiles(profiles), .with_request_profiles(profiles),
), ),
&RoutingContext { &RoutingContext {
@@ -6414,6 +6400,8 @@ fn deadline_before_first_event_is_persisted_as_failed_attempt() {
#[test] #[test]
fn global_location_and_group_fast_policy_reach_every_account_retry() { fn global_location_and_group_fast_policy_reach_every_account_retry() {
use gateway_core::routing::{AccountGroupId, RoutingGroupSnapshot};
for mode in [ for mode in [
FastMode::Default, FastMode::Default,
FastMode::Enabled, FastMode::Enabled,
@@ -6425,12 +6413,67 @@ fn global_location_and_group_fast_policy_reach_every_account_retry() {
timezone: "Asia/Tokyo".parse().unwrap(), timezone: "Asia/Tokyo".parse().unwrap(),
..Default::default() ..Default::default()
}; };
let route_plan = plan_with_location_and_fast_policy( let kind = ProviderKind::new("openai").unwrap();
&operation, let first_group = AccountGroupId::new(format!("grp_{:032x}", 1)).unwrap();
plan(&operation).account_selection_policy(), let second_group = AccountGroupId::new(format!("grp_{:032x}", 2)).unwrap();
location.clone(), let second_mode = if mode == FastMode::Disabled {
mode, FastMode::Default
} else {
FastMode::Disabled
};
let directory = Arc::new(
RuntimeAccountDirectory::new(
[
("acct_first", first_group.clone()),
("acct_second", second_group.clone()),
]
.into_iter()
.map(|(account, group)| {
(
ProviderAccountId::new(account).unwrap(),
RuntimeAccount::new(kind.clone(), BTreeSet::from([group])),
)
})
.collect(),
)
.with_group_fast_modes(BTreeMap::from([
(first_group.clone(), mode),
(second_group.clone(), second_mode),
])),
); );
let scope = Arc::new(FrozenAccountScope::new(
Arc::clone(&directory),
ClientRoutingScope::restricted(
vec![
RoutingGroupSnapshot::new(first_group.clone(), "A".into()),
RoutingGroupSnapshot::new(second_group.clone(), "B".into()),
],
BTreeSet::from([first_group, second_group]),
BTreeSet::from([kind.clone()]),
)
.unwrap(),
));
let route_plan = RuntimeSnapshot::new(
ConfigRevision::new(1).unwrap(),
gateway_core::settings::SettingsValues::new(2, "smart", Default::default(), None, None)
.with_request_location(location.clone(), true),
vec![kind.clone()],
vec![ProviderModel::new(
kind,
UpstreamModelId::new("gpt-5").unwrap(),
ModelCapabilities::new(BTreeSet::from([operation.kind()]), Some(32_000)),
)],
Vec::new(),
)
.unwrap()
.with_account_directory(directory)
.plan(
&PublicModelId::new("gpt-5").unwrap(),
&operation,
Arc::clone(&scope),
&RoutingContext::default(),
)
.unwrap();
let (coordinator, _, provider) = coordinator(vec![ let (coordinator, _, provider) = coordinator(vec![
Script::Stream { Script::Stream {
account_id: "acct_first", account_id: "acct_first",
@@ -6459,12 +6502,17 @@ fn global_location_and_group_fast_policy_reach_every_account_retry() {
block_on(session.commit_downstream(Some(200))).unwrap(); block_on(session.commit_downstream(Some(200))).unwrap();
let contexts = provider.contexts.lock().unwrap(); let contexts = provider.contexts.lock().unwrap();
assert_eq!(contexts.len(), 2); assert_eq!(contexts.len(), 2);
assert!( for (context, account, expected) in [
contexts (&contexts[0], "acct_first", mode),
.iter() (&contexts[1], "acct_second", second_mode),
.all(|context| context.request_location() == Some(&location) ] {
&& context.fast_mode() == mode) assert_eq!(context.request_location(), Some(&location));
); assert!(Arc::ptr_eq(context.account_scope().unwrap(), &scope));
assert_eq!(
context.fast_mode_for_account(&ProviderAccountId::new(account).unwrap(), "gpt-5"),
expected,
);
}
} }
} }
@@ -3068,8 +3068,14 @@ impl Provider for ChargedProvider {
request: ProviderRequest, request: ProviderRequest,
context: AttemptContext, context: AttemptContext,
) -> Result<ProviderStream, ProviderError> { ) -> Result<ProviderStream, ProviderError> {
self.policies.lock().unwrap().push(context.fast_mode());
let candidate = request.candidate(); let candidate = request.candidate();
self.policies
.lock()
.unwrap()
.push(context.fast_mode_for_account(
&ProviderAccountId::new("acct_start").unwrap(),
candidate.upstream_model().unwrap().as_str(),
));
let metadata = ProviderCallMetadata::new( let metadata = ProviderCallMetadata::new(
candidate.provider().clone(), candidate.provider().clone(),
candidate.upstream_model().unwrap().clone(), candidate.upstream_model().unwrap().clone(),
@@ -4792,7 +4798,7 @@ fn start_snapshot_with_image_policy(
account_scope(&provider, "acct_start") account_scope(&provider, "acct_start")
.as_ref() .as_ref()
.clone() .clone()
.with_fast_mode(fast_mode) .with_fast_mode_override(Some(fast_mode))
.with_image_generation(allow_image_generation), .with_image_generation(allow_image_generation),
), ),
enabled, enabled,
@@ -5526,7 +5532,7 @@ fn entry_settings_freeze_authentication_and_rebase_only_explicit_overrides() {
.execution_values() .execution_values()
.unwrap() .unwrap()
.fast_mode, .fast_mode,
FastMode::Disabled Some(FastMode::Disabled)
); );
assert_eq!( assert_eq!(
prepared prepared
@@ -5649,7 +5655,7 @@ fn child_settings_recompute_key_scope_without_inheriting_parent_defaults() {
account_scope(&provider, "acct_start") account_scope(&provider, "acct_start")
.as_ref() .as_ref()
.clone() .clone()
.with_fast_mode(FastMode::Disabled) .with_fast_mode_override(Some(FastMode::Disabled))
.with_request_profiles(profiles(name)), .with_request_profiles(profiles(name)),
), ),
true, true,
@@ -5688,7 +5694,7 @@ fn child_settings_recompute_key_scope_without_inheriting_parent_defaults() {
let configuration = RequestSettings::new(snapshots.acquire().unwrap()) let configuration = RequestSettings::new(snapshots.acquire().unwrap())
.with_execution(parent.client().policy(), previous.timeout_ms); .with_execution(parent.client().policy(), previous.timeout_ms);
let mut values = previous.clone(); let mut values = previous.clone();
values.fast_mode = FastMode::Default; values.fast_mode = Some(FastMode::Default);
values.client_limits = RateLimits::unlimited(); values.client_limits = RateLimits::unlimited();
values.timeout_ms = Some(90_000); values.timeout_ms = Some(90_000);
let mut runtime = serde_json::to_value(&values.runtime).unwrap(); let mut runtime = serde_json::to_value(&values.runtime).unwrap();
@@ -5722,7 +5728,7 @@ fn child_settings_recompute_key_scope_without_inheriting_parent_defaults() {
Some(actual.clone()) Some(actual.clone())
); );
assert_eq!(actual.client_limits.max_concurrency, expected_limit); assert_eq!(actual.client_limits.max_concurrency, expected_limit);
assert_eq!(actual.fast_mode, expected_fast); assert_eq!(actual.fast_mode, Some(expected_fast));
assert_eq!(actual.timeout_ms, expected_timeout); assert_eq!(actual.timeout_ms, expected_timeout);
let facts = serde_json::to_value(actual.runtime).unwrap(); let facts = serde_json::to_value(actual.runtime).unwrap();
assert_eq!(facts["request_profiles"]["openai"]["identity"], profile); assert_eq!(facts["request_profiles"]["openai"]["identity"], profile);
@@ -186,7 +186,10 @@ fn gateway_error_should_keep_client_visible_upstream_fields_out_of_safe_diagnost
)); ));
let gateway = GatewayError::from_provider(&error); let gateway = GatewayError::from_provider(&error);
assert_eq!(gateway.safe_message(), "Account quota is exhausted."); assert_eq!(
gateway.safe_message(),
"Upstream account quota is exhausted."
);
assert_eq!(gateway.client_message(), message); assert_eq!(gateway.client_message(), message);
assert_eq!(gateway.client_error_code(), Some("quota_exhausted")); assert_eq!(gateway.client_error_code(), Some("quota_exhausted"));
assert_eq!(gateway.client_error_type(), Some("rate_limit_error")); assert_eq!(gateway.client_error_type(), Some("rate_limit_error"));
@@ -53,7 +53,7 @@ fn policy_with_profiles(
Arc::new( Arc::new(
FrozenAccountScope::new(Arc::default(), ClientRoutingScope::all_accounts()) FrozenAccountScope::new(Arc::default(), ClientRoutingScope::all_accounts())
.with_request_profiles(overrides) .with_request_profiles(overrides)
.with_fast_mode(FastMode::Disabled), .with_fast_mode_override(Some(FastMode::Disabled)),
), ),
true, true,
RateLimits { RateLimits {
@@ -153,7 +153,7 @@ fn scope_changes_recompute_defaults_and_inherit_only_explicit_overrides() {
values.runtime = values values.runtime = values
.runtime .runtime
.with_model_mappings(BTreeMap::from([("alias".into(), "model".into())])); .with_model_mappings(BTreeMap::from([("alias".into(), "model".into())]));
values.fast_mode = FastMode::Default; values.fast_mode = Some(FastMode::Default);
values.client_limits = RateLimits::unlimited(); values.client_limits = RateLimits::unlimited();
values.timeout_ms = Some(90_000); values.timeout_ms = Some(90_000);
let changed = original.replace_execution(&values, "plugin").unwrap(); let changed = original.replace_execution(&values, "plugin").unwrap();
@@ -168,14 +168,14 @@ fn scope_changes_recompute_defaults_and_inherit_only_explicit_overrides() {
parent_values.runtime.request_profiles(), parent_values.runtime.request_profiles(),
&profiles(&[("openai", "parent"), ("xai", "second")]) &profiles(&[("openai", "parent"), ("xai", "second")])
); );
assert_eq!(parent_values.fast_mode, FastMode::Default); assert_eq!(parent_values.fast_mode, Some(FastMode::Default));
let child_settings = rebased.with_execution(&child, Some(60_000)); let child_settings = rebased.with_execution(&child, Some(60_000));
let child_values = child_settings.execution_values().unwrap(); let child_values = child_settings.execution_values().unwrap();
assert_eq!( assert_eq!(
child_values.runtime.request_profiles(), child_values.runtime.request_profiles(),
&profiles(&[("openai", "child"), ("xai", "second")]) &profiles(&[("openai", "child"), ("xai", "second")])
); );
assert_eq!(child_values.fast_mode, FastMode::Disabled); assert_eq!(child_values.fast_mode, Some(FastMode::Disabled));
assert_eq!(child_values.client_limits, child.limits()); assert_eq!(child_values.client_limits, child.limits());
assert_eq!(child_values.timeout_ms, Some(60_000)); assert_eq!(child_values.timeout_ms, Some(60_000));
assert_eq!(child_settings.snapshot().mapped_model("alias"), "model"); assert_eq!(child_settings.snapshot().mapped_model("alias"), "model");
@@ -186,6 +186,81 @@ fn scope_changes_recompute_defaults_and_inherit_only_explicit_overrides() {
); );
} }
#[test]
fn group_fast_policy_survives_settings_resolution_until_explicitly_overridden() {
use gateway_core::{
account::ProviderAccountId,
routing::{AccountGroupId, RoutingGroupSnapshot, RuntimeAccount, RuntimeAccountDirectory},
};
let group = AccountGroupId::new(format!("grp_{:032x}", 1)).unwrap();
let account = ProviderAccountId::new("acct_group_fast").unwrap();
let provider = ProviderKind::new("openai").unwrap();
let scope = Arc::new(FrozenAccountScope::new(
Arc::new(
RuntimeAccountDirectory::new(BTreeMap::from([(
account.clone(),
RuntimeAccount::new(provider.clone(), [group.clone()].into()),
)]))
.with_group_fast_modes([(group.clone(), FastMode::Disabled)].into()),
),
ClientRoutingScope::restricted(
vec![RoutingGroupSnapshot::new(group.clone(), "Standard".into())],
[group].into(),
[provider].into(),
)
.unwrap(),
));
let key = |name: &str| {
ClientPolicy::new(
ClientApiKeyId::new(name).unwrap(),
PlaintextClientApiKey::new(format!("fixture-{name}")).unwrap(),
scope.clone(),
true,
RateLimits::unlimited(),
)
};
let parent = key("parent");
let settings = RequestSettings::new(snapshot(1, "host")).with_execution(&parent, None);
assert_eq!(settings.execution_values().unwrap().fast_mode, None);
let resolved = |settings: &RequestSettings, key| {
settings
.apply_policy(key)
.account_scope()
.fast_mode_for_account(&account, "model")
};
assert_eq!(resolved(&settings, parent.clone()), FastMode::Disabled);
let unchanged = settings
.replace_execution(&settings.execution_values().unwrap(), "pass-through")
.unwrap();
assert_eq!(resolved(&unchanged, parent.clone()), FastMode::Disabled);
let mut values = settings.execution_values().unwrap();
values.fast_mode = Some(FastMode::Default);
let direct_default = settings
.replace_execution(&values, "follow-client")
.unwrap();
assert_eq!(resolved(&direct_default, parent.clone()), FastMode::Default);
values.fast_mode = Some(FastMode::Enabled);
let enabled = settings.replace_execution(&values, "force-fast").unwrap();
assert_eq!(resolved(&enabled, parent.clone()), FastMode::Enabled);
values.fast_mode = Some(FastMode::Default);
let default = enabled.replace_execution(&values, "follow-client").unwrap();
assert_eq!(resolved(&default, parent.clone()), FastMode::Default);
values.fast_mode = None;
let cleared = default.replace_execution(&values, "group-policy").unwrap();
assert_eq!(resolved(&cleared, parent.clone()), FastMode::Disabled);
assert_eq!(
cleared.inspect()["execution"]["fast_mode"]["value"],
serde_json::Value::Null
);
let child = key("child");
assert_eq!(
resolved(&default.with_execution(&child, None), child),
FastMode::Disabled
);
assert_eq!(resolved(&settings, parent), FastMode::Disabled);
}
#[test] #[test]
fn explicitly_selecting_the_host_profiles_overrides_keys_after_rebase() { fn explicitly_selecting_the_host_profiles_overrides_keys_after_rebase() {
let host = snapshot(1, "first"); let host = snapshot(1, "first");
@@ -2727,7 +2727,7 @@ fn decompression_setting_should_validate_and_remain_frozen_across_publication()
} }
#[test] #[test]
fn fast_mode_merges_only_bound_groups_without_changing_account_scope() { fn fast_mode_merges_only_enabled_bound_groups_of_the_selected_account() {
use gateway_core::account::ProviderAccountId; use gateway_core::account::ProviderAccountId;
use gateway_core::routing::AccountGroupId; use gateway_core::routing::AccountGroupId;
for (mode, other_mode, expected) in [ for (mode, other_mode, expected) in [
@@ -2758,6 +2758,8 @@ fn fast_mode_merges_only_bound_groups_without_changing_account_scope() {
let open_group_id = let open_group_id =
AccountGroupId::new("grp_00000000000000000000000000000002").unwrap(); AccountGroupId::new("grp_00000000000000000000000000000002").unwrap();
let account_id = ProviderAccountId::new("acct_fast_policy").unwrap(); let account_id = ProviderAccountId::new("acct_fast_policy").unwrap();
let first_account = ProviderAccountId::new("acct_first_group").unwrap();
let second_account = ProviderAccountId::new("acct_second_group").unwrap();
let facts = SnapshotFacts::new( let facts = SnapshotFacts::new(
revision(1), revision(1),
revision(1), revision(1),
@@ -2786,11 +2788,19 @@ fn fast_mode_merges_only_bound_groups_without_changing_account_scope() {
) )
.with_fast_mode(other_mode), .with_fast_mode(other_mode),
], ],
vec![SnapshotProviderAccountFacts::new( [&account_id, &first_account, &second_account]
account_id.clone(), .into_iter()
"alpha", .map(|id| SnapshotProviderAccountFacts::new(id.clone(), "alpha"))
)], .collect(),
vec![ vec![
SnapshotAccountGroupMemberFacts::new(
group_id.clone(),
first_account.clone(),
),
SnapshotAccountGroupMemberFacts::new(
open_group_id.clone(),
second_account.clone(),
),
SnapshotAccountGroupMemberFacts::new(group_id, account_id.clone()), SnapshotAccountGroupMemberFacts::new(group_id, account_id.clone()),
SnapshotAccountGroupMemberFacts::new(open_group_id, account_id.clone()), SnapshotAccountGroupMemberFacts::new(open_group_id, account_id.clone()),
], ],
@@ -2818,16 +2828,99 @@ fn fast_mode_merges_only_bound_groups_without_changing_account_scope() {
&Default::default(), &Default::default(),
) )
.unwrap(); .unwrap();
for (account, effective) in [
(
&account_id,
if group_enabled { expected } else { other_mode },
),
(
&first_account,
if group_enabled {
mode
} else {
FastMode::Default
},
),
(&second_account, other_mode),
] {
assert_eq!(
plan.account_scope()
.fast_mode_for_account(account, "public-model"),
if bound { effective } else { FastMode::Default },
"account={account}, mode={mode:?}, other={other_mode:?}, enabled={group_enabled}, bound={bound}"
);
}
assert_eq!( assert_eq!(
plan.fast_mode(), plan.account_scope().allows(&first_account),
if bound { expected } else { FastMode::Default }, !bound || group_enabled
"mode={mode:?}, other={other_mode:?}, enabled={group_enabled}, bound={bound}"
); );
} }
} }
} }
} }
#[test]
fn fast_mode_ignores_unbound_groups_and_groups_that_deny_the_model() {
use gateway_core::account::{AccountModelAccess, AccountModelAccessMode, ProviderAccountId};
use gateway_core::routing::AccountGroupId;
let group = |id| AccountGroupId::new(format!("grp_{id:032x}")).unwrap();
let account = ProviderAccountId::new("acct_model_fast").unwrap();
let facts = SnapshotFacts::new(
revision(1),
revision(1),
SettingsValues::new(3, "smart", BTreeMap::new(), None, None),
vec![SnapshotClientPolicyFacts::new(
ClientApiKeyId::new("key_model_fast").unwrap(),
PlaintextClientApiKey::new("fixture-model-fast").unwrap(),
vec![group(1), group(2)],
RateLimits::unlimited(),
)],
vec![
SnapshotAccountGroupFacts::new(group(1), "Fast".into(), true)
.with_fast_mode(FastMode::Enabled)
.with_model_access(
AccountModelAccess::new(
AccountModelAccessMode::Allowlist,
vec!["fast-model".into()],
)
.unwrap(),
),
SnapshotAccountGroupFacts::new(group(2), "Standard".into(), true)
.with_fast_mode(FastMode::Disabled)
.with_model_access(
AccountModelAccess::new(
AccountModelAccessMode::Denylist,
vec!["fast-model".into()],
)
.unwrap(),
),
SnapshotAccountGroupFacts::new(group(3), "Unbound".into(), true)
.with_fast_mode(FastMode::Disabled),
],
vec![SnapshotProviderAccountFacts::new(account.clone(), "alpha")],
(1..=3)
.map(|id| SnapshotAccountGroupMemberFacts::new(group(id), account.clone()))
.collect(),
);
let snapshot = block_on(
RuntimeSnapshotCompiler::new(
Arc::new(TestSnapshotStore::new(Ok(facts))),
Arc::new(TestCatalog::Unavailable),
)
.compile(),
)
.unwrap();
let scope = snapshot.client_policies().next().unwrap().account_scope();
for (model, expected) in [
("fast-model", FastMode::Enabled),
("standard-model", FastMode::Disabled),
] {
assert!(scope.allows_model(&account, model));
assert_eq!(scope.fast_mode_for_account(&account, model), expected);
}
}
#[test] #[test]
fn group_feature_permissions_merge_independently_with_deny_precedence() { fn group_feature_permissions_merge_independently_with_deny_precedence() {
use gateway_core::account::ProviderAccountId; use gateway_core::account::ProviderAccountId;
+1
View File
@@ -48,6 +48,7 @@ tracing = "0.1.44"
tracing-appender = "0.2.5" tracing-appender = "0.2.5"
tracing-subscriber = { version = "0.3.23", features = ["env-filter", "json"] } tracing-subscriber = { version = "0.3.23", features = ["env-filter", "json"] }
yaml-rust2 = "0.13.0" yaml-rust2 = "0.13.0"
uuid = { version = "1.23.3", features = ["v4"] }
[dev-dependencies] [dev-dependencies]
hyper = { version = "=1.11.1", default-features = false, features = ["server"] } hyper = { version = "=1.11.1", default-features = false, features = ["server"] }
+5
View File
@@ -117,6 +117,11 @@ pub async fn initialize_command_line(mut config: HostConfig) -> Result<HostBundl
} }
impl HostBundle { 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) { pub fn report_startup_ready(&self, service: &'static str) {
tracing::info!(target: "gateway_startup", service, "服务启动正常"); tracing::info!(target: "gateway_startup", service, "服务启动正常");
@@ -37,6 +37,7 @@ const MAX_OFFICIAL_PLUGIN_MANIFEST_SIZE: u64 = 256 * 1024;
/// gateway-admin 消费的真实进程/文件系统操作实现 /// gateway-admin 消费的真实进程/文件系统操作实现
#[derive(Clone)] #[derive(Clone)]
pub struct ProcessSystemOperations { pub struct ProcessSystemOperations {
instance_id: String,
cancellation: CancellationToken, cancellation: CancellationToken,
events: Arc<UpdateEvents>, events: Arc<UpdateEvents>,
config: Arc<SystemUpdateConfig>, config: Arc<SystemUpdateConfig>,
@@ -62,6 +63,7 @@ impl ProcessSystemOperations {
ReleaseFiles::installed(&config) ReleaseFiles::installed(&config)
})); }));
Self { Self {
instance_id: uuid::Uuid::new_v4().to_string(),
cancellation, cancellation,
events: Arc::new(UpdateEvents::default()), events: Arc::new(UpdateEvents::default()),
config: Arc::new(config), config: Arc::new(config),
@@ -350,6 +352,8 @@ impl SystemOperations for ProcessSystemOperations {
.await; .await;
Ok(SystemVersion { Ok(SystemVersion {
version: self.config.version.clone(), version: self.config.version.clone(),
instance_id: self.instance_id.clone(),
restart_supported: self.config.self_restart_enabled,
git_sha: self.config.git_sha.clone(), git_sha: self.config.git_sha.clone(),
build_time: self.config.build_time.clone(), build_time: self.config.build_time.clone(),
deployment_mode: self.config.deployment_mode.clone(), deployment_mode: self.config.deployment_mode.clone(),
+12 -5
View File
@@ -122,11 +122,12 @@ impl WorkerSupervisor {
health: &self.health, health: &self.health,
}; };
let deadline = tokio::time::Instant::now() + timeout; 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) if tokio::time::timeout_at(deadline, &mut *handle)
.await .await
.is_err() .is_err()
{ {
tracing::warn!(target: "gateway_shutdown", %worker, "后台任务收尾超时,强制终止");
handle.abort(); handle.abort();
let _ = handle.await; let _ = handle.await;
} }
@@ -459,6 +460,7 @@ async fn acquire_and_run(
let acquisition = AssertUnwindSafe(leader_lease.try_acquire(request)).catch_unwind(); let acquisition = AssertUnwindSafe(leader_lease.try_acquire(request)).catch_unwind();
tokio::pin!(acquisition); tokio::pin!(acquisition);
let acquisition = tokio::select! { let acquisition = tokio::select! {
biased;
() = cancellation.cancelled() => return ScheduledOutcome::ShuttingDown, () = cancellation.cancelled() => return ScheduledOutcome::ShuttingDown,
acquisition = &mut acquisition => acquisition, acquisition = &mut acquisition => acquisition,
}; };
@@ -490,12 +492,13 @@ async fn run_local_cycle(
.catch_unwind(); .catch_unwind();
tokio::pin!(cycle); tokio::pin!(cycle);
tokio::select! { tokio::select! {
outcome = &mut cycle => task_result(outcome), biased;
() = cancellation.cancelled() => { () = cancellation.cancelled() => {
cycle_cancel.cancel(); cycle_cancel.cancel();
let _ = cycle.await; let _ = cycle.await;
ScheduledOutcome::ShuttingDown ScheduledOutcome::ShuttingDown
} }
outcome = &mut cycle => task_result(outcome),
} }
} }
@@ -527,17 +530,21 @@ async fn run_leased_cycle(
let outcome = loop { let outcome = loop {
tokio::select! { tokio::select! {
result = &mut cycle => break task_result(result), biased;
() = cancellation.cancelled() => { () = cancellation.cancelled() => {
cycle_cancel.cancel(); cycle_cancel.cancel();
let _ = cycle.await; let _ = cycle.await;
break ScheduledOutcome::ShuttingDown; break ScheduledOutcome::ShuttingDown;
} }
result = &mut cycle => break task_result(result),
() = &mut renewal => { () = &mut renewal => {
let renewed = renew_guard( let Some(renewed) = cancellation.run_until_cancelled(renew_guard(
guard.as_mut(), guard.as_mut(),
schedule.leader_lease_renewal_interval(), schedule.leader_lease_renewal_interval(),
).await; )).await else {
// 返回循环首个取消分支,统一等待正在执行的周期收尾
continue;
};
if let Err(error) = renewed { if let Err(error) = renewed {
cycle_cancel.cancel(); cycle_cancel.cancel();
let _ = cycle.await; let _ = cycle.await;
@@ -142,6 +142,8 @@ async fn restart_should_request_process_restart_inside_docker() {
config.deployment_mode = "docker".to_owned(); config.deployment_mode = "docker".to_owned();
let shutdown = CancellationToken::new(); let shutdown = CancellationToken::new();
let service = ProcessSystemOperations::new(shutdown.clone(), config); let service = ProcessSystemOperations::new(shutdown.clone(), config);
assert!(!service.update_status().await.expect("status").need_restart);
assert!(service.version().await.expect("version").restart_supported);
service service
.restart(Arc::new(AllowingUpdatePreflight)) .restart(Arc::new(AllowingUpdatePreflight))
.await .await
@@ -152,6 +154,48 @@ async fn restart_should_request_process_restart_inside_docker() {
.expect("shutdown requested"); .expect("shutdown requested");
} }
#[tokio::test]
async fn version_should_distinguish_same_version_service_instances() {
let fixture = Fixture::new();
let config = fixture.config("http://127.0.0.1:1/repos");
let service = ProcessSystemOperations::new(CancellationToken::new(), config.clone());
let version = service.version().await.expect("version");
assert!(!version.instance_id.is_empty());
assert_eq!(
service
.clone()
.version()
.await
.expect("same instance")
.instance_id,
version.instance_id
);
let replacement = ProcessSystemOperations::new(CancellationToken::new(), config);
let restarted = replacement.version().await.expect("new instance");
assert_eq!(restarted.version, version.version);
assert_ne!(restarted.instance_id, version.instance_id);
}
#[tokio::test]
async fn version_should_report_restart_disabled_when_host_rejects_it() {
let fixture = Fixture::new();
let mut config = fixture.config("http://127.0.0.1:1/repos");
config.self_restart_enabled = false;
let shutdown = CancellationToken::new();
let service = ProcessSystemOperations::new(shutdown.clone(), config);
assert!(!service.version().await.expect("version").restart_supported);
assert_eq!(
service
.restart(Arc::new(AllowingUpdatePreflight))
.await
.expect_err("restart disabled")
.kind(),
SystemOperationErrorKind::Conflict
);
assert!(!shutdown.is_cancelled());
}
#[tokio::test(start_paused = true)] #[tokio::test(start_paused = true)]
async fn accepted_restart_excludes_system_operations_until_service_release() { async fn accepted_restart_excludes_system_operations_until_service_release() {
let fixture = Fixture::new(); let fixture = Fixture::new();
+30 -3
View File
@@ -219,6 +219,7 @@ enum LeaseStep {
enum RenewStep { enum RenewStep {
Success, Success,
Error, Error,
Pending,
} }
#[derive(Default)] #[derive(Default)]
@@ -268,11 +269,12 @@ impl WorkerLeaderLeaseGuard for FakeLeaseGuard {
fn renew(&mut self) -> BoxFuture<'_, Result<(), WorkerLeaseError>> { fn renew(&mut self) -> BoxFuture<'_, Result<(), WorkerLeaseError>> {
Box::pin(async move { Box::pin(async move {
lock_unpoisoned(&self.renewals).push(self.worker.clone()); 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) .get_mut(&self.worker)
.and_then(VecDeque::pop_front) .and_then(VecDeque::pop_front)
.unwrap_or(RenewStep::Success) .unwrap_or(RenewStep::Success);
{ match step {
RenewStep::Pending => pending().await,
RenewStep::Success => Ok(()), RenewStep::Success => Ok(()),
RenewStep::Error => Err(WorkerLeaseError::safe("expected renewal failure")), 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; 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)] #[tokio::test(start_paused = true)]
async fn renewal_failure_cancels_old_cycle_before_another_leader_cycle_starts() { async fn renewal_failure_cancels_old_cycle_before_another_leader_cycle_starts() {
let task = ConcurrentCycleTask { let task = ConcurrentCycleTask {
@@ -248,21 +248,21 @@ impl Execution {
request_body_limit, request_body_limit,
) )
.map_err(|error| fault_error(error, UpstreamSendState::NotSent))?; .map_err(|error| fault_error(error, UpstreamSendState::NotSent))?;
let upstream_model = invocation.metadata.upstream_model().ok_or_else(invalid)?;
let request = UpstreamAdapterRequest { let request = UpstreamAdapterRequest {
adapter_id: declaration.id.clone(), adapter_id: declaration.id.clone(),
provider: declaration.provider, provider: declaration.provider,
upstream_model: invocation upstream_model: upstream_model.as_str().to_owned(),
.metadata
.upstream_model()
.ok_or_else(invalid)?
.as_str()
.to_owned(),
client_key_id: invocation.context.client_api_key_ref().as_str().to_owned(), client_key_id: invocation.context.client_api_key_ref().as_str().to_owned(),
account_id: invocation.account.account_id().as_str().to_owned(), account_id: invocation.account.account_id().as_str().to_owned(),
credential_revision: invocation.account.credential_revision().get(), credential_revision: invocation.account.credential_revision().get(),
protocol: invocation.operation.protocol().to_owned(), protocol: invocation.operation.protocol().to_owned(),
client_transport: invocation.context.client_transport().as_str().to_owned(), client_transport: invocation.context.client_transport().as_str().to_owned(),
fast_mode: invocation.context.fast_mode().as_str().to_owned(), fast_mode: invocation
.context
.fast_mode_for_account(invocation.account.account_id(), upstream_model.as_str())
.as_str()
.to_owned(),
request_elapsed_ms: u64::try_from( request_elapsed_ms: u64::try_from(
invocation.context.timing_started_at().elapsed().as_millis(), invocation.context.timing_started_at().elapsed().as_millis(),
) )
@@ -7,13 +7,16 @@ use serde_json::{Value, json};
#[tokio::test] #[tokio::test]
async fn middleware_preserves_fast_modes_and_sources() { async fn middleware_preserves_fast_modes_and_sources() {
for (mode, expected) in [ for (mode, expected) in [
(FastMode::Default, FastMode::Default), (None, None),
(FastMode::Enabled, FastMode::Enabled), (None, Some(FastMode::Default)),
(FastMode::Disabled, FastMode::Disabled), (Some(FastMode::Default), Some(FastMode::Default)),
(FastMode::Enabled, FastMode::Disabled), (Some(FastMode::Enabled), Some(FastMode::Enabled)),
(FastMode::Ultrafast, FastMode::Ultrafast), (Some(FastMode::Disabled), Some(FastMode::Disabled)),
(FastMode::Enabled, FastMode::Ultrafast), (Some(FastMode::Enabled), Some(FastMode::Disabled)),
(FastMode::Disabled, FastMode::Default), (Some(FastMode::Ultrafast), Some(FastMode::Ultrafast)),
(Some(FastMode::Enabled), Some(FastMode::Ultrafast)),
(Some(FastMode::Disabled), Some(FastMode::Default)),
(Some(FastMode::Enabled), None),
] { ] {
let snapshot = gateway_core::routing::RuntimeSnapshot::new( let snapshot = gateway_core::routing::RuntimeSnapshot::new(
ConfigRevision::new(1).unwrap(), ConfigRevision::new(1).unwrap(),
@@ -43,8 +46,7 @@ async fn middleware_preserves_fast_modes_and_sources() {
let settings = settings.replace_execution(&seed, "seed").unwrap(); let settings = settings.replace_execution(&seed, "seed").unwrap();
let wire = serde_json::to_value(&seed).unwrap(); let wire = serde_json::to_value(&seed).unwrap();
let mut updated = wire.clone(); let mut updated = wire.clone();
updated["fast_mode"] = json!(expected.as_str()); updated["fast_mode"] = json!(expected);
updated["timeout_ms"] = json!(90_000);
let contribution = crate::support::contribution( let contribution = crate::support::contribution(
Capability::Middleware, Capability::Middleware,
vec![Stage::Request], vec![Stage::Request],
@@ -61,8 +63,8 @@ async fn middleware_preserves_fast_modes_and_sources() {
id: "fast-settings", id: "fast-settings",
configuration: json!({ configuration: json!({
"mode":"settings", "expected_settings":wire, "settings":updated, "mode":"settings", "expected_settings":wire, "settings":updated,
"expected_fast_source": if mode == FastMode::Default { Value::Null } else { "expected_fast_source": if mode.is_none() { Value::Null } else {
json!({"instance_id":"seed", "order":1, "value":mode.as_str()}) json!({"instance_id":"seed", "order":1, "value":mode})
}, },
}), }),
bindings: vec![binding( bindings: vec![binding(
@@ -102,11 +104,11 @@ async fn middleware_preserves_fast_modes_and_sources() {
assert_eq!(settings.execution_values().unwrap().fast_mode, expected); assert_eq!(settings.execution_values().unwrap().fast_mode, expected);
assert_eq!( assert_eq!(
settings.execution_values().unwrap().timeout_ms, settings.execution_values().unwrap().timeout_ms,
Some(90_000) Some(60_000)
); );
let sources = settings.inspect(); let sources = settings.inspect();
let fast_source = &sources["execution"]["fast_mode"]; let fast_source = &sources["execution"]["fast_mode"];
if mode == FastMode::Default && expected == FastMode::Default { if mode.is_none() && expected.is_none() {
assert!(fast_source.is_null()); assert!(fast_source.is_null());
} else { } else {
assert_eq!( assert_eq!(
@@ -117,12 +119,9 @@ async fn middleware_preserves_fast_modes_and_sources() {
"fast-settings" "fast-settings"
} }
); );
assert_eq!(fast_source["value"], expected.as_str()); assert_eq!(fast_source["value"], json!(expected));
} }
assert_eq!( assert!(sources["execution"]["timeout_ms"].is_null());
sources["execution"]["timeout_ms"]["instance_id"],
"fast-settings"
);
next.run(request).await next.run(request).await
}) })
}), }),
@@ -1277,7 +1277,7 @@ async fn real_request_plugins_rewrite_settings_in_onion_order() {
let baseline = ExecutionSettings { let baseline = ExecutionSettings {
runtime: SettingsValues::new(3, "smart", BTreeMap::new(), None, None) runtime: SettingsValues::new(3, "smart", BTreeMap::new(), None, None)
.with_request_profiles(profiles("key-default")), .with_request_profiles(profiles("key-default")),
fast_mode: FastMode::Disabled, fast_mode: Some(FastMode::Disabled),
client_limits: RateLimits { client_limits: RateLimits {
max_concurrency: 2, max_concurrency: 2,
requests_per_minute: 10, requests_per_minute: 10,
@@ -1314,7 +1314,7 @@ async fn real_request_plugins_rewrite_settings_in_onion_order() {
gateway_core::routing::ClientRoutingScope::all_accounts(), gateway_core::routing::ClientRoutingScope::all_accounts(),
) )
.with_request_profiles(profiles("key-default")) .with_request_profiles(profiles("key-default"))
.with_fast_mode(baseline.fast_mode), .with_fast_mode_override(baseline.fast_mode),
), ),
true, true,
baseline.client_limits, baseline.client_limits,
@@ -179,7 +179,6 @@ fn context_with_body_limit(
ClientApiKeyId::new(key).unwrap(), ClientApiKeyId::new(key).unwrap(),
) )
.with_upstream_adapters(runtime.execution_registry().upstream_adapters(generation)) .with_upstream_adapters(runtime.execution_registry().upstream_adapters(generation))
.with_fast_mode(mode)
.with_request_body_limit(bytes), .with_request_body_limit(bytes),
NonZeroU32::new(1).unwrap(), NonZeroU32::new(1).unwrap(),
SystemTime::now() + Duration::from_secs(5), SystemTime::now() + Duration::from_secs(5),
@@ -187,7 +186,13 @@ fn context_with_body_limit(
gateway_core::account::RotationStrategy::RoundRobin, gateway_core::account::RotationStrategy::RoundRobin,
std::num::NonZeroU32::new(1).unwrap(), std::num::NonZeroU32::new(1).unwrap(),
), ),
AccountAttemptContext::new(Default::default(), None, None), AccountAttemptContext::new(Default::default(), None, None).with_account_scope(Arc::new(
gateway_core::routing::FrozenAccountScope::new(
Arc::default(),
gateway_core::routing::ClientRoutingScope::all_accounts(),
)
.with_fast_mode_override(Some(mode)),
)),
None, None,
CancellationToken::new(), CancellationToken::new(),
) )
@@ -588,7 +588,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
); );
if let Some(expected) = configuration.get("expected_fast_source") { if let Some(expected) = configuration.get("expected_fast_source") {
let sources = &call.request.head.settings_sources["execution"]; let sources = &call.request.head.settings_sources["execution"];
assert_eq!(sources["input"]["fast_mode"], "default"); assert!(sources["input"]["fast_mode"].is_null());
assert_eq!(&sources["fast_mode"], expected); assert_eq!(&sources["fast_mode"], expected);
} }
if let Some(settings) = configuration.get("settings") { if let Some(settings) = configuration.get("settings") {
@@ -489,7 +489,7 @@ let plugin = PluginBuilder::from_json(manifest_json)?
#### 模型请求与 attempt #### 模型请求与 attempt
`RequestCall.request.head` 包含完整 Client Key 与分组归属。request 中间件改写正文后,OpenAI 在进入 attempt 前应用宿主 Fast 策略; `RequestCall.request.head` 包含完整 Client Key 与分组归属。request 中间件改写正文后,OpenAI 按选中账号和上游模型解析宿主 Fast 策略,在进入 attempt 前应用;
attempt 中间件在此基线上继续改写,终端不再应用 Fast 策略。 attempt 中间件在此基线上继续改写,终端不再应用 Fast 策略。
request 与 attempt 阶段通过 `append_header` 添加的请求头会进入上游请求,不适合存放插件内部标记或仅供下游读取的信息。 request 与 attempt 阶段通过 `append_header` 添加的请求头会进入上游请求,不适合存放插件内部标记或仅供下游读取的信息。
OpenAI 与 xAI 的上游 headers 先由账号和画像生成,插件同名字段覆盖基线,同名多值按插件顺序保留;不存在按认证、Cookie 或会话名称划分的保护列表。 OpenAI 与 xAI 的上游 headers 先由账号和画像生成,插件同名字段覆盖基线,同名多值按插件顺序保留;不存在按认证、Cookie 或会话名称划分的保护列表。
@@ -498,7 +498,8 @@ CPR 中间件添加的 HTTP 扩展头在发往 Antigravity 时经过该 Provider
实际账号租约、凭据版本与计费归属仍记录真实选中事实,不随插件修改 header 名称而伪造 实际账号租约、凭据版本与计费归属仍记录真实选中事实,不随插件修改 header 名称而伪造
request 阶段 `request.head.settings` 是本次调用的有效设置对象,包含 `runtime`、`fast_mode`、`client_limits` 和 `timeout_ms`。 request 阶段 `request.head.settings` 是本次调用的有效设置对象,包含 `runtime`、`fast_mode`、`client_limits` 和 `timeout_ms`。
`fast_mode` 使用 `default`、`enabled`、`ultrafast`、`disabled` 四个值,具体档位语义见[账号分组](../../../../../docs/api.md#6-账号分组)。 `fast_mode` 为 `null` 时按选中账号的有效分组解析;显式 `default` 表示跟随客户端,`enabled`、`ultrafast`、`disabled` 覆盖分组策略,具体档位语义见[账号分组](../../../../../docs/api.md#6-账号分组)。
保留该字段不建立新覆盖,改写为 `null` 恢复按分组解析;其他改写形成当前 Key 的显式覆盖,优先于分组策略。attempt 中间件仍可直接改写正文档位
`runtime` 使用宿主快照的设置字段,画像已合并 Client Key 设置;可以修改映射、画像、调度、位置及计价等执行参数。 `runtime` 使用宿主快照的设置字段,画像已合并 Client Key 设置;可以修改映射、画像、调度、位置及计价等执行参数。
SDK 仅在对象改变时提交完整替换,`false`、`0`、空映射和合同允许的 `null` 不表示跳过;不做隐式深合并。 SDK 仅在对象改变时提交完整替换,`false`、`0`、空映射和合同允许的 `null` 不表示跳过;不做隐式深合并。
线协议省略 `next.settings` 才表示保留;显式 `null` 仍按完整替换校验,因不符合设置对象合同而拒绝。 线协议省略 `next.settings` 才表示保留;显式 `null` 仍按完整替换校验,因不符合设置对象合同而拒绝。
@@ -41,7 +41,7 @@ Provider、业务协议和传输名称不能写入宿主兼容清单的 capabili
`TypedCall<UpstreamAdapterRequest>` 包含只读的 Key、账号、凭据版本、模型、协议、Header 和宿主续接投影; `TypedCall<UpstreamAdapterRequest>` 包含只读的 Key、账号、凭据版本、模型、协议、Header 和宿主续接投影;
原始请求正文位于 `call.payload`,原始账号凭据不进入插件输入。宿主首次消费冷流才调用插件 原始请求正文位于 `call.payload`,原始账号凭据不进入插件输入。宿主首次消费冷流才调用插件
`fast_mode` 是本次模型执行的有效设置,取值为 `default`、`enabled`、`ultrafast` 或 `disabled`。OpenAI 在 attempt 中间件之前将 Fast 设置应用到正文基线, `fast_mode` 是按选中账号及上游模型解析后的有效策略,取值为 `default`、`enabled`、`ultrafast` 或 `disabled`,请求设置的显式覆盖优先于分组策略。OpenAI 在 attempt 中间件之前将 Fast 设置应用到正文基线,
适配器收到经过 attempt 中间件处理的正文;attempt 中间件显式改写档位后,宿主不会在发送前再次应用 Fast 策略。 适配器收到经过 attempt 中间件处理的正文;attempt 中间件显式改写档位后,宿主不会在发送前再次应用 Fast 策略。
其他请求设置与 Key 作用域的覆盖规则见[模型请求与 attempt](capabilities.md#模型请求与-attempt) 其他请求设置与 Key 作用域的覆盖规则见[模型请求与 attempt](capabilities.md#模型请求与-attempt)
@@ -3,7 +3,10 @@
use crate::chat_completions::{ use crate::chat_completions::{
ChatError, custom_tool_schema, ChatError, custom_tool_schema,
error::{invalid, unsupported}, error::{invalid, unsupported},
request::string, request::{
block_text, empty_history_content, empty_history_part, function_parameters,
reasoning_effort, response_format, stop_sequences, string,
},
validate_request, validate_request,
}; };
use serde_json::{Map, Value, json}; use serde_json::{Map, Value, json};
@@ -13,7 +16,7 @@ pub fn convert_request(chat: &Map<String, Value>) -> Result<Map<String, Value>,
validate_request(chat)?; validate_request(chat)?;
let mut system = Vec::new(); let mut system = Vec::new();
if let Some(instructions) = chat.get("instructions").filter(|v| !v.is_null()) { if let Some(instructions) = chat.get("instructions").filter(|v| !v.is_null()) {
system.extend(parts(instructions, "instructions", true)?); system.extend(parts(instructions, "instructions", "system")?);
} }
let mut contents = Vec::new(); let mut contents = Vec::new();
let mut calls = BTreeMap::new(); let mut calls = BTreeMap::new();
@@ -30,7 +33,7 @@ pub fn convert_request(chat: &Map<String, Value>) -> Result<Map<String, Value>,
system.extend(parts( system.extend(parts(
&message["content"], &message["content"],
&format!("{path}.content"), &format!("{path}.content"),
true, role,
)?); )?);
continue; continue;
} }
@@ -48,7 +51,7 @@ pub fn convert_request(chat: &Map<String, Value>) -> Result<Map<String, Value>,
} }
let mut text = Vec::new(); let mut text = Vec::new();
let mut media = Vec::new(); let mut media = Vec::new();
for part in parts(&message["content"], &format!("{path}.content"), false)? { for part in parts(&message["content"], &format!("{path}.content"), role)? {
if let Some(value) = part.get("text").and_then(Value::as_str) { if let Some(value) = part.get("text").and_then(Value::as_str) {
text.push(value.to_owned()); text.push(value.to_owned());
} else { } else {
@@ -61,12 +64,12 @@ pub fn convert_request(chat: &Map<String, Value>) -> Result<Map<String, Value>,
} }
vec![response] vec![response]
} else { } else {
let mut content = if message["content"].is_null() { let mut content = parts(&message["content"], &format!("{path}.content"), role)?;
Vec::new() if let Some(refusal) = message
} else { .get("refusal")
parts(&message["content"], &format!("{path}.content"), false)? .and_then(Value::as_str)
}; .filter(|v| !v.is_empty())
if let Some(refusal) = message.get("refusal").and_then(Value::as_str) { {
content.push(json!({"text":refusal})); content.push(json!({"text":refusal}));
} }
for (call_index, call) in message for (call_index, call) in message
@@ -105,6 +108,9 @@ pub fn convert_request(chat: &Map<String, Value>) -> Result<Map<String, Value>,
} }
content content
}; };
if role == "assistant" && content.is_empty() {
continue;
}
append( append(
&mut contents, &mut contents,
if role == "assistant" { "model" } else { "user" }, if role == "assistant" { "model" } else { "user" },
@@ -134,11 +140,10 @@ pub fn convert_request(chat: &Map<String, Value>) -> Result<Map<String, Value>,
generation.insert(to.into(), value.clone()); generation.insert(to.into(), value.clone());
} }
} }
if let Some(effort) = chat if let Some(stops) = stop_sequences(chat)? {
.get("reasoning_effort") generation.insert("stopSequences".into(), stops);
.or_else(|| chat.get("reasoning").and_then(|v| v.get("effort"))) }
.filter(|v| !v.is_null()) if let Some(effort) = reasoning_effort(chat) {
{
let budget: i64 = match effort.as_str() { let budget: i64 = match effort.as_str() {
Some("none") => 0, Some("none") => 0,
Some("minimal" | "low") => 1024, Some("minimal" | "low") => 1024,
@@ -158,11 +163,7 @@ pub fn convert_request(chat: &Map<String, Value>) -> Result<Map<String, Value>,
}, },
); );
} }
if let Some(format) = chat if let Some(format) = response_format(chat) {
.get("response_format")
.or_else(|| chat.get("text").and_then(|v| v.get("format")))
.filter(|v| !v.is_null())
{
match format["type"].as_str() { match format["type"].as_str() {
Some("json_schema") => { Some("json_schema") => {
generation.insert("responseMimeType".into(), json!("application/json")); generation.insert("responseMimeType".into(), json!("application/json"));
@@ -205,7 +206,11 @@ fn append(contents: &mut Vec<Value>, role: &str, parts: Vec<Value>) {
} }
} }
fn parts(value: &Value, path: &str, system: bool) -> Result<Vec<Value>, ChatError> { fn parts(value: &Value, path: &str, role: &str) -> Result<Vec<Value>, ChatError> {
if empty_history_content(role, value) {
return Ok(Vec::new());
}
let system = matches!(role, "system" | "developer");
if let Some(text) = value.as_str() { if let Some(text) = value.as_str() {
return Ok(vec![json!({"text":text})]); return Ok(vec![json!({"text":text})]);
} }
@@ -214,12 +219,13 @@ fn parts(value: &Value, path: &str, system: bool) -> Result<Vec<Value>, ChatErro
.ok_or_else(|| invalid(path))? .ok_or_else(|| invalid(path))?
.iter() .iter()
.enumerate() .enumerate()
.filter(|(_, part)| !empty_history_part(role, part))
.map(|(index, part)| { .map(|(index, part)| {
let path = format!("{path}[{index}]"); let path = format!("{path}[{index}]");
let kind = string(part.get("type"), &format!("{path}.type"), false)?; let kind = string(part.get("type"), &format!("{path}.type"), false)?;
match kind { match kind {
"text" | "input_text" | "output_text" => { "text" | "input_text" | "output_text" => {
Ok(json!({"text":string(part.get("text"), &format!("{path}.text"), true)?})) Ok(json!({"text":block_text(part.get("text"), &path)?}))
} }
"refusal" if !system => Ok( "refusal" if !system => Ok(
json!({"text":string(part.get("refusal"), &format!("{path}.refusal"), true)?}), json!({"text":string(part.get("refusal"), &format!("{path}.refusal"), true)?}),
@@ -314,16 +320,10 @@ fn tools(chat: &Map<String, Value>, result: &mut Map<String, Value>) -> Result<(
let parameters = if kind == "custom" { let parameters = if kind == "custom" {
custom_tool_schema(definition.get("format"), &format!("{path}.custom.format"))? custom_tool_schema(definition.get("format"), &format!("{path}.custom.format"))?
} else { } else {
definition function_parameters(definition, &path)?
.get("parameters")
.cloned()
.unwrap_or_else(|| json!({"type":"object","properties":{}}))
}; };
if !parameters.is_object() {
return Err(invalid(&format!("{path}.function.parameters")));
}
let mut declaration = json!({"name":name,"parametersJsonSchema":parameters}); let mut declaration = json!({"name":name,"parametersJsonSchema":parameters});
if let Some(value) = definition.get("description") { if let Some(value) = definition.get("description").filter(|v| !v.is_null()) {
declaration["description"] = value.clone(); declaration["description"] = value.clone();
} }
declarations.push(declaration); declarations.push(declaration);
@@ -4,7 +4,10 @@ use crate::anthropic::MessagesModelCapabilities;
use crate::chat_completions::{ use crate::chat_completions::{
ChatError, custom_tool_schema, ChatError, custom_tool_schema,
error::{invalid, unsupported}, error::{invalid, unsupported},
request::string, request::{
block_text, empty_history_content, empty_history_part, function_parameters,
reasoning_effort, response_format, stop_sequences, string,
},
validate_request, validate_request,
}; };
use serde_json::{Map, Value, json}; use serde_json::{Map, Value, json};
@@ -37,6 +40,9 @@ pub fn convert_request(
result.insert(field.into(), value.clone()); result.insert(field.into(), value.clone());
} }
} }
if let Some(stops) = stop_sequences(chat)? {
result.insert("stop_sequences".into(), stops);
}
if let Some(tier) = chat.get("service_tier").and_then(Value::as_str) { if let Some(tier) = chat.get("service_tier").and_then(Value::as_str) {
match tier { match tier {
"priority" => { "priority" => {
@@ -53,7 +59,7 @@ pub fn convert_request(
} }
let mut system = Vec::new(); let mut system = Vec::new();
if let Some(instructions) = chat.get("instructions").filter(|v| !v.is_null()) { if let Some(instructions) = chat.get("instructions").filter(|v| !v.is_null()) {
system.extend(content(instructions, "instructions", true)?); system.extend(content(instructions, "instructions", "system")?);
} }
let mut messages = Vec::new(); let mut messages = Vec::new();
let mut calls = BTreeMap::new(); let mut calls = BTreeMap::new();
@@ -70,7 +76,7 @@ pub fn convert_request(
system.extend(content( system.extend(content(
&message["content"], &message["content"],
&format!("{path}.content"), &format!("{path}.content"),
true, role,
)?); )?);
continue; continue;
} }
@@ -84,15 +90,15 @@ pub fn convert_request(
return Err(invalid(&format!("{path}.tool_call_id"))); return Err(invalid(&format!("{path}.tool_call_id")));
} }
vec![ vec![
json!({"type":"tool_result","tool_use_id":id,"content":content(&message["content"], &format!("{path}.content"), false)?}), json!({"type":"tool_result","tool_use_id":id,"content":content(&message["content"], &format!("{path}.content"), role)?}),
] ]
} else { } else {
let mut blocks = if message["content"].is_null() { let mut blocks = content(&message["content"], &format!("{path}.content"), role)?;
Vec::new() if let Some(refusal) = message
} else { .get("refusal")
content(&message["content"], &format!("{path}.content"), false)? .and_then(Value::as_str)
}; .filter(|v| !v.is_empty())
if let Some(refusal) = message.get("refusal").and_then(Value::as_str) { {
blocks.push(json!({"type":"text","text":refusal})); blocks.push(json!({"type":"text","text":refusal}));
} }
for (call_index, call) in message for (call_index, call) in message
@@ -130,6 +136,9 @@ pub fn convert_request(
} }
blocks blocks
}; };
if role == "assistant" && blocks.is_empty() {
continue;
}
append_message( append_message(
&mut messages, &mut messages,
if role == "assistant" { if role == "assistant" {
@@ -148,10 +157,7 @@ pub fn convert_request(
} }
result.insert("messages".into(), messages.into()); result.insert("messages".into(), messages.into());
tools(chat, &mut result, capabilities)?; tools(chat, &mut result, capabilities)?;
let format = chat if let Some(format) = response_format(chat) {
.get("response_format")
.or_else(|| chat.get("text").and_then(|v| v.get("format")));
if let Some(format) = format.filter(|v| !v.is_null()) {
match format["type"].as_str() { match format["type"].as_str() {
Some("json_schema") => { Some("json_schema") => {
let schema = format let schema = format
@@ -190,7 +196,11 @@ fn append_message(messages: &mut Vec<Value>, role: &str, blocks: Vec<Value>) {
} }
} }
fn content(value: &Value, path: &str, system: bool) -> Result<Vec<Value>, ChatError> { fn content(value: &Value, path: &str, role: &str) -> Result<Vec<Value>, ChatError> {
if empty_history_content(role, value) {
return Ok(Vec::new());
}
let system = matches!(role, "system" | "developer");
if let Some(text) = value.as_str() { if let Some(text) = value.as_str() {
return Ok(vec![json!({"type":"text","text":text})]); return Ok(vec![json!({"type":"text","text":text})]);
} }
@@ -200,12 +210,13 @@ fn content(value: &Value, path: &str, system: bool) -> Result<Vec<Value>, ChatEr
.ok_or_else(|| invalid(path))? .ok_or_else(|| invalid(path))?
.iter() .iter()
.enumerate() .enumerate()
.filter(|(_, part)| !empty_history_part(role, part))
{ {
let path = format!("{path}[{index}]"); let path = format!("{path}[{index}]");
let kind = string(part.get("type"), &format!("{path}.type"), false)?; let kind = string(part.get("type"), &format!("{path}.type"), false)?;
let block = match kind { let block = match kind {
"text" | "input_text" | "output_text" => { "text" | "input_text" | "output_text" => {
json!({"type":"text","text":string(part.get("text"), &format!("{path}.text"), true)?}) json!({"type":"text","text":block_text(part.get("text"), &path)?})
} }
"refusal" if !system => { "refusal" if !system => {
json!({"type":"text","text":string(part.get("refusal"), &format!("{path}.refusal"), true)?}) json!({"type":"text","text":string(part.get("refusal"), &format!("{path}.refusal"), true)?})
@@ -295,17 +306,11 @@ fn tools(
let schema = if kind == "custom" { let schema = if kind == "custom" {
custom_tool_schema(declaration.get("format"), &format!("{path}.custom.format"))? custom_tool_schema(declaration.get("format"), &format!("{path}.custom.format"))?
} else { } else {
declaration function_parameters(declaration, &path)?
.get("parameters")
.cloned()
.unwrap_or_else(|| json!({"type":"object","properties":{}}))
}; };
if !schema.is_object() {
return Err(invalid(&format!("{path}.function.parameters")));
}
let mut target = json!({"name":name,"input_schema":schema}); let mut target = json!({"name":name,"input_schema":schema});
for field in ["description", "strict", "cache_control"] { for field in ["description", "strict", "cache_control"] {
if let Some(value) = declaration.get(field) { if let Some(value) = declaration.get(field).filter(|v| !v.is_null()) {
target[field] = value.clone(); target[field] = value.clone();
} }
} }
@@ -393,11 +398,7 @@ fn reasoning(
capabilities: &MessagesModelCapabilities, capabilities: &MessagesModelCapabilities,
max_tokens: u64, max_tokens: u64,
) -> Result<(), ChatError> { ) -> Result<(), ChatError> {
let Some(effort) = chat let Some(effort) = reasoning_effort(chat) else {
.get("reasoning_effort")
.or_else(|| chat.get("reasoning").and_then(|v| v.get("effort")))
.filter(|v| !v.is_null())
else {
return Ok(()); return Ok(());
}; };
let effort = effort.as_str().ok_or_else(|| invalid("reasoning_effort"))?; let effort = effort.as_str().ok_or_else(|| invalid("reasoning_effort"))?;
@@ -30,11 +30,7 @@ pub fn validate_request(body: &Map<String, Value>) -> Result<(), ChatError> {
field: "messages".into(), field: "messages".into(),
expected: "an array", expected: "an array",
})?; })?;
if messages.is_empty() { let mut has_message = false;
return Err(ChatError::EmptyField {
field: "messages".into(),
});
}
for (index, message) in messages.iter().enumerate() { for (index, message) in messages.iter().enumerate() {
let path = format!("messages[{index}]"); let path = format!("messages[{index}]");
let message = message.as_object().ok_or_else(|| invalid(&path))?; let message = message.as_object().ok_or_else(|| invalid(&path))?;
@@ -42,43 +38,53 @@ pub fn validate_request(body: &Map<String, Value>) -> Result<(), ChatError> {
if !matches!(role, "system" | "developer" | "user" | "assistant" | "tool") { if !matches!(role, "system" | "developer" | "user" | "assistant" | "tool") {
return Err(unsupported(&format!("{path}.role"))); return Err(unsupported(&format!("{path}.role")));
} }
for (field, allowed) in [ let calls = match message.get("tool_calls") {
("tool_calls", "assistant"), None | Some(Value::Null) => &[][..],
("refusal", "assistant"), Some(Value::Array(calls)) => calls.as_slice(),
("tool_call_id", "tool"), _ => return Err(invalid(&format!("{path}.tool_calls"))),
] { };
if role != allowed && message.get(field).is_some_and(|v| !v.is_null()) { if role != "assistant" && !calls.is_empty() {
return Err(invalid(&format!("{path}.{field}"))); return Err(invalid(&format!("{path}.tool_calls")));
}
let refusal = message.get("refusal").filter(|v| !v.is_null() && *v != "");
if let Some(value) = refusal {
if role != "assistant" {
return Err(invalid(&format!("{path}.refusal")));
} }
string(Some(value), &format!("{path}.refusal"), true)?;
} }
for field in ["function_call", "audio"] { for field in ["function_call", "audio"] {
if message.get(field).is_some_and(|v| !v.is_null()) { if message.get(field).is_some_and(|v| !v.is_null()) {
return Err(unsupported(&format!("{path}.{field}"))); return Err(unsupported(&format!("{path}.{field}")));
} }
} }
for field in ["name", "refusal"] {
if let Some(value) = message.get(field).filter(|v| !v.is_null()) {
string(Some(value), &format!("{path}.{field}"), true)?;
}
}
if role == "tool" { if role == "tool" {
string( // Responses 的独立工具输出通过名称标识,不依赖前序调用
message.get("tool_call_id"), let field = if message.get("tool_call_id").is_none_or(Value::is_null) {
&format!("{path}.tool_call_id"), "name"
false, } 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 != "")
{
return Err(invalid(&format!("{path}.tool_call_id")));
} }
if let Some(content) = message.get("content").filter(|v| !v.is_null()) { let content = message.get("content").unwrap_or(&Value::Null);
if !empty_history_content(role, content) {
if !content.is_string() && !content.is_array() { if !content.is_string() && !content.is_array() {
return Err(invalid(&format!("{path}.content"))); return Err(invalid(&format!("{path}.content")));
} }
has_message = true;
if let Some(parts) = content.as_array() { if let Some(parts) = content.as_array() {
for (part_index, part) in parts.iter().enumerate() { for (part_index, part) in parts.iter().enumerate() {
let part_path = format!("{path}.content[{part_index}]"); let part_path = format!("{path}.content[{part_index}]");
let kind = string(part.get("type"), &format!("{part_path}.type"), false)?; let kind = string(part.get("type"), &format!("{part_path}.type"), false)?;
match kind { match kind {
"text" | "input_text" | "output_text" => { "text" | "input_text" | "output_text" => {
string(part.get("text"), &format!("{part_path}.text"), true)?; block_text(part.get("text"), &part_path)?;
} }
"image_url" | "file" | "input_audio" | "input_image" | "input_file" "image_url" | "file" | "input_audio" | "input_image" | "input_file"
if matches!(role, "user" | "tool") => {} if matches!(role, "user" | "tool") => {}
@@ -89,45 +95,37 @@ pub fn validate_request(body: &Map<String, Value>) -> Result<(), ChatError> {
} }
} }
} }
} else if role != "assistant"
|| (!message
.get("tool_calls")
.is_some_and(|v| v.as_array().is_some_and(|v| !v.is_empty()))
&& !message.get("refusal").is_some_and(Value::is_string))
{
return Err(invalid(&format!("{path}.content")));
} }
if let Some(calls) = message.get("tool_calls").filter(|v| !v.is_null()) { has_message |= refusal.is_some() || !calls.is_empty();
for (call_index, call) in calls for (call_index, call) in calls.iter().enumerate() {
.as_array() let call_path = format!("{path}.tool_calls[{call_index}]");
.ok_or_else(|| invalid(&format!("{path}.tool_calls")))? string(call.get("id"), &format!("{call_path}.id"), false)?;
.iter() let kind = string(call.get("type"), &format!("{call_path}.type"), false)?;
.enumerate() if !matches!(kind, "function" | "custom") {
{ return Err(unsupported(&format!("{call_path}.type")));
let call_path = format!("{path}.tool_calls[{call_index}]");
string(call.get("id"), &format!("{call_path}.id"), false)?;
let kind = string(call.get("type"), &format!("{call_path}.type"), false)?;
if !matches!(kind, "function" | "custom") {
return Err(unsupported(&format!("{call_path}.type")));
}
string(
call.get(kind).and_then(|v| v.get("name")),
&format!("{call_path}.{kind}.name"),
false,
)?;
let data_field = if kind == "function" {
"arguments"
} else {
"input"
};
string(
call.get(kind).and_then(|v| v.get(data_field)),
&format!("{call_path}.{kind}.{data_field}"),
true,
)?;
} }
string(
call.get(kind).and_then(|v| v.get("name")),
&format!("{call_path}.{kind}.name"),
false,
)?;
let data_field = if kind == "function" {
"arguments"
} else {
"input"
};
string(
call.get(kind).and_then(|v| v.get(data_field)),
&format!("{call_path}.{kind}.{data_field}"),
true,
)?;
} }
} }
if !has_message {
return Err(ChatError::EmptyField {
field: "messages".into(),
});
}
for (field, value) in body.iter().filter(|(_, v)| !v.is_null()) { for (field, value) in body.iter().filter(|(_, v)| !v.is_null()) {
let valid = match field.as_str() { let valid = match field.as_str() {
"n" => value.as_u64() == Some(1), "n" => value.as_u64() == Some(1),
@@ -150,7 +148,7 @@ pub fn validate_request(body: &Map<String, Value>) -> Result<(), ChatError> {
} }
} }
if let Some(options) = body.get("stream_options").filter(|v| !v.is_null()) { if let Some(options) = body.get("stream_options").filter(|v| !v.is_null()) {
if body.get("stream") != Some(&Value::Bool(true)) || !options.is_object() { if !options.is_object() {
return Err(invalid("stream_options")); return Err(invalid("stream_options"));
} }
for field in ["include_usage", "include_obfuscation"] { for field in ["include_usage", "include_obfuscation"] {
@@ -161,13 +159,99 @@ pub fn validate_request(body: &Map<String, Value>) -> Result<(), ChatError> {
return Err(invalid(&format!("stream_options.{field}"))); return Err(invalid(&format!("stream_options.{field}")));
} }
} }
if options.get("include_obfuscation") == Some(&Value::Bool(true)) { if body.get("stream") == Some(&Value::Bool(true))
&& options.get("include_obfuscation") == Some(&Value::Bool(true))
{
return Err(unsupported("stream_options.include_obfuscation")); return Err(unsupported("stream_options.include_obfuscation"));
} }
} }
Ok(()) Ok(())
} }
// 用户输入和工具结果保留原值,空指令或 assistant 正文不生成上游内容块
pub(super) fn empty_history_content(role: &str, content: &Value) -> bool {
can_omit_empty_text(role)
&& (content.is_null()
|| content == ""
|| content
.as_array()
.is_some_and(|parts| parts.iter().all(plain_empty_text)))
}
fn can_omit_empty_text(role: &str) -> bool {
matches!(role, "system" | "developer" | "assistant")
}
fn plain_empty_text(part: &Value) -> bool {
// 只移除纯文本占位,带缓存断点等附加字段的块交给目标转换器
part.get("text")
.is_some_and(|text| text.is_null() || text == "")
&& matches!(
part.get("type").and_then(Value::as_str),
Some("text" | "input_text" | "output_text")
)
&& part.as_object().is_some_and(|fields| {
fields
.iter()
.all(|(key, value)| matches!(key.as_str(), "type" | "text") || value.is_null())
})
}
pub(super) fn empty_history_part(role: &str, part: &Value) -> bool {
can_omit_empty_text(role) && plain_empty_text(part)
}
// 部分 Chat 客户端用显式 null 表示空文本,缺少 text 或其他类型仍按原字段报错
pub(super) fn block_text<'a>(
value: Option<&'a Value>,
part_path: &str,
) -> Result<&'a str, ChatError> {
match value {
Some(Value::Null) => Ok(""),
value => string(value, &format!("{part_path}.text"), true),
}
}
pub(super) fn response_format(body: &Map<String, Value>) -> Option<&Value> {
body.get("response_format")
.filter(|v| !v.is_null())
.or_else(|| body.get("text")?.get("format").filter(|v| !v.is_null()))
}
pub(super) fn reasoning_effort(body: &Map<String, Value>) -> Option<&Value> {
body.get("reasoning_effort")
.filter(|v| !v.is_null())
.or_else(|| {
body.get("reasoning")?
.get("effort")
.filter(|v| !v.is_null())
})
}
pub(super) fn stop_sequences(body: &Map<String, Value>) -> Result<Option<Value>, ChatError> {
match body.get("stop") {
None | Some(Value::Null) => Ok(None),
Some(Value::String(text)) => Ok(Some(json!([text]))),
Some(Value::Array(values)) => {
for (index, value) in values.iter().enumerate() {
if !value.is_string() {
return Err(invalid(&format!("stop[{index}]")));
}
}
Ok((!values.is_empty()).then(|| Value::Array(values.clone())))
}
_ => Err(invalid("stop")),
}
}
pub(super) fn function_parameters(function: &Value, path: &str) -> Result<Value, ChatError> {
match function.get("parameters") {
None | Some(Value::Null) => Ok(json!({"type":"object","properties":{}})),
Some(schema) if schema.is_object() => Ok(schema.clone()),
_ => Err(invalid(&format!("{path}.function.parameters"))),
}
}
pub(super) fn string<'a>( pub(super) fn string<'a>(
value: Option<&'a Value>, value: Option<&'a Value>,
path: &str, path: &str,
@@ -222,28 +306,16 @@ pub(crate) fn request_facts(body: &Map<String, Value>) -> RequestFacts {
.any(|tool| tool.get("type").and_then(Value::as_str) == Some("image_generation")), .any(|tool| tool.get("type").and_then(Value::as_str) == Some("image_generation")),
reasoning: body.get("reasoning_effort").is_some_and(|v| !v.is_null()) reasoning: body.get("reasoning_effort").is_some_and(|v| !v.is_null())
|| body.get("reasoning").is_some_and(Value::is_object), || body.get("reasoning").is_some_and(Value::is_object),
json_schema: body json_schema: response_format(body)
.get("response_format")
.and_then(|v| v.get("type")) .and_then(|v| v.get("type"))
.and_then(Value::as_str) .and_then(Value::as_str)
== Some("json_schema") == Some("json_schema"),
|| body
.get("text")
.and_then(|v| v.pointer("/format/type"))
.and_then(Value::as_str)
== Some("json_schema"),
..RequestFacts::default() ..RequestFacts::default()
} }
} }
pub(crate) fn request_effort(body: &Map<String, Value>) -> Option<&str> { pub(crate) fn request_effort(body: &Map<String, Value>) -> Option<&str> {
body.get("reasoning_effort") reasoning_effort(body).and_then(Value::as_str)
.and_then(Value::as_str)
.or_else(|| {
body.get("reasoning")
.and_then(|value| value.get("effort"))
.and_then(Value::as_str)
})
} }
/// 将无格式约束的 custom 工具表达为字符串参数,受约束格式必须由目标原生支持 /// 将无格式约束的 custom 工具表达为字符串参数,受约束格式必须由目标原生支持
@@ -4,7 +4,11 @@ use std::collections::HashSet;
use serde_json::{Map, Value, json}; use serde_json::{Map, Value, json};
use crate::chat_completions::{ChatError as RequestDecodeError, validate_request}; use crate::chat_completions::{
ChatError as RequestDecodeError,
request::{block_text, empty_history_content, empty_history_part},
validate_request,
};
/// 将已验证的 Chat 正文直接转换为 Responses 请求 /// 将已验证的 Chat 正文直接转换为 Responses 请求
pub fn convert_request( pub fn convert_request(
@@ -161,14 +165,8 @@ fn messages(value: Value) -> Result<Vec<Value>, RequestDecodeError> {
let path = format!("messages[{index}]"); let path = format!("messages[{index}]");
let mut message = object(value, &path)?; let mut message = object(value, &path)?;
let role = required_string(&mut message, "role", &format!("{path}.role"), false)?; let role = required_string(&mut message, "role", &format!("{path}.role"), false)?;
let name = optional(&mut message, "name").filter(|name| name != "");
if role == "tool" { if role == "tool" {
let call_id = required_string( let call_id = optional(&mut message, "tool_call_id");
&mut message,
"tool_call_id",
&format!("{path}.tool_call_id"),
false,
)?;
let content_path = format!("{path}.content"); let content_path = format!("{path}.content");
let content = required(&mut message, "content", &content_path)?; let content = required(&mut message, "content", &content_path)?;
let output = if content.is_string() { let output = if content.is_string() {
@@ -176,14 +174,24 @@ fn messages(value: Value) -> Result<Vec<Value>, RequestDecodeError> {
} else { } else {
content_parts(content, &role, &content_path, false)?.into() 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" "custom_tool_call_output"
} else { } else {
"function_call_output" "function_call_output"
}; };
let mut item = json!({"type": kind, "call_id": call_id, "output": output}); let mut item = json!({"type": kind, "output": output});
if let Some(name) = name { if let Some(call_id) = call_id {
item["name"] = name; 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); input.push(item);
continue; continue;
@@ -193,8 +201,9 @@ fn messages(value: Value) -> Result<Vec<Value>, RequestDecodeError> {
.map(|value| tool_calls(value, &format!("{path}.tool_calls"))) .map(|value| tool_calls(value, &format!("{path}.tool_calls")))
.transpose()? .transpose()?
.unwrap_or_default(); .unwrap_or_default();
let refusal = optional(&mut message, "refusal"); let refusal = optional(&mut message, "refusal").filter(|v| v != "");
let content = optional(&mut message, "content"); let content =
optional(&mut message, "content").filter(|v| !empty_history_content(&role, v));
let is_assistant = role == "assistant"; let is_assistant = role == "assistant";
let mut parts = content let mut parts = content
.map(|value| content_parts(value, &role, &format!("{path}.content"), is_assistant)) .map(|value| content_parts(value, &role, &format!("{path}.content"), is_assistant))
@@ -233,20 +242,23 @@ fn content_parts(
is_assistant: bool, is_assistant: bool,
) -> Result<Vec<Value>, RequestDecodeError> { ) -> Result<Vec<Value>, RequestDecodeError> {
let parts = match value { let parts = match value {
Value::String(text) => return Ok(vec![text_part(text, is_assistant)]), Value::String(text) => return Ok(vec![text_part(&text, is_assistant)]),
Value::Array(parts) => parts, Value::Array(parts) => parts,
_ => return Err(invalid_type(path, "a string or an array")), _ => return Err(invalid_type(path, "a string or an array")),
}; };
let mut result = Vec::with_capacity(parts.len()); let mut result = Vec::with_capacity(parts.len());
for (index, value) in parts.into_iter().enumerate() { for (index, value) in parts
.into_iter()
.enumerate()
.filter(|(_, part)| !empty_history_part(role, part))
{
let path = format!("{path}[{index}]"); let path = format!("{path}[{index}]");
let mut part = object(value, &path)?; let mut part = object(value, &path)?;
let kind = required_string(&mut part, "type", &format!("{path}.type"), false)?; let kind = required_string(&mut part, "type", &format!("{path}.type"), false)?;
let mut converted = match kind.as_str() { let mut converted = match kind.as_str() {
"text" | "input_text" | "output_text" => text_part( "text" | "input_text" | "output_text" => {
required_string(&mut part, "text", &format!("{path}.text"), true)?, text_part(block_text(part.get("text"), &path)?, is_assistant)
is_assistant, }
),
"image_url" if matches!(role, "user" | "tool") => image_part( "image_url" if matches!(role, "user" | "tool") => image_part(
required(&mut part, "image_url", &format!("{path}.image_url"))?, required(&mut part, "image_url", &format!("{path}.image_url"))?,
&format!("{path}.image_url"), &format!("{path}.image_url"),
@@ -278,7 +290,7 @@ fn content_parts(
Ok(result) Ok(result)
} }
fn text_part(text: String, is_assistant: bool) -> Value { fn text_part(text: &str, is_assistant: bool) -> Value {
if is_assistant { if is_assistant {
json!({"type": "output_text", "text": text, "annotations": []}) json!({"type": "output_text", "text": text, "annotations": []})
} else { } else {
@@ -369,16 +381,33 @@ fn tools(value: Value) -> Result<Vec<Value>, RequestDecodeError> {
.into_iter() .into_iter()
.enumerate() .enumerate()
.map(|(index, value)| { .map(|(index, value)| {
let path = format!("tools[{index}]"); let mut path = format!("tools[{index}]");
let mut tool = object(value, &path)?; let mut tool = object(value, &path)?;
let kind = required_string(&mut tool, "type", &format!("{path}.type"), false)?; let kind = required_string(&mut tool, "type", &format!("{path}.type"), false)?;
if matches!(kind.as_str(), "function" | "custom") { if matches!(kind.as_str(), "function" | "custom") {
if let Some(nested) = optional(&mut tool, &kind) { if let Some(nested) = optional(&mut tool, &kind) {
tool = object(nested, &format!("{path}.{kind}"))?; path = format!("{path}.{kind}");
tool = object(nested, &path)?;
} }
if kind == "function" && tool.get("strict").is_none_or(Value::is_null) { if tool.get("description") == Some(&Value::Null) {
// Chat 的缺省是宽松 schema,不能让 Responses 收紧参数合同 tool.remove("description");
tool.insert("strict".into(), false.into()); }
if kind == "function" {
if tool.get("parameters") == Some(&Value::Null) {
tool.remove("parameters");
}
if tool.get("strict").is_none_or(Value::is_null) {
// Chat 的缺省是宽松 schema,不能让 Responses 收紧参数合同
tool.insert("strict".into(), false.into());
}
} 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 决定 // hosted 工具采用原生 Responses 结构,支持范围由选中的 Provider 决定
+18 -1
View File
@@ -1,4 +1,21 @@
//! 跨协议 HTTP 传输、下游环境头分类与重试时间解析 //! 跨协议 HTTP 头分类、响应关联与重试时间解析
/// 响应关联 ID 的头名与优先级沿用官方 Codex
pub const RESPONSE_REQUEST_ID_HEADERS: [&str; 4] = [
"x-request-id",
"x-oai-request-id",
"x-openai-request-id",
"x-ms-request-id",
];
/// 从各传输容器提供的可读 HTTP 头值中选取关联 ID,空值不阻止别名回退
pub fn preferred_response_request_id<'a>(
mut header: impl FnMut(&str) -> Option<&'a str>,
) -> Option<&'a str> {
RESPONSE_REQUEST_ID_HEADERS
.iter()
.find_map(|name| header(name).filter(|value| !value.trim().is_empty()))
}
/// 上游可交给客户端的秒级与毫秒级重试等待头 /// 上游可交给客户端的秒级与毫秒级重试等待头
pub const RETRY_AFTER_HEADERS: [&str; 2] = ["retry-after", "retry-after-ms"]; pub const RETRY_AFTER_HEADERS: [&str; 2] = ["retry-after", "retry-after-ms"];
@@ -4,7 +4,15 @@ use gateway_protocol::{
chat_completions::{CHAT_PROTOCOL, ChatError, genai, messages, parse_request, responses}, chat_completions::{CHAT_PROTOCOL, ChatError, genai, messages, parse_request, responses},
request::{request_facts, request_observation}, request::{request_facts, request_observation},
}; };
use serde_json::json; use serde_json::{Map, Value, json};
fn target_requests(body: &Map<String, Value>) -> [Result<Map<String, Value>, ChatError>; 3] {
[
responses::convert_request(body),
messages::convert_request(body, &Default::default()),
genai::convert_request(body),
]
}
#[test] #[test]
fn parsing_retains_original_protocol_and_usage_preference() { fn parsing_retains_original_protocol_and_usage_preference() {
@@ -42,7 +50,7 @@ fn invalid_envelopes_and_chat_controls_keep_safe_field_errors() {
("n", json!(2)), ("n", json!(2)),
("store", json!(true)), ("store", json!(true)),
("previous_response_id", json!("resp_previous")), ("previous_response_id", json!("resp_previous")),
("stream_options", json!({"include_usage":true})), ("stream_options", json!(true)),
] { ] {
let mut request = super::request(); let mut request = super::request();
request.insert(field.into(), value); request.insert(field.into(), value);
@@ -55,14 +63,48 @@ fn invalid_envelopes_and_chat_controls_keep_safe_field_errors() {
#[test] #[test]
fn invalid_tool_history_reports_source_path() { fn invalid_tool_history_reports_source_path() {
let request = json!({"model":"m","messages":[{"role":"tool","content":"ok"}]}); for (identity, parameter) in [
assert_eq!( (json!({}), "messages[0].name"),
parse_request(&serde_json::to_vec(&request).unwrap()) (json!({"name":null}), "messages[0].name"),
.err() (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() .unwrap()
.parameter(), .extend(identity.as_object().unwrap().clone());
Some("messages[0].tool_call_id") 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] #[test]
@@ -104,9 +146,320 @@ fn capability_facts_only_read_protocol_declarations() {
assert!(!request_facts(CHAT_PROTOCOL, &body).tools); assert!(!request_facts(CHAT_PROTOCOL, &body).tools);
} }
#[test]
fn empty_history_is_omitted_only_when_converting() {
let mut baseline = super::request();
baseline["messages"] = json!([
{"role":"developer","content":"Keep replies short."},
{"role":"user","content":"hello"}
]);
let expected = target_requests(&baseline).map(Result::unwrap);
for role in ["system", "developer", "assistant"] {
for content in [
None,
Some(Value::Null),
Some(json!("")),
Some(json!([])),
Some(json!([{"type":"text","text":""},{"type":"output_text","text":""}])),
Some(json!([{"type":"input_text","text":null}])),
Some(json!([{"type":"text","text":"","prompt_cache_breakpoint":null}])),
] {
let mut placeholder =
json!({"role":role,"tool_calls":[],"refusal":"","tool_call_id":""});
if let Some(content) = content {
placeholder["content"] = content;
}
let mut body = baseline.clone();
body["messages"]
.as_array_mut()
.unwrap()
.insert(1, placeholder.clone());
let parsed = parse_request(&serde_json::to_vec(&body).unwrap()).unwrap();
assert_eq!(parsed, body);
assert_eq!(target_requests(&parsed).map(Result::unwrap), expected);
body["messages"] = json!([placeholder]);
for error in target_requests(&body).map(Result::unwrap_err) {
assert_eq!(error.parameter(), Some("messages"));
}
}
}
}
#[test]
fn empty_history_fields_preserve_tool_calls_results_and_refusals() {
let mut body = super::request();
body["messages"] = json!([
{"role":"user","content":"hello"},
{"role":"assistant","tool_calls":[{"id":"c","type":"function","function":{"name":"f","arguments":"{}"}}]},
{"role":"tool","tool_call_id":"c","content":""},
{"role":"assistant","refusal":"declined"}
]);
let expected = target_requests(&body).map(Result::unwrap);
assert_eq!(expected[0]["input"][1]["call_id"], "c");
assert_eq!(expected[0]["input"][2]["output"], "");
assert_eq!(expected[1]["messages"][1]["content"][0]["type"], "tool_use");
assert_eq!(expected[1]["messages"][3]["content"][0]["text"], "declined");
assert_eq!(
expected[2]["contents"][2]["parts"][0]["functionResponse"]["id"],
"c"
);
assert_eq!(expected[2]["contents"][3]["parts"][0]["text"], "declined");
body["messages"][0] = json!({"role":"user","content":"hello","name":17,"refusal":"","tool_calls":[],"tool_call_id":""});
for content in [
Value::Null,
json!(""),
json!([]),
json!([{"type":"text","text":""}]),
json!([{"type":"output_text","text":null}]),
] {
body["messages"][1]["content"] = content.clone();
body["messages"][3]["content"] = content;
assert_eq!(target_requests(&body).map(Result::unwrap), expected);
}
body["messages"][2]["content"] =
json!([{"type":"text","text":""},{"type":"text","text":"x"},{"type":"text","text":""}]);
let [responses, messages, genai] = target_requests(&body).map(Result::unwrap);
assert_eq!(responses["input"][2]["output"].as_array().unwrap().len(), 3);
assert_eq!(
messages["messages"][2]["content"][0]["content"]
.as_array()
.unwrap()
.len(),
3
);
assert_eq!(
genai["contents"][2]["parts"][0]["functionResponse"]["response"]["output"],
"\nx\n"
);
body["messages"][2]["content"][0]["text"] = Value::Null;
assert_eq!(
target_requests(&body).map(Result::unwrap),
[responses, messages, genai]
);
body["messages"][2]["content"] = json!("");
body["messages"][2]["name"] = json!(17);
let parsed = parse_request(&serde_json::to_vec(&body).unwrap()).unwrap();
let [responses, messages, genai] = target_requests(&parsed);
assert_eq!(responses.unwrap_err().parameter(), Some("messages[2].name"));
assert_eq!(messages.unwrap(), expected[1]);
assert_eq!(genai.unwrap(), expected[2]);
}
#[test]
fn filters_only_plain_empty_history_parts_and_keeps_source_indices() {
let mut body = super::request();
let blank = json!({"type":"input_text","text":""});
let space = json!({"type":"text","text":" "});
for role in ["system", "developer", "assistant", "user"] {
body["messages"] = json!([{"role":role,"content":[space]}, {"role":"user","content":"hi"}]);
let expected = target_requests(&body).map(Result::unwrap);
body["messages"][0]["content"] = json!([blank, space, blank]);
let actual = target_requests(&body).map(Result::unwrap);
body["messages"][0]["content"][0]["text"] = Value::Null;
assert_eq!(target_requests(&body).map(Result::unwrap), actual);
if role == "user" {
assert_eq!(
actual[0]["input"][0]["content"].as_array().unwrap().len(),
3
);
assert_eq!(actual[1]["messages"][0]["content"][1]["text"], " ");
assert_eq!(actual[2]["contents"][0]["parts"][1]["text"], " ");
} else {
assert_eq!(actual, expected);
}
}
let marked = json!({"type":"text","text":null,"prompt_cache_breakpoint":{"mode":"explicit"}});
body["messages"][0] = json!({"role":"developer","content":[blank,marked]});
let converted = responses::convert_request(&body).unwrap();
assert_eq!(
converted["input"][0]["content"],
json!([{"type":"input_text","text":"","prompt_cache_breakpoint":{"mode":"explicit"}}])
);
body["messages"][0]["role"] = json!("assistant");
assert_eq!(
responses::convert_request(&body).unwrap_err().parameter(),
Some("messages[0].content[1].prompt_cache_breakpoint")
);
for (part, code) in [
(json!({"type":"text"}), "missing_required_parameter"),
(json!({"type":"text","text":17}), "invalid_type"),
(json!({"type":"text","text":{}}), "invalid_type"),
] {
body["messages"][0]["content"] = json!([{"type":"text","text":null},part]);
for error in target_requests(&body).map(Result::unwrap_err) {
assert_eq!(error.parameter(), Some("messages[0].content[1].text"));
assert_eq!(error.code(), code);
}
}
}
#[test]
fn null_chat_controls_fall_back_to_native_format_and_effort() {
let mut body = super::request();
let schema = json!({"type":"object","properties":{"q":{"type":"string"}}});
body.insert(
"text".into(),
json!({"format":{"type":"json_schema","name":"answer","schema":schema}}),
);
body.insert("reasoning".into(), json!({"effort":"low"}));
let expected = target_requests(&body).map(Result::unwrap);
assert_eq!(expected[1]["output_config"]["format"]["schema"], schema);
assert_eq!(
expected[2]["generationConfig"]["responseJsonSchema"],
schema
);
assert_eq!(expected[1]["thinking"]["budget_tokens"], 1024);
assert_eq!(
expected[2]["generationConfig"]["thinkingConfig"]["thinkingBudget"],
1024
);
body.insert("response_format".into(), Value::Null);
body.insert("reasoning_effort".into(), Value::Null);
assert_eq!(target_requests(&body).map(Result::unwrap), expected);
assert!(request_facts(CHAT_PROTOCOL, &body).json_schema);
body["response_format"] = json!({"type":"text"});
body["reasoning_effort"] = json!("none");
let [responses, messages, genai] = target_requests(&body).map(Result::unwrap);
assert!(!request_facts(CHAT_PROTOCOL, &body).json_schema);
assert_eq!(responses["text"]["format"]["type"], "text");
assert!(messages.get("output_config").is_none());
assert!(
genai["generationConfig"]
.get("responseJsonSchema")
.is_none()
);
assert_eq!(messages["thinking"]["type"], "disabled");
assert_eq!(
genai["generationConfig"]["thinkingConfig"]["thinkingBudget"],
0
);
body["reasoning_effort"] = json!(5);
for error in target_requests(&body).map(Result::unwrap_err) {
assert_eq!(error.parameter(), Some("reasoning_effort"));
}
}
#[test]
fn null_function_parameters_follow_each_targets_default() {
let mut body = super::request();
body.insert(
"tools".into(),
json!([{"type":"function","function":{"name":"clock"}}]),
);
let expected = target_requests(&body).map(Result::unwrap);
assert!(expected[0]["tools"][0].get("parameters").is_none());
let default_schema = json!({"type":"object","properties":{}});
assert_eq!(expected[1]["tools"][0]["input_schema"], default_schema);
assert_eq!(
expected[2]["tools"][0]["functionDeclarations"][0]["parametersJsonSchema"],
default_schema
);
body["tools"][0]["function"] =
json!({"name":"clock","parameters":null,"description":null,"strict":null});
assert_eq!(target_requests(&body).map(Result::unwrap), expected);
let schema =
json!({"type":"object","properties":{"q":{"type":["string","null"],"default":null}}});
body["tools"][0]["function"]["parameters"] = schema.clone();
let [responses, messages, genai] = target_requests(&body).map(Result::unwrap);
assert_eq!(responses["tools"][0]["parameters"], schema);
assert_eq!(messages["tools"][0]["input_schema"], schema);
assert_eq!(
genai["tools"][0]["functionDeclarations"][0]["parametersJsonSchema"],
schema
);
}
#[test]
fn stop_sequences_are_mapped_only_for_targets_that_support_them() {
let mut body = super::request();
let baseline = target_requests(&body).map(Result::unwrap);
for stop in [Value::Null, json!([])] {
body.insert("stop".into(), stop);
assert_eq!(target_requests(&body).map(Result::unwrap), baseline);
}
for (stop, expected) in [
(json!(" END"), json!([" END"])),
(json!([" END", "\n"]), json!([" END", "\n"])),
] {
body["stop"] = stop;
let [responses, messages, genai] = target_requests(&body).map(Result::unwrap);
assert_eq!(responses, baseline[0]);
assert_eq!(messages["stop_sequences"], expected);
assert_eq!(genai["generationConfig"]["stopSequences"], expected);
}
for (stop, param) in [(json!(5), "stop"), (json!(["end", null]), "stop[1]")] {
body["stop"] = stop;
let [responses, messages, genai] = target_requests(&body);
assert_eq!(responses.unwrap(), baseline[0]);
for result in [messages, genai] {
assert_eq!(result.unwrap_err().parameter(), Some(param));
}
}
}
#[test]
fn stream_options_affect_only_streaming_delivery() {
for stream in [None, Some(false), Some(true)] {
let mut body = super::request();
if let Some(stream) = stream {
body.insert("stream".into(), json!(stream));
}
let expected = target_requests(&body).map(Result::unwrap);
body.insert(
"stream_options".into(),
json!({"include_usage":true, "include_obfuscation":false}),
);
assert_eq!(target_requests(&body).map(Result::unwrap), expected);
body["stream_options"]["include_obfuscation"] = json!(true);
if stream == Some(true) {
for error in target_requests(&body).map(Result::unwrap_err) {
assert_eq!(
error.parameter(),
Some("stream_options.include_obfuscation")
);
}
} else {
assert_eq!(target_requests(&body).map(Result::unwrap), expected);
}
}
}
#[test] #[test]
fn all_targets_apply_the_same_common_request_validation() { fn all_targets_apply_the_same_common_request_validation() {
for (field, value, parameter) in [ for (field, value, parameter) in [
(
"messages",
json!([{"role":"system","content":null},{"role":"developer","content":null}]),
"messages",
),
(
"messages",
json!([{"role":"developer"},{"role":"assistant","audio":{"id":"audio"}}]),
"messages[1].audio",
),
(
"messages",
json!([{"role":"system","content":42}]),
"messages[0].content",
),
(
"messages",
json!([{"role":"system","content":null},{"role":"user","content":null}]),
"messages[1].content",
),
(
"messages",
json!([{"role":"tool","tool_call_id":"c","content":null}]),
"messages[0].content",
),
(
"messages",
json!([{"role":"system","content":null,"tool_calls":[{}]}]),
"messages[0].tool_calls",
),
( (
"messages", "messages",
json!([{"role":"assistant","content":"ok","refusal":17}]), json!([{"role":"assistant","content":"ok","refusal":17}]),
@@ -114,13 +467,18 @@ fn all_targets_apply_the_same_common_request_validation() {
), ),
( (
"messages", "messages",
json!([{"role":"user","content":"ok","name":17}]), json!([{"role":"assistant","tool_calls":{}}]),
"messages[0].name", "messages[0].tool_calls",
), ),
( (
"messages", "messages",
json!([{"role":"user","content":"ok","tool_calls":[]}]), json!([{"role":"developer","tool_call_id":"c"}]),
"messages[0].tool_calls", "messages[0].tool_call_id",
),
(
"messages",
json!([{"role":"user","content":"ok","refusal":"declined"}]),
"messages[0].refusal",
), ),
( (
"messages", "messages",
@@ -130,8 +488,8 @@ fn all_targets_apply_the_same_common_request_validation() {
("n", json!(2), "n"), ("n", json!(2), "n"),
( (
"stream_options", "stream_options",
json!({"include_usage":true}), json!({"include_usage":1}),
"stream_options", "stream_options.include_usage",
), ),
] { ] {
let mut body = super::request(); let mut body = super::request();
@@ -140,11 +498,7 @@ fn all_targets_apply_the_same_common_request_validation() {
.err() .err()
.unwrap(); .unwrap();
assert_eq!(expected.parameter(), Some(parameter)); assert_eq!(expected.parameter(), Some(parameter));
for result in [ for result in target_requests(&body) {
responses::convert_request(&body),
messages::convert_request(&body, &Default::default()),
genai::convert_request(&body),
] {
assert_eq!(result.unwrap_err(), expected); assert_eq!(result.unwrap_err(), expected);
} }
} }
@@ -152,11 +506,14 @@ fn all_targets_apply_the_same_common_request_validation() {
#[test] #[test]
fn custom_format_constraints_are_preserved_or_rejected_by_the_target() { fn custom_format_constraints_are_preserved_or_rejected_by_the_target() {
for format in [ for (format, expected) in [
json!(null), (json!(null), json!(null)),
json!({"type":"text"}), (json!({"type":"text"}), json!({"type":"text"})),
json!({"type":"grammar","grammar":{"syntax":"lark","definition":"PRIVATE_GRAMMAR"}}), (
json!(17), 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(); let mut body = super::request();
body.insert( body.insert(
@@ -164,7 +521,7 @@ fn custom_format_constraints_are_preserved_or_rejected_by_the_target() {
json!([{"type":"custom","custom":{"name":"run","format":format}}]), json!([{"type":"custom","custom":{"name":"run","format":format}}]),
); );
let responses = responses::convert_request(&body).unwrap(); let responses = responses::convert_request(&body).unwrap();
assert_eq!(responses["tools"][0]["format"], format); assert_eq!(responses["tools"][0]["format"], expected);
for result in [ for result in [
messages::convert_request(&body, &Default::default()), messages::convert_request(&body, &Default::default()),
genai::convert_request(&body), 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()); 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] #[test]
fn web_search_options_require_a_hosted_search_and_flatten_location() { fn web_search_options_require_a_hosted_search_and_flatten_location() {
for (options, expected) in [ for (options, expected) in [
@@ -278,7 +303,7 @@ fn custom_tools_keep_native_input_and_mixed_call_families_through_history() {
]})); ]}));
assert_eq!( assert_eq!(
converted["tools"][0], converted["tools"][0],
json!({"type":"custom", "name":"patch", "format":schema}) json!({"type":"custom", "name":"patch", "format":{"type":"grammar","syntax":"lark","definition":"start: /.+/"}})
); );
assert_eq!( assert_eq!(
converted["tool_choice"], 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"); 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] #[test]
fn files_and_audio_are_preserved_as_inputs_instead_of_losing_the_user_turn() { fn files_and_audio_are_preserved_as_inputs_instead_of_losing_the_user_turn() {
for file in [ for file in [
+53 -1
View File
@@ -1,9 +1,61 @@
//! 验证传输头部分类,以及响应中的连接级和身份字段过滤 //! 验证传输头部分类,以及响应中的连接级和身份字段过滤
use gateway_protocol::http::{ use gateway_protocol::http::{
is_transport_managed_request_header, parse_retry_after_seconds, response_header_is_forwardable, is_transport_managed_request_header, parse_retry_after_seconds, preferred_response_request_id,
response_header_is_forwardable,
}; };
#[test]
fn response_request_ids_follow_official_header_priority() {
let names = [
"x-request-id",
"x-oai-request-id",
"x-openai-request-id",
"x-ms-request-id",
];
let mut headers = http::HeaderMap::new();
for name in names {
headers.insert(name, http::HeaderValue::from_static(name));
}
headers.insert("cf-ray", http::HeaderValue::from_static("trace-only"));
for name in names {
assert_eq!(
preferred_response_request_id(|name| headers.get(name)?.to_str().ok()),
Some(name),
);
headers.remove(name);
}
assert_eq!(
preferred_response_request_id(|name| headers.get(name)?.to_str().ok()),
None,
);
}
#[test]
fn response_request_ids_skip_unusable_first_values_without_rewriting_headers() {
let mut headers = http::HeaderMap::new();
headers.insert(
"x-request-id",
http::HeaderValue::from_bytes(b"\xff").unwrap(),
);
headers.append(
"x-request-id",
http::HeaderValue::from_static("second-value"),
);
headers.insert("x-oai-request-id", http::HeaderValue::from_static(" \t "));
headers.insert("x-openai-request-id", http::HeaderValue::from_static(""));
headers.insert(
"x-ms-request-id",
http::HeaderValue::from_static(" opaque-id "),
);
assert_eq!(
preferred_response_request_id(|name| headers.get(name)?.to_str().ok()),
Some(" opaque-id "),
);
assert_eq!(headers["x-request-id"].as_bytes(), b"\xff");
assert_eq!(headers.get_all("x-request-id").iter().count(), 2);
}
#[test] #[test]
fn retry_after_should_accept_nonnegative_seconds_and_http_dates() { fn retry_after_should_accept_nonnegative_seconds_and_http_dates() {
for (header, expected) in [ for (header, expected) in [
@@ -69,7 +69,9 @@ impl ClientAdmissionRecoveryRepository for PgClientAdmissionRecoveryRepository {
lease.lease_expires_at, request.outcome lease.lease_expires_at, request.outcome
from model_requests request from model_requests request
left join model_request_leases lease on lease.request_id = request.id 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", order by request.client_api_key_ref, request.started_at, request.id",
) )
.bind(window_started_at) .bind(window_started_at)
@@ -155,8 +155,6 @@ impl ClientAdmissionRequest {
return Err(invalid("lease TTL must be positive")); return Err(invalid("lease TTL must be positive"));
} }
redis_duration_millis(self.lease_ttl)?; 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(()) Ok(())
} }
} }
@@ -287,6 +285,7 @@ impl ClientAdmissionRepository for RedisClientAdmissionRepository {
.key(&keys[1]) .key(&keys[1])
.arg(&request.model_request_id) .arg(&request.model_request_id)
.arg(lease_ttl_ms) .arg(lease_ttl_ms)
// ZCARD 的取值都能精确表示,超过 Lua 精确范围的限额始终大于实际计数
.arg(request.limits.max_concurrency) .arg(request.limits.max_concurrency)
.arg(request.limits.requests_per_minute) .arg(request.limits.requests_per_minute)
.arg(MAX_REDIS_EXACT_INTEGER) .arg(MAX_REDIS_EXACT_INTEGER)
+13 -10
View File
@@ -240,18 +240,21 @@ pub(crate) struct StaleModelRequestRecoveryTask {
impl ScheduledTask for StaleModelRequestRecoveryTask { impl ScheduledTask for StaleModelRequestRecoveryTask {
fn run_cycle( fn run_cycle(
&self, &self,
_context: WorkerCycleContext, context: WorkerCycleContext,
) -> futures::future::BoxFuture<'_, Result<(), WorkerTaskError>> { ) -> futures::future::BoxFuture<'_, Result<(), WorkerTaskError>> {
Box::pin(async move { Box::pin(async move {
gateway_core::engine::ExecutionStore::recover_expired( context
self.execution.as_ref(), .cancellation()
SystemTime::now(), .run_until_cancelled(gateway_core::engine::ExecutionStore::recover_expired(
) self.execution.as_ref(),
.await SystemTime::now(),
.map(|_| ()) ))
.map_err(|source| { .await
WorkerTaskError::safe("stale request recovery failed").with_source(source) .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 .await
.expect("remove missing lease fixture"); .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 repository = PgClientAdmissionRecoveryRepository::new(database.pool.clone());
let actual = repository let actual = repository
.load_client_admission_recovery(window_started_at) .load_client_admission_recovery(window_started_at)
@@ -18,11 +18,19 @@ fn client_admission_rejects_zero_ttl() {
assert!(request.validate().is_err()); assert!(request.validate().is_err());
} }
#[test] #[tokio::test]
fn client_admission_rejects_values_outside_redis_exact_integer_range() { async fn configured_limits_above_lua_integer_precision_allow_requests() {
let mut request = admission_request("request-1", "key-1", Duration::from_secs(30)); 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; 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] #[test]
@@ -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"] } reqwest = { version = "=0.12.28", default-features = false, features = ["json", "rustls-tls-native-roots", "socks", "stream"] }
serde = { version = "1.0.228", features = ["derive"] } serde = { version = "1.0.228", features = ["derive"] }
serde_json = { version = "1.0.150", features = ["raw_value"] } serde_json = { version = "1.0.150", features = ["raw_value"] }
sevenz-rust2 = { version = "0.27.0", default-features = false }
sha2 = "0.11.0" sha2 = "0.11.0"
tar = { version = "0.4.46", default-features = false } tar = { version = "0.4.46", default-features = false }
tempfile = "3.27.0" 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"] } zip = { version = "9.8.0", default-features = false, features = ["deflate-flate2"] }
[dev-dependencies] [dev-dependencies]
sevenz-rust2 = { version = "0.27.0", default-features = false, features = ["compress"] }
wiremock = "0.6.5" wiremock = "0.6.5"
tokio = { version = "=1.53.3", features = ["rt-multi-thread"] } 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 { if current.account.authentication_kind() == super::api_key::API_KEY {
let material = super::api_key::ApiKeyMaterial::load(&current)?; let material = super::api_key::ApiKeyMaterial::load(&current)?;
let client = crate::transport::GenAiClient::new( let client = crate::transport::GenAiClient::new(
@@ -316,7 +328,12 @@ impl CatalogService {
) )
.map_err(|e| error(AdminKind::Unavailable).with_source(e))?; .map_err(|e| error(AdminKind::Unavailable).with_source(e))?;
let observed_at = SystemTime::now(); 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) error(AdminKind::Unavailable)
.with_public_message("GenAI 模型目录查询失败") .with_public_message("GenAI 模型目录查询失败")
.with_source(e) .with_source(e)
@@ -333,15 +350,16 @@ impl CatalogService {
let client = CloudCodeClient::new(&self.origin, current.account.outbound_proxy(), &profile) let client = CloudCodeClient::new(&self.origin, current.account.outbound_proxy(), &profile)
.map_err(|e| error(AdminKind::Unavailable).with_source(e))?; .map_err(|e| error(AdminKind::Unavailable).with_source(e))?;
let observed_at = SystemTime::now(); let observed_at = SystemTime::now();
let catalog = client let result = client.catalog(&material.access_token).await;
.catalog(&material.access_token) if let Err(error) = &result {
.await super::record_account_failure(self.accounts.as_ref(), &current.account, error).await;
.map_err(|e| match e.kind() { }
Kind::Unauthorized => error(AdminKind::CredentialRefreshRequired).with_source(e), let catalog = result.map_err(|e| match e.kind() {
_ => error(AdminKind::Unavailable) Kind::Unauthorized => error(AdminKind::CredentialRefreshRequired).with_source(e),
.with_public_message("Antigravity 项目或模型目录查询失败") _ => error(AdminKind::Unavailable)
.with_source(e), .with_public_message("Antigravity 项目或模型目录查询失败")
})?; .with_source(e),
})?;
self.publish( self.publish(
&current.account, &current.account,
current.account.plan_type().map(str::to_owned), current.account.plan_type().map(str::to_owned),
@@ -452,6 +470,13 @@ impl CatalogService {
&self, &self,
cancellation: &gateway_core::lifecycle::CancellationToken, cancellation: &gateway_core::lifecycle::CancellationToken,
) -> Result<(), gateway_core::task::WorkerTaskError> { ) -> 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 futures::{StreamExt, stream};
use gateway_core::task::WorkerTaskError; use gateway_core::task::WorkerTaskError;
let catalogs = self let catalogs = self
@@ -469,7 +494,11 @@ impl CatalogService {
.await .await
.map_err(|e| WorkerTaskError::safe("读取 Antigravity 账号失败").with_source(e))?; .map_err(|e| WorkerTaskError::safe("读取 Antigravity 账号失败").with_source(e))?;
due.retain(|account| { 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| { && observations.get(account.id()).is_none_or(|observation| {
observation.revision != account.revision() observation.revision != account.revision()
|| observation.observed_at.elapsed().unwrap_or_default() || 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(); let offset = self.refresh_cursor.fetch_add(32, Ordering::Relaxed) % due.len();
due.rotate_left(offset); due.rotate_left(offset);
due.truncate(32); due.truncate(32);
let mut updates=stream::iter(due).map(|account|async move { let mut updates = stream::iter(due)
tokio::select! {biased;_=cancellation.cancelled()=>Ok(()),result=self.account_models(account.id(),true)=>result.map(|_|())} .map(|account| async move { self.account_models(account.id(), true).await })
}).buffer_unordered(4); .buffer_unordered(4);
let mut first_error = None; let mut first_error = None;
while let Some(result) = updates.next().await { while let Some(result) = updates.next().await {
if let Err(error) = result 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; mod authorization;
pub(crate) mod catalog; pub(crate) mod catalog;
mod documents; mod documents;
mod failure;
pub(crate) use failure::record_account_failure;
mod model_groups; mod model_groups;
pub(crate) mod oauth; pub(crate) mod oauth;
pub(crate) mod quota; pub(crate) mod quota;
@@ -175,15 +175,20 @@ impl QuotaService {
.map_err(upstream)?; .map_err(upstream)?;
// 用查询开始时间隔离交错返回的旧结果,失败不覆盖已有快照 // 用查询开始时间隔离交错返回的旧结果,失败不覆盖已有快照
let observed_at = SystemTime::now(); let observed_at = SystemTime::now();
let info = client let result = async {
.account_info(&material.access_token) let info = client.account_info(&material.access_token).await?;
.await let (catalog, summary) = tokio::try_join!(
.map_err(upstream)?; client.catalog_for_project(&material.access_token, info.project.clone()),
let (catalog, summary) = tokio::try_join!( client.quota_summary(&material.access_token, &info.project),
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))
) }
.map_err(upstream)?; .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 { let (tier, plan_description) = match info.paid_tier {
Some(paid) => (Some(paid.tier), paid.description), Some(paid) => (Some(paid.tier), paid.description),
None => (info.current_tier, None), None => (info.current_tier, None),
@@ -298,6 +303,13 @@ impl QuotaService {
&self, &self,
cancel: &CancellationToken, cancel: &CancellationToken,
) -> Result<(), WorkerTaskError> { ) -> 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 let accounts = self
.accounts .accounts
.list_for_provider(&self.kind, false) .list_for_provider(&self.kind, false)
@@ -317,10 +329,15 @@ impl QuotaService {
let stale_before = now - interval; let stale_before = now - interval;
let mut due = Vec::new(); let mut due = Vec::new();
let mut stale = Vec::new(); let mut stale = Vec::new();
for account in accounts for account in accounts.iter().filter(|a| {
.iter() a.enabled()
.filter(|a| a.enabled() && a.authentication_kind() == "oauth") && a.authentication_kind() == "oauth"
{ && !matches!(
a.credential_state(),
gateway_core::account::CredentialState::Invalid
| gateway_core::account::CredentialState::Banned
)
}) {
let snapshot = observations let snapshot = observations
.remove(account.id()) .remove(account.id())
.filter(|s| s.credential_revision == account.revision()); .filter(|s| s.credential_revision == account.revision());
@@ -355,13 +372,7 @@ impl QuotaService {
due.rotate_left(offset); due.rotate_left(offset);
due.truncate(32); due.truncate(32);
let mut results = stream::iter(due) let mut results = stream::iter(due)
.map(|id| async move { .map(|id| async move { self.refresh(&id).await })
tokio::select! {
biased;
_ = cancel.cancelled() => Ok(()),
result = self.refresh(&id) => result,
}
})
.buffer_unordered(4); .buffer_unordered(4);
while let Some(result) = results.next().await { while let Some(result) = results.next().await {
if let Err(e) = result 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_admin::ports::provider::{ProviderAdminError, ProviderAdminErrorKind as Kind};
use gateway_core::{ use gateway_core::{
account::{ account::{
CredentialCasOutcome, CredentialCasUpdate, CredentialRevision, CredentialState, CredentialCasOutcome, CredentialCasUpdate, CredentialRevision, LoadedCredential,
LoadedCredential, PlaintextCredential, ProviderAccountUpdate, ProviderRefreshQuery, PlaintextCredential, ProviderAccountUpdate, ProviderRefreshQuery,
}, },
provider_ports::provider_refresh_backoff_at, provider_ports::provider_refresh_backoff_at,
task::WorkerTaskError, task::WorkerTaskError,
@@ -79,8 +79,8 @@ impl CredentialService {
material, material,
facts.access_token_expires_at.map(Into::into), facts.access_token_expires_at.map(Into::into),
None, None,
)? )?;
.with_account_state(CredentialState::Ready, SystemTime::now(), None, None); // AT 续期不证明资源服务已解除验证或封禁,提交时保留当前账号访问状态
match self match self
.accounts .accounts
.compare_and_swap_credential(record) .compare_and_swap_credential(record)
@@ -304,6 +304,7 @@ impl CredentialService {
Ok(grant) => grant, Ok(grant) => grant,
}; };
self.rotation(&current.account, grant, guards) self.rotation(&current.account, grant, guards)
.map(PreparedCredentialRotation::preserving_credential_state)
} }
pub(super) fn rotation( pub(super) fn rotation(
@@ -9,17 +9,24 @@ mod transport;
use gateway_admin::ports::provider::ProviderBundle; use gateway_admin::ports::provider::ProviderBundle;
use gateway_core::{provider_ports::ProviderStorePorts, routing::ProviderKind}; use gateway_core::{provider_ports::ProviderStorePorts, routing::ProviderKind};
use std::sync::Arc; use std::{path::PathBuf, sync::Arc};
#[derive(Debug, thiserror::Error)] #[derive(Debug, thiserror::Error)]
#[error("Antigravity Provider 初始化失败")] #[error("Antigravity Provider 初始化失败")]
pub struct ConfigError; 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 kind = ProviderKind::new("antigravity").map_err(|_| ConfigError)?;
let oauth = Arc::new(credential::GoogleOAuth::for_provider()?); let oauth = Arc::new(credential::GoogleOAuth::for_provider()?);
let origin = oauth.resource_origin().clone(); 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( let credentials = Arc::new(credential::CredentialService::new(
kind.clone(), kind.clone(),
&ports, &ports,
@@ -20,12 +20,12 @@ impl Drop for ParseGuard {
} }
} }
pub(crate) struct CancellableFile { pub(crate) struct CancellableFile<R = std::fs::File> {
file: std::fs::File, file: R,
cancellation: CancellationToken, cancellation: CancellationToken,
} }
impl CancellableFile { impl<R> CancellableFile<R> {
pub(crate) fn new(file: std::fs::File) -> (Self, ParseGuard) { pub(crate) fn new(file: R) -> (Self, ParseGuard) {
let cancellation = CancellationToken::new(); let cancellation = CancellationToken::new();
( (
Self { 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> { fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
if self.cancellation.is_cancelled() { if self.cancellation.is_cancelled() {
return Err(io::Error::other("制品解析已取消")); return Err(io::Error::other("制品解析已取消"));
@@ -44,6 +44,14 @@ impl Read for CancellableFile {
self.file.read(buffer) 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 { pub(crate) fn invalid() -> WorkerTaskError {
WorkerTaskError::safe("Antigravity 发布包核验失败") WorkerTaskError::safe("Antigravity 发布包核验失败")
@@ -131,10 +139,6 @@ impl<'a> RemoteArtifact<'a> {
} }
Ok(body.into()) 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( fn archive(
&self, &self,
member: Option<(u64, Bytes)>, member: Vec<(u64, Bytes)>,
) -> Result<zip::ZipArchive<Segments>, WorkerTaskError> { ) -> Result<zip::ZipArchive<Segments>, WorkerTaskError> {
let mut chunks = vec![( let mut chunks = vec![(
self.artifact.size - self.tail.len() as u64, self.artifact.size - self.tail.len() as u64,
@@ -209,12 +213,22 @@ impl<'a> RemoteZip<'a> {
name: &str, name: &str,
maximum: usize, maximum: usize,
) -> Result<Vec<u8>, WorkerTaskError> { ) -> 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 index = archive.index_for_name(name).ok_or_else(invalid)?;
let entry = archive let entry = archive
.by_index_data(index) .by_index_data(index)
.map_err(|e| invalid().with_source(e))?; .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()); return Err(invalid());
} }
let start = entry.header_start(); let start = entry.header_start();
@@ -224,12 +238,25 @@ impl<'a> RemoteZip<'a> {
.checked_add(30 + 2 * u64::from(u16::MAX)) .checked_add(30 + 2 * u64::from(u16::MAX))
.ok_or_else(invalid)? .ok_or_else(invalid)?
.min(self.artifact.size.checked_sub(start).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 members = Vec::new();
let mut archive = self.archive(Some((start, member)))?; let mut offset = start;
let file = archive while offset < start + length {
.by_name(name) let length = (start + length - offset).min(MAX_RANGE_BYTES);
.map_err(|e| invalid().with_source(e))?; members.push((offset, self.artifact.read(offset, length).await?));
bounded(file, maximum) 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, client: &Client,
url: &str, url: &str,
sha512: Option<&str>, sha512: Option<&str>,
artifact_dir: &std::path::Path,
) -> Result<std::fs::File, WorkerTaskError> { ) -> Result<std::fs::File, WorkerTaskError> {
let mut response = client let mut response = client
.get(url) .get(url)
@@ -296,7 +324,11 @@ pub(crate) async fn download(
{ {
return Err(invalid()); 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 file = tokio::fs::File::from_std(file);
let mut count = 0u64; let mut count = 0u64;
let mut digest = Sha512::new(); 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 super::selection::{Architecture, ClientKind, Platform, ReleaseTarget};
use gateway_core::task::WorkerTaskError; use gateway_core::task::WorkerTaskError;
use std::io::Read; use std::io::Read;
@@ -14,8 +14,8 @@ pub(crate) struct Release {
pub(crate) sha512: Option<String>, pub(crate) sha512: Option<String>,
} }
const MAX_ASAR_BYTES: usize = 16 * 1024 * 1024; pub(super) const MAX_ASAR_BYTES: usize = 16 * 1024 * 1024;
const MAX_BINARY_BYTES: u64 = 512 * 1024 * 1024; pub(super) const MAX_BINARY_BYTES: u64 = 512 * 1024 * 1024;
pub(crate) async fn verify( pub(crate) async fn verify(
client: &reqwest::Client, client: &reqwest::Client,
@@ -23,7 +23,8 @@ pub(crate) async fn verify(
version: &str, version: &str,
url: &str, url: &str,
sha512: Option<&str>, sha512: Option<&str>,
) -> Result<(), WorkerTaskError> { artifact_dir: &std::path::Path,
) -> Result<u64, WorkerTaskError> {
match (target.client, target.platform) { match (target.client, target.platform) {
(ClientKind::Desktop, Platform::Macos) => { (ClientKind::Desktop, Platform::Macos) => {
let url = url.strip_suffix(".dmg").ok_or_else(invalid)?; let url = url.strip_suffix(".dmg").ok_or_else(invalid)?;
@@ -40,23 +41,27 @@ pub(crate) async fn verify(
let executable = archive let executable = archive
.read("Antigravity.app/Contents/MacOS/Antigravity", 1024 * 1024) .read("Antigravity.app/Contents/MacOS/Antigravity", 1024 * 1024)
.await?; .await?;
architecture(&executable, target) architecture(&executable, target)?;
} archive
(ClientKind::Desktop, Platform::Windows) => { .inspect(
let artifact = RemoteArtifact::open(client, url.to_owned()).await?; "Antigravity.app/Contents/Resources/bin/language_server",
let header = artifact.prefix(1024 * 1024).await?; MAX_BINARY_BYTES,
let (offset, size) = pe_resources(&header)?; move |reader| verify_binary(reader, target, None),
let resources = artifact.read(offset, size).await?; )
windows_version(&resources, version) .await
} }
_ => { _ => {
let file = download(client, url, sha512).await?; let file = download(client, url, sha512, artifact_dir).await?;
// 取消 worker 时同步中止阻塞解包,临时文件由解析任务退出时关闭 // 取消 worker 时同步中止阻塞解包,临时文件由解析任务退出时关闭
let (file, _guard) = CancellableFile::new(file); let (file, _guard) = CancellableFile::new(file);
let version = version.to_owned(); let version = version.to_owned();
tokio::task::spawn_blocking(move || { tokio::task::spawn_blocking(move || {
if target.client == ClientKind::Cli && target.platform == Platform::Windows { if target.platform == Platform::Windows {
verify_binary(file, target, &version) if target.client == ClientKind::Cli {
verify_binary(file, target, Some(&version))
} else {
super::installer::verify(file, target, &version)
}
} else { } else {
verify_tar(file, target, &version) verify_tar(file, target, &version)
} }
@@ -124,11 +129,12 @@ pub(crate) fn verify_tar(
file: impl Read, file: impl Read,
target: ReleaseTarget, target: ReleaseTarget,
version: &str, version: &str,
) -> Result<(), WorkerTaskError> { ) -> Result<u64, WorkerTaskError> {
let decoder = flate2::read::GzDecoder::new(file); let decoder = flate2::read::GzDecoder::new(file);
let mut archive = tar::Archive::new(decoder.take(2 * 1024 * 1024 * 1024)); let mut archive = tar::Archive::new(decoder.take(2 * 1024 * 1024 * 1024));
let mut found_version = false; let mut found_version = false;
let mut found_executable = false; let mut found_executable = false;
let mut changelist = None;
for (index, entry) in archive for (index, entry) in archive
.entries() .entries()
.map_err(|e| invalid().with_source(e))? .map_err(|e| invalid().with_source(e))?
@@ -153,7 +159,7 @@ pub(crate) fn verify_tar(
if found_executable || entry.size() > MAX_BINARY_BYTES { if found_executable || entry.size() > MAX_BINARY_BYTES {
return Err(invalid()); return Err(invalid());
} }
verify_binary(&mut entry, target, version)?; changelist = Some(verify_binary(&mut entry, target, Some(version))?);
found_version = true; found_version = true;
found_executable = true; found_executable = true;
} else if target.client == ClientKind::Desktop { } else if target.client == ClientKind::Desktop {
@@ -163,6 +169,11 @@ pub(crate) fn verify_tar(
return Err(invalid()); return Err(invalid());
} }
found_version = true; 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" { } else if name == "antigravity" {
if found_executable { if found_executable {
return Err(invalid()); return Err(invalid());
@@ -177,7 +188,7 @@ pub(crate) fn verify_tar(
} }
} }
if found_version && found_executable { if found_version && found_executable {
Ok(()) changelist.ok_or_else(invalid)
} else { } else {
Err(invalid()) Err(invalid())
} }
@@ -186,24 +197,54 @@ pub(crate) fn verify_tar(
pub(crate) fn verify_binary( pub(crate) fn verify_binary(
mut reader: impl Read, mut reader: impl Read,
target: ReleaseTarget, target: ReleaseTarget,
version: &str, version: Option<&str>,
) -> Result<(), WorkerTaskError> { ) -> Result<u64, WorkerTaskError> {
let mut header = [0; 1024]; let mut header = [0; 1024];
reader reader
.read_exact(&mut header) .read_exact(&mut header)
.map_err(|e| invalid().with_source(e))?; .map_err(|e| invalid().with_source(e))?;
architecture(&header, target)?; architecture(&header, target)?;
// 官方 CLI 把版本文件嵌入 Go 制品,保留其换行与终止字节避免匹配依赖版本 // 官方 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 tail = header.to_vec();
let mut chunk = [0; 64 * 1024]; let mut chunk = [0; 64 * 1024];
let mut count = 1024u64; let mut count = 1024u64;
let mut found = false; let mut found = marker.is_none();
let mut changelist = None;
loop { 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; 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); tail.drain(..keep);
let size = reader let size = reader
.read(&mut chunk) .read(&mut chunk)
@@ -217,7 +258,11 @@ pub(crate) fn verify_binary(
} }
tail.extend_from_slice(&chunk[..size]); 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> { fn pe_offset(body: &[u8]) -> Result<usize, WorkerTaskError> {
@@ -231,52 +276,6 @@ fn pe_offset(body: &[u8]) -> Result<usize, WorkerTaskError> {
Ok(offset) 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> { fn u16_at(body: &[u8], offset: usize) -> Result<u16, WorkerTaskError> {
Ok(u16::from_le_bytes( Ok(u16::from_le_bytes(
body.get(offset..offset + 2) 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 archive;
pub(crate) mod artifact; pub(crate) mod artifact;
pub(crate) mod installer;
pub(crate) mod release; pub(crate) mod release;
pub(crate) mod selection; pub(crate) mod selection;
pub(crate) mod verification; pub(crate) mod verification;
@@ -17,17 +18,9 @@ pub(crate) fn resolve(
releases: &ReleaseService, releases: &ReleaseService,
) -> Result<ClientProfile, ProviderAdminError> { ) -> Result<ClientProfile, ProviderAdminError> {
let selection = Selection::parse(configuration)?; let selection = Selection::parse(configuration)?;
Ok(selection.resolve( Ok(releases.snapshot(selection.target()).profile(&selection))
releases
.snapshot(selection.target())
.version(selection.client),
))
} }
pub(crate) fn default_profile(releases: &ReleaseService) -> ClientProfile { pub(crate) fn default_profile(releases: &ReleaseService) -> ClientProfile {
let selection = Selection::default(); let selection = Selection::default();
selection.resolve( releases.snapshot(selection.target()).profile(&selection)
releases
.snapshot(selection.target())
.version(selection.client),
)
} }
@@ -1,16 +1,19 @@
//! 按客户端、平台与架构刷新官方发布资料,失败时保留上次成功结果 //! 跟踪官方发布资料并整组切换已核验画像,更新失败时保留当前画像
pub(crate) use super::artifact::Release; 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 super::verification::{VerificationCache, VerifiedArtifact};
use crate::ConfigError; use crate::ConfigError;
use chrono::{DateTime, Utc}; use chrono::{DateTime, TimeDelta, Utc};
use futures::{StreamExt, future::BoxFuture, stream}; use futures::{StreamExt, future::BoxFuture, stream};
use gateway_core::task::{ScheduledTask, WorkerCycleContext, WorkerTaskError}; use gateway_core::task::{ScheduledTask, WorkerCycleContext, WorkerTaskError};
use gateway_core::{provider_ports::ProviderArtifactProfileCachePort, routing::ProviderKind}; use gateway_core::{provider_ports::ProviderArtifactProfileCachePort, routing::ProviderKind};
use serde::Deserialize; use serde::Deserialize;
use std::{ use std::{
collections::{BTreeMap, BTreeSet}, collections::{BTreeMap, BTreeSet},
path::PathBuf,
sync::{Arc, Mutex, RwLock}, sync::{Arc, Mutex, RwLock},
time::Duration, time::Duration,
}; };
@@ -20,32 +23,49 @@ const DESKTOP_PREFIX: &str = "https://storage.googleapis.com/antigravity-public/
const CLI_MANIFESTS: &str = const CLI_MANIFESTS: &str =
"https://antigravity-cli-auto-updater-974169037036.us-central1.run.app/manifests"; "https://antigravity-cli-auto-updater-974169037036.us-central1.run.app/manifests";
const MAX_RELEASE_BYTES: usize = 2 * 1024 * 1024; const MAX_RELEASE_BYTES: usize = 2 * 1024 * 1024;
const RELEASE_CHECK_INTERVAL: TimeDelta = TimeDelta::hours(1);
#[derive(Clone, Default)] #[derive(Clone, Default)]
pub(crate) struct ReleaseSnapshot { pub(crate) struct ReleaseSnapshot {
pub(crate) release: Option<Release>, pub(crate) candidate: Option<Release>,
pub(crate) checked: Option<DateTime<Utc>>, pub(crate) checked: Option<DateTime<Utc>>,
pub(crate) failed: bool, pub(crate) discovery_failed: bool,
pub(crate) verification_failed: bool,
verified: Option<VerifiedArtifact>, verified: Option<VerifiedArtifact>,
} }
impl ReleaseSnapshot { 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>> { pub(crate) fn verified_at(&self, version: &str) -> Option<DateTime<Utc>> {
self.verified self.verified
.as_ref() .as_ref()
.filter(|verified| { .filter(|verified| verified.release.version == version)
verified.release.version == version
&& self.release.as_ref() == Some(&verified.release)
})
.map(|v| v.verified_at) .map(|v| v.verified_at)
} }
pub(crate) fn version(&self, client: ClientKind) -> &str { pub(crate) fn pending_verification(&self) -> bool {
self.release self.candidate.is_some()
.as_ref() && self.candidate.as_ref() != self.verified.as_ref().map(|artifact| &artifact.release)
.map_or(client.baseline().version, |release| {
release.version.as_str()
})
} }
} }
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 { pub(crate) struct ReleaseService {
client: reqwest::Client, client: reqwest::Client,
state: RwLock<BTreeMap<ReleaseTarget, ReleaseSnapshot>>, state: RwLock<BTreeMap<ReleaseTarget, ReleaseSnapshot>>,
@@ -55,6 +75,7 @@ pub(crate) struct ReleaseService {
impl ReleaseService { impl ReleaseService {
pub(crate) fn new( pub(crate) fn new(
cache: Arc<dyn ProviderArtifactProfileCachePort>, cache: Arc<dyn ProviderArtifactProfileCachePort>,
artifact_dir: PathBuf,
) -> Result<Self, ConfigError> { ) -> Result<Self, ConfigError> {
let client = gateway_egress::http_client(None) let client = gateway_egress::http_client(None)
.map_err(|_| ConfigError)? .map_err(|_| ConfigError)?
@@ -70,6 +91,7 @@ impl ReleaseService {
verification: VerificationCache::new( verification: VerificationCache::new(
ProviderKind::new("antigravity").map_err(|_| ConfigError)?, ProviderKind::new("antigravity").map_err(|_| ConfigError)?,
cache, cache,
artifact_dir,
), ),
}) })
} }
@@ -85,16 +107,40 @@ impl ReleaseService {
.cloned() .cloned()
.unwrap_or_default() .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 let mut state = self
.state .state
.write() .write()
.unwrap_or_else(std::sync::PoisonError::into_inner); .unwrap_or_else(std::sync::PoisonError::into_inner);
let entry = state.entry(target).or_default(); let entry = state.entry(target).or_default();
entry.checked = Some(Utc::now()); entry.checked = Some(Utc::now());
entry.failed = result.is_none(); entry.discovery_failed = result.is_none();
if let Some(release) = result { 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> { async fn fetch(&self, url: &str) -> Result<Vec<u8>, WorkerTaskError> {
@@ -124,15 +170,16 @@ impl ReleaseService {
} }
pub(crate) async fn update(&self) -> Result<(), WorkerTaskError> { pub(crate) async fn update(&self) -> Result<(), WorkerTaskError> {
let due = { let due = {
let now = Utc::now();
let state = self let state = self
.state .state
.read() .read()
.unwrap_or_else(std::sync::PoisonError::into_inner); .unwrap_or_else(std::sync::PoisonError::into_inner);
state.is_empty() state.is_empty()
|| state.values().any(|s| { || state.values().any(|s| {
s.failed s.discovery_failed
|| s.checked || 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 { let mut first_error = if due {
@@ -150,23 +197,31 @@ impl ReleaseService {
let mut verification = stream::iter(targets) let mut verification = stream::iter(targets)
.map(|target| async move { .map(|target| async move {
let snapshot = self.snapshot(target); let snapshot = self.snapshot(target);
let Some(release) = snapshot.release.as_ref() else { let Some(release) = snapshot.candidate.as_ref() else {
return Ok(()); return Ok(());
}; };
let verified = self let verified = self
.verification .verification
.verify(&self.client, target, release, snapshot.verified.as_ref()) .verify(&self.client, target, release, snapshot.verified.as_ref())
.await?; .await;
let mut state = self let mut state = self
.state .state
.write() .write()
.unwrap_or_else(std::sync::PoisonError::into_inner); .unwrap_or_else(std::sync::PoisonError::into_inner);
if let Some(current) = state.get_mut(&target) let Some(current) = state
&& current.release.as_ref() == Some(&verified.release) .get_mut(&target)
{ .filter(|current| current.candidate.as_ref() == Some(release))
current.verified = Some(verified); 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); .buffer_unordered(2);
while let Some(result) = verification.next().await { while let Some(result) = verification.next().await {
@@ -179,39 +234,23 @@ impl ReleaseService {
async fn refresh(&self) -> Result<(), WorkerTaskError> { async fn refresh(&self) -> Result<(), WorkerTaskError> {
let page = self.fetch(DOWNLOAD_PAGE).await; let page = self.fetch(DOWNLOAD_PAGE).await;
let mut first_error = None; let mut first_error = None;
for platform in [Platform::Macos, Platform::Linux, Platform::Windows] { for target in targets(ClientKind::Desktop) {
for arch in [Architecture::Arm64, Architecture::Amd64] { let release = page
let target = ReleaseTarget { .as_ref()
client: ClientKind::Desktop, .ok()
platform, .and_then(|page| std::str::from_utf8(page).ok())
arch, .and_then(|page| parse_desktop(page, target));
}; if release.is_none() {
let release = page first_error = Some(WorkerTaskError::safe(
.as_ref() "无法解析 Antigravity Desktop 发布资料",
.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);
} }
self.observe(target, release);
} }
if let Err(error) = page { if let Err(error) = page {
first_error = Some(error); first_error = Some(error);
} }
let targets = [Platform::Macos, Platform::Linux, Platform::Windows] let mut updates = stream::iter(targets(ClientKind::Cli))
.into_iter()
.flat_map(|platform| {
[Architecture::Arm64, Architecture::Amd64].map(move |arch| ReleaseTarget {
client: ClientKind::Cli,
platform,
arch,
})
});
let mut updates = stream::iter(targets)
.map(|target| async move { .map(|target| async move {
let url = format!( let url = format!(
"{CLI_MANIFESTS}/{}_{}.json", "{CLI_MANIFESTS}/{}_{}.json",
@@ -222,7 +261,7 @@ impl ReleaseService {
.fetch(&url) .fetch(&url)
.await .await
.and_then(|body| parse_cli(&body, target)); .and_then(|body| parse_cli(&body, target));
self.publish(target, result.as_ref().ok().cloned()); self.observe(target, result.as_ref().ok().cloned());
result result
}) })
.buffer_unordered(3); .buffer_unordered(3);
@@ -1,6 +1,5 @@
//! 客户端选择与冻结身份,不读取网络或运行时设置 //! 客户端选择与冻结身份,不读取网络或运行时设置
use chrono::{DateTime, TimeZone, Utc};
use gateway_admin::ports::provider::{ProviderAdminError, ProviderAdminErrorKind}; use gateway_admin::ports::provider::{ProviderAdminError, ProviderAdminErrorKind};
use gateway_core::account::OpaqueProviderData; use gateway_core::account::OpaqueProviderData;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
@@ -12,10 +11,6 @@ pub(crate) enum ClientKind {
Desktop, Desktop,
Cli, Cli,
} }
pub(crate) struct ClientBuild {
pub(crate) version: &'static str,
changelist: u64,
}
impl ClientKind { impl ClientKind {
pub(crate) const fn product(self) -> &'static str { pub(crate) const fn product(self) -> &'static str {
match self { match self {
@@ -23,17 +18,10 @@ impl ClientKind {
Self::Cli => "Antigravity CLI", Self::Cli => "Antigravity CLI",
} }
} }
pub(crate) const fn baseline(self) -> ClientBuild { pub(crate) const fn baseline(self) -> &'static str {
// 版本与 CL 成对取自官方二进制及已认证请求,下载目录的编号不是 CL
match self { match self {
Self::Desktop => ClientBuild { Self::Desktop => "2.37.0",
version: "2.34.0", Self::Cli => "1.5.23",
changelist: 1_026_637_980,
},
Self::Cli => ClientBuild {
version: "1.5.17",
changelist: 1_029_496_841,
},
} }
} }
const fn subclient(self) -> &'static str { const fn subclient(self) -> &'static str {
@@ -142,19 +130,15 @@ impl Selection {
arch: self.arch.unwrap_or_else(|| self.platform.default_arch()), 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 version = self.client_version.as_deref().unwrap_or(latest);
let baseline = self.client.baseline();
ClientProfile { ClientProfile {
client: self.client, client: self.client,
platform: self.platform, platform: self.platform,
arch: self.target().arch, arch: self.target().arch,
client_version: version.into(), client_version: version.into(),
// 发布资料只有版本号;未知版本不沿用另一个版本的构建号 // 固定版本不能借用其他版本制品中的 CL
changelist: match (self.client, version) { changelist: changelist.filter(|cl| version == latest && *cl > 0),
(ClientKind::Cli, "1.5.15") => Some(1_027_820_220),
_ => (version == baseline.version).then_some(baseline.changelist),
},
system_prompt: self system_prompt: self
.system_prompt .system_prompt
.as_deref() .as_deref()
@@ -195,22 +179,6 @@ impl ClientProfile {
pub(crate) fn frozen(&self) -> OpaqueProviderData { pub(crate) fn frozen(&self) -> OpaqueProviderData {
object(json!(self)) 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 { pub(crate) fn client_identifier(&self) -> String {
format!( format!(
"antigravity/{}/{}", "antigravity/{}/{}",
@@ -232,6 +200,7 @@ impl ClientProfile {
// CLI 的个人 OAuth 身份携带此字段;Desktop 的已认证请求未携带 // CLI 的个人 OAuth 身份携带此字段;Desktop 的已认证请求未携带
user_agent.push_str("; auth_method=consumer"); user_agent.push_str("; auth_method=consumer");
} }
// datacollection_opt_in=false 属于官方管理员强制关闭遥测的策略,不能由普通遥测开关推导
user_agent.push(')'); user_agent.push(')');
user_agent user_agent
} }
@@ -251,7 +220,7 @@ fn invalid() -> ProviderAdminError {
.with_public_message("Antigravity 客户端配置无效;固定版本须为三段数字") .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."; 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> { fn validate_system_prompt(prompt: &str) -> Result<(), ProviderAdminError> {
@@ -2,7 +2,7 @@
use super::{ use super::{
artifact::{self, Release}, artifact::{self, Release},
selection::ReleaseTarget, selection::{ReleaseTarget, valid_version},
}; };
use chrono::{DateTime, Utc}; use chrono::{DateTime, Utc};
use gateway_core::{ use gateway_core::{
@@ -13,6 +13,7 @@ use gateway_core::{
}; };
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::{ use std::{
path::PathBuf,
sync::Arc, sync::Arc,
time::{Duration, Instant}, time::{Duration, Instant},
}; };
@@ -23,8 +24,9 @@ const RENEW_INTERVAL: Duration = Duration::from_secs(86400);
#[derive(Clone)] #[derive(Clone)]
pub(crate) struct VerifiedArtifact { pub(crate) struct VerifiedArtifact {
pub(crate) release: Release, pub(crate) release: Release,
pub(crate) changelist: u64,
pub(crate) verified_at: DateTime<Utc>, pub(crate) verified_at: DateTime<Utc>,
renewed_at: Instant, renewed_at: Option<Instant>,
} }
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
@@ -32,18 +34,59 @@ pub(crate) struct VerifiedArtifact {
struct Payload { struct Payload {
target: ReleaseTarget, target: ReleaseTarget,
release: Release, release: Release,
changelist: u64,
} }
pub(crate) struct VerificationCache { pub(crate) struct VerificationCache {
provider: ProviderKind, provider: ProviderKind,
cache: Arc<dyn ProviderArtifactProfileCachePort>, cache: Arc<dyn ProviderArtifactProfileCachePort>,
artifact_dir: PathBuf,
} }
impl VerificationCache { impl VerificationCache {
pub(crate) fn new( pub(crate) fn new(
provider: ProviderKind, provider: ProviderKind,
cache: Arc<dyn ProviderArtifactProfileCachePort>, cache: Arc<dyn ProviderArtifactProfileCachePort>,
artifact_dir: PathBuf,
) -> Self { ) -> 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( pub(crate) async fn verify(
@@ -54,59 +97,43 @@ impl VerificationCache {
previous: Option<&VerifiedArtifact>, previous: Option<&VerifiedArtifact>,
) -> Result<VerifiedArtifact, WorkerTaskError> { ) -> Result<VerifiedArtifact, WorkerTaskError> {
let sequence = sequence(&release.version)?; let sequence = sequence(&release.version)?;
if let Some(previous) = previous.filter(|previous| previous.release == *release) if let Some(previous) = previous {
&& previous.renewed_at.elapsed() < RENEW_INTERVAL validate_successor(previous, release, sequence)?;
{ if previous.release == *release
return Ok(previous.clone()); && previous
.renewed_at
.is_some_and(|at| at.elapsed() < RENEW_INTERVAL)
{
return Ok(previous.clone());
}
} }
let key = key(target); let cached = self.load(target).await?;
let cached = self if let Some(cached) = &cached {
.cache validate_successor(cached, release, sequence)?;
.read(&self.provider, &key) }
.await let matching = cached
.map_err(|e| error().with_source(e))?; .as_ref()
let verified_at = if let Some(cached) = cached { .filter(|v| v.release == *release)
let payload: Payload = serde_json::from_value(serde_json::Value::Object( .or_else(|| previous.filter(|v| v.release == *release));
cached.profile().expose_to_provider().clone(), let (verified_at, changelist) = match matching {
)) Some(artifact) => (artifact.verified_at, artifact.changelist),
.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,
None => { None => {
artifact::verify( let changelist = artifact::verify(
client, client,
target, target,
&release.version, &release.version,
&release.url, &release.url,
release.sha512.as_deref(), release.sha512.as_deref(),
&self.artifact_dir,
) )
.await?; .await?;
Utc::now() (Utc::now(), changelist)
} }
}; };
let payload = serde_json::to_value(Payload { let payload = serde_json::to_value(Payload {
target, target,
release: release.clone(), release: release.clone(),
changelist,
}) })
.map_err(|e| error().with_source(e))?; .map_err(|e| error().with_source(e))?;
let serde_json::Value::Object(payload) = payload else { let serde_json::Value::Object(payload) = payload else {
@@ -114,7 +141,7 @@ impl VerificationCache {
}; };
let profile = ProviderArtifactProfile::new( let profile = ProviderArtifactProfile::new(
self.provider.clone(), self.provider.clone(),
key, key(target),
sequence, sequence,
verified_at.into(), verified_at.into(),
OpaqueProviderData::new(payload), OpaqueProviderData::new(payload),
@@ -129,19 +156,36 @@ impl VerificationCache {
} }
Ok(VerifiedArtifact { Ok(VerifiedArtifact {
release: release.clone(), release: release.clone(),
changelist,
verified_at, 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 { pub(crate) fn key(target: ReleaseTarget) -> String {
let client = match target.client { let client = match target.client {
super::selection::ClientKind::Desktop => "desktop", super::selection::ClientKind::Desktop => "desktop",
super::selection::ClientKind::Cli => "cli", super::selection::ClientKind::Cli => "cli",
}; };
format!( format!(
"{client}-{}-{}", "build-v1-{client}-{}-{}",
target.platform.os_type(), target.platform.os_type(),
target.arch.label() target.arch.label()
) )
@@ -14,33 +14,39 @@ use serde_json::{Value, json};
pub(crate) fn options() -> OpaqueProviderData { 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<_>>(); 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( 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 { pub(crate) fn dashboard(selection: &Selection, releases: &ReleaseService) -> DashboardWireProfile {
let snapshot = releases.snapshot(selection.target()); 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 fixed = selection.version_mode == VersionMode::Fixed;
let release = (!fixed).then(|| DashboardDesktopRelease { let release = (!fixed).then(|| DashboardDesktopRelease {
status: if snapshot.failed { status: if snapshot.discovery_failed || snapshot.verification_failed {
DesktopReleaseStatus::Failed DesktopReleaseStatus::Failed
} else if snapshot.release.is_none() { } else if snapshot.candidate.is_none() {
DesktopReleaseStatus::Unchecked DesktopReleaseStatus::Unchecked
} else if snapshot.pending_verification() {
DesktopReleaseStatus::UpdateAvailable
} else { } else {
DesktopReleaseStatus::Current DesktopReleaseStatus::Current
}, },
checked_at: snapshot.checked, checked_at: snapshot.checked,
latest_version: snapshot.release.as_ref().map(|r| r.version.clone()), latest_version: snapshot.candidate.as_ref().map(|r| r.version.clone()),
latest_build: snapshot.release.as_ref().and_then(|r| r.build.clone()), latest_build: snapshot.candidate.as_ref().and_then(|r| r.build.clone()),
download_url: snapshot.release.as_ref().map(|r| r.url.clone()), download_url: snapshot.candidate.as_ref().map(|r| r.url.clone()),
published_at: None, published_at: None,
minimum_system_version: None, minimum_system_version: None,
hardware_requirements: None, hardware_requirements: None,
download_size: None, download_size: None,
signature_present: None, signature_present: None,
error: snapshot error: if snapshot.discovery_failed {
.failed Some("无法读取 Google 官方客户端版本".into())
.then(|| "无法读取 Google 官方客户端版本".into()), } else if snapshot.verification_failed {
Some("无法核验 Google 官方客户端发布包".into())
} else {
None
},
}); });
DashboardWireProfile { DashboardWireProfile {
provider: "antigravity".into(), provider: "antigravity".into(),
@@ -65,9 +71,7 @@ pub(crate) fn dashboard(selection: &Selection, releases: &ReleaseService) -> Das
], ],
user_agent: profile.user_agent(), user_agent: profile.user_agent(),
release, release,
verified_at: snapshot verified_at: snapshot.verified_at(&profile.client_version),
.verified_at(&profile.client_version)
.or_else(|| profile.verified_at()),
} }
} }
pub(crate) fn preview( pub(crate) fn preview(
@@ -137,6 +137,7 @@ impl AntigravityProvider {
}; };
let body = operation.middleware_body().map_err(|_| unsent(Kind::InvalidRequest))?; let body = operation.middleware_body().map_err(|_| unsent(Kind::InvalidRequest))?;
let translated_chat = translator.is_some(); let translated_chat = translator.is_some();
let native_error = !translated_chat && count_translator.is_none();
let events = async_stream::try_stream! { let events = async_stream::try_stream! {
if cancellation.is_cancelled() { if cancellation.is_cancelled() {
Err(unsent(Kind::Cancelled))?; Err(unsent(Kind::Cancelled))?;
@@ -144,12 +145,12 @@ impl AntigravityProvider {
if deadline.is_elapsed() { if deadline.is_elapsed() {
Err(unsent(Kind::Timeout))?; Err(unsent(Kind::Timeout))?;
} }
let probe_token = (terminal_context.account_eligibility() == AccountEligibilityPolicy::BypassForDiagnostic) let error_token = selected.material.token().to_owned();
.then(|| selected.material.token().to_owned());
let record_failure = async |error| { let record_failure = async |error| {
let error = match &probe_token { let error = match terminal_context.account_eligibility() {
Some(token) => crate::transport::connection_test_error(error, token), AccountEligibilityPolicy::BypassForDiagnostic => crate::transport::connection_test_error(error, &error_token),
None => error, AccountEligibilityPolicy::Enforce => crate::transport::client_error(error, &error_token, native_error),
_ => error,
}; };
feedback.record_failure(&selected.account, &model, records_account_feedback, error).await feedback.record_failure(&selected.account, &model, records_account_feedback, error).await
}; };
@@ -18,42 +18,29 @@ impl AntigravityProvider {
records_account_feedback: bool, records_account_feedback: bool,
error: ProviderError, error: ProviderError,
) -> ProviderError { ) -> ProviderError {
if error.send_state() != UpstreamSendState::Sent if error.send_state() != UpstreamSendState::Sent {
|| !matches!(error.kind(), Kind::Unauthorized | Kind::RateLimited)
{
return error; return error;
} }
// 明确拒绝没有生成结果;换号仍受 Core 的交付屏障、范围与预算约束 // 明确拒绝没有生成结果;换号仍受 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 { if !records_account_feedback {
return error; return error;
} }
crate::credential::record_account_failure(self.accounts.as_ref(), account, &error).await;
let feedback = async { let feedback = async {
match error.kind() { match error.kind() {
Kind::Unauthorized => { Kind::RateLimited | Kind::QuotaExhausted | Kind::UpstreamCapacityUnavailable => {
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 => {
if let Some(until) = error if let Some(until) = error
.retry_after() .retry_after()
.and_then(|delay| SystemTime::now().checked_add(delay)) .and_then(|delay| SystemTime::now().checked_add(delay))
@@ -103,30 +103,43 @@ struct RefreshTask {
impl ScheduledTask for RefreshTask { impl ScheduledTask for RefreshTask {
fn run_cycle(&self, context: WorkerCycleContext) -> BoxFuture<'_, Result<(), WorkerTaskError>> { fn run_cycle(&self, context: WorkerCycleContext) -> BoxFuture<'_, Result<(), WorkerTaskError>> {
Box::pin(async move { Box::pin(async move {
let (candidates, concurrency) = self.credentials.refresh_candidates().await?; let cancellation = context.cancellation();
if candidates.is_empty() || context.cancellation().is_cancelled() { 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(()); return Ok(());
} }
let mut catalogs = self let Some(catalogs) = cancellation
.catalog .run_until_cancelled(self.catalog.capture_refresh_catalogs(&candidates))
.capture_refresh_catalogs(&candidates)
.await .await
.unwrap_or_else(|_| { else {
tracing::warn!("Antigravity 目录读取失败,凭据续期后重新查询目录"); return Ok(());
Default::default() };
}); let mut catalogs = catalogs.unwrap_or_else(|_| {
tracing::warn!("Antigravity 目录读取失败,凭据续期后重新查询目录");
Default::default()
});
let mut updates = stream::iter(candidates) let mut updates = stream::iter(candidates)
.map(|loaded| { .map(|loaded| {
let cancellation = context.cancellation();
let catalog = catalogs.remove(loaded.account.id()); let catalog = catalogs.remove(loaded.account.id());
async move { async move {
if cancellation.is_cancelled() { if cancellation.is_cancelled() {
return Ok(()); return Ok(());
} }
let revision = self.credentials.refresh_due(&loaded).await?; let revision = self.credentials.refresh_due(&loaded).await?;
self.catalog cancellation
.after_credential_refresh(loaded.account.id(), revision, catalog) .run_until_cancelled(self.catalog.after_credential_refresh(
loaded.account.id(),
revision,
catalog,
))
.await .await
.unwrap_or(Ok(()))
} }
}) })
.buffer_unordered(concurrency); .buffer_unordered(concurrency);
@@ -368,7 +368,16 @@ pub(super) async fn control<T: DeserializeOwned>(
} }
data.extend_from_slice(&chunk); 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)] #[derive(Deserialize)]
@@ -35,6 +35,9 @@ pub(crate) fn count_events(
body.extend_from_slice(&chunk); body.extend_from_slice(&chunk);
} }
let value: Value = serde_json::from_slice(&body).map_err(|_| sent(Kind::Protocol))?; 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 // Cloud Code 的 protobuf JSON 会省略零值;公开计数接口显式交付 totalTokens
if value.as_object().is_some_and(serde_json::Map::is_empty) { if value.as_object().is_some_and(serde_json::Map::is_empty) {
body = br#"{"totalTokens":0}"#.to_vec(); body = br#"{"totalTokens":0}"#.to_vec();
@@ -2,10 +2,10 @@
use gateway_core::{ use gateway_core::{
error::{ error::{
ClientVisibleUpstreamError, GatewayError, ProviderError, ProviderErrorKind as Kind, ClientVisibleUpstreamError, ClientVisibleUpstreamResponse, GatewayError,
RawUpstreamError, OpaqueUpstreamValue, ProviderError, ProviderErrorKind as Kind, RawUpstreamError,
}, },
upstream::UpstreamSendState, upstream::{UpstreamFailureFields, UpstreamSendState},
}; };
use reqwest::{Response, StatusCode}; use reqwest::{Response, StatusCode};
use serde_json::Value; 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 { 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 document = serde_json::from_str::<Value>(body).ok();
let error = sent(status.map_or(Kind::Unavailable, status_kind)); let failure = document.as_ref().and_then(google_error);
let error = if let Some(status) = status { let status = status
error.with_status(status.as_u16()) .filter(|code| (400..=599).contains(code))
} else { .or_else(|| failure.and_then(rpc_status));
error 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) attach_body(error, body, token)
} }
fn attach_body(error: ProviderError, body: &str, token: &str) -> ProviderError { 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() { if body.is_empty() {
return error; 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 end = body.floor_char_boundary(MAX_ERROR_BYTES.min(body.len()));
let text = if end < body.len() { let text = if end < body.len() {
format!("{}\n[truncated]", &body[..end]) 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 { let Some(failure) = google_error(&document) else {
return error; return error;
}; };
let info = google_error_detail(failure, "type.googleapis.com/google.rpc.ErrorInfo"); let info = error_info(failure);
let safe_text = |value: &Value| { let safe_text = |value: &Value| {
value value
.as_str() .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 document
.get("error") .get("error")
.or_else(|| document.pointer("/response/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> { fn google_error_detail<'a>(error: &'a Value, kind: &str) -> Option<&'a Value> {
error error
.get("details")? .get("details")?
@@ -177,10 +403,6 @@ pub(super) async fn successful(
.get(reqwest::header::RETRY_AFTER) .get(reqwest::header::RETRY_AFTER)
.and_then(|v| v.to_str().ok()) .and_then(|v| v.to_str().ok())
.and_then(retry_after); .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 body = Vec::new();
let mut truncated = false; let mut truncated = false;
let read = tokio::time::timeout(Duration::from_secs(10), async { let read = tokio::time::timeout(Duration::from_secs(10), async {
@@ -195,14 +417,25 @@ pub(super) async fn successful(
Ok::<_, reqwest::Error>(()) Ok::<_, reqwest::Error>(())
}) })
.await; .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 { match read {
Ok(Ok(())) => {} Ok(Ok(())) => {}
Ok(Err(source)) => error = error.with_source(source.without_url()), Ok(Err(source)) => error = error.with_source(source.without_url()),
Err(source) => error = error.with_source(source), Err(source) => error = error.with_source(source),
} }
let text = String::from_utf8_lossy(&body).into_owned();
if truncated { if truncated {
return Err(error.redact_sensitive_context(&text)); 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 api_key::GenAiClient;
pub(crate) use client::{Catalog, CloudCodeClient, GenerateMode, Model, unwrap_frame}; pub(crate) use client::{Catalog, CloudCodeClient, GenerateMode, Model, unwrap_frame};
pub(crate) use count::count_events; 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 headers::request_headers;
pub(crate) use pool::ClientPool; pub(crate) use pool::ClientPool;
pub(crate) use response::{ResponseContext, events, genai_events}; pub(crate) use response::{ResponseContext, events, genai_events};
@@ -23,6 +23,10 @@ pub(super) fn request_body(
edit_object( edit_object(
raw, raw,
|name, value| { |name, value| {
// Gateway 入口的本地状态不能声明成 OAuth 生成请求字段;正文和工具参数不递归改写
if matches!(name, "hasFingerprintSet" | "has_fingerprint_set") {
return Ok(Edit::Remove);
}
// 合并到已有的字段处理,避免为签名再解析、复制和校验整个请求 // 合并到已有的字段处理,避免为签名再解析、复制和校验整个请求
if name == "contents" { if name == "contents" {
return super::signatures::prepare_contents(value, model); return super::signatures::prepare_contents(value, model);
@@ -46,7 +46,11 @@ pub(super) async fn fixture() -> (MockServer, CredentialService, Arc<MemoryPorts
runtime_policy: store.clone(), runtime_policy: store.clone(),
credential_state: store.clone(), credential_state: store.clone(),
release: Arc::new( 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( oauth: Arc::new(GoogleOAuth::with_endpoints(
config, 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() { async fn import_resolves_scopes_and_freezes_global_profile_until_the_next_refresh() {
let (server, credentials, store) = fixture().await; let (server, credentials, store) = fixture().await;
*store.request_profile.lock().unwrap() = Some(crate::profile::object(json!({ *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(); let mut response = token_response();
response.as_object_mut().unwrap().remove("scope"); 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 { for request in requests {
assert_eq!( assert_eq!(
request.headers["user-agent"], 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; server.verify().await;
@@ -10,7 +10,7 @@ use wiremock::{
pub(crate) async fn refreshed_credential(server: &MockServer) -> (Url, String) { pub(crate) async fn refreshed_credential(server: &MockServer) -> (Url, String) {
let origin = server.uri(); 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(); 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(); config.validate().unwrap();
let oauth = GoogleOAuth::with_endpoints( let oauth = GoogleOAuth::with_endpoints(
@@ -8,12 +8,17 @@ mod api_key_tests;
mod authorization; mod authorization;
#[path = "../../src/credential/documents.rs"] #[path = "../../src/credential/documents.rs"]
mod documents; mod documents;
#[path = "../../src/credential/failure.rs"]
mod failure;
pub(crate) use failure::record_account_failure;
#[path = "../../src/credential/model_groups.rs"] #[path = "../../src/credential/model_groups.rs"]
mod model_groups; mod model_groups;
#[path = "../../src/credential/oauth.rs"] #[path = "../../src/credential/oauth.rs"]
pub(crate) mod oauth; pub(crate) mod oauth;
#[path = "../../src/credential/refresh.rs"] #[path = "../../src/credential/refresh.rs"]
mod refresh; mod refresh;
#[path = "refresh.rs"]
mod refresh_tests;
#[path = "../../src/credential/service.rs"] #[path = "../../src/credential/service.rs"]
mod service; mod service;
pub(crate) use authorization::AuthorizationService; 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 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( let oauth = GoogleOAuth::with_endpoints(
serde_json::from_value(registration()).unwrap(), serde_json::from_value(registration()).unwrap(),
&format!("{}/token", server.uri()), &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; upstream(&server, json!(0.5), Duration::ZERO).await;
let f = Fixture::new(&server.uri()); let f = Fixture::new(&server.uri());
let account = f.store.primary().loaded.lock().unwrap().account.clone(); 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( *f.store.request_profile.lock().unwrap() = Some(crate::profile::object(
json!({"client":"cli","platform":"linux","versionMode":"fixed","clientVersion":version,"arch":null}), 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), request(false),
context( context(
crate::profile::Selection::default() crate::profile::Selection::default()
.resolve("2.34.0") .resolve("2.34.0", None)
.frozen(), .frozen(),
CancellationToken::new(), CancellationToken::new(),
), ),
@@ -453,7 +453,7 @@ async fn peer_model_facts_keep_membership_quota_and_revision_separate() {
crate::support::request(false), crate::support::request(false),
crate::support::context( crate::support::context(
crate::profile::Selection::default() crate::profile::Selection::default()
.resolve("2.34.0") .resolve("2.34.0", None)
.frozen(), .frozen(),
CancellationToken::new(), CancellationToken::new(),
), ),
@@ -539,7 +539,7 @@ async fn google_one_credits_require_opt_in_and_sufficient_balance() {
request(false), request(false),
context( context(
crate::profile::Selection::default() crate::profile::Selection::default()
.resolve("2.34.0") .resolve("2.34.0", None)
.frozen(), .frozen(),
CancellationToken::new(), 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"
);
}

Some files were not shown because too many files have changed in this diff Show More