mirror of
https://github.com/zyycn/codex-proxy-rs.git
synced 2026-12-01 16:01:04 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2bf0ca146d | ||
|
|
5c1e27fc47 | ||
|
|
03f21c26eb | ||
|
|
280ded5707 | ||
|
|
8fb07f993c | ||
|
|
ee691246c7 | ||
|
|
e406a6bcd8 | ||
|
|
4ffaeb3051 | ||
|
|
a126c194f5 | ||
|
|
964e22eb91 | ||
|
|
5a5d07d1c7 | ||
|
|
a41a0498d1 | ||
|
|
9aea228fa8 | ||
|
|
25965cbfb3 | ||
|
|
fa0bedd28b | ||
|
|
1bd27ef6c8 | ||
|
|
0981996ef3 | ||
|
|
783e4578ba | ||
|
|
0db3c6a215 | ||
|
|
fe1c38aeb7 | ||
|
|
2cbdd62b4e | ||
|
|
39cc23d2f0 | ||
|
|
102131056b | ||
|
|
c94a443620 | ||
|
|
ef870690e3 | ||
|
|
f4254104c9 | ||
|
|
36136728c6 | ||
|
|
0d731c5059 | ||
|
|
3fe4248fd6 | ||
|
|
3cc9c71ab5 | ||
|
|
2dc3ba8d56 | ||
|
|
7c16190936 | ||
|
|
c89152ce08 | ||
|
|
4b8825a28f | ||
|
|
95a89e9010 |
@@ -1,6 +1,6 @@
|
||||
---
|
||||
name: cpr-dev-guide
|
||||
description: Codex Proxy RS 的需求评估、排障、开发、代码审查与文档维护入口
|
||||
description: Codex Proxy RS 的需求评估、排障、开发、代码审查与文档维护,包括对代码和文档改动的验收
|
||||
---
|
||||
|
||||
# 开发指南
|
||||
@@ -22,9 +22,9 @@ description: Codex Proxy RS 的需求评估、排障、开发、代码审查与
|
||||
|
||||
## 先确定领域与必读规范
|
||||
|
||||
按受影响行为和实际文件执行下表所有命中项。流程引用首次完整读取,长文档按标题定位指定章节
|
||||
确定方案前按受影响行为和实际文件执行下表所有命中项。流程引用首次完整读取,长文档按标题定位指定章节。单独验收和开发收尾采用同一组领域规范
|
||||
|
||||
| 领域或操作,行为影响与文件路径满足其一即可 | 确定方案前读取与执行 |
|
||||
| 领域或操作,行为影响与文件路径满足其一即可 | 必读规范与检查 |
|
||||
| --- | --- |
|
||||
| 调整页面、弹窗、表单、按钮、文案、样式或交互;目标在 `frontend/`、`modules/ui/`、插件前端,或是 `.vue` 文件 | [前端流程](references/frontend.md),局部修改同样按影响范围检查组件复用、文案、Token、样式、视觉状态和运行证据 |
|
||||
| 插件接入、SDK、Runtime、扩展接口或独立网关插件,含账号、调度或 API 中为插件新增的处理;目标在 `backend/crates/gateway-plugin/`、`modules/plugins/` | [插件职责边界](references/plugin-boundaries.md)及所用 [SDK](../../../backend/crates/gateway-plugin/sdk/README.md) 类型与能力合同;独立插件开发、排查或审查同时执行 [cpr-plugin-dev](../cpr-plugin-dev/SKILL.md) |
|
||||
@@ -41,11 +41,13 @@ description: Codex Proxy RS 的需求评估、排障、开发、代码审查与
|
||||
|
||||
## 执行与收尾
|
||||
|
||||
长任务按 [任务延续与收尾](../../../AGENTS.md#任务延续与收尾)恢复已匹配的领域、具体约束与验证进度。单独收到验收请求时,先确认待验收版本和范围,发现偏差按当前授权处理
|
||||
|
||||
1. 遵守已提供的 [AGENTS.md](../../../AGENTS.md),按其 CodeGraph 约定定位代码;确认工作区、任务范围与已有改动,找到事实归属、同类实现和调用链,补齐上表命中规范及[项目约定](../../../CONTRIBUTING.md#项目约定)对应条目后再修改
|
||||
2. 以最终差异重新匹配上表,补齐新增领域的规范并检查实际实现,再处理本次引入的职责越界、重复规则、冗余状态与无依据分支;删除或替换功能时一并清理失效的配置、类型、调用、测试与文档,已部署数据和公开合同仍遵守所属迁移及兼容规则;仅审查时报告,不自行修复
|
||||
2. 按最终差异与受影响行为重新匹配上表,逐项对照适用条款检查实际实现。处理本次引入的职责越界、重复规则、冗余状态与无依据分支;删除或替换功能时一并清理失效的配置、类型、调用、测试与文档,已部署数据和公开合同仍遵守所属迁移及兼容规则;仅审查时报告,不自行修复
|
||||
3. 模块移动或重命名时,同步核对源码、测试、公开导出及配置、脚本中的名称和路径引用;在本任务内更新受影响的文档、示例和引用
|
||||
4. 按变更范围执行[验证](../../../CONTRIBUTING.md#验证)及其停止条件,后端命令见[验证命令](../../../docs/architecture.md#验证命令);复用仍适用的验证证据与用户已确定的验收分工,区分通过、失败、跳过与未执行
|
||||
5. 交付前按[首要写作要求](#首要写作要求言简意赅)通读本次新增或修改的文字。交代实际结果与验证缺口;前端按[前端流程](references/frontend.md)核对运行证据,后端按上表检查生命周期,不把构建通过当作行为验收
|
||||
5. 交付前按[首要写作要求](#首要写作要求言简意赅)通读本次新增或修改的文字。验收结论同时依据规范核对结果与行为验证证据;有规范偏差或缺少必要证据时,指出具体位置或未验证场景。前端按[前端流程](references/frontend.md)核对运行证据,后端按上表检查生命周期
|
||||
6. 按授权完成提交与交付;提交前按[提交约定](../../../CONTRIBUTING.md#项目约定)准备提交信息与实际共同作者署名,提交后核对实际提交消息,PR 的 AI 披露不能替代提交署名
|
||||
|
||||
## 测试维护
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
interface:
|
||||
display_name: "cpr-dev-guide"
|
||||
short_description: "开发、排障与审查入口,按行为影响匹配领域边界并验证实现"
|
||||
default_prompt: "使用 $cpr-dev-guide 按请求、行为影响和实际文件匹配领域必读规范,读完职责边界再确定方案,完成已授权的开发或审查、自审与验证。"
|
||||
short_description: "开发、排障、审查与验收入口,按受影响行为匹配并执行领域规范"
|
||||
default_prompt: "使用 $cpr-dev-guide 按受影响行为和实际文件匹配领域规范,开发时据此确定方案,验收时对照最终实现和验证证据。"
|
||||
policy:
|
||||
allow_implicit_invocation: true
|
||||
|
||||
@@ -27,6 +27,7 @@ updates:
|
||||
# 按官方 Codex 锁文件、协议指纹或已审计 fork 固定;完成对应核对与实测后再手动升级。
|
||||
ignore:
|
||||
- dependency-name: aws-lc-rs
|
||||
- dependency-name: h2
|
||||
- dependency-name: hyper
|
||||
- dependency-name: hyper-rustls
|
||||
- dependency-name: hyper-tls
|
||||
@@ -71,6 +72,8 @@ updates:
|
||||
directories:
|
||||
- /deploy
|
||||
labels: []
|
||||
ignore:
|
||||
- dependency-name: rust
|
||||
schedule:
|
||||
interval: weekly
|
||||
day: monday
|
||||
|
||||
@@ -125,7 +125,7 @@ jobs:
|
||||
run: cargo clippy --all-targets --all-features --locked -- -D warnings
|
||||
|
||||
- name: Setup nextest
|
||||
uses: taiki-e/install-action@75a7c0f87bd666af3cdb75c5b9e9d03ab6044e6f # v2.90.6
|
||||
uses: taiki-e/install-action@073e1fd0bc889c9aee68dbaaa927cde1b5653a83 # v2.90.11
|
||||
with:
|
||||
tool: cargo-nextest@0.9.143
|
||||
fallback: none
|
||||
|
||||
@@ -115,7 +115,7 @@ jobs:
|
||||
cache-bin: false
|
||||
save-if: ${{ github.event_name != 'pull_request' }}
|
||||
- name: Setup nextest
|
||||
uses: taiki-e/install-action@75a7c0f87bd666af3cdb75c5b9e9d03ab6044e6f # v2.90.6
|
||||
uses: taiki-e/install-action@073e1fd0bc889c9aee68dbaaa927cde1b5653a83 # v2.90.11
|
||||
with:
|
||||
tool: cargo-nextest@0.9.143
|
||||
fallback: none
|
||||
@@ -434,7 +434,7 @@ jobs:
|
||||
uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1
|
||||
|
||||
- name: Install Cosign
|
||||
uses: sigstore/cosign-installer@756fe2d284c7292c4e9b62c8a28f1e5629c59532 # v4.1.3
|
||||
uses: sigstore/cosign-installer@881c63bd87e38389154debd8331404ce7ca8a3ab # v4.1.4
|
||||
|
||||
- name: Login to GHCR
|
||||
uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0
|
||||
|
||||
@@ -34,7 +34,7 @@ jobs:
|
||||
ref: ${{ inputs.ref || github.event.pull_request.head.sha || github.sha }}
|
||||
|
||||
- name: Install cargo-audit
|
||||
uses: taiki-e/install-action@75a7c0f87bd666af3cdb75c5b9e9d03ab6044e6f # v2.90.6
|
||||
uses: taiki-e/install-action@073e1fd0bc889c9aee68dbaaa927cde1b5653a83 # v2.90.11
|
||||
with:
|
||||
tool: cargo-audit@0.22.2
|
||||
fallback: none
|
||||
|
||||
@@ -4,13 +4,13 @@
|
||||
|
||||
| 任务意图与常见说法 | 必用技能 |
|
||||
| --- | --- |
|
||||
| 需求评估、排障、开发、修复、代码审查、改文档,包括“看下这个 Issue”“改弹窗/样式/文案”“修接口/调度/数据库” | [cpr-dev-guide](.agents/skills/cpr-dev-guide/SKILL.md),按实际操作和文件匹配规范,跨前后端同时执行 |
|
||||
| 需求评估、排障、开发、修复、代码审查、改文档、验收实现,包括“看下这个 Issue”“改弹窗/样式/文案”“修接口/调度/数据库”“验收一下这次改动” | [cpr-dev-guide](.agents/skills/cpr-dev-guide/SKILL.md),按实际操作和文件匹配规范,跨前后端同时执行 |
|
||||
| 提交/提个 PR、准备或更新 PR、看下 PR、回复 PR 讨论、处理 PR 审查意见 | [cpr-github-pr](.agents/skills/cpr-github-pr/SKILL.md);实现自审、审查或修改同时执行 cpr-dev-guide |
|
||||
| 提 Issue、反馈到仓库、把问题或建议整理成 Issue、补充或回复 Issue | [cpr-github-issue](.agents/skills/cpr-github-issue/SKILL.md) |
|
||||
| 写、修或审查独立网关插件,排查插件接入、打包插件 | [cpr-plugin-dev](.agents/skills/cpr-plugin-dev/SKILL.md),同时执行 cpr-dev-guide;仅改宿主能力时由 cpr-dev-guide 加载插件边界 |
|
||||
| 发版、准备版本、发布 beta/实验版、整理发布说明、打发行 tag | [cpr-release](.agents/skills/cpr-release/SKILL.md) |
|
||||
|
||||
结合上下文识别“提交吧”“看看这个问题”等省略说法:普通 Git 提交不自动变成 PR,代码排查不自动变成 Issue;审查与发版准备不代表获准远程写入
|
||||
结合当前任务判断“继续”“验收一下”等省略说法。验收代码或文档改动时执行开发指南;核对发布产物时走发版技能。普通 Git 提交不自动变成 PR,代码排查不自动变成 Issue;审查与发版准备不代表获准远程写入
|
||||
|
||||
首次命中技能时完整读取其 `SKILL.md`,再读取领域必读规范,之后按当前步骤补充实现、命令和示例。技能名称、描述或入口摘要不能代替首次读取的正文与必读引用;引用中明确要求“先读”“必须读取”或“执行”的规范也要落实,其他资料按需读取
|
||||
|
||||
@@ -26,7 +26,7 @@ Issue 和 PR 回复统一按 [GitHub 回复口吻](CONTRIBUTING.md#github-回复
|
||||
### 任务延续与收尾
|
||||
|
||||
- 在任务上下文和压缩摘要中保留目标、授权、当前阶段、已读规范的路径与关键约束、验证命令与结果及对应代码状态、剩余事项
|
||||
- 同一任务可复用实际完成的读取与验证记录;仅在规范变更、进入未覆盖领域或具体决策缺少条款时补读对应内容。输出截断只补缺失部分,上下文压缩与阶段切换本身不触发重读或重验
|
||||
- 续接任务时,从记录中恢复当前步骤适用的规范与待查项,核对已有证据对应的实现。规范变更、进入新领域或缺少具体约束时补读对应条款,输出截断只补缺失部分。已有证据仍适用的检查直接复用
|
||||
- 远端更新或合并冲突后,按实际变更及其依赖影响补充自审和验证,复用未受影响的证据
|
||||
- 实现、自审与必要验证完成后,按[验证停止条件](CONTRIBUTING.md#验证)停止扩围;完成已获授权的剩余交付步骤并确认结果后结束
|
||||
|
||||
|
||||
+1
-1
@@ -55,7 +55,7 @@ AI 开发和审查入口是根目录的 [AGENTS.md](AGENTS.md)。在仓库上下
|
||||
### 项目技能
|
||||
|
||||
仓库技能位于 `.agents/skills/`,随代码共享。技能提供执行流程,协作与审查标准仍以本文和 `AGENTS.md` 为准。
|
||||
AI 开发、排查、代码审查和文档修改必须执行 `cpr-dev-guide`;准备、创建、更新及审查 PR 必须执行 `cpr-github-pr`,不以用户是否显式点名技能为条件。PR 内修复仍须经过开发流程,不能用填写 PR 正文代替实现自审与验证
|
||||
AI 开发、排查、代码审查、文档修改及对这些改动的验收必须执行 `cpr-dev-guide`;准备、创建、更新及审查 PR 必须执行 `cpr-github-pr`,不以用户是否显式点名技能为条件。PR 内修复仍须经过开发流程,不能用填写 PR 正文代替实现自审与验证
|
||||
|
||||
| 技能 | 用途 | 调用示例 |
|
||||
| --- | --- | --- |
|
||||
|
||||
Generated
+42
-40
@@ -153,9 +153,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "async-compression"
|
||||
version = "0.4.52"
|
||||
version = "0.4.54"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6ad47a740fb906fffdd891e8b6d5fde2511600f7bfaebd68939fa08a14999459"
|
||||
checksum = "0c31224bd2c09447484a1143f2fc1d871eb405789859c8e5470a3e7f95f40a18"
|
||||
dependencies = [
|
||||
"compression-codecs",
|
||||
"compression-core",
|
||||
@@ -292,9 +292,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "aws-sdk-s3"
|
||||
version = "1.161.0"
|
||||
version = "1.162.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d9c63e3ca6e56670513469e992759f4a51041603fde329471b29c5c1f5eaeefe"
|
||||
checksum = "4ffd93a622eaef65d9dee213b1c8afb8b5d999aa2020fe1c9ba6a94ec5e973e4"
|
||||
dependencies = [
|
||||
"arc-swap",
|
||||
"aws-credential-types",
|
||||
@@ -483,9 +483,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "aws-smithy-runtime-api"
|
||||
version = "1.22.0"
|
||||
version = "1.22.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c0b79dbb5331ccd297686df811d50ab3f39db171f5c765372a69272a0990b014"
|
||||
checksum = "20b0ce5fd8f8ec576f6737cf9a3a02172fddad2b90b8874577a4647fab11425c"
|
||||
dependencies = [
|
||||
"aws-smithy-async",
|
||||
"aws-smithy-runtime-api-macros",
|
||||
@@ -522,9 +522,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "aws-smithy-types"
|
||||
version = "1.9.4"
|
||||
version = "1.9.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "aff4bf014c512840b2bba80a20417b723cbd6a0a65c02e2d81f50b4268aedfc7"
|
||||
checksum = "2085f9721fb3755821f8db7611a67ed15f4d6fdba6785b4db8ed7cd18eebee0f"
|
||||
dependencies = [
|
||||
"base64-simd",
|
||||
"bytes",
|
||||
@@ -842,9 +842,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "clap"
|
||||
version = "4.6.8"
|
||||
version = "4.6.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ac230478587d0269d8d6998b82ae69ea51509d55df66d9e92edd1f986904cd4a"
|
||||
checksum = "50066ca966813ca8957ee15361752f19424a8ff620dbe9c8993d9f99d99b04b3"
|
||||
dependencies = [
|
||||
"clap_builder",
|
||||
"clap_derive",
|
||||
@@ -852,9 +852,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "clap_builder"
|
||||
version = "4.6.7"
|
||||
version = "4.6.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d"
|
||||
checksum = "a0ed97c96ef4efb3cc84e09fa388df4463e7cc3224ec38d7b1d9e45749333590"
|
||||
dependencies = [
|
||||
"anstream",
|
||||
"anstyle",
|
||||
@@ -864,9 +864,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "clap_derive"
|
||||
version = "4.6.8"
|
||||
version = "4.6.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "895c9d8d2ac2dd8b8a29f3724a14e72aaaa6debcf8c38c82f97305c6a172767a"
|
||||
checksum = "b4c174f11f949b9ca8c60580925e282b9cbd5454750e506f08648b2038080cd7"
|
||||
dependencies = [
|
||||
"heck",
|
||||
"proc-macro2",
|
||||
@@ -961,9 +961,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "compression-codecs"
|
||||
version = "0.4.47"
|
||||
version = "0.4.49"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "84f840cff84d10085260e460023934d0af699e71212b09b2a41452e8bd9cda43"
|
||||
checksum = "f938fc0d88fbe2c8d6f0e1ba96ba1165d89ff698e98468cd019d92cff2ecd367"
|
||||
dependencies = [
|
||||
"compression-core",
|
||||
"flate2",
|
||||
@@ -1109,9 +1109,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "crc32fast"
|
||||
version = "1.5.5"
|
||||
version = "1.5.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2b929dd2a135771f40afabd1073f85eed59c800b7c61901e5c254270497dad64"
|
||||
checksum = "fd9ae8fcb3ea71b0b26338b4ffb13006bb175de8fd07921089a906ce7e5e6945"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
]
|
||||
@@ -1888,7 +1888,7 @@ dependencies = [
|
||||
"tracing-appender",
|
||||
"tracing-subscriber",
|
||||
"wiremock",
|
||||
"yaml-rust2 0.13.0",
|
||||
"yaml-rust2 0.13.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2073,9 +2073,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "h2"
|
||||
version = "0.4.20"
|
||||
version = "0.4.19"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7d29020232d6aa3fb1daca64c1127cf662cf97f254ae16c18c05b8ab635fc118"
|
||||
checksum = "ef8e5e5a340588f4452631496976cf8636d4a7ecf600239fdc27615d2530bc16"
|
||||
dependencies = [
|
||||
"atomic-waker",
|
||||
"bytes",
|
||||
@@ -2551,9 +2551,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "jsonschema"
|
||||
version = "0.61.2"
|
||||
version = "0.63.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0e37f27df77c7887edbc5f5a59ecd8e5ec4a669319266ec1b61068667a603183"
|
||||
checksum = "b0802aebc749a4ef12e76aee083622b100249be0dc6d2103d84bbb2f7936a1ae"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"bytecount",
|
||||
@@ -2579,18 +2579,18 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "jsonschema-regex"
|
||||
version = "0.61.2"
|
||||
version = "0.63.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7e41151614b6c927e21982be8bef5a26741ae5a0ae6a781eedee2aa930a980e6"
|
||||
checksum = "ba1527289dfcb1400df61b5c591218e8e30031376671f611faecb5b9a1ff4987"
|
||||
dependencies = [
|
||||
"regex-syntax",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "jsonschema-value"
|
||||
version = "0.61.2"
|
||||
version = "0.63.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1515b9a91134ef67d7bac95c2d76fbc7e383c4c55ee544204ceec8088f881fef"
|
||||
checksum = "a95285ab129d630f01cf2f1345c28662116340fac1a35eb0795e5dbbf0ef990d"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"bytecount",
|
||||
@@ -2694,9 +2694,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lru"
|
||||
version = "0.19.0"
|
||||
version = "0.19.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4a9f71e3591c7ec44d3e563e87bf14ddc2bada8519dca046e5b0e560cd004e2d"
|
||||
checksum = "d4e2a1b977b42ee8b53a2a4adbd1183431c493f1d1960b7ccd893e2f0b9407ba"
|
||||
dependencies = [
|
||||
"hashbrown 0.17.1",
|
||||
]
|
||||
@@ -3444,7 +3444,7 @@ dependencies = [
|
||||
"hyper",
|
||||
"hyper-rustls",
|
||||
"hyper-util",
|
||||
"lru 0.19.0",
|
||||
"lru 0.19.2",
|
||||
"native-tls",
|
||||
"openssl",
|
||||
"openssl-sys",
|
||||
@@ -3499,6 +3499,8 @@ dependencies = [
|
||||
"jsonwebtoken",
|
||||
"p256",
|
||||
"reqwest",
|
||||
"rustls",
|
||||
"rustls-native-certs",
|
||||
"semver",
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -3692,9 +3694,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "redis"
|
||||
version = "1.8.2"
|
||||
version = "1.8.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4bef8fa589dd53a8a379a7856de1365d0a1be50c6b8aebb5c01c1ec441a2c509"
|
||||
checksum = "c85db9332bbc47e826283f0a6058d747c478ed2278976279cefd22154d541b98"
|
||||
dependencies = [
|
||||
"arc-swap",
|
||||
"arcstr",
|
||||
@@ -3748,9 +3750,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "referencing"
|
||||
version = "0.61.2"
|
||||
version = "0.63.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a028057ef852c58a42d75e09da87b5e733f4030f4c7411728955e4f87203a577"
|
||||
checksum = "858eb92e3a3c1d120695a04d5c6e8861915ee4394b8f77c90adbf686d6ddbf6e"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"fluent-uri",
|
||||
@@ -4213,9 +4215,9 @@ checksum = "bbfa15b3dddfee50a0fff136974b3e1bde555604ba463834a7eb7deb6417705d"
|
||||
|
||||
[[package]]
|
||||
name = "sha2"
|
||||
version = "0.11.1"
|
||||
version = "0.11.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19"
|
||||
checksum = "5b0e5c7d67bc53f435386b2130fdc900488c5703770f6d8a4633060e34288a27"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cpufeatures 0.3.0",
|
||||
@@ -5649,9 +5651,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "yaml-rust2"
|
||||
version = "0.13.0"
|
||||
version = "0.13.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "57e5b818a27a4cd30884ea380857a5e56f7ec3ba24a3990a3cc0b95af3238e18"
|
||||
checksum = "4a8af4469040402b7fe43c26575bab9a3069f0717c4a2931ecf4fb8728ee4cec"
|
||||
dependencies = [
|
||||
"arraydeque",
|
||||
"encoding_rs",
|
||||
@@ -5777,9 +5779,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "zip"
|
||||
version = "9.8.0"
|
||||
version = "9.8.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "721c8158b9503b2660291ad3056a20f722deaeed21bb908a9a363d7e17b34f0e"
|
||||
checksum = "2d8dbe089cf6b0448b78f5fc50139ab5aaa40d08ac07cdc1baf2c13add35fcce"
|
||||
dependencies = [
|
||||
"constant_time_eq",
|
||||
"crc32fast",
|
||||
|
||||
+1
-1
@@ -45,7 +45,7 @@ opt-level = 2
|
||||
[profile.dev.package.blake2]
|
||||
opt-level = 2
|
||||
|
||||
[profile.dev.package."sha2@0.11.1"]
|
||||
[profile.dev.package.sha2]
|
||||
opt-level = 2
|
||||
|
||||
[profile.dev.package."miniz_oxide@0.9.1"]
|
||||
|
||||
@@ -42,6 +42,7 @@ pub struct ProviderAccountCapabilities {
|
||||
/// 导入时应用的账号设置;名称只覆盖单账号导入,其余设置统一应用
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct AccountImportSettings {
|
||||
pub platform_icon: Option<String>,
|
||||
pub name: Option<String>,
|
||||
pub notes: Option<String>,
|
||||
pub enabled: bool,
|
||||
@@ -222,6 +223,7 @@ pub struct AccountPage {
|
||||
/// 同一状态快照下的账号事实与唯一状态投影
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct AccountPageItem {
|
||||
pub platform_icon: Option<String>,
|
||||
pub protection_rules: Vec<gateway_core::account::AccountProtectionMatch>,
|
||||
pub account: AccountRecord,
|
||||
pub projection: AccountStatusProjection,
|
||||
@@ -240,6 +242,7 @@ pub struct AccountCapacity {
|
||||
/// 账号可编辑事实的一次性替换命令
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct UpdateAccount {
|
||||
pub platform_icon: Option<String>,
|
||||
pub account_id: String,
|
||||
/// 缺省保留名称,空字符串清除名称并使用邮箱展示
|
||||
pub name: Option<String>,
|
||||
|
||||
@@ -350,7 +350,9 @@ impl ClientKeyBudgetWindowPeriod {
|
||||
|
||||
/// 手动对齐只需要账号身份,列表不读取凭据、额度或用量
|
||||
#[derive(serde::Serialize, Debug)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct BudgetReferenceAccount {
|
||||
pub platform_icon: Option<String>,
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub email: Option<String>,
|
||||
|
||||
@@ -783,6 +783,7 @@ pub struct AccountRequestBucket {
|
||||
/// Dashboard 中一个账号的完整用量事实
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct DashboardAccountUsage {
|
||||
pub platform_icon: Option<String>,
|
||||
pub upstream: Option<super::upstream_info::ProviderUpstreamInfo>,
|
||||
pub account_id: String,
|
||||
pub provider_kind: String,
|
||||
@@ -890,6 +891,7 @@ impl UsageErrorOrigin {
|
||||
/// 使用记录表格的窄读模型
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct UsageListRecord {
|
||||
pub platform_icon: Option<String>,
|
||||
pub outcome: RequestOutcome,
|
||||
/// 已保存的上游错误对象含非空字符串 code、type 或 message
|
||||
pub has_upstream_error: bool,
|
||||
@@ -1167,7 +1169,8 @@ pub struct DiagnosticsObservation {
|
||||
pub struct DiagnosticObservation {
|
||||
pub key: String,
|
||||
pub name: String,
|
||||
pub account_provider_kind: Option<String>,
|
||||
pub providers: Vec<String>,
|
||||
pub platform_icon: Option<String>,
|
||||
pub account_authentication_kind: Option<String>,
|
||||
pub account_plan_type: Option<String>,
|
||||
pub account_plan_type_display: Option<String>,
|
||||
@@ -1640,6 +1643,8 @@ pub struct UsageInsight {
|
||||
/// 已完成分母计算的诊断项
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct DiagnosticsItem {
|
||||
pub providers: Vec<String>,
|
||||
pub platform_icon: Option<String>,
|
||||
pub key: String,
|
||||
pub name: String,
|
||||
pub account_authentication_kind: Option<String>,
|
||||
|
||||
@@ -1319,6 +1319,7 @@ impl fmt::Debug for ProviderExport {
|
||||
/// 统一账号目录的一行完整结果
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct AccountDirectoryItem {
|
||||
pub platform_icon: Option<String>,
|
||||
pub protection_rules: Vec<gateway_core::account::AccountProtectionMatch>,
|
||||
pub account: AccountRecord,
|
||||
pub capacity: super::accounts::AccountCapacity,
|
||||
|
||||
@@ -27,6 +27,7 @@ pub struct ProxyListQuery {
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ProxyAccountRef {
|
||||
pub platform_icon: Option<String>,
|
||||
pub upstream: Option<super::upstream_info::ProviderUpstreamInfo>,
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
|
||||
@@ -513,6 +513,7 @@ impl DefaultAccountsService {
|
||||
lookback,
|
||||
);
|
||||
Ok(AccountDirectoryItem {
|
||||
platform_icon: stored.platform_icon,
|
||||
protection_rules: stored.protection_rules,
|
||||
capacity: super::peer_link::upstream::account_capacity(
|
||||
&stored.account,
|
||||
@@ -647,6 +648,7 @@ impl AccountsService for DefaultAccountsService {
|
||||
lookback,
|
||||
);
|
||||
Ok(AccountDirectoryItem {
|
||||
platform_icon: item.platform_icon,
|
||||
protection_rules: item.protection_rules,
|
||||
capacity: crate::model::accounts::AccountCapacity {
|
||||
used_slots: in_flight
|
||||
|
||||
@@ -382,9 +382,11 @@ impl ObservabilityService for DefaultObservabilityService {
|
||||
account_authentication_kind: item.account_authentication_kind,
|
||||
account_plan_type_display: self.historical_plan_display(
|
||||
item.account_plan_type_display,
|
||||
item.account_provider_kind.as_deref(),
|
||||
item.providers.first().map(String::as_str),
|
||||
item.account_plan_type.as_deref(),
|
||||
),
|
||||
providers: item.providers,
|
||||
platform_icon: item.platform_icon,
|
||||
account_plan_type: item.account_plan_type,
|
||||
request_count: item.request_count,
|
||||
success_count: item.success_count,
|
||||
|
||||
@@ -740,6 +740,7 @@ impl FakeAccountStore {
|
||||
last_error_message: account.last_error_message.clone(),
|
||||
};
|
||||
AccountPageItem {
|
||||
platform_icon: None,
|
||||
protection_rules: Vec::new(),
|
||||
capacity: gateway_admin::model::accounts::AccountCapacity {
|
||||
used_slots: None,
|
||||
@@ -1895,6 +1896,7 @@ async fn accounts_update_should_commit_then_release_disabled_account_and_publish
|
||||
.update(
|
||||
&context("update-request"),
|
||||
UpdateAccount {
|
||||
platform_icon: None,
|
||||
name: None,
|
||||
notes: None,
|
||||
model_access: Default::default(),
|
||||
@@ -1935,6 +1937,7 @@ async fn accounts_update_should_not_notify_provider_when_store_commit_fails() {
|
||||
.update(
|
||||
&context("update-failure"),
|
||||
UpdateAccount {
|
||||
platform_icon: None,
|
||||
name: None,
|
||||
notes: None,
|
||||
model_access: Default::default(),
|
||||
@@ -4017,6 +4020,7 @@ fn unsupported() -> ProviderAdminError {
|
||||
|
||||
pub(super) fn import_settings() -> gateway_admin::model::accounts::AccountImportSettings {
|
||||
gateway_admin::model::accounts::AccountImportSettings {
|
||||
platform_icon: None,
|
||||
name: None,
|
||||
notes: Some("团队备用".to_owned()),
|
||||
model_access: Default::default(),
|
||||
|
||||
@@ -516,6 +516,7 @@ async fn dashboard_should_preserve_provider_plan_names() {
|
||||
*store.account_usage.lock().unwrap() = plans
|
||||
.iter()
|
||||
.map(|(plan, _)| DashboardAccountUsage {
|
||||
platform_icon: None,
|
||||
upstream: None,
|
||||
account_id: format!("account-{plan}"),
|
||||
provider_kind: "openai".to_owned(),
|
||||
|
||||
@@ -451,6 +451,7 @@ fn total_record(
|
||||
now: DateTime<Utc>,
|
||||
) -> UsageListRecord {
|
||||
UsageListRecord {
|
||||
platform_icon: None,
|
||||
provider_account_upstream_peer: None,
|
||||
has_upstream_error: false,
|
||||
error_code: None,
|
||||
@@ -542,7 +543,8 @@ fn diagnostic(name: &str, request_count: u64) -> DiagnosticObservation {
|
||||
caller_error_count: 0,
|
||||
retry_count: 0,
|
||||
retried_request_count: 0,
|
||||
account_provider_kind: None,
|
||||
providers: vec![],
|
||||
platform_icon: None,
|
||||
account_authentication_kind: None,
|
||||
account_plan_type: None,
|
||||
account_plan_type_display: None,
|
||||
|
||||
@@ -355,6 +355,7 @@ async fn linked_accounts_share_plan_resolution_and_only_read_cached_quota() {
|
||||
.provider(provider.clone())
|
||||
.proxies(Arc::new(TestProxies {
|
||||
accounts: Some(vec![ProxyAccountRef {
|
||||
platform_icon: None,
|
||||
upstream: None,
|
||||
id: "acct_plan".to_owned(),
|
||||
name: "套餐测试".to_owned(),
|
||||
|
||||
@@ -2,6 +2,25 @@
|
||||
|
||||
use super::*;
|
||||
|
||||
pub(super) async fn validate_platform_icons(
|
||||
state: &impl crate::SessionState,
|
||||
names: &[&str],
|
||||
) -> Result<(), AdminError> {
|
||||
if names.iter().any(|name| !name.is_empty()) {
|
||||
let catalog = state
|
||||
.platform_icon_names()
|
||||
.await
|
||||
.map_err(|_| AdminError::service_unavailable())?;
|
||||
if names
|
||||
.iter()
|
||||
.any(|&name| !name.is_empty() && !catalog.contains(name))
|
||||
{
|
||||
return Err(map_wire_error(WireValidationError::new("platformIcon")));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_account_notes(notes: Option<&str>) -> Result<(), WireValidationError> {
|
||||
if notes.is_some_and(|notes| {
|
||||
notes.chars().count() > 500
|
||||
@@ -22,6 +41,8 @@ fn parse_provider(value: &str) -> Result<ProviderKind, WireValidationError> {
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct AccountImportSettingsRequest {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub platform_icon: Option<String>,
|
||||
pub name: Option<String>,
|
||||
pub notes: Option<String>,
|
||||
pub enabled: bool,
|
||||
@@ -52,6 +73,7 @@ impl AccountImportSettingsRequest {
|
||||
.name
|
||||
.map(|name| name.trim().to_owned())
|
||||
.filter(|name| !name.is_empty()),
|
||||
platform_icon: self.platform_icon,
|
||||
notes: self.notes,
|
||||
enabled: self.enabled,
|
||||
concurrency_limit: parse_concurrency_limit(self.concurrency_limit)?,
|
||||
@@ -213,6 +235,7 @@ fn validate_authorization_flow(
|
||||
#[derive(Clone, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct UpdateAccountRequest {
|
||||
pub platform_icon: Option<String>,
|
||||
pub connection: Option<AccountConnectionUpdateRequest>,
|
||||
pub outbound_proxy_id: Option<String>,
|
||||
pub account_id: String,
|
||||
@@ -253,6 +276,7 @@ impl UpdateAccountRequest {
|
||||
outbound_proxy: super::wire::proxy_selection(self.outbound_proxy_id)?,
|
||||
account_id: self.account_id,
|
||||
name: self.name.map(|name| name.trim().to_owned()),
|
||||
platform_icon: self.platform_icon,
|
||||
notes: self.notes,
|
||||
enabled: self.enabled,
|
||||
concurrency_limit: parse_concurrency_limit(self.concurrency_limit)?,
|
||||
|
||||
@@ -182,6 +182,15 @@ async fn import_accounts<S>(
|
||||
where
|
||||
S: SessionState + Send + Sync,
|
||||
{
|
||||
super::credentials::validate_platform_icons(
|
||||
&state,
|
||||
request
|
||||
.settings
|
||||
.as_ref()
|
||||
.and_then(|settings| settings.platform_icon.as_deref())
|
||||
.as_slice(),
|
||||
)
|
||||
.await?;
|
||||
let (provider, command) = request
|
||||
.into_command(auth.context().mutation_context())
|
||||
.map_err(map_wire_error)?;
|
||||
@@ -232,6 +241,15 @@ async fn complete_account_authorization<S>(
|
||||
where
|
||||
S: SessionState + Send + Sync,
|
||||
{
|
||||
super::credentials::validate_platform_icons(
|
||||
&state,
|
||||
request
|
||||
.settings
|
||||
.as_ref()
|
||||
.and_then(|settings| settings.platform_icon.as_deref())
|
||||
.as_slice(),
|
||||
)
|
||||
.await?;
|
||||
let (provider, command) = request
|
||||
.into_command(auth.context().mutation_context())
|
||||
.map_err(map_wire_error)?;
|
||||
@@ -255,6 +273,11 @@ async fn update_account<S>(
|
||||
where
|
||||
S: SessionState + Send + Sync,
|
||||
{
|
||||
super::credentials::validate_platform_icons(
|
||||
&state,
|
||||
request.platform_icon.as_deref().as_slice(),
|
||||
)
|
||||
.await?;
|
||||
let (command, connection) = request.into_command().map_err(map_wire_error)?;
|
||||
let context = auth.context().mutation_context();
|
||||
let result = if let Some(provider_material) = connection {
|
||||
|
||||
@@ -149,6 +149,12 @@ where
|
||||
if request.items.is_empty() || request.items.len() > MAX_IMPORT_TASK_ITEMS {
|
||||
return Err(map_wire_error(WireValidationError::new("items")));
|
||||
}
|
||||
let icons: Vec<_> = request
|
||||
.items
|
||||
.iter()
|
||||
.filter_map(|item| item.settings.as_ref()?.platform_icon.as_deref())
|
||||
.collect();
|
||||
super::credentials::validate_platform_icons(&state, &icons).await?;
|
||||
let encoded = serde_json::to_vec(&request.items)
|
||||
.map_err(|_| map_wire_error(WireValidationError::new("items")))?;
|
||||
let fingerprint = Sha256::digest(&encoded).into();
|
||||
|
||||
@@ -67,6 +67,7 @@ pub(super) fn account_view(
|
||||
time: crate::time::TimePresenter,
|
||||
) -> AccountView {
|
||||
let AccountDirectoryItem {
|
||||
platform_icon,
|
||||
account,
|
||||
capacity,
|
||||
capabilities,
|
||||
@@ -111,6 +112,7 @@ pub(super) fn account_view(
|
||||
let (mut quota, refresh_token_expires_at) = account_quota_view(quota, cooldown, now, time);
|
||||
quota.protection_rules = protection_rules;
|
||||
AccountView {
|
||||
platform_icon,
|
||||
quota_settings: account.quota_settings,
|
||||
auto_use_quota_credits: account.auto_use_quota_credits,
|
||||
upstream,
|
||||
|
||||
@@ -247,6 +247,7 @@ pub struct AccountSummaryView {
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AccountView {
|
||||
pub platform_icon: Option<String>,
|
||||
pub quota_settings: gateway_core::account::AccountQuotaSettings,
|
||||
pub auto_use_quota_credits: bool,
|
||||
pub upstream: Option<super::AccountUpstreamInfoView>,
|
||||
|
||||
@@ -276,6 +276,7 @@ pub(crate) fn usage_list_record_view(
|
||||
account_id: record.provider_account_ref,
|
||||
account_email: record.provider_account_email,
|
||||
account_name: record.provider_account_name,
|
||||
platform_icon: record.platform_icon,
|
||||
account_notes: record.provider_account_notes,
|
||||
account_plan_type: record.provider_account_plan_type,
|
||||
account_plan_type_display: record.provider_account_plan_type_display,
|
||||
@@ -940,6 +941,7 @@ pub(crate) fn dashboard_view(
|
||||
.email
|
||||
.clone()
|
||||
.unwrap_or_else(|| credential.name.clone()),
|
||||
platform_icon: credential.platform_icon,
|
||||
notes: credential.notes,
|
||||
plan_type: credential.plan_type.clone(),
|
||||
plan_type_display: credential
|
||||
@@ -1350,6 +1352,8 @@ pub(crate) fn diagnostics_view(
|
||||
.items
|
||||
.into_iter()
|
||||
.map(|item| DiagnosticItemView {
|
||||
providers: item.providers,
|
||||
platform_icon: item.platform_icon,
|
||||
key: item.key,
|
||||
authentication_kind: item.account_authentication_kind,
|
||||
name: if item.name == "__none__" {
|
||||
|
||||
@@ -86,6 +86,7 @@ pub struct ImageBillingView {
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct UsageListRecordView {
|
||||
pub platform_icon: Option<String>,
|
||||
pub error_origin: &'static str,
|
||||
pub client_status_code: Option<u16>,
|
||||
pub upstream_status_code: Option<u16>,
|
||||
@@ -432,6 +433,7 @@ pub enum DashboardAccountMetric {
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DashboardAccountUsageView {
|
||||
pub platform_icon: Option<String>,
|
||||
pub upstream: Option<crate::admin::accounts::AccountUpstreamInfoView>,
|
||||
pub id: String,
|
||||
pub provider: String,
|
||||
@@ -872,6 +874,8 @@ pub struct UsageCacheView {
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DiagnosticItemView {
|
||||
pub providers: Vec<String>,
|
||||
pub platform_icon: Option<String>,
|
||||
pub key: String,
|
||||
pub name: String,
|
||||
pub authentication_kind: Option<String>,
|
||||
|
||||
@@ -152,6 +152,7 @@ impl From<ProxyTestResult> for ProxyTestView {
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct ProxyAccountView {
|
||||
platform_icon: Option<String>,
|
||||
upstream: Option<super::accounts::AccountUpstreamInfoView>,
|
||||
id: String,
|
||||
name: String,
|
||||
@@ -345,6 +346,7 @@ where
|
||||
.items
|
||||
.into_iter()
|
||||
.map(|account| ProxyAccountView {
|
||||
platform_icon: account.platform_icon,
|
||||
upstream: account.upstream.map(|info| {
|
||||
super::accounts::upstream_info_view(
|
||||
info,
|
||||
|
||||
@@ -41,7 +41,7 @@ pub(crate) async fn models(
|
||||
Query(query): Query<ModelsQuery>,
|
||||
headers: HeaderMap,
|
||||
) -> Response {
|
||||
let anthropic = headers.contains_key("anthropic-version") || headers.contains_key("x-api-key");
|
||||
let anthropic = headers.contains_key("anthropic-version");
|
||||
let service = state.data_plane();
|
||||
let client = match authenticate_client(service, &headers, ClientKeyHeaders::Anthropic).await {
|
||||
Ok(client) => client,
|
||||
@@ -104,7 +104,7 @@ pub(crate) async fn model_detail(
|
||||
headers: HeaderMap,
|
||||
Path(model_id): Path<String>,
|
||||
) -> Response {
|
||||
let anthropic = headers.contains_key("anthropic-version") || headers.contains_key("x-api-key");
|
||||
let anthropic = headers.contains_key("anthropic-version");
|
||||
let service = state.data_plane();
|
||||
let client = match authenticate_client(service, &headers, ClientKeyHeaders::Anthropic).await {
|
||||
Ok(client) => client,
|
||||
|
||||
@@ -216,6 +216,7 @@ pub fn initialize(
|
||||
})
|
||||
};
|
||||
let state = ApiState {
|
||||
platform_icon_catalog: Arc::new(config.asset_directory.join("platform-icons.json")),
|
||||
admin,
|
||||
data_plane: DataPlaneService::new(execution, lifecycle),
|
||||
health: HealthStatus::new(probes, worker_health, diagnostics.clone()),
|
||||
@@ -337,6 +338,7 @@ pub enum ApiError {
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct ApiState {
|
||||
platform_icon_catalog: Arc<PathBuf>,
|
||||
admin: AdminServices,
|
||||
data_plane: DataPlaneService,
|
||||
health: HealthStatus,
|
||||
@@ -355,6 +357,11 @@ impl ApiState {
|
||||
}
|
||||
|
||||
impl SessionState for ApiState {
|
||||
async fn platform_icon_names(&self) -> std::io::Result<std::collections::HashSet<String>> {
|
||||
let bytes = tokio::fs::read(self.platform_icon_catalog.as_ref()).await?;
|
||||
Ok(serde_json::from_slice(&bytes)?)
|
||||
}
|
||||
|
||||
fn admin_services(&self) -> &AdminServices {
|
||||
&self.admin
|
||||
}
|
||||
|
||||
@@ -4,5 +4,8 @@ use gateway_admin::AdminServices;
|
||||
|
||||
/// 控制面 HTTP adapter 消费同一组用例;权限由各入口服务端校验
|
||||
pub trait SessionState {
|
||||
fn platform_icon_names(
|
||||
&self,
|
||||
) -> impl Future<Output = std::io::Result<std::collections::HashSet<String>>> + Send;
|
||||
fn admin_services(&self) -> &AdminServices;
|
||||
}
|
||||
|
||||
@@ -411,6 +411,7 @@ fn account_page_item(
|
||||
use gateway_core::account::resolve_account_status;
|
||||
|
||||
AccountPageItem {
|
||||
platform_icon: None,
|
||||
protection_rules: Vec::new(),
|
||||
account: AccountRecord {
|
||||
quota_paused: false,
|
||||
@@ -670,6 +671,67 @@ async fn connection_update_requires_admin_and_validates_before_calling_the_servi
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn account_icon_requires_a_known_preset_before_mutation() {
|
||||
let fixture = AdminTestFixture::new().await;
|
||||
fixture.auth.insert_session("valid-session");
|
||||
for (name, expected) in [
|
||||
("DeepSeek", StatusCode::SERVICE_UNAVAILABLE),
|
||||
("", StatusCode::SERVICE_UNAVAILABLE),
|
||||
("Unlisted", StatusCode::BAD_REQUEST),
|
||||
("https://example.invalid/logo.svg", StatusCode::BAD_REQUEST),
|
||||
] {
|
||||
let settings = serde_json::json!({
|
||||
"platformIcon": name, "enabled": true,
|
||||
"concurrencyLimit": null, "weight": 1, "groupIds": []
|
||||
});
|
||||
for (route, payload) in [
|
||||
(
|
||||
"update",
|
||||
serde_json::json!({
|
||||
"accountId": "acct_api", "platformIcon": name, "enabled": true,
|
||||
"concurrencyLimit": null, "weight": 1, "groupIds": []
|
||||
}),
|
||||
),
|
||||
(
|
||||
"import",
|
||||
serde_json::json!({"provider": "openai", "data": {}, "settings": settings}),
|
||||
),
|
||||
(
|
||||
"oauth/complete",
|
||||
serde_json::json!({
|
||||
"provider": "xai", "flowId": "flow-test", "callbackUrl": "code", "settings": settings
|
||||
}),
|
||||
),
|
||||
] {
|
||||
let request = Request::post(format!("/api/admin/accounts/{route}"))
|
||||
.header("x-request-id", "req_account_icon")
|
||||
.header(header::COOKIE, "cpr_session=valid-session")
|
||||
.header(header::CONTENT_TYPE, "application/json")
|
||||
.body(Body::from(payload.to_string()))
|
||||
.unwrap();
|
||||
let response = admin::router::<AdminTestState>()
|
||||
.with_state(fixture.state())
|
||||
.oneshot(request)
|
||||
.await
|
||||
.unwrap();
|
||||
let status = response.status();
|
||||
let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
|
||||
let body: serde_json::Value = serde_json::from_slice(&body).unwrap();
|
||||
if expected == StatusCode::BAD_REQUEST {
|
||||
assert_eq!(status, expected, "{route}: {name}");
|
||||
assert_eq!(body["message"], "platformIcon 字段不合法");
|
||||
} else if route == "update" {
|
||||
assert_eq!(status, expected, "{route}: {name}");
|
||||
} else {
|
||||
// 夹具 Provider 未实现导入和授权,合法图标应通过校验并到达 Provider
|
||||
assert_eq!(status, StatusCode::BAD_REQUEST, "{route}: {name}: {body}");
|
||||
assert_eq!(body["message"], "该服务商不支持此操作");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn personal_info_requires_admin_and_a_valid_account_query() {
|
||||
let fixture = AdminTestFixture::new().await;
|
||||
|
||||
@@ -564,6 +564,7 @@ mod provider {
|
||||
last_error_message: None,
|
||||
};
|
||||
AccountPageItem {
|
||||
platform_icon: None,
|
||||
protection_rules: Vec::new(),
|
||||
capacity: gateway_admin::model::accounts::AccountCapacity {
|
||||
used_slots: None,
|
||||
|
||||
@@ -311,6 +311,10 @@ impl ClientDistributionResolver for StaticClientDistribution {
|
||||
pub(super) struct AdminTestState(AdminServices);
|
||||
|
||||
impl SessionState for AdminTestState {
|
||||
async fn platform_icon_names(&self) -> std::io::Result<std::collections::HashSet<String>> {
|
||||
Ok(["DeepSeek".to_owned()].into())
|
||||
}
|
||||
|
||||
fn admin_services(&self) -> &AdminServices {
|
||||
&self.0
|
||||
}
|
||||
|
||||
@@ -748,7 +748,8 @@ async fn diagnostics_should_keep_stable_key_and_display_name_contract() {
|
||||
total_request_count: 4,
|
||||
items: vec![DiagnosticObservation {
|
||||
key: "acct_diag".to_owned(),
|
||||
account_provider_kind: Some("openai".to_owned()),
|
||||
providers: vec!["openai".to_owned()],
|
||||
platform_icon: Some("Adobe".to_owned()),
|
||||
account_authentication_kind: authentication_kind.map(str::to_owned),
|
||||
account_plan_type: plan_type.map(str::to_owned),
|
||||
account_plan_type_display: None,
|
||||
@@ -791,6 +792,8 @@ async fn diagnostics_should_keep_stable_key_and_display_name_contract() {
|
||||
value["data"]["items"][0]["accountUpstreamPeer"],
|
||||
json!(peer.map(|(d, o)| d && o))
|
||||
);
|
||||
assert_eq!(value["data"]["items"][0]["providers"], json!(["openai"]));
|
||||
assert_eq!(value["data"]["items"][0]["platformIcon"], "Adobe");
|
||||
assert_eq!(value["data"]["items"][0]["requestShare"], 0.5);
|
||||
assert_eq!(value["data"]["items"][0]["retryCount"], 3);
|
||||
assert_eq!(value["data"]["items"][0]["retryRate"], 0.5);
|
||||
@@ -981,6 +984,7 @@ async fn usage_route_projects_request_facts_and_billing() {
|
||||
.lock()
|
||||
.expect("usage records")
|
||||
.push(UsageListRecord {
|
||||
platform_icon: None,
|
||||
provider_account_upstream_peer: None,
|
||||
has_upstream_error: false,
|
||||
error_code: None,
|
||||
@@ -1962,6 +1966,7 @@ async fn dashboard_summary_identifies_trend_metrics_and_account_usage_values() {
|
||||
.map(|(index, (requests, tokens, last_used_at))| {
|
||||
let account_id = format!("acct_metric_{index}");
|
||||
DashboardAccountUsage {
|
||||
platform_icon: None,
|
||||
upstream: None,
|
||||
account_id: account_id.clone(),
|
||||
provider_kind: "openai".to_owned(),
|
||||
@@ -2153,6 +2158,7 @@ async fn dashboard_relative_time_preserves_server_anchor_boundaries_and_deployme
|
||||
provider_accounts: Default::default(),
|
||||
trend: Vec::new(),
|
||||
account_usage: vec![DashboardAccountUsage {
|
||||
platform_icon: None,
|
||||
upstream: None,
|
||||
account_id: "acct_relative_time".to_owned(),
|
||||
provider_kind: "openai".to_owned(),
|
||||
|
||||
@@ -287,6 +287,7 @@ impl ProxyStore for MemoryProxies {
|
||||
}
|
||||
Ok(ProxyAccountPage {
|
||||
items: vec![ProxyAccountRef {
|
||||
platform_icon: None,
|
||||
upstream: None,
|
||||
id: "acct_linked".to_owned(),
|
||||
name: "工作账号".to_owned(),
|
||||
@@ -569,7 +570,7 @@ async fn proxy_routes_save_reload_test_rename_and_delete_without_exposing_creden
|
||||
assert_eq!(
|
||||
linked["data"]["items"],
|
||||
json!([{
|
||||
"id":"acct_linked", "name":"工作账号", "email":"work@example.invalid",
|
||||
"id":"acct_linked", "name":"工作账号", "email":"work@example.invalid", "platformIcon":null,
|
||||
"provider":"openai", "enabled":true, "authenticationKind":"oauth",
|
||||
"planType":"plus", "planTypeDisplay":"Plus", "groups":[], "upstream":null
|
||||
}])
|
||||
|
||||
@@ -34,7 +34,9 @@ async fn anthropic_models_use_explicit_headers_and_cursor_pagination() {
|
||||
.clone()
|
||||
.oneshot(
|
||||
Request::get(path)
|
||||
.header(AUTHORIZATION, "Bearer sk_models_test")
|
||||
.header("x-api-key", "sk_models_test")
|
||||
.header("anthropic-version", "2023-06-01")
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
@@ -90,6 +92,7 @@ async fn anthropic_model_detail_keeps_public_model_access() {
|
||||
.oneshot(
|
||||
Request::get(path)
|
||||
.header("x-api-key", "sk_models_test")
|
||||
.header("anthropic-version", "2023-06-01")
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
@@ -296,6 +299,22 @@ impl ExecutionService for ModelsExecution {
|
||||
}
|
||||
}
|
||||
|
||||
fn authenticated_model_requests(path: &str) -> [Request<Body>; 3] {
|
||||
let api_key_request = Request::get(path)
|
||||
.header("x-api-key", "sk_models_test")
|
||||
.body(Body::empty())
|
||||
.expect("API key request");
|
||||
let mut dual_header_request = authorized_request(path);
|
||||
dual_header_request
|
||||
.headers_mut()
|
||||
.insert("x-api-key", "sk_models_test".parse().expect("API key"));
|
||||
[
|
||||
authorized_request(path),
|
||||
api_key_request,
|
||||
dual_header_request,
|
||||
]
|
||||
}
|
||||
|
||||
fn authorized_request(path: &str) -> Request<Body> {
|
||||
Request::get(path)
|
||||
.header(AUTHORIZATION, "Bearer sk_models_test")
|
||||
@@ -490,18 +509,20 @@ async fn native_catalog_failure_does_not_publish_a_synthetic_or_empty_success()
|
||||
requested_versions: Mutex::default(),
|
||||
middleware: None,
|
||||
});
|
||||
let response = api_router(execution)
|
||||
.await
|
||||
.oneshot(authorized_request("/v1/models?client_version=0.154.0"))
|
||||
.await
|
||||
.expect("response");
|
||||
assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
|
||||
let body = to_bytes(response.into_body(), usize::MAX)
|
||||
.await
|
||||
.expect("body");
|
||||
let value: serde_json::Value = serde_json::from_slice(&body).expect("JSON");
|
||||
assert_eq!(value["error"]["code"], "model_catalog_unavailable");
|
||||
assert!(value.get("models").is_none());
|
||||
for request in authenticated_model_requests("/v1/models?client_version=0.154.0") {
|
||||
let response = api_router(execution.clone())
|
||||
.await
|
||||
.oneshot(request)
|
||||
.await
|
||||
.expect("response");
|
||||
assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
|
||||
let body = to_bytes(response.into_body(), usize::MAX)
|
||||
.await
|
||||
.expect("body");
|
||||
let value: serde_json::Value = serde_json::from_slice(&body).expect("JSON");
|
||||
assert_eq!(value["error"]["code"], "model_catalog_unavailable");
|
||||
assert!(value.get("models").is_none());
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -781,52 +802,64 @@ async fn models_should_preserve_unknown_context_windows() {
|
||||
|
||||
#[tokio::test]
|
||||
async fn models_should_keep_the_codex_contract_when_profiles_are_empty() {
|
||||
let response = api_router(ModelsExecution::new())
|
||||
.await
|
||||
.oneshot(authorized_request("/v1/models?client_version=0.145.0"))
|
||||
.await
|
||||
.expect("list empty Codex models response");
|
||||
let body = to_bytes(response.into_body(), usize::MAX)
|
||||
.await
|
||||
.expect("read empty Codex models body");
|
||||
let value: serde_json::Value = serde_json::from_slice(&body).expect("Codex models JSON");
|
||||
for request in authenticated_model_requests("/v1/models?client_version=0.145.0") {
|
||||
let response = api_router(ModelsExecution::new())
|
||||
.await
|
||||
.oneshot(request)
|
||||
.await
|
||||
.expect("list empty Codex models response");
|
||||
let body = to_bytes(response.into_body(), usize::MAX)
|
||||
.await
|
||||
.expect("read empty Codex models body");
|
||||
let value: serde_json::Value = serde_json::from_slice(&body).expect("Codex models JSON");
|
||||
|
||||
assert_eq!(value, serde_json::json!({ "models": [] }));
|
||||
assert_eq!(value, serde_json::json!({ "models": [] }));
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn models_with_provider_profiles_should_keep_the_openai_list_contract() {
|
||||
let response = api_router(ModelsExecution::with_profiles())
|
||||
.await
|
||||
.oneshot(authorized_request("/v1/models"))
|
||||
.await
|
||||
.expect("list compatible models response");
|
||||
let body = to_bytes(response.into_body(), usize::MAX)
|
||||
.await
|
||||
.expect("read compatible models body");
|
||||
let value: serde_json::Value = serde_json::from_slice(&body).expect("models JSON");
|
||||
for request in authenticated_model_requests("/v1/models") {
|
||||
let response = api_router(ModelsExecution::with_profiles())
|
||||
.await
|
||||
.oneshot(request)
|
||||
.await
|
||||
.expect("list compatible models response");
|
||||
let body = to_bytes(response.into_body(), usize::MAX)
|
||||
.await
|
||||
.expect("read compatible models body");
|
||||
let value: serde_json::Value = serde_json::from_slice(&body).expect("models JSON");
|
||||
|
||||
assert_eq!(
|
||||
value,
|
||||
serde_json::json!({
|
||||
"object": "list",
|
||||
"data": [
|
||||
{"id":"model-a","object":"model","created":1700000000_i64,"owned_by":"gateway"},
|
||||
{"id":"model-b","object":"model","created":1700000000_i64,"owned_by":"gateway"}
|
||||
]
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
value,
|
||||
serde_json::json!({
|
||||
"object": "list",
|
||||
"data": [
|
||||
{"id":"model-a","object":"model","created":1700000000_i64,"owned_by":"gateway"},
|
||||
{"id":"model-b","object":"model","created":1700000000_i64,"owned_by":"gateway"}
|
||||
]
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn model_detail_should_keep_the_official_path_id_contract() {
|
||||
let response = api_router(ModelsExecution::new())
|
||||
.await
|
||||
.oneshot(authorized_request("/v1/models/model-a"))
|
||||
.await
|
||||
.expect("model detail response");
|
||||
for request in authenticated_model_requests("/v1/models/responses-only") {
|
||||
let response = api_router(ModelsExecution::new())
|
||||
.await
|
||||
.oneshot(request)
|
||||
.await
|
||||
.expect("model detail response");
|
||||
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
let body = to_bytes(response.into_body(), usize::MAX)
|
||||
.await
|
||||
.expect("model body");
|
||||
let value: serde_json::Value = serde_json::from_slice(&body).expect("model JSON");
|
||||
assert_eq!(value["id"], "responses-only");
|
||||
assert_eq!(value["object"], "model");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
||||
@@ -91,6 +91,7 @@ async fn fixture(sharing: ClientPeerSharing, plaintext: &str) -> (AdminTestFixtu
|
||||
last_error_message: None,
|
||||
};
|
||||
*fixture.account.lock().unwrap() = Some(AccountPageItem {
|
||||
platform_icon: None,
|
||||
protection_rules: Vec::new(),
|
||||
capacity: AccountCapacity {
|
||||
used_slots: None,
|
||||
|
||||
@@ -101,6 +101,7 @@ pub(super) async fn fixture() -> AdminTestFixture {
|
||||
|
||||
fn usage_record() -> UsageListRecord {
|
||||
UsageListRecord {
|
||||
platform_icon: None,
|
||||
provider_account_upstream_peer: None,
|
||||
has_upstream_error: false,
|
||||
error_code: None,
|
||||
|
||||
@@ -24,7 +24,7 @@ gateway-plugin-sdk = { path = "../sdk", features = ["io"] }
|
||||
gateway-protocol = { path = "../../gateway-protocol" }
|
||||
hex = "0.4.3"
|
||||
image = { version = "0.25.8", default-features = false, features = ["bmp", "gif", "ico", "jpeg", "png", "webp"] }
|
||||
jsonschema = { version = "0.61.2", default-features = false }
|
||||
jsonschema = { version = "0.63.2", default-features = false }
|
||||
roxmltree = "0.21.1"
|
||||
semver = "1.0.27"
|
||||
secrecy = "0.10.3"
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
use std::{
|
||||
collections::BTreeMap,
|
||||
sync::{
|
||||
Arc, Mutex,
|
||||
Arc, Mutex, MutexGuard,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
},
|
||||
time::{Duration, Instant},
|
||||
@@ -31,7 +31,8 @@ pub(crate) struct Shared {
|
||||
pub stopped: watch::Sender<bool>,
|
||||
callback_slots: Arc<Semaphore>,
|
||||
pub(super) execution: ExecutionCapacity,
|
||||
cancellations_changed: Notify,
|
||||
maximum_queue_timeout: Duration,
|
||||
pub(super) cancellations_changed: Notify,
|
||||
}
|
||||
|
||||
struct State {
|
||||
@@ -46,7 +47,7 @@ struct PendingCall {
|
||||
handler: Arc<dyn CallbackHandler>,
|
||||
revoked: bool,
|
||||
transmitted: bool,
|
||||
cancellation: Option<RpcError>,
|
||||
cancellation: Option<PendingCancellation>,
|
||||
context: CallContext,
|
||||
result: Option<oneshot::Sender<Result<RpcReply, RpcError>>>,
|
||||
stream: Option<StreamIngress>,
|
||||
@@ -54,6 +55,12 @@ struct PendingCall {
|
||||
callbacks: BTreeMap<u64, CallbackTask>,
|
||||
}
|
||||
|
||||
struct PendingCancellation {
|
||||
error: RpcError,
|
||||
deadline: tokio::time::Instant,
|
||||
transmitted: bool,
|
||||
}
|
||||
|
||||
// 调度状态只属于父任务;回调完成与恢复授权分别推进
|
||||
enum Scheduling {
|
||||
Running {
|
||||
@@ -154,6 +161,7 @@ impl Shared {
|
||||
limits.maximum_queue_timeout,
|
||||
),
|
||||
cancellations_changed: Notify::new(),
|
||||
maximum_queue_timeout: limits.maximum_queue_timeout,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -252,9 +260,12 @@ impl Shared {
|
||||
}
|
||||
|
||||
pub fn fail(&self, error: RpcError) {
|
||||
self.fail_with_state(error, self.state());
|
||||
}
|
||||
|
||||
fn fail_with_state(&self, error: RpcError, mut state: MutexGuard<'_, State>) {
|
||||
let uptime = self.started_at.elapsed();
|
||||
let (calls, failure_observer) = {
|
||||
let mut state = self.state();
|
||||
if state.failure.is_some() {
|
||||
return;
|
||||
}
|
||||
@@ -268,6 +279,7 @@ impl Shared {
|
||||
}
|
||||
(std::mem::take(&mut state.calls), observer)
|
||||
};
|
||||
drop(state);
|
||||
self.execution.close();
|
||||
for call in calls.into_values() {
|
||||
call.finish(Err(error.clone()));
|
||||
@@ -406,8 +418,8 @@ impl Shared {
|
||||
true
|
||||
}
|
||||
|
||||
/// 先撤销调用权限,再等待对端确认;只有无响应对端才终止整个 incarnation
|
||||
pub fn cancel(self: &Arc<Self>, id: u64, error: RpcError) {
|
||||
/// 先撤销调用权限,再有界等待取消帧发送与对端确认
|
||||
pub fn cancel(&self, id: u64, error: RpcError) {
|
||||
let mut state = self.state();
|
||||
let Some(call) = state.calls.get_mut(&id) else {
|
||||
return;
|
||||
@@ -436,7 +448,11 @@ impl Shared {
|
||||
}
|
||||
return;
|
||||
}
|
||||
call.cancellation = Some(error.clone());
|
||||
call.cancellation = Some(PendingCancellation {
|
||||
error: error.clone(),
|
||||
deadline: tokio::time::Instant::now() + self.maximum_queue_timeout,
|
||||
transmitted: false,
|
||||
});
|
||||
// 同步撤销不能跨越取消确认:收到确认的并发任务可能立即复用实例
|
||||
// CallbackHandler::finish 合同要求非阻塞;真正的等待与结果交付放在锁外
|
||||
call.revoke();
|
||||
@@ -455,16 +471,63 @@ impl Shared {
|
||||
stream.finish(Err(error.clone()));
|
||||
}
|
||||
if let Some(result) = result {
|
||||
let _ = result.send(Err(error.clone()));
|
||||
let _ = result.send(Err(error));
|
||||
}
|
||||
self.send_control(Frame::control(Message::Cancel { id }));
|
||||
let shared = Arc::clone(self);
|
||||
tokio::spawn(async move {
|
||||
tokio::time::sleep(Duration::from_millis(250)).await;
|
||||
if shared.is_cancelling(id) {
|
||||
shared.fail(error);
|
||||
}
|
||||
});
|
||||
self.cancellations_changed.notify_waiters();
|
||||
}
|
||||
|
||||
pub(super) fn cancellation_transmitted(&self, id: u64) {
|
||||
let mut state = self.state();
|
||||
let Some(cancellation) = state
|
||||
.calls
|
||||
.get_mut(&id)
|
||||
.and_then(|call| call.cancellation.as_mut())
|
||||
else {
|
||||
// 对端确认可能先于写泵恢复执行,已退休调用不再建立期限
|
||||
return;
|
||||
};
|
||||
cancellation.transmitted = true;
|
||||
// 写入管道不代表对端已处理,确认还需经过插件输入与输出队列
|
||||
cancellation.deadline = tokio::time::Instant::now() + self.maximum_queue_timeout;
|
||||
drop(state);
|
||||
self.cancellations_changed.notify_waiters();
|
||||
}
|
||||
|
||||
pub(super) fn cancellation_deadline(&self) -> Option<tokio::time::Instant> {
|
||||
self.state()
|
||||
.calls
|
||||
.values()
|
||||
.filter_map(|call| call.cancellation.as_ref().map(|pending| pending.deadline))
|
||||
.min()
|
||||
}
|
||||
|
||||
pub(super) fn expire_cancellation(&self) -> bool {
|
||||
let state = self.state();
|
||||
let now = tokio::time::Instant::now();
|
||||
let Some((call, cancellation)) = state.calls.values().find_map(|call| {
|
||||
call.cancellation
|
||||
.as_ref()
|
||||
.filter(|pending| pending.deadline <= now)
|
||||
.map(|pending| (call, pending))
|
||||
}) else {
|
||||
return false;
|
||||
};
|
||||
tracing::warn!(
|
||||
event = "plugin.rpc.cancellation_timeout",
|
||||
instance_id = call.context.instance_id,
|
||||
call_id = call.context.call_id,
|
||||
phase = if cancellation.transmitted {
|
||||
"confirmation"
|
||||
} else {
|
||||
"send_queue"
|
||||
},
|
||||
"插件取消未在期限内完成,终止会话"
|
||||
);
|
||||
let error = cancellation.error.clone();
|
||||
// 期限复核与失败提交共用调用表锁,确认到达后不能被旧检查结果关闭
|
||||
self.fail_with_state(error, state);
|
||||
true
|
||||
}
|
||||
|
||||
pub fn acknowledge_cancellation(&self, id: u64) -> Result<(), RpcError> {
|
||||
|
||||
@@ -14,6 +14,7 @@ pub struct RpcLimits {
|
||||
pub maximum_calls: usize,
|
||||
pub maximum_executing_calls: usize,
|
||||
pub maximum_queued_calls: usize,
|
||||
/// 初次准入、恢复、取消发送排队及确认等待各自使用此期限
|
||||
pub maximum_queue_timeout: Duration,
|
||||
pub maximum_callbacks: usize,
|
||||
pub handshake_timeout: Duration,
|
||||
|
||||
@@ -70,6 +70,10 @@ async fn write_loop<W: AsyncWrite + Unpin>(
|
||||
)));
|
||||
return;
|
||||
}
|
||||
if let Message::Cancel { id } = frame.message() {
|
||||
// 确认预算从控制帧完整写出后开始,不包含其他帧造成的发送排队
|
||||
shared.cancellation_transmitted(*id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -84,10 +88,32 @@ async fn read_loop<R: AsyncRead + Unpin>(
|
||||
if *stopped.borrow() {
|
||||
return;
|
||||
}
|
||||
let frame = tokio::select! {
|
||||
biased;
|
||||
_ = stopped.changed() => return,
|
||||
frame = read_frame(&mut reader) => frame,
|
||||
let frame = read_frame(&mut reader);
|
||||
tokio::pin!(frame);
|
||||
let frame = loop {
|
||||
let changed = shared.cancellations_changed.notified();
|
||||
tokio::pin!(changed);
|
||||
changed.as_mut().enable();
|
||||
let deadline = shared.cancellation_deadline();
|
||||
let expired = async {
|
||||
match deadline {
|
||||
Some(deadline) => tokio::time::sleep_until(deadline).await,
|
||||
None => std::future::pending().await,
|
||||
}
|
||||
};
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = stopped.changed() => return,
|
||||
// 读取与取消超时只有一个裁决者,已就绪的确认优先于超时
|
||||
frame = &mut frame => break frame,
|
||||
// 保留同一个读帧 future,期限变更不能丢弃已读取的半帧
|
||||
_ = &mut changed => {},
|
||||
() = expired => {
|
||||
if shared.expire_cancellation() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
let frame = match frame {
|
||||
Ok(frame) => frame,
|
||||
|
||||
@@ -36,26 +36,22 @@ async fn http_waiting_next_releases_execution_for_reject_plugin() {
|
||||
#[tokio::test]
|
||||
async fn http_in_flight_limit_never_delegates_and_recovers_after_cancellation() {
|
||||
for policy in [PluginFailurePolicy::Delegate, PluginFailurePolicy::Reject] {
|
||||
assert_capacity(
|
||||
policy,
|
||||
RpcLimits {
|
||||
maximum_calls: 64,
|
||||
..Default::default()
|
||||
},
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
assert_capacity(policy, RpcLimits::default(), true).await;
|
||||
}
|
||||
}
|
||||
|
||||
async fn assert_capacity(policy: PluginFailurePolicy, limits: RpcLimits, saturated: bool) {
|
||||
const CONCURRENT_CALLS: usize = 64;
|
||||
let concurrent_calls = if saturated {
|
||||
limits.maximum_calls
|
||||
} else {
|
||||
limits.maximum_executing_calls
|
||||
};
|
||||
let (cache, runtime, generation, plan) =
|
||||
http_plugin_with_policy("passthrough", limits, policy).await;
|
||||
let release = Arc::new(tokio::sync::Semaphore::new(0));
|
||||
let (started, mut entered) = tokio::sync::mpsc::unbounded_channel();
|
||||
let mut slow_calls = tokio::task::JoinSet::new();
|
||||
for index in 0..CONCURRENT_CALLS {
|
||||
for index in 0..concurrent_calls {
|
||||
let plan = plan.clone();
|
||||
let release = release.clone();
|
||||
let started = started.clone();
|
||||
@@ -120,7 +116,7 @@ async fn assert_capacity(policy: PluginFailurePolicy, limits: RpcLimits, saturat
|
||||
assert!(matches!(result, Err(error) if error.is_cancelled()));
|
||||
}
|
||||
}
|
||||
release.add_permits(CONCURRENT_CALLS);
|
||||
release.add_permits(concurrent_calls);
|
||||
while let Some(result) = slow_calls.join_next().await {
|
||||
let response = result.unwrap().unwrap();
|
||||
assert_eq!(response.headers()["x-http-plugin"], "active");
|
||||
|
||||
@@ -812,9 +812,153 @@ async fn explicit_policy_denial_keeps_its_error_kind_and_status() {
|
||||
session.shutdown(Duration::from_secs(1)).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn queued_cancellation_survives_backpressure_but_a_stalled_writer_is_bounded() {
|
||||
for recover in [true, false] {
|
||||
let (cache, prepared, handshake, processes) = prepared_session();
|
||||
let session = RpcSession::start(
|
||||
prepared,
|
||||
handshake,
|
||||
RpcLimits {
|
||||
maximum_queue_timeout: Duration::from_secs(2),
|
||||
..Default::default()
|
||||
},
|
||||
&processes,
|
||||
Arc::new(Callbacks::default()),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let entered = cache.path().join("frame-entered");
|
||||
let release = cache.path().join("frame-release");
|
||||
let mut hanging = Box::pin(session.call(
|
||||
"hang",
|
||||
session.context(Stage::Request, Duration::from_secs(10)),
|
||||
json!({}),
|
||||
vec![],
|
||||
));
|
||||
assert!(futures::poll!(&mut hanging).is_pending());
|
||||
session
|
||||
.call(
|
||||
"pause_next_frame",
|
||||
session.context(Stage::Request, Duration::from_secs(10)),
|
||||
json!({"entered": entered, "release": release}),
|
||||
vec![],
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let mut blocked = Box::pin(session.call(
|
||||
"echo",
|
||||
session.context(Stage::Request, Duration::from_secs(10)),
|
||||
json!({}),
|
||||
vec![42; 4 * 1024 * 1024],
|
||||
));
|
||||
assert!(futures::poll!(&mut blocked).is_pending());
|
||||
tokio::time::timeout(Duration::from_secs(5), async {
|
||||
while !entered.exists() {
|
||||
tokio::time::sleep(Duration::from_millis(5)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
drop(hanging);
|
||||
// Cancel 尚未写出,不能将共享写泵的排队时间视为对端拒绝确认
|
||||
tokio::time::sleep(Duration::from_millis(350)).await;
|
||||
assert!(session.is_ready(), "queued cancellation closed the session");
|
||||
if recover {
|
||||
std::fs::write(release, b"ready").unwrap();
|
||||
let reply = tokio::time::timeout(Duration::from_secs(5), blocked)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(reply.payload, vec![42; 4 * 1024 * 1024]);
|
||||
assert!(
|
||||
session
|
||||
.call(
|
||||
"echo",
|
||||
session.context(Stage::Request, Duration::from_secs(2)),
|
||||
json!("after-cancel"),
|
||||
vec![],
|
||||
)
|
||||
.await
|
||||
.is_ok()
|
||||
);
|
||||
} else {
|
||||
assert!(matches!(
|
||||
tokio::time::timeout(Duration::from_secs(3), blocked)
|
||||
.await
|
||||
.unwrap(),
|
||||
Err(RpcError::Cancelled)
|
||||
));
|
||||
assert!(!session.is_ready());
|
||||
}
|
||||
session.shutdown(Duration::from_secs(1)).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cancellation_confirmation_survives_peer_backpressure() {
|
||||
let (cache, session) = session(Arc::new(Callbacks::default())).await;
|
||||
let entered = cache.path().join("cancel-entered");
|
||||
let release = cache.path().join("cancel-release");
|
||||
let mut hanging = Box::pin(session.call(
|
||||
"hang",
|
||||
session.context(Stage::Request, Duration::from_secs(10)),
|
||||
json!({}),
|
||||
vec![],
|
||||
));
|
||||
assert!(futures::poll!(&mut hanging).is_pending());
|
||||
session
|
||||
.call(
|
||||
"pause_next_frame",
|
||||
session.context(Stage::Request, Duration::from_secs(10)),
|
||||
json!({"entered": entered, "release": release}),
|
||||
vec![],
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
drop(hanging);
|
||||
tokio::time::timeout(Duration::from_secs(5), async {
|
||||
while !entered.exists() {
|
||||
tokio::time::sleep(Duration::from_millis(5)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
// 小控制帧已写入管道,但对端仍可能在处理此前排队的调用与确认
|
||||
tokio::time::sleep(Duration::from_millis(350)).await;
|
||||
assert!(
|
||||
session.is_ready(),
|
||||
"pending confirmation closed the session"
|
||||
);
|
||||
std::fs::write(release, b"ready").unwrap();
|
||||
let reply = session
|
||||
.call(
|
||||
"echo",
|
||||
session.context(Stage::Request, Duration::from_secs(2)),
|
||||
json!("after-cancel"),
|
||||
vec![],
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(reply.result, json!("after-cancel"));
|
||||
session.shutdown(Duration::from_secs(1)).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ignored_cancellation_closes_the_incarnation_and_settles_other_calls() {
|
||||
let (_cache, session) = session(Arc::new(Callbacks::default())).await;
|
||||
let (_cache, prepared, handshake, processes) = prepared_session();
|
||||
let session = RpcSession::start(
|
||||
prepared,
|
||||
handshake,
|
||||
RpcLimits {
|
||||
maximum_queue_timeout: Duration::from_millis(350),
|
||||
..Default::default()
|
||||
},
|
||||
&processes,
|
||||
Arc::new(Callbacks::default()),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let first = session.call(
|
||||
"hang_uncancellable",
|
||||
session.context(Stage::Request, Duration::from_millis(100)),
|
||||
@@ -823,13 +967,18 @@ async fn ignored_cancellation_closes_the_incarnation_and_settles_other_calls() {
|
||||
);
|
||||
let second = session.call(
|
||||
"hang",
|
||||
session.context(Stage::Request, Duration::from_secs(2)),
|
||||
session.context(Stage::Request, Duration::from_secs(10)),
|
||||
json!({}),
|
||||
vec![],
|
||||
);
|
||||
let (first, second) = tokio::join!(first, second);
|
||||
let (first, second) = tokio::time::timeout(Duration::from_secs(3), async {
|
||||
tokio::join!(first, second)
|
||||
})
|
||||
.await
|
||||
.expect("unacknowledged cancellation must close the session before other calls expire");
|
||||
assert!(matches!(first, Err(RpcError::Timeout)));
|
||||
assert!(matches!(second, Err(RpcError::Timeout)));
|
||||
assert!(!session.is_ready());
|
||||
session.shutdown(Duration::from_secs(1)).await;
|
||||
}
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@ use gateway_plugin_sdk::{
|
||||
client::{read_frame, write_frame},
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
use tokio::io::AsyncWriteExt as _;
|
||||
use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};
|
||||
use tokio::sync::{Mutex, Notify, mpsc, oneshot};
|
||||
|
||||
use gateway_plugin_sdk::call::{
|
||||
@@ -1577,7 +1577,20 @@ async fn main() {
|
||||
let mut tasks = BTreeMap::new();
|
||||
let mut uncancellable = std::collections::BTreeSet::new();
|
||||
let mut last_call = 0;
|
||||
while let Ok(frame) = read_frame(&mut input).await {
|
||||
let mut paused_read: Option<(String, String)> = None;
|
||||
loop {
|
||||
let frame = if let Some((entered, release)) = paused_read.take() {
|
||||
// 先确认下一帧已经开始写入,再暂停消费,稳定制造共享写泵的背压
|
||||
let prefix = input.read_u32().await.unwrap().to_be_bytes();
|
||||
std::fs::write(entered, b"reading").unwrap();
|
||||
while !std::path::Path::new(&release).exists() {
|
||||
tokio::time::sleep(Duration::from_millis(5)).await;
|
||||
}
|
||||
read_frame(&mut prefix.as_slice().chain(&mut input)).await
|
||||
} else {
|
||||
read_frame(&mut input).await
|
||||
};
|
||||
let Ok(frame) = frame else { break };
|
||||
match frame.message {
|
||||
Message::Call {
|
||||
id,
|
||||
@@ -1587,6 +1600,21 @@ async fn main() {
|
||||
} => {
|
||||
assert!(id > last_call && !id.is_multiple_of(2) && context.call_id == id);
|
||||
last_call = id;
|
||||
if method == "pause_next_frame" {
|
||||
paused_read = Some((
|
||||
params["entered"].as_str().unwrap().to_owned(),
|
||||
params["release"].as_str().unwrap().to_owned(),
|
||||
));
|
||||
peer.send(
|
||||
Message::Result {
|
||||
id,
|
||||
result: json!({}),
|
||||
},
|
||||
vec![],
|
||||
)
|
||||
.await;
|
||||
continue;
|
||||
}
|
||||
peer.append_observation_marker(
|
||||
"call_context_marker",
|
||||
&json!({"method":method, "context":context}),
|
||||
|
||||
@@ -84,6 +84,9 @@ SDK 和宿主的 `maximum_callbacks` 默认 320、最大 512,统一限制全
|
||||
取消或丢弃回调 future 会释放该回调;宿主不保证已发出的业务操作可以撤销,不自动重试或补偿。
|
||||
已返回响应头的流继续占用总在途预算,不占首结果执行名额,由正文或连接的 owner 管理真实寿命
|
||||
|
||||
取消控制帧的发送排队与确认等待分别使用宿主排队期限,默认各 30 秒;确认期限从控制帧完整写出后开始计算。
|
||||
发送排队或确认超时会终止该插件会话并回收在途调用,运行日志区分这两个阶段
|
||||
|
||||
实际容量由宿主预算与 SDK 会话配置共同限制,较小的插件侧上限会提前拒绝新调用。
|
||||
达到容量或等待上限时,中间件返回过载错误;HTTP 响应为 503(`middleware_capacity_unavailable`),
|
||||
不跳过插件或重放请求。调整 SDK 会话配置需重新构建插件包,容量应结合插件耗时、正文和响应流的资源占用评估
|
||||
|
||||
@@ -493,6 +493,7 @@ let plugin = PluginBuilder::from_json(manifest_json)?
|
||||
attempt 中间件在此基线上继续改写,终端不再应用 Fast 策略。
|
||||
request 与 attempt 阶段通过 `append_header` 添加的请求头会进入上游请求,不适合存放插件内部标记或仅供下游读取的信息。
|
||||
OpenAI 与 xAI 的上游 headers 先由账号和画像生成,插件同名字段覆盖基线,同名多值按插件顺序保留;不存在按认证、Cookie 或会话名称划分的保护列表。
|
||||
xAI 明确换号时会在合并后清理 `traceparent`、`tracestate`、`sentry-trace`、`baggage`,避免将上一账号的追踪上下文带入新账号。
|
||||
CPR 中间件添加的 HTTP 扩展头在发往 Antigravity 时经过该 Provider 的过滤:账号身份、客户端画像和 HTTP 传输字段由网关生成,明确换号时清理已识别的追踪头,其余头保留多值字节,具体范围见 [AGY 请求合同](../../../../../docs/api.md#antigravity-客户端原生生成)。
|
||||
实际账号租约、凭据版本与计费归属仍记录真实选中事实,不随插件修改 header 名称而伪造
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! 跨协议 HTTP 头部传输边界与重试时间解析
|
||||
//! 跨协议 HTTP 传输、下游环境头分类与重试时间解析
|
||||
|
||||
/// 解析 HTTP 和流内错误共用的 Retry-After,保留零延迟并向上取整剩余秒数
|
||||
pub fn parse_retry_after_seconds(value: &str) -> Option<u64> {
|
||||
@@ -46,6 +46,26 @@ pub fn is_transport_managed_request_header(name: &str) -> bool {
|
||||
)
|
||||
}
|
||||
|
||||
/// 判断小写请求头是否描述下游反代、浏览器或 SDK 环境
|
||||
///
|
||||
/// 仅提供分类,由 Provider 决定是否过滤,不加入 API 的通用传输头过滤
|
||||
/// 不包含厂商身份、会话别名或业务字段,也不检查请求正文
|
||||
#[must_use]
|
||||
pub fn is_downstream_environment_request_header(name: &str) -> bool {
|
||||
// 反代来源信息只描述客户端到网关这一段,cf-* 还可能携带 Access 认证
|
||||
name.starts_with("cf-")
|
||||
|| name.starts_with("x-forwarded-")
|
||||
|| matches!(
|
||||
name,
|
||||
"forwarded" | "via" | "cdn-loop" | "x-real-ip" | "true-client-ip"
|
||||
)
|
||||
// SDK、浏览器与页面来源不代表网关连接上游时的环境
|
||||
|| name.starts_with("x-stainless-")
|
||||
|| name.starts_with("sec-ch-ua")
|
||||
|| name.starts_with("sec-fetch-")
|
||||
|| matches!(name, "origin" | "referer")
|
||||
}
|
||||
|
||||
/// 判断响应头是否满足 HTTP 传输和通用鉴权材料的转发边界
|
||||
///
|
||||
/// `connection_options` 来自同一响应的 `Connection` 字段,调用方应先按逗号拆分并
|
||||
|
||||
@@ -772,8 +772,8 @@ impl ClientKeyStore for PgAdminClientKeyStore {
|
||||
.ok_or_else(|| admin_store_error(ENTITY, StoreError::NotFound {
|
||||
source: None, entity: ENTITY, id: id.as_str().to_owned()
|
||||
}))?;
|
||||
let rows: Vec<(String, String, Option<String>, String)> = sqlx::query_as(
|
||||
"select a.id, a.name, a.email, a.provider_kind from provider_accounts a
|
||||
let rows: Vec<(String, String, Option<String>, String, Option<String>)> = sqlx::query_as(
|
||||
"select a.id, a.name, a.email, a.provider_kind, a.platform_icon from provider_accounts a
|
||||
where a.id > $1
|
||||
and ($2 = '' or strpos(lower(a.name), lower($2)) > 0
|
||||
or strpos(lower(coalesce(a.email, '')), lower($2)) > 0)
|
||||
@@ -793,12 +793,15 @@ impl ClientKeyStore for PgAdminClientKeyStore {
|
||||
let items: Vec<_> = rows
|
||||
.into_iter()
|
||||
.take(usize::from(PAGE_SIZE))
|
||||
.map(|(id, name, email, provider)| BudgetReferenceAccount {
|
||||
id,
|
||||
name,
|
||||
email,
|
||||
provider,
|
||||
})
|
||||
.map(
|
||||
|(id, name, email, provider, platform_icon)| BudgetReferenceAccount {
|
||||
platform_icon,
|
||||
id,
|
||||
name,
|
||||
email,
|
||||
provider,
|
||||
},
|
||||
)
|
||||
.collect();
|
||||
let next_cursor = items.last().filter(|_| has_more).map(|row| row.id.clone());
|
||||
Ok(BudgetReferenceAccountPage { items, next_cursor })
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
use super::*;
|
||||
|
||||
const PROVIDER_SET: &str = "coalesce(array_agg(distinct provider_kind) filter(where provider_kind <> ''), '{}'::text[]) as providers,";
|
||||
|
||||
/// 输入 matching 提供分组键、指标输入列及 is_completed_usage
|
||||
/// 精确分位数在整个结果组内计算,不把局部分位数合并成新的分位数
|
||||
pub(super) fn push_fact_aggregation(
|
||||
@@ -16,6 +18,7 @@ pub(super) fn push_fact_aggregation(
|
||||
DistributionRead::Full,
|
||||
None,
|
||||
None,
|
||||
false,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -26,6 +29,7 @@ pub(super) fn push_fact_aggregation_selected(
|
||||
distributions: DistributionRead,
|
||||
counter_names: Option<&[&str]>,
|
||||
distribution_names: Option<&[&str]>,
|
||||
model_providers: bool,
|
||||
) {
|
||||
if read_costs && matches!(distributions, DistributionRead::Statistics) {
|
||||
push_fact_statistics_by_currency(query, counter_names, distribution_names);
|
||||
@@ -35,6 +39,9 @@ pub(super) fn push_fact_aggregation_selected(
|
||||
let statistics_only = matches!(distributions, DistributionRead::Statistics);
|
||||
let counters = selected_counter_expressions(counter_names);
|
||||
query.push(", counted as (select output_bucket,name,max(started_at) filter(where is_completed_usage) as last_used_at,");
|
||||
if model_providers {
|
||||
query.push(PROVIDER_SET);
|
||||
}
|
||||
push_counter_object(query, &counters);
|
||||
query.push(" as counts");
|
||||
if read_distributions && (exact_percentiles || statistics_only) {
|
||||
@@ -51,21 +58,16 @@ pub(super) fn push_fact_aggregation_selected(
|
||||
// 空币种仍参与场景费用,金额为空的实际费用继续在展开后排除
|
||||
query.push(", cost_groups as (select output_bucket,name,cost_currency,sum(cost_amount) as cost_amount,sum(standard_cost_amount) as standard_cost_amount,sum(no_cache_cost_amount) as no_cache_cost_amount from matching where is_completed_usage group by output_bucket,name,cost_currency), cost_values as (select output_bucket,name,currency,sum(amount)::text as amount from cost_groups cross join lateral (values (cost_currency,cost_amount),('standard_usd',standard_cost_amount),('no_cache_usd',no_cache_cost_amount)) cost(currency,amount) where currency is not null and amount is not null group by output_bucket,name,currency), merged_costs as (select output_bucket,name,jsonb_object_agg(currency,amount) as costs from cost_values group by output_bucket,name)");
|
||||
}
|
||||
if !read_distributions {
|
||||
query.push(" select c.output_bucket as bucket_start,c.name,c.counts,c.last_used_at,'{}'::jsonb as distributions,'{}'::jsonb as exact_percentiles,");
|
||||
query.push(if read_costs {
|
||||
"coalesce(k.costs,'{}'::jsonb)"
|
||||
} else {
|
||||
"'{}'::jsonb"
|
||||
});
|
||||
query.push(" as costs from counted c");
|
||||
if read_costs {
|
||||
query.push(" left join merged_costs k using(output_bucket,name)");
|
||||
if !read_distributions || exact_percentiles || statistics_only {
|
||||
query.push(" select c.output_bucket as bucket_start,c.name,c.counts,c.last_used_at,");
|
||||
if model_providers {
|
||||
query.push("c.providers,");
|
||||
}
|
||||
return;
|
||||
}
|
||||
if exact_percentiles || statistics_only {
|
||||
query.push(" select c.output_bucket as bucket_start,c.name,c.counts,c.last_used_at,c.distributions,c.exact_percentiles,");
|
||||
query.push(if read_distributions {
|
||||
"c.distributions,c.exact_percentiles,"
|
||||
} else {
|
||||
"'{}'::jsonb as distributions,'{}'::jsonb as exact_percentiles,"
|
||||
});
|
||||
query.push(if read_costs {
|
||||
"coalesce(k.costs,'{}'::jsonb)"
|
||||
} else {
|
||||
@@ -99,6 +101,9 @@ pub(super) fn push_fact_aggregation_selected(
|
||||
query.push(" from sample_stats s");
|
||||
query.push(" left join merged_bins b using(output_bucket,name,metric)");
|
||||
query.push(" group by s.output_bucket,s.name) select c.output_bucket as bucket_start,c.name,c.counts,c.last_used_at,");
|
||||
if model_providers {
|
||||
query.push("c.providers,");
|
||||
}
|
||||
query.push(if read_costs {
|
||||
"coalesce(k.costs,'{}'::jsonb)"
|
||||
} else {
|
||||
@@ -133,6 +138,7 @@ fn push_fact_statistics_by_currency(
|
||||
true,
|
||||
counter_names,
|
||||
distribution_names,
|
||||
false,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -322,6 +328,7 @@ pub(super) fn push_summary_aggregation(
|
||||
costs: bool,
|
||||
counter_names: Option<&[&str]>,
|
||||
distribution_names: Option<&[&str]>,
|
||||
model_providers: bool,
|
||||
) {
|
||||
push_summary_aggregation_from(
|
||||
query,
|
||||
@@ -330,6 +337,7 @@ pub(super) fn push_summary_aggregation(
|
||||
costs,
|
||||
counter_names,
|
||||
distribution_names,
|
||||
model_providers,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -341,6 +349,7 @@ fn push_summary_aggregation_from(
|
||||
costs: bool,
|
||||
counter_names: Option<&[&str]>,
|
||||
distribution_names: Option<&[&str]>,
|
||||
model_providers: bool,
|
||||
) {
|
||||
let distributions = !matches!(distribution_read, DistributionRead::None);
|
||||
// 每个源汇总只展开一次固定指标,避免按指标键放大行数再排序
|
||||
@@ -359,6 +368,9 @@ fn push_summary_aggregation_from(
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
query.push(", grouped as (select output_bucket,name,max(last_used_at) as last_used_at,");
|
||||
if model_providers {
|
||||
query.push(PROVIDER_SET);
|
||||
}
|
||||
push_counter_object(query, &counters);
|
||||
query
|
||||
.push(" as counts from ")
|
||||
@@ -404,6 +416,9 @@ fn push_summary_aggregation_from(
|
||||
}
|
||||
}
|
||||
query.push(" select g.output_bucket as bucket_start,g.name,g.last_used_at,g.counts,");
|
||||
if model_providers {
|
||||
query.push("g.providers,");
|
||||
}
|
||||
query.push(if costs {
|
||||
"coalesce(k.costs,'{}'::jsonb)"
|
||||
} else {
|
||||
@@ -475,6 +490,14 @@ pub(super) fn fact_dimension_sql(dimension: Option<DiagnosticDimension>) -> &'st
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn summary_provider_column(collection: &str) -> &'static str {
|
||||
if matches!(collection, "account_model" | "key_model") {
|
||||
"dimensions[2]"
|
||||
} else {
|
||||
"dimensions[1]"
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn summary_dimension_sql(
|
||||
collection: &str,
|
||||
dimension: Option<DiagnosticDimension>,
|
||||
@@ -483,7 +506,10 @@ pub(super) fn summary_dimension_sql(
|
||||
match dimension {
|
||||
None => "''::text".to_owned(),
|
||||
Some(DiagnosticDimension::Provider) => {
|
||||
format!("coalesce(nullif(dimensions[{}],''),'unrouted')", 1 + offset)
|
||||
format!(
|
||||
"coalesce(nullif({},''),'unrouted')",
|
||||
summary_provider_column(collection)
|
||||
)
|
||||
}
|
||||
Some(DiagnosticDimension::Model) => format!(
|
||||
"coalesce(nullif(dimensions[{}],''),dimensions[{}],'')",
|
||||
|
||||
@@ -81,7 +81,14 @@ impl AnalyticsSnapshot<'_> {
|
||||
granularity,
|
||||
boundaries.as_deref(),
|
||||
);
|
||||
q.push(format!(" as output_bucket,{name} as name,counts,costs from request_analytics_1h where collection=")).push_bind(AGGREGATE_COLLECTION).push(" and bucket_start >= ").push_bind(range.start).push(" and bucket_start < ").push_bind(range.end);
|
||||
let model_providers =
|
||||
dimension == Some(DiagnosticDimension::Model) && account_models.is_none();
|
||||
let provider = if model_providers {
|
||||
"dimensions[1] as provider_kind,"
|
||||
} else {
|
||||
""
|
||||
};
|
||||
q.push(format!(" as output_bucket,{name} as name,{provider}counts,costs from request_analytics_1h where collection=")).push_bind(AGGREGATE_COLLECTION).push(" and bucket_start >= ").push_bind(range.start).push(" and bucket_start < ").push_bind(range.end);
|
||||
for (index, value) in [
|
||||
(1, &filter.provider_kind),
|
||||
(2, &filter.model),
|
||||
@@ -124,7 +131,14 @@ impl AnalyticsSnapshot<'_> {
|
||||
if selection.costs {
|
||||
q.push(" union all select output_bucket,name,'cost',c.key,c.value::numeric from matching cross join lateral jsonb_each_text(costs) c");
|
||||
}
|
||||
q.push("), totals as (select output_bucket,name,kind,key,sum(value)::text as value from entries group by output_bucket,name,kind,key) select output_bucket,name,jsonb_object_agg(key,value) filter(where kind='count') as counts,jsonb_object_agg(key,value) filter(where kind='cost') as costs from totals group by output_bucket,name");
|
||||
if model_providers {
|
||||
q.push(" union all select distinct output_bucket,name,'provider',provider_kind,0::numeric from matching where provider_kind <> ''");
|
||||
}
|
||||
q.push("), totals as (select output_bucket,name,kind,key,sum(value)::text as value from entries group by output_bucket,name,kind,key) select output_bucket,name,jsonb_object_agg(key,value) filter(where kind='count') as counts,jsonb_object_agg(key,value) filter(where kind='cost') as costs");
|
||||
if model_providers {
|
||||
q.push(",array_agg(key) filter(where kind='provider') as providers");
|
||||
}
|
||||
q.push(" from totals group by output_bucket,name");
|
||||
let mut rows = q.build().fetch(&mut *self.tx);
|
||||
while let Some(row) = rows
|
||||
.try_next()
|
||||
@@ -140,6 +154,11 @@ impl AnalyticsSnapshot<'_> {
|
||||
}
|
||||
let key = (get(&row, "output_bucket")?, name);
|
||||
let state = states.entry(key).or_default();
|
||||
if model_providers {
|
||||
state
|
||||
.providers
|
||||
.extend(get::<Option<Vec<String>>>(&row, "providers")?.unwrap_or_default());
|
||||
}
|
||||
let counts =
|
||||
get::<Option<sqlx::types::Json<BTreeMap<String, String>>>>(&row, "counts")?
|
||||
.map(|v| v.0)
|
||||
|
||||
@@ -104,6 +104,7 @@ impl AnalyticsSnapshot<'_> {
|
||||
"unavailable_count",
|
||||
]),
|
||||
None,
|
||||
false,
|
||||
);
|
||||
sql.push(") fact_parts");
|
||||
}
|
||||
|
||||
@@ -22,6 +22,9 @@ pub(crate) struct MetricState {
|
||||
pub(super) distributions: BTreeMap<String, Histogram>,
|
||||
pub(super) costs: BTreeMap<String, String>,
|
||||
pub(super) last_used_at: Option<DateTime<Utc>>,
|
||||
// 模型诊断查询时从分组维度提取,不写入持久化指标
|
||||
#[serde(skip)]
|
||||
pub(super) providers: BTreeSet<String>,
|
||||
#[serde(skip)]
|
||||
exact_percentiles: Option<BTreeMap<String, Vec<Option<f64>>>>,
|
||||
}
|
||||
@@ -38,6 +41,7 @@ impl MetricState {
|
||||
)?
|
||||
.0,
|
||||
last_used_at: get(row, "last_used_at")?,
|
||||
providers: BTreeSet::new(),
|
||||
exact_percentiles: None,
|
||||
})
|
||||
}
|
||||
@@ -125,6 +129,7 @@ impl MetricState {
|
||||
if self.count("request_count") == 0 {
|
||||
self.exact_percentiles.clone_from(&other.exact_percentiles);
|
||||
}
|
||||
self.providers.extend(other.providers.iter().cloned());
|
||||
self.last_used_at = self.last_used_at.max(other.last_used_at);
|
||||
for (name, count) in &other.counts {
|
||||
self.increment(name, *count)?;
|
||||
|
||||
@@ -634,7 +634,8 @@ impl<'a> AnalyticsSnapshot<'a> {
|
||||
observations.push(DiagnosticObservation {
|
||||
key: key.clone(),
|
||||
name: key,
|
||||
account_provider_kind: None,
|
||||
providers: state.providers.iter().cloned().collect(),
|
||||
platform_icon: None,
|
||||
account_authentication_kind: None,
|
||||
account_plan_type: None,
|
||||
account_plan_type_display: None,
|
||||
@@ -671,9 +672,9 @@ impl<'a> AnalyticsSnapshot<'a> {
|
||||
.map(|item| item.key.clone())
|
||||
.collect::<Vec<_>>();
|
||||
let statement = if dimension == DiagnosticDimension::Account {
|
||||
"select requested.id, historical.provider_kind, historical.provider_account_authentication_kind_snapshot as authentication_kind, historical.provider_account_plan_type_snapshot as plan_type, historical.provider_account_plan_type_display_snapshot as plan_type_display, coalesce(historical.provider_account_email_snapshot,historical.provider_account_name_snapshot,requested.id) as name from unnest($1::text[]) requested(id) left join lateral (select provider_kind,provider_account_authentication_kind_snapshot,provider_account_plan_type_snapshot,provider_account_plan_type_display_snapshot,provider_account_email_snapshot,provider_account_name_snapshot from model_request_observations mr where mr.provider_account_ref=requested.id order by mr.started_at desc,mr.id desc limit 1) historical on true"
|
||||
"select requested.id, coalesce(historical.provider_kind,a.provider_kind) as provider_kind, a.platform_icon, historical.provider_account_authentication_kind_snapshot as authentication_kind, historical.provider_account_plan_type_snapshot as plan_type, historical.provider_account_plan_type_display_snapshot as plan_type_display, coalesce(historical.provider_account_email_snapshot,historical.provider_account_name_snapshot,requested.id) as name from unnest($1::text[]) requested(id) left join provider_accounts a on a.id=requested.id left join lateral (select provider_kind,provider_account_authentication_kind_snapshot,provider_account_plan_type_snapshot,provider_account_plan_type_display_snapshot,provider_account_email_snapshot,provider_account_name_snapshot from model_request_observations mr where mr.provider_account_ref=requested.id order by mr.started_at desc,mr.id desc limit 1) historical on true"
|
||||
} else {
|
||||
"select requested.id, null::text as provider_kind, null::text as authentication_kind, null::text as plan_type, null::text as plan_type_display, coalesce(historical.client_api_key_name_snapshot,requested.id) as name from unnest($1::text[]) requested(id) left join lateral (select client_api_key_name_snapshot from model_request_observations mr where mr.client_api_key_ref=requested.id order by mr.started_at desc,mr.id desc limit 1) historical on true"
|
||||
"select requested.id, null::text as provider_kind, null::text as platform_icon, null::text as authentication_kind, null::text as plan_type, null::text as plan_type_display, coalesce(historical.client_api_key_name_snapshot,requested.id) as name from unnest($1::text[]) requested(id) left join lateral (select client_api_key_name_snapshot from model_request_observations mr where mr.client_api_key_ref=requested.id order by mr.started_at desc,mr.id desc limit 1) historical on true"
|
||||
};
|
||||
let labels = sqlx::query(statement)
|
||||
.bind(ids)
|
||||
@@ -684,7 +685,10 @@ impl<'a> AnalyticsSnapshot<'a> {
|
||||
let id: String = get(&row, "id")?;
|
||||
if let Some(item) = observations.iter_mut().find(|item| item.key == id) {
|
||||
item.name = get(&row, "name")?;
|
||||
item.account_provider_kind = get(&row, "provider_kind")?;
|
||||
item.providers = get::<Option<String>>(&row, "provider_kind")?
|
||||
.into_iter()
|
||||
.collect();
|
||||
item.platform_icon = get(&row, "platform_icon")?;
|
||||
item.account_authentication_kind = get(&row, "authentication_kind")?;
|
||||
item.account_plan_type = get(&row, "plan_type")?;
|
||||
item.account_plan_type_display = get(&row, "plan_type_display")?;
|
||||
@@ -951,6 +955,7 @@ impl<'a> AnalyticsSnapshot<'a> {
|
||||
let read_distributions = !matches!(distributions, DistributionRead::None);
|
||||
filter.validate()?;
|
||||
self.require_visible(Some(range))?;
|
||||
let model_providers = dimension == Some(DiagnosticDimension::Model);
|
||||
let selected = collection_for(filter, dimension);
|
||||
let boundaries = if granularity == Some(ObservationGranularity::Day) {
|
||||
Some(calendar_buckets(range, timezone)?)
|
||||
@@ -1004,7 +1009,15 @@ impl<'a> AnalyticsSnapshot<'a> {
|
||||
} else {
|
||||
"'{}'::jsonb as distributions"
|
||||
};
|
||||
query.push(format!(" as output_bucket,{name} as name,outcome,counts,{costs},{distribution_sql},last_used_at from {table} a where collection="))
|
||||
let provider = if model_providers {
|
||||
format!(
|
||||
"{} as provider_kind,",
|
||||
aggregate::summary_provider_column(collection)
|
||||
)
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
query.push(format!(" as output_bucket,{name} as name,{provider}outcome,counts,{costs},{distribution_sql},last_used_at from {table} a where collection="))
|
||||
.push_bind(collection).push(" and schema_version=").push_bind(SCHEMA_VERSION)
|
||||
.push(" and histogram_version=").push_bind(HISTOGRAM_VERSION);
|
||||
push_summary_buckets(&mut query, &buckets, seconds);
|
||||
@@ -1032,6 +1045,7 @@ impl<'a> AnalyticsSnapshot<'a> {
|
||||
read_costs,
|
||||
counters,
|
||||
distribution_names,
|
||||
model_providers,
|
||||
);
|
||||
let mut rows = query.build().fetch(&mut *self.tx);
|
||||
while let Some(row) = rows
|
||||
@@ -1041,7 +1055,11 @@ impl<'a> AnalyticsSnapshot<'a> {
|
||||
{
|
||||
let bucket = get(&row, "bucket_start")?;
|
||||
let name = get(&row, "name")?;
|
||||
let state = MetricState::decode(&row)?;
|
||||
let mut state = MetricState::decode(&row)?;
|
||||
if model_providers {
|
||||
state.providers =
|
||||
get::<Vec<String>>(&row, "providers")?.into_iter().collect();
|
||||
}
|
||||
result.entry((bucket, name)).or_default().merge(&state)?;
|
||||
}
|
||||
}
|
||||
@@ -1124,6 +1142,7 @@ impl<'a> AnalyticsSnapshot<'a> {
|
||||
distributions,
|
||||
counters,
|
||||
distribution_names,
|
||||
model_providers,
|
||||
);
|
||||
let mut rows = query.build().fetch(&mut *self.tx);
|
||||
while let Some(row) = rows
|
||||
@@ -1132,10 +1151,13 @@ impl<'a> AnalyticsSnapshot<'a> {
|
||||
.map_err(|error| postgres_unavailable("aggregate analytics facts", error))?
|
||||
{
|
||||
let key = (get(&row, "bucket_start")?, get(&row, "name")?);
|
||||
let state = MetricState::decode_aggregate(
|
||||
let mut state = MetricState::decode_aggregate(
|
||||
&row,
|
||||
exact && matches!(distributions, DistributionRead::Full),
|
||||
)?;
|
||||
if model_providers {
|
||||
state.providers = get::<Vec<String>>(&row, "providers")?.into_iter().collect();
|
||||
}
|
||||
if exact {
|
||||
result.insert(key, state);
|
||||
} else {
|
||||
|
||||
@@ -111,6 +111,7 @@ pub(crate) async fn declare_usage_statistics(
|
||||
DistributionRead::None,
|
||||
Some(&names),
|
||||
None,
|
||||
false,
|
||||
);
|
||||
query.push(") facts");
|
||||
}
|
||||
|
||||
@@ -107,15 +107,15 @@ impl PgRequestAnalyticsRepository {
|
||||
order by pending.oldest_pending_at, pending.request_id limit ($1::bigint - (select count(*) from live))
|
||||
) select request_id, change_version from live union all select request_id, change_version from oldest")
|
||||
.bind(i64::from(batch_size)).fetch_all(&mut *transaction).await.map_err(|error| postgres_unavailable("load analytics request queue", error))?;
|
||||
let mut jobs = Vec::with_capacity(rows.len());
|
||||
let mut ids = Vec::<String>::with_capacity(rows.len());
|
||||
let mut versions = Vec::<i64>::with_capacity(rows.len());
|
||||
for row in rows {
|
||||
jobs.push(ProjectionJob { id: get(&row,"request_id")?, version: get(&row,"change_version")? });
|
||||
ids.push(get(&row,"request_id")?);
|
||||
versions.push(get(&row,"change_version")?);
|
||||
}
|
||||
self.project_batch(&mut transaction, &jobs).await?;
|
||||
result.projected_requests = jobs.len() as u64;
|
||||
self.project_batch(&mut transaction, &ids).await?;
|
||||
result.projected_requests = ids.len() as u64;
|
||||
result.backfilled_requests = self.backfill(&mut transaction, batch_size).await?;
|
||||
let ids = jobs.iter().map(|job|job.id.clone()).collect::<Vec<_>>();
|
||||
let versions = jobs.iter().map(|job|job.version).collect::<Vec<_>>();
|
||||
if result.projected_requests + result.backfilled_requests > 0 {
|
||||
publish_generation(&mut transaction, true).await?;
|
||||
}
|
||||
@@ -153,38 +153,35 @@ impl PgRequestAnalyticsRepository {
|
||||
async fn project_batch(
|
||||
&self,
|
||||
tx: &mut sqlx::Transaction<'_, Postgres>,
|
||||
jobs: &[ProjectionJob],
|
||||
ids: &[String],
|
||||
) -> StoreResult<()> {
|
||||
if jobs.is_empty() {
|
||||
if ids.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let ids = jobs.iter().map(|job| job.id.clone()).collect::<Vec<_>>();
|
||||
let versions = jobs.iter().map(|job| job.version).collect::<Vec<_>>();
|
||||
let previous = sqlx::query(sqlx::AssertSqlSafe(format!(
|
||||
"{} where mr.id=any($1::text[])",
|
||||
fact_select()
|
||||
)))
|
||||
.bind(&ids)
|
||||
.bind(ids)
|
||||
.fetch_all(&mut **tx)
|
||||
.await
|
||||
.map_err(|error| postgres_unavailable("read previous analytics contributions", error))?;
|
||||
sqlx::query("delete from request_analytics_facts where id=any($1::text[])")
|
||||
.bind(&ids)
|
||||
.bind(ids)
|
||||
.execute(&mut **tx)
|
||||
.await
|
||||
.map_err(|error| postgres_unavailable("replace analytics facts", error))?;
|
||||
sqlx::query(PROJECT_REQUEST)
|
||||
.bind(&ids)
|
||||
.bind(versions)
|
||||
.bind(ids)
|
||||
.execute(&mut **tx)
|
||||
.await
|
||||
.map_err(|error| postgres_unavailable("project analytics facts", error))?;
|
||||
self.project_billing_batch(tx, &ids).await?;
|
||||
self.project_billing_batch(tx, ids).await?;
|
||||
let current = sqlx::query(sqlx::AssertSqlSafe(format!(
|
||||
"{} where mr.id=any($1::text[])",
|
||||
fact_select()
|
||||
)))
|
||||
.bind(&ids)
|
||||
.bind(ids)
|
||||
.fetch_all(&mut **tx)
|
||||
.await
|
||||
.map_err(|error| postgres_unavailable("read current analytics contributions", error))?;
|
||||
@@ -204,7 +201,7 @@ impl PgRequestAnalyticsRepository {
|
||||
return Ok(0);
|
||||
}
|
||||
let mut query = QueryBuilder::<Postgres>::new(
|
||||
"select id,started_at,nextval('request_analytics_change_version') as version,exists(select 1 from request_analytics_facts f where f.id=model_requests.id) as projected from model_requests",
|
||||
"select id,started_at,exists(select 1 from request_analytics_facts f where f.id=model_requests.id) as projected from model_requests",
|
||||
);
|
||||
// 首批与后续批次使用两种明确的计划,避免可空游标的 OR 使通用计划退化为全索引过滤
|
||||
if let Some(start) = get::<Option<DateTime<Utc>>>(&state, "backfill_cursor_started_at")? {
|
||||
@@ -225,17 +222,14 @@ impl PgRequestAnalyticsRepository {
|
||||
.fetch_all(&mut **tx)
|
||||
.await
|
||||
.map_err(|error| postgres_unavailable("read analytics backfill batch", error))?;
|
||||
let mut jobs = Vec::with_capacity(rows.len());
|
||||
let mut ids = Vec::<String>::with_capacity(rows.len());
|
||||
for row in &rows {
|
||||
if get::<bool>(row, "projected")? {
|
||||
continue;
|
||||
}
|
||||
jobs.push(ProjectionJob {
|
||||
id: get(row, "id")?,
|
||||
version: get(row, "version")?,
|
||||
});
|
||||
ids.push(get(row, "id")?);
|
||||
}
|
||||
self.project_batch(tx, &jobs).await?;
|
||||
self.project_batch(tx, &ids).await?;
|
||||
if let Some(last) = rows.last() {
|
||||
sqlx::query("update request_analytics_build_state set backfill_cursor_started_at = $1, backfill_cursor_id = $2, coverage_start = $1 + interval '1 microsecond' where singleton")
|
||||
.bind(get::<DateTime<Utc>>(last,"started_at")?).bind(get::<String>(last,"id")?).execute(&mut **tx).await.map_err(|error| postgres_unavailable("save analytics backfill cursor", error))?;
|
||||
@@ -377,11 +371,6 @@ pub(super) fn collections(
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
struct ProjectionJob {
|
||||
id: String,
|
||||
version: i64,
|
||||
}
|
||||
|
||||
async fn publish_generation(
|
||||
tx: &mut sqlx::Transaction<'_, Postgres>,
|
||||
facts_changed: bool,
|
||||
@@ -391,4 +380,4 @@ async fn publish_generation(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
const PROJECT_REQUEST: &str = "insert into request_analytics_facts (id, started_at, completed_at, client_api_key_ref, provider_account_ref, routing_group_refs, operation, provider_kind, requested_model_id, upstream_model_id, outcome, client_status_code, upstream_status_code, client_transport, upstream_transport, attempt_count, client_response_id, upstream_response_id, upstream_request_id, recovered_at, downstream_committed_at, request_kind, image_generation_requested, image_generation_succeeded, error_kind, input_tokens, output_tokens, cached_input_tokens, cache_write_input_tokens, reasoning_output_tokens, image_input_tokens, image_output_tokens, total_tokens, cost_source, cost_currency, cost_amount, first_token_ms, latency_ms, admission_decision_ms, account_selection_wait_ms, upstream_response_ms, capacity_used_slots, capacity_total_slots, source_version, ops_failure_count, ops_rate_limited_count, ops_auth_failure_count, ops_provider_5xx_count) select mr.id, mr.started_at, mr.completed_at, mr.client_api_key_ref, mr.provider_account_ref, array(select distinct group_ref from unnest(mr.routing_group_refs) group_ref order by group_ref), mr.operation, mr.provider_kind, mr.requested_model_id, mr.upstream_model_id, mr.outcome, mr.client_status_code, mr.upstream_status_code, mr.client_transport, mr.upstream_transport, mr.attempt_count, mr.client_response_id, mr.upstream_response_id, mr.upstream_request_id, mr.recovered_at, mr.downstream_committed_at, mr.request_kind, mr.image_generation_requested, mr.image_generation_succeeded, mr.error_kind, mr.input_tokens, mr.output_tokens, mr.cached_input_tokens, mr.cache_write_input_tokens, mr.reasoning_output_tokens, mr.image_input_tokens, mr.image_output_tokens, mr.total_tokens, mr.cost_source, mr.cost_currency, mr.cost_amount, mr.first_token_ms, mr.latency_ms, mr.admission_decision_ms, mr.account_selection_wait_ms, mr.upstream_response_ms, mr.capacity_used_slots, mr.capacity_total_slots, job.version, ops.failure_count, ops.rate_limited_count, ops.auth_failure_count, ops.provider_5xx_count from unnest($1::text[],$2::bigint[]) job(id,version) join model_request_observations mr on mr.id=job.id cross join lateral (select count(*)::bigint as failure_count, count(*) filter(where failure_kind in ('rate_limited','quota_exhausted') or status_code=429)::bigint as rate_limited_count, count(*) filter(where failure_kind in ('authentication','authorization','invalid_credential') or status_code in (401,403))::bigint as auth_failure_count, count(*) filter(where status_code between 500 and 599)::bigint as provider_5xx_count from ops_events where model_request_id=mr.id) ops returning id, started_at";
|
||||
const PROJECT_REQUEST: &str = "insert into request_analytics_facts (id, started_at, completed_at, client_api_key_ref, provider_account_ref, routing_group_refs, operation, provider_kind, requested_model_id, upstream_model_id, outcome, client_status_code, upstream_status_code, client_transport, upstream_transport, attempt_count, client_response_id, upstream_response_id, upstream_request_id, recovered_at, downstream_committed_at, request_kind, image_generation_requested, image_generation_succeeded, error_kind, input_tokens, output_tokens, cached_input_tokens, cache_write_input_tokens, reasoning_output_tokens, image_input_tokens, image_output_tokens, total_tokens, cost_source, cost_currency, cost_amount, first_token_ms, latency_ms, admission_decision_ms, account_selection_wait_ms, upstream_response_ms, capacity_used_slots, capacity_total_slots, ops_failure_count, ops_rate_limited_count, ops_auth_failure_count, ops_provider_5xx_count) select mr.id, mr.started_at, mr.completed_at, mr.client_api_key_ref, mr.provider_account_ref, array(select distinct group_ref from unnest(mr.routing_group_refs) group_ref order by group_ref), mr.operation, mr.provider_kind, mr.requested_model_id, mr.upstream_model_id, mr.outcome, mr.client_status_code, mr.upstream_status_code, mr.client_transport, mr.upstream_transport, mr.attempt_count, mr.client_response_id, mr.upstream_response_id, mr.upstream_request_id, mr.recovered_at, mr.downstream_committed_at, mr.request_kind, mr.image_generation_requested, mr.image_generation_succeeded, mr.error_kind, mr.input_tokens, mr.output_tokens, mr.cached_input_tokens, mr.cache_write_input_tokens, mr.reasoning_output_tokens, mr.image_input_tokens, mr.image_output_tokens, mr.total_tokens, mr.cost_source, mr.cost_currency, mr.cost_amount, mr.first_token_ms, mr.latency_ms, mr.admission_decision_ms, mr.account_selection_wait_ms, mr.upstream_response_ms, mr.capacity_used_slots, mr.capacity_total_slots, ops.failure_count, ops.rate_limited_count, ops.auth_failure_count, ops.provider_5xx_count from unnest($1::text[]) job(id) join model_request_observations mr on mr.id=job.id cross join lateral (select count(*)::bigint as failure_count, count(*) filter(where failure_kind in ('rate_limited','quota_exhausted') or status_code=429)::bigint as rate_limited_count, count(*) filter(where failure_kind in ('authentication','authorization','invalid_credential') or status_code in (401,403))::bigint as auth_failure_count, count(*) filter(where status_code between 500 and 599)::bigint as provider_5xx_count from ops_events where model_request_id=mr.id) ops returning id, started_at";
|
||||
|
||||
@@ -139,6 +139,7 @@ pub(crate) fn admin_dashboard_account_usage(
|
||||
authentication_kind: usage.authentication_kind,
|
||||
name: usage.name,
|
||||
email: usage.email,
|
||||
platform_icon: usage.platform_icon,
|
||||
notes: usage.notes,
|
||||
plan_type: usage.plan_type,
|
||||
plan_type_display: None,
|
||||
@@ -279,7 +280,8 @@ fn admin_diagnostic_observation(
|
||||
admin_observability::DiagnosticObservation {
|
||||
key: observation.key,
|
||||
name: observation.name,
|
||||
account_provider_kind: observation.account_provider_kind,
|
||||
providers: observation.providers,
|
||||
platform_icon: observation.platform_icon,
|
||||
account_authentication_kind: observation.account_authentication_kind,
|
||||
account_plan_type: observation.account_plan_type,
|
||||
account_plan_type_display: observation.account_plan_type_display,
|
||||
@@ -389,6 +391,7 @@ pub(crate) fn usage_list_record_from_row(
|
||||
provider_account_ref: get(row, "provider_account_ref")?,
|
||||
provider_account_name: get(row, "provider_account_name")?,
|
||||
provider_account_email: get(row, "provider_account_email")?,
|
||||
platform_icon: get(row, "platform_icon")?,
|
||||
provider_account_notes: get(row, "provider_account_notes")?,
|
||||
provider_account_upstream_peer: None,
|
||||
provider_account_plan_type: get(row, "provider_account_plan_type")?,
|
||||
|
||||
@@ -228,6 +228,7 @@ pub use gateway_admin::model::observability::AccountRequestBucket as ProviderAcc
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ProviderAccountUsageObservation {
|
||||
pub platform_icon: Option<String>,
|
||||
pub account_id: String,
|
||||
pub provider_kind: String,
|
||||
pub authentication_kind: String,
|
||||
@@ -383,7 +384,8 @@ pub struct DiagnosticsObservation {
|
||||
pub struct DiagnosticObservation {
|
||||
pub key: String,
|
||||
pub name: String,
|
||||
pub account_provider_kind: Option<String>,
|
||||
pub providers: Vec<String>,
|
||||
pub platform_icon: Option<String>,
|
||||
pub account_authentication_kind: Option<String>,
|
||||
pub account_plan_type: Option<String>,
|
||||
pub account_plan_type_display: Option<String>,
|
||||
|
||||
@@ -14,7 +14,9 @@ pub(crate) async fn provider_account_usage(
|
||||
}
|
||||
|
||||
// 账号卡片先确定有限候选,避免为少量账号聚合整个历史范围
|
||||
let mut statement = QueryBuilder::<Postgres>::new("select pa.* from provider_accounts pa");
|
||||
let mut statement = QueryBuilder::<Postgres>::new(
|
||||
"select pa.*, pa.platform_icon as platform_icon from provider_accounts pa",
|
||||
);
|
||||
if let Some(account_ids) = &query.account_ids {
|
||||
statement
|
||||
.push(" where pa.id=any(")
|
||||
@@ -85,6 +87,7 @@ pub(crate) async fn provider_account_usage(
|
||||
authentication_kind: get(&row, "authentication_kind")?,
|
||||
name: get(&row, "name")?,
|
||||
email: get(&row, "email")?,
|
||||
platform_icon: get(&row, "platform_icon")?,
|
||||
notes: get(&row, "notes")?,
|
||||
plan_type: get(&row, "plan_type")?,
|
||||
request_count: state.count("completed_request_count"),
|
||||
|
||||
@@ -136,6 +136,7 @@ pub(crate) const USAGE_LIST_RECORD_SELECT: &str =
|
||||
mr.provider_kind, mr.provider_account_ref,
|
||||
mr.provider_account_name_snapshot as provider_account_name,
|
||||
mr.provider_account_email_snapshot as provider_account_email,
|
||||
(select a.platform_icon from provider_accounts a where a.id = mr.provider_account_ref) as platform_icon,
|
||||
mr.provider_account_notes_snapshot as provider_account_notes,
|
||||
mr.provider_account_plan_type_snapshot as provider_account_plan_type,
|
||||
mr.provider_account_plan_type_display_snapshot as provider_account_plan_type_display,
|
||||
|
||||
@@ -264,8 +264,8 @@ impl PluginStore for PgPluginStore {
|
||||
.map_err(|error| admin_store_error("plugin", error))?;
|
||||
let mut platforms = metadata.platforms.clone();
|
||||
platforms.sort();
|
||||
let row = sqlx::query("insert into plugin_artifacts (sha256, plugin_id, version, metadata_json, source_json, outbound_proxy_id, archive) values ($1,$2,$3,$4,$5,$6,$7) returning metadata_json, source_json, installed_at, accepted_at")
|
||||
.bind(&metadata.sha256).bind(&metadata.plugin_id).bind(&metadata.version)
|
||||
let row = sqlx::query("insert into plugin_artifacts (sha256, plugin_id, metadata_json, source_json, outbound_proxy_id, archive) values ($1,$2,$3,$4,$5,$6) returning metadata_json, source_json, installed_at, accepted_at")
|
||||
.bind(&metadata.sha256).bind(&metadata.plugin_id)
|
||||
.bind(sqlx::types::Json(&metadata)).bind(sqlx::types::Json(&source))
|
||||
.bind(outbound_proxy.map(|proxy| proxy.id)).bind(artifact.archive.as_ref())
|
||||
.fetch_one(&mut *transaction).await.map_err(|error| {
|
||||
|
||||
@@ -343,13 +343,13 @@ impl AccountStore for PgAdminAccountStore {
|
||||
let item_ids = page
|
||||
.accounts
|
||||
.iter()
|
||||
.map(|account| account.id.clone())
|
||||
.map(|(account, _)| account.id.clone())
|
||||
.collect::<Vec<_>>();
|
||||
let mut groups_by_account = self.account_groups_by_account(&item_ids).await?;
|
||||
let items = page
|
||||
.accounts
|
||||
.into_iter()
|
||||
.map(|summary| {
|
||||
.map(|(summary, platform_icon)| {
|
||||
let account_id = summary.id.clone();
|
||||
let projection = account_status_projection(
|
||||
&summary,
|
||||
@@ -359,6 +359,7 @@ impl AccountStore for PgAdminAccountStore {
|
||||
let mut account = admin_account_record(summary)?;
|
||||
account.groups = groups_by_account.remove(&account_id).unwrap_or_default();
|
||||
Ok(AccountPageItem {
|
||||
platform_icon,
|
||||
protection_rules: runtime
|
||||
.protection_rules
|
||||
.get(&account.id)
|
||||
@@ -404,9 +405,9 @@ impl AccountStore for PgAdminAccountStore {
|
||||
.await?;
|
||||
let mut account = admin_account_record(record.summary)?;
|
||||
account.groups = groups.remove(&account_id).unwrap_or_default();
|
||||
let default_concurrency: i64 = sqlx::query_scalar(
|
||||
"select max_concurrent_per_account from runtime_settings where id = 1",
|
||||
)
|
||||
let (default_concurrency, platform_icon): (i64, Option<String>) = sqlx::query_as(
|
||||
"select s.max_concurrent_per_account, (select a.platform_icon from provider_accounts a where a.id = $1) from runtime_settings s where s.id = 1",
|
||||
).bind(&account_id)
|
||||
.fetch_one(&self.pool)
|
||||
.await
|
||||
.map_err(|source| {
|
||||
@@ -423,6 +424,7 @@ impl AccountStore for PgAdminAccountStore {
|
||||
)
|
||||
})?;
|
||||
Ok(Some(AccountPageItem {
|
||||
platform_icon,
|
||||
protection_rules: runtime
|
||||
.protection_rules
|
||||
.get(&account_id)
|
||||
@@ -675,6 +677,9 @@ impl AccountStore for PgAdminAccountStore {
|
||||
if command.outbound_proxy.is_some() {
|
||||
changed_fields.push("outbound_proxy".to_owned());
|
||||
}
|
||||
if command.platform_icon.is_some() {
|
||||
changed_fields.push("platform_icon".to_owned());
|
||||
}
|
||||
if command.notes.is_some() {
|
||||
changed_fields.push("notes".to_owned());
|
||||
}
|
||||
@@ -689,6 +694,7 @@ impl AccountStore for PgAdminAccountStore {
|
||||
quota_settings: None,
|
||||
auto_use_quota_credits: None,
|
||||
name: command.name,
|
||||
platform_icon: command.platform_icon,
|
||||
notes: command.notes,
|
||||
enabled: Some(command.enabled),
|
||||
concurrency_limit: Some(command.concurrency_limit),
|
||||
@@ -800,6 +806,7 @@ impl AccountStore for PgAdminAccountStore {
|
||||
quota_settings: command.quota_settings,
|
||||
auto_use_quota_credits: command.auto_use_quota_credits,
|
||||
name: None,
|
||||
platform_icon: None,
|
||||
notes: None,
|
||||
enabled: command.enabled,
|
||||
concurrency_limit: command.concurrency_limit,
|
||||
@@ -944,6 +951,9 @@ pub(super) fn prepare_import(
|
||||
if let Some(settings) = &settings {
|
||||
changed_fields
|
||||
.extend(["enabled", "concurrency_limit", "weight", "group_ids"].map(str::to_owned));
|
||||
if settings.platform_icon.is_some() {
|
||||
changed_fields.push("platform_icon".to_owned());
|
||||
}
|
||||
if settings.notes.is_some() {
|
||||
changed_fields.push("notes".to_owned());
|
||||
}
|
||||
@@ -1038,6 +1048,9 @@ pub(super) fn prepare_rotation(
|
||||
if settings.outbound_proxy.is_some() {
|
||||
changed_fields.push("outbound_proxy".to_owned());
|
||||
}
|
||||
if settings.platform_icon.is_some() {
|
||||
changed_fields.push("platform_icon".to_owned());
|
||||
}
|
||||
if settings.notes.is_some() {
|
||||
changed_fields.push("notes".to_owned());
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@ use super::*;
|
||||
pub(crate) struct AdminAccountPageRows {
|
||||
pub(crate) config_revision: AdminRevision,
|
||||
pub(crate) default_concurrency: u64,
|
||||
pub(crate) accounts: Vec<ProviderAccountSummary>,
|
||||
pub(crate) accounts: Vec<(ProviderAccountSummary, Option<String>)>,
|
||||
pub(crate) total: u64,
|
||||
pub(crate) summary: AccountSummary,
|
||||
}
|
||||
@@ -105,7 +105,7 @@ pub(crate) async fn load_admin_account_page(
|
||||
from runtime_settings
|
||||
where id = 1
|
||||
)
|
||||
select coalesce(p.enabled, true) as outbound_proxy_enabled, coalesce(p.max_websocket_connections, 0) as outbound_proxy_max_websocket_connections, p.auto_location, p.detected_location_json, p.location_country, p.location_region, p.location_city, p.location_timezone, a.outbound_proxy_id, a.outbound_proxy_url, a.id, a.provider_kind, a.name, a.notes, a.email, a.upstream_user_id,
|
||||
select coalesce(p.enabled, true) as outbound_proxy_enabled, coalesce(p.max_websocket_connections, 0) as outbound_proxy_max_websocket_connections, p.auto_location, p.detected_location_json, p.location_country, p.location_region, p.location_city, p.location_timezone, a.outbound_proxy_id, a.outbound_proxy_url, a.id, a.provider_kind, a.name, a.notes, a.platform_icon as platform_icon, a.email, a.upstream_user_id,
|
||||
a.upstream_account_id, a.plan_type, a.authentication_kind,
|
||||
a.credential_revision, a.has_refresh_token, a.access_token_expires_at,
|
||||
a.next_refresh_at, a.enabled, a.quota_settings, a.quota_paused, a.auto_use_quota_credits, a.concurrency_limit, a.weight, a.model_access_json,
|
||||
@@ -201,7 +201,10 @@ pub(crate) async fn load_admin_account_page(
|
||||
.flatten()
|
||||
.map(|_| row)
|
||||
})
|
||||
.map(account_summary_from_row)
|
||||
.map(|row| {
|
||||
let icon = get(&row, "platform_icon")?;
|
||||
Ok((account_summary_from_row(row)?, icon))
|
||||
})
|
||||
.collect::<StoreResult<Vec<_>>>()
|
||||
.map_err(|error| admin_store_error(ENTITY, error))?;
|
||||
Ok(AdminAccountPageRows {
|
||||
|
||||
@@ -64,11 +64,14 @@ impl PgProviderAccountRepository {
|
||||
observation: &AccountCatalogObservation,
|
||||
document: &[u8],
|
||||
) -> Result<bool, CoreStoreError> {
|
||||
// 相同正文复用旧 TOAST 值,定期复查只更新账号观测,减少正文重写及 WAL
|
||||
let result = sqlx::query("insert into provider_account_model_catalogs (account_id, credential_revision, plan_type, observed_at, document, etag)
|
||||
select a.id, a.credential_revision, a.plan_type, $4, $5, $6 from provider_accounts a
|
||||
where a.id=$1 and a.credential_revision=$2 and a.plan_type is not distinct from $3 for share
|
||||
on conflict (account_id) do update set credential_revision=excluded.credential_revision, plan_type=excluded.plan_type,
|
||||
etag=excluded.etag, observed_at=excluded.observed_at, document=excluded.document
|
||||
etag=excluded.etag, observed_at=excluded.observed_at, document=case
|
||||
when provider_account_model_catalogs.document_hash=excluded.document_hash
|
||||
then provider_account_model_catalogs.document else excluded.document end
|
||||
where provider_account_model_catalogs.credential_revision < excluded.credential_revision or
|
||||
(provider_account_model_catalogs.credential_revision=excluded.credential_revision and provider_account_model_catalogs.observed_at <= excluded.observed_at)")
|
||||
.bind(observation.account_id.as_str()).bind(i64::try_from(observation.revision.get()).map_err(|_|CoreStoreError::new(CoreStoreErrorKind::InvalidData))?)
|
||||
|
||||
@@ -570,6 +570,7 @@ impl ProviderAccountAdminRepository for PgProviderAccountRepository {
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
set_platform_icon(&mut transaction, &command.account_ids, command.platform_icon.as_deref()).await?;
|
||||
if let Some(notes) = command.notes.as_deref() {
|
||||
update_provider_account_notes_in_transaction(
|
||||
&mut transaction,
|
||||
@@ -685,6 +686,21 @@ async fn update_provider_account_name_in_transaction(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn set_platform_icon(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
ids: &[String],
|
||||
icon: Option<&str>,
|
||||
) -> StoreResult<()> {
|
||||
let Some(icon) = icon else { return Ok(()) };
|
||||
sqlx::query("update provider_accounts set platform_icon = nullif($2, '') where id = any($1)")
|
||||
.bind(ids)
|
||||
.bind(icon)
|
||||
.execute(&mut **transaction)
|
||||
.await
|
||||
.map_err(|source| postgres_unavailable("set account platform icon", source))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn update_provider_account_notes_in_transaction(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
account_ids: &[String],
|
||||
@@ -1165,6 +1181,7 @@ pub(super) async fn import_provider_accounts_in_transaction(
|
||||
&settings.group_ids,
|
||||
)
|
||||
.await?;
|
||||
set_platform_icon(transaction, &unique_ids, settings.platform_icon.as_deref()).await?;
|
||||
if let Some(notes) = settings.notes.as_deref() {
|
||||
update_provider_account_notes_in_transaction(transaction, &unique_ids, notes).await?;
|
||||
}
|
||||
@@ -1236,6 +1253,7 @@ pub(super) async fn rotate_provider_account_admin_in_transaction(
|
||||
.await?;
|
||||
replace_account_group_assignments_in_transaction(transaction, ids, &settings.group_ids)
|
||||
.await?;
|
||||
set_platform_icon(transaction, ids, settings.platform_icon.as_deref()).await?;
|
||||
if let Some(notes) = settings.notes.as_deref() {
|
||||
update_provider_account_notes_in_transaction(transaction, ids, notes).await?;
|
||||
}
|
||||
|
||||
@@ -252,6 +252,7 @@ impl fmt::Debug for RotateProviderAccount {
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct BatchUpdateProviderAccountsAdmin {
|
||||
pub platform_icon: Option<String>,
|
||||
pub pauses: gateway_admin::model::accounts::PreparedQuotaPauses,
|
||||
pub quota_settings: Option<gateway_core::account::AccountQuotaSettings>,
|
||||
pub auto_use_quota_credits: Option<bool>,
|
||||
|
||||
@@ -542,7 +542,7 @@ impl ProxyStore for PgProxyRepository {
|
||||
})
|
||||
})?;
|
||||
let mut items = sqlx::query(
|
||||
"select id, name, email, provider_kind, authentication_kind, plan_type, enabled from provider_accounts
|
||||
"select id, name, email, provider_kind, authentication_kind, plan_type, enabled, a.platform_icon as platform_icon from provider_accounts a
|
||||
where outbound_proxy_id = $1 and (strpos(lower(name), lower($2)) > 0
|
||||
or strpos(lower(coalesce(email, '')), lower($2)) > 0)
|
||||
order by name, id limit $3 offset $4",
|
||||
@@ -557,6 +557,7 @@ impl ProxyStore for PgProxyRepository {
|
||||
.into_iter()
|
||||
.map(|row| {
|
||||
Ok(ProxyAccountRef {
|
||||
platform_icon: row.try_get("platform_icon").map_err(|source| invalid().with_source(source))?,
|
||||
upstream: None,
|
||||
id: row.try_get("id").map_err(|source| invalid().with_source(source))?,
|
||||
name: row.try_get("name").map_err(|source| invalid().with_source(source))?,
|
||||
|
||||
@@ -395,7 +395,7 @@ async fn health_counters_match_for_rollups_and_facts_without_counting_recovery_o
|
||||
("health_recovered", "failed", 502),
|
||||
] {
|
||||
seed(&database.pool, id, start + TimeDelta::minutes(5), &[]).await;
|
||||
sqlx::query("update model_requests set outcome=$2,client_status_code=$3 where id=$1")
|
||||
sqlx::query("update model_requests set outcome=$2,client_status_code=$3,provider_kind=case when $1='health_success' then 'xai' else 'openai' end where id=$1")
|
||||
.bind(id)
|
||||
.bind(outcome)
|
||||
.bind(status)
|
||||
@@ -459,6 +459,7 @@ async fn health_counters_match_for_rollups_and_facts_without_counting_recovery_o
|
||||
assert_eq!(diagnostic.total_request_count, 5);
|
||||
assert_eq!(diagnostic.items.len(), 1);
|
||||
let counts = &diagnostic.items[0];
|
||||
assert_eq!(counts.providers, ["openai", "xai"]);
|
||||
assert_eq!(
|
||||
(
|
||||
counts.request_count,
|
||||
|
||||
@@ -449,7 +449,7 @@ async fn extrema_rebuild_reads_only_its_bucket_when_history_is_large() {
|
||||
}
|
||||
drain_analytics(&pool).await;
|
||||
// 只扩充其他时间桶的事实,规划器拿到真实行数后不能再为一个分组扫描全部历史
|
||||
sqlx::query("insert into request_analytics_facts select ('history_'||n)::text as id,(f.started_at-make_interval(hours=>n/1000+2))::timestamptz,f.completed_at-make_interval(hours=>n/1000+2),f.client_api_key_ref,f.provider_account_ref,f.routing_group_refs,f.operation,f.provider_kind,f.requested_model_id,f.upstream_model_id,f.outcome,f.client_status_code,f.upstream_status_code,f.client_transport,f.upstream_transport,f.attempt_count,null,null,null,f.recovered_at,f.downstream_committed_at,f.request_kind,f.image_generation_requested,f.image_generation_succeeded,f.error_kind,f.input_tokens,f.output_tokens,f.cached_input_tokens,f.cache_write_input_tokens,f.reasoning_output_tokens,f.image_input_tokens,f.image_output_tokens,f.total_tokens,f.cost_source,f.cost_currency,f.cost_amount,f.first_token_ms,f.latency_ms,f.admission_decision_ms,f.account_selection_wait_ms,f.upstream_response_ms,f.capacity_used_slots,f.capacity_total_slots,f.standard_cost_amount,f.no_cache_cost_amount,f.source_version,f.schema_version,f.ops_failure_count,f.ops_rate_limited_count,f.ops_auth_failure_count,f.ops_provider_5xx_count from request_analytics_facts f cross join generate_series(1,300000) n where f.id='rebuild_range_2'")
|
||||
sqlx::query("insert into request_analytics_facts select ('history_'||n)::text as id,(f.started_at-make_interval(hours=>n/1000+2))::timestamptz,f.completed_at-make_interval(hours=>n/1000+2),f.client_api_key_ref,f.provider_account_ref,f.routing_group_refs,f.operation,f.provider_kind,f.requested_model_id,f.upstream_model_id,f.outcome,f.client_status_code,f.upstream_status_code,f.client_transport,f.upstream_transport,f.attempt_count,null,null,null,f.recovered_at,f.downstream_committed_at,f.request_kind,f.image_generation_requested,f.image_generation_succeeded,f.error_kind,f.input_tokens,f.output_tokens,f.cached_input_tokens,f.cache_write_input_tokens,f.reasoning_output_tokens,f.image_input_tokens,f.image_output_tokens,f.total_tokens,f.cost_source,f.cost_currency,f.cost_amount,f.first_token_ms,f.latency_ms,f.admission_decision_ms,f.account_selection_wait_ms,f.upstream_response_ms,f.capacity_used_slots,f.capacity_total_slots,f.standard_cost_amount,f.no_cache_cost_amount,f.schema_version,f.ops_failure_count,f.ops_rate_limited_count,f.ops_auth_failure_count,f.ops_provider_5xx_count from request_analytics_facts f cross join generate_series(1,300000) n where f.id='rebuild_range_2'")
|
||||
.execute(&pool).await.unwrap();
|
||||
sqlx::query("analyze request_analytics_facts")
|
||||
.execute(&pool)
|
||||
|
||||
@@ -34,7 +34,7 @@ async fn business_backup_restores_core_state_and_usage_without_request_history()
|
||||
insert into client_api_key_budget_windows values('restore_key',now(),now()+interval '1 day',now(),now()+interval '7 days',2.5,9.5);
|
||||
insert into client_api_key_charge_events(request_id,client_api_key_id,amount_usd,completed_at) values('native_a','restore_key',2.5,now());
|
||||
insert into plugin_update_sources(plugin_id,source_json) values('backup.test','{}');
|
||||
insert into plugin_artifacts(sha256,plugin_id,version,metadata_json,source_json,archive,accepted_at) values(repeat('a',64),'backup.test','1.0.0','{}','{}',decode('010203','hex'),now());
|
||||
insert into plugin_artifacts(sha256,plugin_id,metadata_json,source_json,archive,accepted_at) values(repeat('a',64),'backup.test','{\"version\":\"1.0.0\"}','{}',decode('010203','hex'),now());
|
||||
update runtime_settings set usage_retention_days=3;
|
||||
update model_requests set cost_source='provider_reported',cost_amount=0.5,cost_currency='USD';
|
||||
insert into request_analytics_1h(bucket_start,collection,dimensions,outcome,schema_version,histogram_version,counts,costs,distributions)
|
||||
|
||||
@@ -31,6 +31,7 @@ async fn import_name_only_overrides_a_single_account_and_keeps_batch_names() {
|
||||
.import_provider_accounts(ImportProviderAccounts {
|
||||
outbound_proxy: None,
|
||||
settings: Some(AccountImportSettings {
|
||||
platform_icon: None,
|
||||
name: name.map(str::to_owned),
|
||||
notes: None,
|
||||
model_access: Default::default(),
|
||||
@@ -769,3 +770,166 @@ async fn reset_credit_automation_persists_pending_checks_cas_and_follows_account
|
||||
);
|
||||
database.close().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn platform_icon_is_owned_by_account_and_survives_credential_changes() {
|
||||
use gateway_admin::model::accounts::AccountImportSettings;
|
||||
|
||||
let Some(database) = TestDatabase::create("account_icon").await else {
|
||||
return;
|
||||
};
|
||||
let repository = PgProviderAccountRepository::new(database.pool.clone());
|
||||
let api_account = |id: &str, identity: &str| {
|
||||
let mut record = account(id, identity);
|
||||
record.authentication_kind = "api_key".to_owned();
|
||||
record.provider_credentials_json = JsonObject::try_from_value(
|
||||
"provider_credentials_json",
|
||||
serde_json::json!({
|
||||
"base_url": "https://example.invalid/v1",
|
||||
"api_key": "test-key"
|
||||
}),
|
||||
256 * 1024,
|
||||
)
|
||||
.unwrap();
|
||||
record
|
||||
};
|
||||
for id in ["acct_first", "acct_second"] {
|
||||
repository
|
||||
.insert_provider_account(api_account(id, id))
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
let store = admin_account_store(&database.pool);
|
||||
let context = MutationContext {
|
||||
actor: MutationActor::System,
|
||||
request_id: "account-icon".to_owned(),
|
||||
};
|
||||
let mut edit = UpdateAccount {
|
||||
account_id: "acct_first".to_owned(),
|
||||
platform_icon: Some("DeepSeek".to_owned()),
|
||||
name: None,
|
||||
notes: None,
|
||||
enabled: true,
|
||||
concurrency_limit: None,
|
||||
weight: gateway_core::account::AccountWeight::DEFAULT,
|
||||
model_access: None,
|
||||
group_ids: vec![],
|
||||
outbound_proxy: None,
|
||||
};
|
||||
let icon_for = async |id: &str| {
|
||||
store
|
||||
.load_account(id, AccountRuntimeSnapshot::default())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.platform_icon
|
||||
};
|
||||
store.update_account(edit.clone(), &context).await.unwrap();
|
||||
assert_eq!(icon_for("acct_first").await.as_deref(), Some("DeepSeek"));
|
||||
assert!(icon_for("acct_second").await.is_none());
|
||||
edit.account_id = "acct_second".to_owned();
|
||||
edit.platform_icon = Some("Claude".to_owned());
|
||||
store.update_account(edit.clone(), &context).await.unwrap();
|
||||
assert_eq!(icon_for("acct_first").await.as_deref(), Some("DeepSeek"));
|
||||
|
||||
// 省略整份设置或仅省略图标,都保留已有账号的选择;新账号不继承同地址图标
|
||||
for (index, settings) in [
|
||||
None,
|
||||
Some(AccountImportSettings {
|
||||
platform_icon: None,
|
||||
name: None,
|
||||
notes: None,
|
||||
enabled: true,
|
||||
concurrency_limit: None,
|
||||
weight: gateway_core::account::AccountWeight::DEFAULT,
|
||||
model_access: None,
|
||||
group_ids: vec![],
|
||||
}),
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
repository
|
||||
.import_provider_accounts(ImportProviderAccounts {
|
||||
outbound_proxy: None,
|
||||
settings,
|
||||
scope: ProviderAccountAdminScope {
|
||||
provider_kind: "openai".to_owned(),
|
||||
},
|
||||
accounts: vec![
|
||||
api_account("acct_candidate", "acct_first"),
|
||||
api_account("acct_new", "acct_new"),
|
||||
],
|
||||
audit: audit(
|
||||
&format!("audit_icon_import_{index}"),
|
||||
"import",
|
||||
"provider_accounts",
|
||||
),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(icon_for("acct_first").await.as_deref(), Some("DeepSeek"));
|
||||
assert!(icon_for("acct_new").await.is_none());
|
||||
}
|
||||
let mut credential = credential_update("acct_first", 3, "rotated");
|
||||
credential.provider_credentials_json = JsonObject::try_from_value(
|
||||
"provider_credentials_json",
|
||||
serde_json::json!({
|
||||
"base_url": "https://other.example.invalid/v2",
|
||||
"api_key": "rotated-key"
|
||||
}),
|
||||
256 * 1024,
|
||||
)
|
||||
.unwrap();
|
||||
repository
|
||||
.rotate_provider_account(RotateProviderAccount {
|
||||
settings: None,
|
||||
scope: ProviderAccountAdminScope {
|
||||
provider_kind: "openai".to_owned(),
|
||||
},
|
||||
profile: profile("acct_first", "first"),
|
||||
replacement_identity: None,
|
||||
credential,
|
||||
audit: audit("audit_icon_rotate", "rotate", "acct_first"),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(icon_for("acct_first").await.as_deref(), Some("DeepSeek"));
|
||||
|
||||
edit.account_id = "acct_first".to_owned();
|
||||
edit.platform_icon = Some("Gemini".to_owned());
|
||||
let before = repository
|
||||
.load_provider_account("acct_first")
|
||||
.await
|
||||
.unwrap();
|
||||
// 审计失败发生在图标写入之后,凭据和图标必须一起回滚
|
||||
assert!(
|
||||
repository
|
||||
.rotate_provider_account(RotateProviderAccount {
|
||||
settings: Some(edit.clone()),
|
||||
scope: ProviderAccountAdminScope {
|
||||
provider_kind: "openai".to_owned()
|
||||
},
|
||||
profile: profile("acct_first", "failed"),
|
||||
replacement_identity: None,
|
||||
credential: credential_update("acct_first", 4, "failed"),
|
||||
audit: audit("audit_icon_rotate", "rotate", "acct_first"),
|
||||
})
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert_eq!(
|
||||
repository
|
||||
.load_provider_account("acct_first")
|
||||
.await
|
||||
.unwrap(),
|
||||
before
|
||||
);
|
||||
assert_eq!(icon_for("acct_first").await.as_deref(), Some("DeepSeek"));
|
||||
|
||||
edit.platform_icon = Some(String::new());
|
||||
store.update_account(edit, &context).await.unwrap();
|
||||
assert!(icon_for("acct_first").await.is_none());
|
||||
assert_eq!(icon_for("acct_second").await.as_deref(), Some("Claude"));
|
||||
database.close().await;
|
||||
}
|
||||
|
||||
@@ -426,6 +426,7 @@ async fn reauthorization_replay_keeps_the_committed_revision_and_later_profile_e
|
||||
)),
|
||||
);
|
||||
let rename = UpdateAccount {
|
||||
platform_icon: None,
|
||||
account_id: id.to_string(),
|
||||
name: Some("renamed team".to_owned()),
|
||||
notes: None,
|
||||
|
||||
@@ -261,6 +261,55 @@ async fn bulk_catalog_restore_keeps_ten_thousand_owners_and_fences_late_writes()
|
||||
.map(|a| a.id().as_str())
|
||||
.collect::<std::collections::BTreeSet<_>>();
|
||||
assert_eq!(ids, std::collections::BTreeSet::from(["acct_1", "acct_5"]));
|
||||
// 相同正文的复查仍更新账号观测,正文变化后单独恢复,迟到写入不能撤回新目录
|
||||
let refreshed = AccountCatalogObservation {
|
||||
account_id: ProviderAccountId::new("acct_5").unwrap(),
|
||||
observed_at: SystemTime::now(),
|
||||
etag: Some("v2".into()),
|
||||
..observation.clone()
|
||||
};
|
||||
assert!(
|
||||
repo.save_account_catalog(&refreshed, &document)
|
||||
.await
|
||||
.unwrap()
|
||||
);
|
||||
let restored = repo.load_account_catalogs(&provider).await.unwrap();
|
||||
assert_eq!(restored.len(), 1);
|
||||
let owner = restored[0]
|
||||
.accounts
|
||||
.iter()
|
||||
.find(|owner| owner.account_id == refreshed.account_id)
|
||||
.unwrap();
|
||||
assert_eq!(owner.etag, refreshed.etag);
|
||||
assert_eq!(
|
||||
chrono::DateTime::<Utc>::from(owner.observed_at).timestamp_micros(),
|
||||
chrono::DateTime::<Utc>::from(refreshed.observed_at).timestamp_micros()
|
||||
);
|
||||
assert_eq!(&restored[0].document[..], &document);
|
||||
let changed = AccountCatalogObservation {
|
||||
observed_at: SystemTime::now(),
|
||||
etag: Some("v3".into()),
|
||||
..refreshed.clone()
|
||||
};
|
||||
assert!(
|
||||
repo.save_account_catalog(&changed, b"changed")
|
||||
.await
|
||||
.unwrap()
|
||||
);
|
||||
assert!(
|
||||
!repo
|
||||
.save_account_catalog(&refreshed, &document)
|
||||
.await
|
||||
.unwrap()
|
||||
);
|
||||
let restored = repo.load_account_catalogs(&provider).await.unwrap();
|
||||
assert_eq!(restored.len(), 2);
|
||||
let changed_group = restored
|
||||
.iter()
|
||||
.find(|group| &group.document[..] == b"changed")
|
||||
.unwrap();
|
||||
assert_eq!(changed_group.accounts.len(), 1);
|
||||
assert_eq!(changed_group.accounts[0].account_id, changed.account_id);
|
||||
database.close().await;
|
||||
}
|
||||
|
||||
|
||||
@@ -472,6 +472,7 @@ async fn profile_changes_survive_inflight_background_and_manual_token_refresh()
|
||||
admin_account_store(&database.pool)
|
||||
.update_account(
|
||||
UpdateAccount {
|
||||
platform_icon: None,
|
||||
account_id: id.to_string(),
|
||||
name: Some("renamed team".to_owned()),
|
||||
notes: None,
|
||||
@@ -1284,6 +1285,7 @@ async fn terminal_admin_mutations_keep_revision_account_and_audit_atomic() {
|
||||
let result = store
|
||||
.update_account(
|
||||
UpdateAccount {
|
||||
platform_icon: None,
|
||||
name: None,
|
||||
notes: None,
|
||||
model_access: Default::default(),
|
||||
@@ -1373,6 +1375,7 @@ async fn account_proxy_edits_preserve_credentials_and_clear_egress_without_audit
|
||||
request_id: "proxy-edit".to_owned(),
|
||||
};
|
||||
let command = UpdateAccount {
|
||||
platform_icon: None,
|
||||
name: None,
|
||||
notes: None,
|
||||
model_access: Default::default(),
|
||||
@@ -1450,6 +1453,7 @@ async fn account_rename_preserves_facts_and_is_searchable() {
|
||||
request_id: "rename-account".to_owned(),
|
||||
};
|
||||
let command = UpdateAccount {
|
||||
platform_icon: None,
|
||||
account_id: "acct_rename".to_owned(),
|
||||
name: Some(" 研发团队 ".to_owned()),
|
||||
notes: None,
|
||||
@@ -1557,6 +1561,7 @@ async fn account_notes_round_trip_and_survive_import_and_scheduling_updates() {
|
||||
request_id: "notes-edit".to_owned(),
|
||||
};
|
||||
let command = UpdateAccount {
|
||||
platform_icon: None,
|
||||
name: None,
|
||||
account_id: "acct_notes".to_owned(),
|
||||
notes: Some(" 团队备用\n下月续费 ".to_owned()),
|
||||
@@ -1640,6 +1645,7 @@ async fn account_notes_round_trip_and_survive_import_and_scheduling_updates() {
|
||||
},
|
||||
accounts: vec![account("acct_notes", "notes-user")],
|
||||
settings: Some(gateway_admin::model::accounts::AccountImportSettings {
|
||||
platform_icon: None,
|
||||
name: None,
|
||||
notes: None,
|
||||
enabled: true,
|
||||
@@ -1711,6 +1717,7 @@ async fn invalid_account_notes_roll_back_scheduling_revision_and_audit() {
|
||||
let result = admin_account_store(&database.pool)
|
||||
.update_account(
|
||||
UpdateAccount {
|
||||
platform_icon: None,
|
||||
name: None,
|
||||
account_id: "acct_notes".to_owned(),
|
||||
notes: Some("备".repeat(501)),
|
||||
@@ -2214,6 +2221,7 @@ async fn authorization_create_returns_existing_account_id_when_identity_is_upser
|
||||
)
|
||||
.unwrap(),
|
||||
settings: Some(gateway_admin::model::accounts::AccountImportSettings {
|
||||
platform_icon: None,
|
||||
name: None,
|
||||
notes: Some(" OAuth 新建备注 ".to_owned()),
|
||||
model_access: Default::default(),
|
||||
@@ -2750,6 +2758,7 @@ async fn provider_account_admin_mutations_are_scoped_audited_and_atomic() {
|
||||
|
||||
let revision = repository
|
||||
.batch_update_provider_accounts_admin(BatchUpdateProviderAccountsAdmin {
|
||||
platform_icon: None,
|
||||
pauses: Default::default(),
|
||||
quota_settings: None,
|
||||
auto_use_quota_credits: None,
|
||||
@@ -2822,6 +2831,7 @@ async fn credential_rotation_and_settings_share_one_transaction() {
|
||||
.await
|
||||
.expect("seed group");
|
||||
let settings = UpdateAccount {
|
||||
platform_icon: None,
|
||||
name: Some(" 团队新名称 ".to_owned()),
|
||||
account_id: ACCOUNT_ID.to_owned(),
|
||||
notes: Some("统一保存".to_owned()),
|
||||
@@ -3608,6 +3618,7 @@ async fn proxy_edit_preserves_an_inflight_token_refresh() {
|
||||
admin_account_store(&database.pool)
|
||||
.update_account(
|
||||
UpdateAccount {
|
||||
platform_icon: None,
|
||||
name: None,
|
||||
notes: None,
|
||||
model_access: Default::default(),
|
||||
@@ -3667,6 +3678,7 @@ async fn account_import_settings_apply_atomically_to_new_and_existing_identities
|
||||
.await
|
||||
.expect("seed group");
|
||||
let settings = AccountImportSettings {
|
||||
platform_icon: Some("DeepSeek".to_owned()),
|
||||
name: None,
|
||||
notes: Some(" 批量新建\n团队备用 ".to_owned()),
|
||||
model_access: Default::default(),
|
||||
@@ -3693,14 +3705,14 @@ async fn account_import_settings_apply_atomically_to_new_and_existing_identities
|
||||
.expect("import with settings");
|
||||
assert_eq!(result.config_revision.get(), 2);
|
||||
for id in ["acct_new_settings", "acct_existing_settings"] {
|
||||
let row: (bool, Option<i64>, i16) = sqlx::query_as(
|
||||
"select enabled, concurrency_limit, weight from provider_accounts where id = $1",
|
||||
let row: (bool, Option<i64>, i16, Option<String>) = sqlx::query_as(
|
||||
"select enabled, concurrency_limit, weight, platform_icon from provider_accounts where id = $1",
|
||||
)
|
||||
.bind(id)
|
||||
.fetch_one(&database.pool)
|
||||
.await
|
||||
.expect("saved settings");
|
||||
assert_eq!(row, (false, Some(3), 7));
|
||||
assert_eq!(row, (false, Some(3), 7, Some("DeepSeek".to_owned())));
|
||||
assert_eq!(account_group_ids(&database.pool, id).await, [GROUP_ID]);
|
||||
assert_eq!(
|
||||
repository
|
||||
@@ -3727,6 +3739,7 @@ async fn account_import_settings_apply_atomically_to_new_and_existing_identities
|
||||
},
|
||||
AccountImportSettings {
|
||||
notes: Some("备".repeat(501)),
|
||||
platform_icon: Some("Gemini".to_owned()),
|
||||
..settings
|
||||
},
|
||||
] {
|
||||
@@ -3765,6 +3778,16 @@ async fn account_import_settings_apply_atomically_to_new_and_existing_identities
|
||||
account_group_ids(&database.pool, "acct_existing_settings").await,
|
||||
[GROUP_ID]
|
||||
);
|
||||
assert_eq!(
|
||||
sqlx::query_scalar::<_, Option<String>>(
|
||||
"select platform_icon from provider_accounts where id = 'acct_existing_settings'"
|
||||
)
|
||||
.fetch_one(&database.pool)
|
||||
.await
|
||||
.unwrap()
|
||||
.as_deref(),
|
||||
Some("DeepSeek")
|
||||
);
|
||||
assert_eq!(
|
||||
sqlx::query_scalar::<_, i64>(
|
||||
"select count(*) from admin_audit_events where id = 'audit_import_settings_failed'"
|
||||
|
||||
@@ -429,6 +429,7 @@ fn success() -> ProxyTestResult {
|
||||
|
||||
fn update(account_id: &str, selection: AccountProxySelection) -> UpdateAccount {
|
||||
UpdateAccount {
|
||||
platform_icon: None,
|
||||
name: None,
|
||||
notes: None,
|
||||
model_access: Default::default(),
|
||||
|
||||
@@ -635,6 +635,10 @@ async fn diagnostics_should_fallback_to_name_then_ref_for_missing_snapshots() {
|
||||
.expect("insert legacy request without live account");
|
||||
finalize_request(&database.pool, "req_snap_legacy", started_at).await;
|
||||
|
||||
sqlx::query("update provider_accounts set platform_icon='Adobe' where id='acct_snap_c'")
|
||||
.execute(&database.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let repository = observability_repository(&database.pool);
|
||||
super::drain_analytics(&database.pool).await;
|
||||
let diagnostics = repository
|
||||
@@ -647,6 +651,13 @@ async fn diagnostics_should_fallback_to_name_then_ref_for_missing_snapshots() {
|
||||
.await
|
||||
.expect("account diagnostics")
|
||||
.items;
|
||||
for row in &diagnostics {
|
||||
assert_eq!(row.providers, ["openai"]);
|
||||
assert_eq!(
|
||||
row.platform_icon.as_deref(),
|
||||
(row.key == "acct_snap_c").then_some("Adobe")
|
||||
);
|
||||
}
|
||||
let by_key = diagnostics
|
||||
.iter()
|
||||
.map(|item| (item.key.as_str(), item.name.as_str()))
|
||||
|
||||
@@ -403,6 +403,16 @@ async fn empty_native_history_still_shows_aggregates_and_bad_values_return_error
|
||||
.request_count,
|
||||
7
|
||||
);
|
||||
let models = repo
|
||||
.usage_diagnostics(
|
||||
range,
|
||||
NativeFilter::default(),
|
||||
gateway_store::postgres::DiagnosticDimension::Model,
|
||||
10,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(models.items[0].providers, ["openai"]);
|
||||
store
|
||||
.write_aggregates(aggregates(vec![contribution("only", i64::MIN, 90, "1")]))
|
||||
.await
|
||||
|
||||
@@ -236,6 +236,14 @@ impl CloudCodeClient {
|
||||
GenerateMode::Json | GenerateMode::Stream => Some(self.system_instruction.as_ref()),
|
||||
};
|
||||
let request = super::request::request_body(body, instruction, false)?;
|
||||
let request = if matches!(mode, GenerateMode::Json | GenerateMode::Stream)
|
||||
&& model.starts_with("claude-")
|
||||
{
|
||||
super::tool_ids::repair(request)
|
||||
.map_err(|error| unsent(Kind::InvalidRequest).with_source(error))?
|
||||
} else {
|
||||
request
|
||||
};
|
||||
let (send, media) = if matches!(
|
||||
mode,
|
||||
GenerateMode::Stream | GenerateMode::Chat { stream: true }
|
||||
|
||||
@@ -7,6 +7,7 @@ mod headers;
|
||||
mod pool;
|
||||
mod request;
|
||||
mod response;
|
||||
mod tool_ids;
|
||||
pub(crate) use client::{Catalog, CloudCodeClient, GenerateMode, Model, unwrap_frame};
|
||||
pub(crate) use count::count_events;
|
||||
pub(crate) use failure::{sent, unsent};
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
//! 为 Claude 原生生成补齐能唯一配对的工具 ID,保留其余原始 JSON 字节
|
||||
|
||||
use std::{borrow::Cow, collections::BTreeMap};
|
||||
|
||||
use serde::{Deserialize, Deserializer};
|
||||
use serde_json::value::RawValue;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Request<'a> {
|
||||
#[serde(default, borrow)]
|
||||
contents: Vec<Content<'a>>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Content<'a> {
|
||||
#[serde(borrow)]
|
||||
role: Cow<'a, str>,
|
||||
#[serde(default, borrow)]
|
||||
parts: Vec<&'a RawValue>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Part<'a> {
|
||||
#[serde(default, borrow, alias = "functionCall")]
|
||||
function_call: Option<&'a RawValue>,
|
||||
#[serde(default, borrow, alias = "functionResponse")]
|
||||
function_response: Option<&'a RawValue>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Function<'a> {
|
||||
#[serde(borrow)]
|
||||
name: Cow<'a, str>,
|
||||
#[serde(default, borrow, deserialize_with = "present_id")]
|
||||
id: Option<&'a RawValue>,
|
||||
}
|
||||
|
||||
// null、空串和非字符串 ID 仍由上游校验,不能把已提供的字段当作缺失再插入
|
||||
fn present_id<'de, D: Deserializer<'de>>(
|
||||
deserializer: D,
|
||||
) -> Result<Option<&'de RawValue>, D::Error> {
|
||||
<&RawValue>::deserialize(deserializer).map(Some)
|
||||
}
|
||||
|
||||
struct Tool<'a> {
|
||||
raw: &'a RawValue,
|
||||
part: usize,
|
||||
name: Cow<'a, str>,
|
||||
id: Option<Cow<'a, str>>,
|
||||
}
|
||||
|
||||
fn tools<'a>(content: &Content<'a>) -> Option<Vec<Tool<'a>>> {
|
||||
let mut tools = Vec::new();
|
||||
for (part, raw) in content.parts.iter().enumerate() {
|
||||
let part_view: Part<'_> = serde_json::from_str(raw.get()).ok()?;
|
||||
let raw = match (
|
||||
content.role.as_ref(),
|
||||
part_view.function_call,
|
||||
part_view.function_response,
|
||||
) {
|
||||
("model", Some(call), None) => call,
|
||||
("user", None, Some(response)) => response,
|
||||
(_, None, None) => continue,
|
||||
_ => return None,
|
||||
};
|
||||
let function: Function<'_> = serde_json::from_str(raw.get()).ok()?;
|
||||
let id = function
|
||||
.id
|
||||
.map(|id| serde_json::from_str::<Cow<'_, str>>(id.get()))
|
||||
.transpose()
|
||||
.ok()?;
|
||||
if function.name.is_empty() || id.as_ref().is_some_and(|id| id.is_empty()) {
|
||||
return None;
|
||||
}
|
||||
tools.push(Tool {
|
||||
raw,
|
||||
part,
|
||||
name: function.name,
|
||||
id,
|
||||
});
|
||||
}
|
||||
Some(tools)
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Pair {
|
||||
call: Option<usize>,
|
||||
response: Option<usize>,
|
||||
ambiguous: bool,
|
||||
}
|
||||
|
||||
pub(super) fn repair(body: Box<RawValue>) -> Result<Box<RawValue>, serde_json::Error> {
|
||||
// AGY CLI 1.5.20 的 convertToVertexV1 清空两侧 ID,见 #807
|
||||
// https://github.com/zyycn/codex-proxy-rs/issues/807
|
||||
// 客户端恢复保留 ID 后移除此补偿;不为格式错误或有歧义的历史猜测关联
|
||||
let Ok(request) = serde_json::from_str::<Request<'_>>(body.get()) else {
|
||||
return Ok(body);
|
||||
};
|
||||
let Some(turns) = request
|
||||
.contents
|
||||
.iter()
|
||||
.map(tools)
|
||||
.collect::<Option<Vec<_>>>()
|
||||
else {
|
||||
return Ok(body);
|
||||
};
|
||||
if turns.iter().flatten().all(|tool| tool.id.is_some()) {
|
||||
return Ok(body);
|
||||
}
|
||||
let mut ids = BTreeMap::<Cow<'_, str>, usize>::new();
|
||||
for id in turns.iter().flatten().filter_map(|tool| tool.id.as_deref()) {
|
||||
*ids.entry(Cow::Borrowed(id)).or_default() += 1;
|
||||
}
|
||||
let mut insertions = BTreeMap::new();
|
||||
for (turn, contents) in request.contents.windows(2).enumerate() {
|
||||
if contents[0].role != "model" || contents[1].role != "user" {
|
||||
continue;
|
||||
}
|
||||
let calls = &turns[turn];
|
||||
let responses = &turns[turn + 1];
|
||||
let mut pairs = BTreeMap::<&str, Pair>::new();
|
||||
for (index, call) in calls.iter().enumerate() {
|
||||
let pair = pairs.entry(&call.name).or_default();
|
||||
pair.ambiguous |= pair.call.replace(index).is_some();
|
||||
}
|
||||
for (index, response) in responses.iter().enumerate() {
|
||||
let pair = pairs.entry(&response.name).or_default();
|
||||
pair.ambiguous |= pair.response.replace(index).is_some();
|
||||
}
|
||||
for pair in pairs.values().filter(|pair| !pair.ambiguous) {
|
||||
let (Some(call), Some(response)) = (pair.call, pair.response) else {
|
||||
continue;
|
||||
};
|
||||
let (call, response) = (&calls[call], &responses[response]);
|
||||
let id = match (call.id.as_deref(), response.id.as_deref()) {
|
||||
(Some(_), Some(_)) => continue,
|
||||
(Some(id), None) | (None, Some(id)) => {
|
||||
if ids.get(id) != Some(&1) {
|
||||
continue;
|
||||
}
|
||||
id.to_owned()
|
||||
}
|
||||
(None, None) => {
|
||||
// 轮次与 part 位置使追加历史和重试保持稳定;同时避开客户端已有 ID
|
||||
let mut id = format!("toolu_cpr_{turn}_{}", call.part);
|
||||
while ids.contains_key(id.as_str()) {
|
||||
id.push('_');
|
||||
}
|
||||
id
|
||||
}
|
||||
};
|
||||
ids.insert(Cow::Owned(id.clone()), 2);
|
||||
let insertion = format!(",\"id\":{}", serde_json::to_string(&id)?);
|
||||
for tool in [call, response]
|
||||
.into_iter()
|
||||
.filter(|tool| tool.id.is_none())
|
||||
{
|
||||
// RawValue 来自同一正文,插入点由解析器确定,不重编码参数、结果或签名
|
||||
let end = tool.raw.get().as_ptr() as usize - body.get().as_ptr() as usize
|
||||
+ tool.raw.get().len()
|
||||
- 1;
|
||||
insertions.insert(end, insertion.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
if insertions.is_empty() {
|
||||
return Ok(body);
|
||||
}
|
||||
let mut output = String::with_capacity(body.get().len());
|
||||
let mut cursor = 0;
|
||||
for (position, insertion) in insertions {
|
||||
output.push_str(&body.get()[cursor..position]);
|
||||
output.push_str(&insertion);
|
||||
cursor = position;
|
||||
}
|
||||
output.push_str(&body.get()[cursor..]);
|
||||
RawValue::from_string(output)
|
||||
}
|
||||
@@ -4,3 +4,4 @@ mod client;
|
||||
mod count;
|
||||
mod pool;
|
||||
mod request;
|
||||
mod tool_ids;
|
||||
|
||||
@@ -0,0 +1,280 @@
|
||||
//! 原生 Claude 工具 ID 配对、透明保留及生成模式边界
|
||||
|
||||
use crate::{
|
||||
profile,
|
||||
transport::{CloudCodeClient, GenerateMode},
|
||||
};
|
||||
use serde_json::{Value, json, value::RawValue};
|
||||
use wiremock::{Mock, MockServer, ResponseTemplate, matchers::path};
|
||||
|
||||
async fn client() -> (MockServer, CloudCodeClient) {
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(path("/v1internal:generateContent"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({"response":{}})))
|
||||
.mount(&server)
|
||||
.await;
|
||||
Mock::given(path("/v1internal:streamGenerateContent"))
|
||||
.respond_with(
|
||||
ResponseTemplate::new(200)
|
||||
.set_body_raw("data: {\"response\":{}}\n\n", "text/event-stream"),
|
||||
)
|
||||
.mount(&server)
|
||||
.await;
|
||||
Mock::given(path("/v1internal:countTokens"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({"totalTokens":42})))
|
||||
.mount(&server)
|
||||
.await;
|
||||
let client = CloudCodeClient::new(
|
||||
&server.uri().parse().unwrap(),
|
||||
None,
|
||||
&profile::Selection::default().resolve("2.34.0"),
|
||||
)
|
||||
.unwrap();
|
||||
(server, client)
|
||||
}
|
||||
|
||||
async fn generate(
|
||||
server: &MockServer,
|
||||
client: &CloudCodeClient,
|
||||
body: &str,
|
||||
model: &str,
|
||||
mode: GenerateMode,
|
||||
) -> Box<RawValue> {
|
||||
client
|
||||
.generate("project", model, "token", body.as_bytes(), mode, &[])
|
||||
.await
|
||||
.unwrap();
|
||||
let requests = server.received_requests().await.unwrap();
|
||||
let envelope: std::collections::BTreeMap<String, Box<RawValue>> =
|
||||
serde_json::from_slice(&requests.last().unwrap().body).unwrap();
|
||||
envelope["request"].clone()
|
||||
}
|
||||
|
||||
fn call(name: &str, id: Option<&str>) -> Value {
|
||||
let mut call = json!({"name":name,"args":{}});
|
||||
if let Some(id) = id {
|
||||
call["id"] = id.into();
|
||||
}
|
||||
json!({"functionCall":call})
|
||||
}
|
||||
|
||||
fn response(name: &str, id: Option<&str>) -> Value {
|
||||
let mut response = json!({"name":name,"response":{"output":"ok"}});
|
||||
if let Some(id) = id {
|
||||
response["id"] = id.into();
|
||||
}
|
||||
json!({"functionResponse":response})
|
||||
}
|
||||
|
||||
fn history(calls: Vec<Value>, responses: Vec<Value>) -> Value {
|
||||
json!({"contents":[{"role":"model","parts":calls},{"role":"user","parts":responses}]})
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn missing_ids_pair_by_unique_name_without_reencoding_business_fields() {
|
||||
let (server, client) = client().await;
|
||||
let contents = r#"[{"role":"model","parts":[{"thought":true,"text":"reason","thoughtSignature":"opaque=="},{"functionCall":{"name":"look\u0075p","args":{"large":98765432109876543210987654,"n":1e+09,"n":2}}},{"function_call":{"name":"read","args":{}}}]},{"role":"user","parts":[{"function_response":{"name":"read","response":{"output":"second"}}},{"functionResponse":{"name":"lookup","response":{"output":"first","functionCall":{"name":"nested"}}}}]}]"#;
|
||||
let body = format!(r#"{{"contents":{contents},"unknown":1e+09,"unknown":2}}"#);
|
||||
for mode in [GenerateMode::Json, GenerateMode::Stream] {
|
||||
let outgoing = generate(&server, &client, &body, "claude-opus-5-5-medium", mode).await;
|
||||
let value: Value = serde_json::from_str(outgoing.get()).unwrap();
|
||||
let first = value["contents"][0]["parts"][1]["functionCall"]["id"]
|
||||
.as_str()
|
||||
.unwrap();
|
||||
let second = value["contents"][0]["parts"][2]["function_call"]["id"]
|
||||
.as_str()
|
||||
.unwrap();
|
||||
assert!(!first.is_empty());
|
||||
assert_ne!(first, second);
|
||||
assert_eq!(
|
||||
value["contents"][1]["parts"][1]["functionResponse"]["id"],
|
||||
first
|
||||
);
|
||||
assert_eq!(
|
||||
value["contents"][1]["parts"][0]["function_response"]["id"],
|
||||
second
|
||||
);
|
||||
let restored = outgoing
|
||||
.get()
|
||||
.replace(&format!(",\"id\":\"{first}\""), "")
|
||||
.replace(&format!(",\"id\":\"{second}\""), "");
|
||||
assert!(restored.contains(contents));
|
||||
assert!(restored.contains(r#""unknown":1e+09,"unknown":2"#));
|
||||
assert!(
|
||||
value["contents"][1]["parts"][1]["functionResponse"]["response"]["functionCall"]
|
||||
.get("id")
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn existing_ids_are_reused_and_generated_ids_survive_retries_and_appended_rounds() {
|
||||
let (server, client) = client().await;
|
||||
let body = history(
|
||||
vec![
|
||||
call("run", None),
|
||||
call("read", Some("existing-call")),
|
||||
call("lookup", None),
|
||||
],
|
||||
vec![
|
||||
response("lookup", Some("existing-result")),
|
||||
response("read", None),
|
||||
response("run", None),
|
||||
],
|
||||
);
|
||||
let first = generate(
|
||||
&server,
|
||||
&client,
|
||||
&body.to_string(),
|
||||
"claude-opus-5-5-medium",
|
||||
GenerateMode::Json,
|
||||
)
|
||||
.await;
|
||||
let first_value: Value = serde_json::from_str(first.get()).unwrap();
|
||||
let id = first_value["contents"][0]["parts"][0]["functionCall"]["id"]
|
||||
.as_str()
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
first_value["contents"][1]["parts"][2]["functionResponse"]["id"],
|
||||
id
|
||||
);
|
||||
assert_eq!(
|
||||
first_value["contents"][1]["parts"][1]["functionResponse"]["id"],
|
||||
"existing-call"
|
||||
);
|
||||
assert_eq!(
|
||||
first_value["contents"][0]["parts"][2]["functionCall"]["id"],
|
||||
"existing-result"
|
||||
);
|
||||
let retry = generate(
|
||||
&server,
|
||||
&client,
|
||||
&body.to_string(),
|
||||
"claude-opus-5-5-medium",
|
||||
GenerateMode::Json,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(first.get(), retry.get());
|
||||
let mut extended = body.clone();
|
||||
extended["contents"].as_array_mut().unwrap().extend([
|
||||
json!({"role":"model","parts":[call("run",None)]}),
|
||||
json!({"role":"user","parts":[response("run",None)]}),
|
||||
]);
|
||||
let extended = generate(
|
||||
&server,
|
||||
&client,
|
||||
&extended.to_string(),
|
||||
"claude-opus-5-5-medium",
|
||||
GenerateMode::Json,
|
||||
)
|
||||
.await;
|
||||
let extended: Value = serde_json::from_str(extended.get()).unwrap();
|
||||
assert_eq!(
|
||||
&extended["contents"].as_array().unwrap()[..2],
|
||||
first_value["contents"].as_array().unwrap()
|
||||
);
|
||||
assert_ne!(
|
||||
extended["contents"][2]["parts"][0]["functionCall"]["id"],
|
||||
id
|
||||
);
|
||||
assert_eq!(
|
||||
extended["contents"][2]["parts"][0]["functionCall"]["id"],
|
||||
extended["contents"][3]["parts"][0]["functionResponse"]["id"]
|
||||
);
|
||||
|
||||
// 客户端已有的 ID 即使占用补偿命名空间,也不能和新配对共用
|
||||
let collision = history(
|
||||
vec![call("run", None), call("read", Some(id))],
|
||||
vec![response("run", None), response("read", Some(id))],
|
||||
);
|
||||
let collision = generate(
|
||||
&server,
|
||||
&client,
|
||||
&collision.to_string(),
|
||||
"claude-opus-5-5-medium",
|
||||
GenerateMode::Json,
|
||||
)
|
||||
.await;
|
||||
let collision: Value = serde_json::from_str(collision.get()).unwrap();
|
||||
assert_ne!(
|
||||
collision["contents"][0]["parts"][0]["functionCall"]["id"],
|
||||
id
|
||||
);
|
||||
assert_eq!(
|
||||
collision["contents"][0]["parts"][1]["functionCall"]["id"],
|
||||
id
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ambiguous_or_invalid_history_and_existing_ids_remain_unchanged() {
|
||||
let (server, client) = client().await;
|
||||
let mut cases = vec![
|
||||
history(
|
||||
vec![call("run", None), call("run", None)],
|
||||
vec![response("run", None), response("run", None)],
|
||||
),
|
||||
history(
|
||||
vec![call("run", None)],
|
||||
vec![response("run", None), response("run", None)],
|
||||
),
|
||||
history(vec![call("run", None)], vec![response("other", None)]),
|
||||
history(
|
||||
vec![call("run", Some("a"))],
|
||||
vec![response("run", Some("b"))],
|
||||
),
|
||||
history(
|
||||
vec![call("run", Some("a"))],
|
||||
vec![response("run", Some("a"))],
|
||||
),
|
||||
history(
|
||||
vec![call("run", Some("used")), call("read", Some("used"))],
|
||||
vec![response("run", None), response("read", Some("used"))],
|
||||
),
|
||||
json!({"contents":[{"role":"model","parts":[call("run",None)]},{"role":"user","parts":[{"text":"intervening"}]},{"role":"user","parts":[response("run",None)]}]}),
|
||||
json!({"contents":[{"role":"user","parts":[response("run",None)]}]}),
|
||||
];
|
||||
for id in [json!(null), json!(""), json!(42)] {
|
||||
let mut body = history(vec![call("run", None)], vec![response("run", None)]);
|
||||
body["contents"][0]["parts"][0]["functionCall"]["id"] = id;
|
||||
cases.push(body);
|
||||
}
|
||||
for body in cases {
|
||||
let outgoing = generate(
|
||||
&server,
|
||||
&client,
|
||||
&body.to_string(),
|
||||
"claude-opus-5-5-medium",
|
||||
GenerateMode::Json,
|
||||
)
|
||||
.await;
|
||||
let outgoing: Value = serde_json::from_str(outgoing.get()).unwrap();
|
||||
assert_eq!(outgoing["contents"], body["contents"]);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn compatibility_is_limited_to_native_claude_generation() {
|
||||
let (server, client) = client().await;
|
||||
let body = history(vec![call("run", None)], vec![response("run", None)]);
|
||||
for (model, mode) in [
|
||||
("gemini-4-hydrogen", GenerateMode::Json),
|
||||
(
|
||||
"claude-opus-5-5-medium",
|
||||
GenerateMode::Chat { stream: false },
|
||||
),
|
||||
("claude-opus-5-5-medium", GenerateMode::WebSearch),
|
||||
] {
|
||||
let outgoing = generate(&server, &client, &body.to_string(), model, mode).await;
|
||||
let outgoing: Value = serde_json::from_str(outgoing.get()).unwrap();
|
||||
assert_eq!(outgoing["contents"], body["contents"]);
|
||||
}
|
||||
client
|
||||
.count_tokens("token", body.to_string().as_bytes(), &[])
|
||||
.await
|
||||
.unwrap();
|
||||
let requests = server.received_requests().await.unwrap();
|
||||
let envelope: Value = serde_json::from_slice(&requests.last().unwrap().body).unwrap();
|
||||
assert_eq!(envelope["request"]["contents"], body["contents"]);
|
||||
}
|
||||
@@ -30,7 +30,7 @@ lru = "0.19.0"
|
||||
# hyper-util 固定到包含 SOCKS IPv6 修复的正式版
|
||||
# 升级前须重复采样 ClientHello,核对算法、扩展集合及排序约束、key_share 与 ALPN。
|
||||
aws-lc-rs = "=1.18.1"
|
||||
h2 = "=0.4.20"
|
||||
h2 = "=0.4.19"
|
||||
hyper = { version = "=1.11.1", default-features = false }
|
||||
hyper-rustls = "=0.27.7"
|
||||
hyper-util = { version = "=0.1.21", features = ["client-legacy", "http1", "tokio"] }
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
//! 已识别的非 Codex 环境信息过滤;官方身份和会话规则由 transport 自身维护
|
||||
|
||||
use gateway_protocol::http::is_downstream_environment_request_header;
|
||||
|
||||
/// 调用方须传入 HeaderName 规范化后的小写名称
|
||||
///
|
||||
/// 此处的“官方”仅指 Codex Core/Desktop 发往 Codex 上游的请求协议,
|
||||
@@ -8,32 +10,7 @@
|
||||
/// 过滤表示网关不继承下游环境,不代表官方服务端必然拒绝该字段
|
||||
/// 按已知来源命名空间覆盖扩展;其他未知业务头不因源码中未出现而被过滤
|
||||
pub(crate) fn is_non_codex_request_header(name: &str) -> bool {
|
||||
// Cloudflare 链路信息及 Access 认证不跨到上游;cf-* 不只包含诊断字段
|
||||
name.starts_with("cf-")
|
||||
// 反代记录的是客户端到网关这一段地址、协议和路由
|
||||
|| name.starts_with("x-forwarded-")
|
||||
// OpenAI 官方 Python/Node SDK 也发送 X-Stainless-*;Pi 的普通 Responses
|
||||
// 适配通过该 SDK 发送这些环境、版本和重试信息,不作为 Codex 上游画像继承
|
||||
|| name.starts_with("x-stainless-")
|
||||
// UA Client Hints 与 Fetch Metadata 是浏览器标准,描述下游浏览器
|
||||
// 和页面请求上下文,不能当作网关连接上游时的环境
|
||||
|| name.starts_with("sec-ch-ua")
|
||||
|| name.starts_with("sec-fetch-")
|
||||
|| matches!(
|
||||
name,
|
||||
// Forwarded、Via、CDN-Loop 有 RFC 定义;剥离是本应用重建
|
||||
// Provider 请求的策略,不是通用 HTTP 代理的协议要求
|
||||
"forwarded"
|
||||
| "via"
|
||||
| "cdn-loop"
|
||||
// Nginx/代理与 Cloudflare 使用的原始访客地址
|
||||
| "x-real-ip"
|
||||
| "true-client-ip"
|
||||
// 页面来源与引用地址属于下游请求,不继承到上游
|
||||
| "origin"
|
||||
| "referer"
|
||||
// Pi 普通 Responses 适配使用的会话头别名;协议层已提取其
|
||||
// 会话语义,上游按 session-id 输出,这里仅过滤原始 HTTP 头
|
||||
| "session_id"
|
||||
)
|
||||
is_downstream_environment_request_header(name)
|
||||
// Codex 会话别名已提取为 session-id,不能作为跨 Provider 的环境头规则
|
||||
|| name == "session_id"
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@ pub(super) const WEBSOCKET_SEND_TIMEOUT: Duration = Duration::from_secs(5 * 60);
|
||||
pub(super) enum PumpCommand {
|
||||
Upload {
|
||||
text: tungstenite::Utf8Bytes,
|
||||
deadline: tokio::time::Instant,
|
||||
admission_deadline: tokio::time::Instant,
|
||||
accepted:
|
||||
oneshot::Sender<oneshot::Receiver<Result<UploadOutcome, CodexWebSocketExchangeError>>>,
|
||||
},
|
||||
|
||||
@@ -340,13 +340,13 @@ impl PumpedWebSocket {
|
||||
&self,
|
||||
text: tungstenite::Utf8Bytes,
|
||||
) -> Result<UploadOutcome, CodexWebSocketExchangeError> {
|
||||
let deadline = Instant::now() + WEBSOCKET_SEND_TIMEOUT;
|
||||
let admission_deadline = Instant::now() + WEBSOCKET_SEND_TIMEOUT;
|
||||
let (accepted, admission) = tokio::sync::oneshot::channel();
|
||||
let result = tokio::time::timeout_at(deadline, async {
|
||||
let result = tokio::time::timeout_at(admission_deadline, async {
|
||||
self.tx_command
|
||||
.send(PumpCommand::Upload {
|
||||
text,
|
||||
deadline,
|
||||
admission_deadline,
|
||||
accepted,
|
||||
})
|
||||
.await
|
||||
@@ -359,7 +359,7 @@ impl PumpedWebSocket {
|
||||
.map_err(|_| CodexWebSocketExchangeError::SendTimeout {
|
||||
timeout: WEBSOCKET_SEND_TIMEOUT,
|
||||
})??;
|
||||
// 接单后由 pump 执行同一截止时间,调用方不能先超时并丢弃已经读到的上游回复
|
||||
// 接单后由 pump 监测分片写入,调用方等待最终发送结果或已读到的上游回复
|
||||
result
|
||||
.await
|
||||
.unwrap_or_else(|_| Err(tungstenite::Error::ConnectionClosed.into()))
|
||||
@@ -648,36 +648,45 @@ async fn handle_command(
|
||||
PumpCommand::Send { message, ack } => (message, ack),
|
||||
PumpCommand::Upload {
|
||||
text,
|
||||
deadline,
|
||||
admission_deadline,
|
||||
accepted,
|
||||
} => {
|
||||
let (ack, result) = tokio::sync::oneshot::channel();
|
||||
if closed.load(Ordering::Acquire)
|
||||
|| Instant::now() >= deadline
|
||||
|| Instant::now() >= admission_deadline
|
||||
|| accepted.send(result).is_err()
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let mut upload = super::upload::Upload::new(messages, pending.is_some());
|
||||
let write = tokio::time::timeout_at(deadline, upload.send(inner, text)).await;
|
||||
if let Some(activity) = upload.last_activity {
|
||||
record_activity(lifecycle, activity);
|
||||
}
|
||||
let (error, metric_reason) = match write {
|
||||
Ok(Ok(())) => {
|
||||
let mut frames = super::upload::text_frames(text);
|
||||
let (error, metric_reason) = loop {
|
||||
let Some(frame) = frames.next() else {
|
||||
let _ = ack.send(Ok(UploadOutcome::Flushed));
|
||||
return None;
|
||||
};
|
||||
// 只有正文分片写出并刷新后才开始下一个窗口,入站心跳不会延长写入等待
|
||||
let write =
|
||||
tokio::time::timeout(WEBSOCKET_SEND_TIMEOUT, upload.send_frame(inner, frame))
|
||||
.await;
|
||||
if let Some(activity) = upload.last_activity.take() {
|
||||
record_activity(lifecycle, activity);
|
||||
}
|
||||
Ok(Err(error)) => {
|
||||
let reason = transport_metric_reason(&error);
|
||||
(CodexWebSocketExchangeError::Transport(error), reason)
|
||||
match write {
|
||||
Ok(Ok(())) => {}
|
||||
Ok(Err(error)) => {
|
||||
let reason = transport_metric_reason(&error);
|
||||
break (CodexWebSocketExchangeError::Transport(error), reason);
|
||||
}
|
||||
Err(_) => {
|
||||
break (
|
||||
CodexWebSocketExchangeError::SendTimeout {
|
||||
timeout: WEBSOCKET_SEND_TIMEOUT,
|
||||
},
|
||||
"send_timeout",
|
||||
);
|
||||
}
|
||||
}
|
||||
Err(_) => (
|
||||
CodexWebSocketExchangeError::SendTimeout {
|
||||
timeout: WEBSOCKET_SEND_TIMEOUT,
|
||||
},
|
||||
"send_timeout",
|
||||
),
|
||||
};
|
||||
let reason = upload
|
||||
.close
|
||||
|
||||
@@ -127,44 +127,42 @@ impl<'a> Upload<'a> {
|
||||
Poll::Pending
|
||||
}
|
||||
|
||||
pub(super) async fn send(
|
||||
pub(super) async fn send_frame(
|
||||
&mut self,
|
||||
socket: &mut RawWsStream,
|
||||
text: Utf8Bytes,
|
||||
frame: Message,
|
||||
) -> Result<(), Error> {
|
||||
for frame in text_frames(text) {
|
||||
let mut frame = Some(frame);
|
||||
let mut first_poll = true;
|
||||
let result = poll_fn(|cx| {
|
||||
let read_first = std::mem::take(&mut first_poll);
|
||||
if read_first {
|
||||
let _ = self.poll_incoming(socket, cx, false)?;
|
||||
}
|
||||
let write = (|| {
|
||||
if frame.is_some() {
|
||||
ready!(socket.poll_ready_unpin(cx))?;
|
||||
}
|
||||
if let Some(frame) = frame.take() {
|
||||
let result = socket.start_send_unpin(frame);
|
||||
// I/O 错误可能发生在首帧头已部分写出之后
|
||||
self.started |= matches!(result, Ok(()) | Err(Error::Io(_)));
|
||||
result?;
|
||||
}
|
||||
socket.poll_flush_unpin(cx)
|
||||
})();
|
||||
if !read_first && write.is_pending() {
|
||||
let _ = self.poll_incoming(socket, cx, false)?;
|
||||
}
|
||||
write
|
||||
})
|
||||
.await;
|
||||
if let Err(error) = result {
|
||||
if self.started && !matches!(error, Error::ConnectionClosed) {
|
||||
// 只取已就绪的回复,不能为了等待假设的 Close 延长写入期限
|
||||
let _ = poll_fn(|cx| self.poll_incoming(socket, cx, true)).await;
|
||||
}
|
||||
return Err(error);
|
||||
let mut frame = Some(frame);
|
||||
let mut first_poll = true;
|
||||
let result = poll_fn(|cx| {
|
||||
let read_first = std::mem::take(&mut first_poll);
|
||||
if read_first {
|
||||
let _ = self.poll_incoming(socket, cx, false)?;
|
||||
}
|
||||
let write = (|| {
|
||||
if frame.is_some() {
|
||||
ready!(socket.poll_ready_unpin(cx))?;
|
||||
}
|
||||
if let Some(frame) = frame.take() {
|
||||
let result = socket.start_send_unpin(frame);
|
||||
// I/O 错误可能发生在首帧头已部分写出之后
|
||||
self.started |= matches!(result, Ok(()) | Err(Error::Io(_)));
|
||||
result?;
|
||||
}
|
||||
socket.poll_flush_unpin(cx)
|
||||
})();
|
||||
if !read_first && write.is_pending() {
|
||||
let _ = self.poll_incoming(socket, cx, false)?;
|
||||
}
|
||||
write
|
||||
})
|
||||
.await;
|
||||
if let Err(error) = result {
|
||||
if self.started && !matches!(error, Error::ConnectionClosed) {
|
||||
// 只取已就绪的回复,不能为了等待假设的 Close 延长写入期限
|
||||
let _ = poll_fn(|cx| self.poll_incoming(socket, cx, true)).await;
|
||||
}
|
||||
return Err(error);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -45,6 +45,7 @@ const DOWNSTREAM_CLIENT_HEADERS: &[(&str, &str)] = &[
|
||||
];
|
||||
|
||||
const BUSINESS_EXTENSION_HEADERS: &[(&str, &str)] = &[
|
||||
("Accept-Language", "zh-CN"),
|
||||
("x-openai-fedramp", "true"),
|
||||
("x-grok-turn-idx", "7"),
|
||||
("X-Grok-Model-Override", "synthetic-model"),
|
||||
|
||||
@@ -364,6 +364,49 @@ fn large_upload_client(addr: std::net::SocketAddr) -> (CodexBackendClient, Codex
|
||||
(client, request)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn fragmented_upload_can_outlast_five_minutes_with_write_progress() {
|
||||
let socket = tokio::net::TcpSocket::new_v4().unwrap();
|
||||
socket.set_recv_buffer_size(65536).unwrap();
|
||||
socket.bind("127.0.0.1:0".parse().unwrap()).unwrap();
|
||||
let listener = socket.listen(1).unwrap();
|
||||
let (client, request) = large_upload_client(listener.local_addr().unwrap());
|
||||
let (completed, received) = tokio::sync::oneshot::channel();
|
||||
let server = tokio::spawn(async move {
|
||||
let (mut socket, _) = listener.accept().await.unwrap();
|
||||
upgrade_raw_socket(&mut socket, false).await;
|
||||
let mut frames = 0;
|
||||
loop {
|
||||
let frame = read_client_frame(&mut socket).await;
|
||||
frames += 1;
|
||||
if frames == 1 || frames == 8 {
|
||||
// 两次推进之间排空多个正文分片,让总耗时超过发送时限
|
||||
tokio::time::pause();
|
||||
tokio::time::sleep(Duration::from_secs(170)).await;
|
||||
tokio::time::resume();
|
||||
}
|
||||
if frame.first_byte == 0x80 {
|
||||
break;
|
||||
}
|
||||
assert!(matches!(frame.first_byte, 0x00 | 0x01));
|
||||
}
|
||||
assert!(frames > 8);
|
||||
write_server_text_frame(
|
||||
&mut socket,
|
||||
&completed_websocket_response("resp_slow_upload", 1, 1),
|
||||
)
|
||||
.await;
|
||||
received.await.unwrap();
|
||||
});
|
||||
let response = client
|
||||
.create_response(&request, request_context("slow-upload", None))
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(response.body.contains("resp_slow_upload"));
|
||||
completed.send(()).unwrap();
|
||||
server.await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn fragmented_upload_sends_pong_before_final_continuation() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
@@ -517,12 +560,12 @@ async fn upload_timeout_delivers_buffered_upstream_error() {
|
||||
.expect("peer error and following Ping should be read during upload");
|
||||
// Pong 证明此前的业务错误已经入队,保留连接直到写超时和错误交付均已完成
|
||||
tokio::time::pause();
|
||||
tokio::time::advance(Duration::from_secs(301)).await;
|
||||
tokio::time::resume();
|
||||
timeout(Duration::from_secs(5), released)
|
||||
// 已进入内核的分片仍可刷新时限,让时钟在停读后随实际等待自动推进
|
||||
timeout(Duration::from_secs(610), released)
|
||||
.await
|
||||
.unwrap()
|
||||
.expect("stalled upload must deliver the buffered error")
|
||||
.unwrap();
|
||||
tokio::time::resume();
|
||||
});
|
||||
let mut response = client
|
||||
.create_response_stream(&request, request_context("upload_timeout_reply", None))
|
||||
|
||||
@@ -20,8 +20,10 @@ gateway-core = { path = "../../gateway-core" }
|
||||
gateway-protocol = { path = "../../gateway-protocol" }
|
||||
getrandom = "0.4.3"
|
||||
jsonwebtoken = { version = "=12.0.0", default-features = false, features = ["aws_lc_rs"] }
|
||||
# 与官方 Grok CLI 一致:reqwest 不启用压缩特性,上游请求不带 accept-encoding。
|
||||
# 推理 transport 不协商压缩,避免启用影响其他 Provider 的 reqwest 全局特性
|
||||
reqwest = { version = "=0.12.28", default-features = false, features = ["stream", "rustls-tls-native-roots", "http2", "socks"] }
|
||||
rustls = { version = "=0.23.46", default-features = false, features = ["aws_lc_rs", "prefer-post-quantum", "std", "tls12"] }
|
||||
rustls-native-certs = "=0.8.3"
|
||||
serde = { version = "1.0.228", features = ["derive"] }
|
||||
serde_json = { version = "1.0.150", features = ["arbitrary_precision", "preserve_order"] }
|
||||
semver = "1.0.27"
|
||||
|
||||
@@ -60,20 +60,20 @@ pub use transport::{
|
||||
GROK_BILLING_URL, GROK_CLI_BASE_URL, GROK_MODEL_CATALOG_URL, GROK_SUBSCRIPTION_URL,
|
||||
GrokBillingClient, GrokBillingError, GrokBillingRequest, GrokBillingSnapshot,
|
||||
GrokBillingTransport, GrokBillingTransportError, GrokBillingTransportErrorKind,
|
||||
GrokBillingTransportFuture, GrokBillingTransportResponse, GrokCanonicalDecoder,
|
||||
GrokCatalogApiBackend, GrokCatalogCapabilities, GrokCatalogCapabilityEvidence,
|
||||
GrokCatalogLimits, GrokCatalogMetadata, GrokCatalogModel, GrokCatalogReasoningEffort,
|
||||
GrokClientIdentity, GrokCredentialFailure, GrokCredentialFeedbackFuture,
|
||||
GrokDnsResolutionError, GrokDnsResolutionPlan, GrokDnsResolutionPolicy, GrokEndpointPolicy,
|
||||
GrokHeader, GrokHeaderValue, GrokInferenceChunkStream, GrokInferenceClientCacheStatus,
|
||||
GrokInferenceDnsObservation, GrokInferenceDnsSource, GrokInferenceRequest,
|
||||
GrokInferenceResponse, GrokInferenceTransport, GrokInferenceTransportError,
|
||||
GrokInferenceTransportErrorKind, GrokInferenceTransportFuture, GrokInferenceTransportMetrics,
|
||||
GrokModelCatalogClient, GrokModelCatalogError, GrokModelCatalogRequest,
|
||||
GrokModelCatalogSession, GrokModelCatalogSessionError, GrokModelCatalogSnapshot,
|
||||
GrokModelCatalogTransport, GrokModelCatalogTransportError, GrokModelCatalogTransportErrorKind,
|
||||
GrokModelCatalogTransportFuture, GrokModelCatalogTransportResponse, GrokProviderConfigError,
|
||||
GrokProviderTransport, GrokRequestEncodeError, GrokReqwestTransportBuildError,
|
||||
GrokBillingTransportFuture, GrokBillingTransportResponse, GrokCatalogApiBackend,
|
||||
GrokCatalogCapabilities, GrokCatalogCapabilityEvidence, GrokCatalogLimits, GrokCatalogMetadata,
|
||||
GrokCatalogModel, GrokCatalogReasoningEffort, GrokClientIdentity, GrokCredentialFailure,
|
||||
GrokCredentialFeedbackFuture, GrokDnsResolutionError, GrokDnsResolutionPlan,
|
||||
GrokDnsResolutionPolicy, GrokEndpointPolicy, GrokHeader, GrokHeaderValue,
|
||||
GrokInferenceChunkStream, GrokInferenceClientCacheStatus, GrokInferenceDnsObservation,
|
||||
GrokInferenceDnsSource, GrokInferenceRequest, GrokInferenceResponse, GrokInferenceTransport,
|
||||
GrokInferenceTransportError, GrokInferenceTransportErrorKind, GrokInferenceTransportFuture,
|
||||
GrokInferenceTransportMetrics, GrokModelCatalogClient, GrokModelCatalogError,
|
||||
GrokModelCatalogRequest, GrokModelCatalogSession, GrokModelCatalogSessionError,
|
||||
GrokModelCatalogSnapshot, GrokModelCatalogTransport, GrokModelCatalogTransportError,
|
||||
GrokModelCatalogTransportErrorKind, GrokModelCatalogTransportFuture,
|
||||
GrokModelCatalogTransportResponse, GrokProviderConfigError, GrokProviderTransport,
|
||||
GrokRequestEncodeError, GrokReqwestTransportBuildError, GrokResponseDecoder,
|
||||
GrokResponsesRequest, GrokSessionAffinityKey, GrokSessionBinding, GrokSessionDataError,
|
||||
GrokSessionLeaseGuard, GrokSessionSelection, GrokSessionSelector, GrokSessionSelectorError,
|
||||
GrokSessionSelectorFuture, MAX_GROK_BILLING_BYTES, MAX_GROK_MODEL_CATALOG_BYTES,
|
||||
|
||||
@@ -19,11 +19,11 @@ impl Default for XaiWireProfile {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
client_identifier: "grok-shell".to_owned(),
|
||||
client_version: "1.0.13".to_owned(),
|
||||
client_version: "1.0.92".to_owned(),
|
||||
client_mode: "headless".to_owned(),
|
||||
target_os: "linux".to_owned(),
|
||||
target_arch: "x86_64".to_owned(),
|
||||
verified_at: DateTime::UNIX_EPOCH + chrono::Duration::seconds(1_788_105_600),
|
||||
verified_at: DateTime::UNIX_EPOCH + chrono::Duration::seconds(1_795_996_800),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -62,11 +62,13 @@ impl GrokBuildProvider {
|
||||
credential_recovery: Arc::clone(&self.credential_recovery),
|
||||
responses_url: self.responses_url.clone(),
|
||||
request,
|
||||
request_headers: crate::transport::headers::request_headers(&generate),
|
||||
account_switch: account_switched(&context, &selected),
|
||||
middleware_headers,
|
||||
upstream_model,
|
||||
context,
|
||||
session: Arc::clone(&selected),
|
||||
session_capture: None,
|
||||
session_state: None,
|
||||
},
|
||||
);
|
||||
let stream = ProviderStream::new(metadata, events, selected)
|
||||
|
||||
@@ -1,32 +1,10 @@
|
||||
//! xAI 原生续接、账号归属与完整历史重放
|
||||
//! xAI 原生续接的账号与会话元数据,历史内容由客户端持有
|
||||
|
||||
use super::*;
|
||||
|
||||
#[derive(Clone, Serialize, Deserialize)]
|
||||
pub(super) struct XaiSessionState {
|
||||
pub(super) account_id: String,
|
||||
pub(super) session_id: Option<String>,
|
||||
pub(super) transcript: Vec<XaiReplayItem>,
|
||||
pub(super) instructions: Option<Value>,
|
||||
pub(super) response_stored: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub(super) enum XaiReplayItem {
|
||||
ClientInput(Value),
|
||||
SanitizedOutput(Value),
|
||||
AccountOutput { account_id: String, item: Value },
|
||||
}
|
||||
|
||||
pub(super) struct GrokSessionCapture {
|
||||
pub(super) previous: Option<XaiSessionState>,
|
||||
pub(super) request_input: Vec<Value>,
|
||||
pub(super) instructions: Option<Value>,
|
||||
pub(super) response_stored: bool,
|
||||
pub(super) account_id: String,
|
||||
pub(super) session_id: Option<String>,
|
||||
pub(super) output_items: BTreeMap<u32, Value>,
|
||||
}
|
||||
|
||||
pub(super) fn decode_xai_session_state(
|
||||
@@ -35,314 +13,94 @@ pub(super) fn decode_xai_session_state(
|
||||
request
|
||||
.provider_session_state(XAI_PROVIDER_NAME)
|
||||
.map(|state| {
|
||||
let payload = Value::Object(state.payload().clone());
|
||||
if serde_json::to_vec(&payload)
|
||||
.map_err(|_| protocol_not_sent())?
|
||||
.len()
|
||||
> XAI_SESSION_STATE_MAX_BYTES
|
||||
{
|
||||
return Err(protocol_not_sent());
|
||||
}
|
||||
serde_json::from_value(payload).map_err(|_| protocol_not_sent())
|
||||
let payload = state.payload();
|
||||
// 仅读取路由元数据,旧缓存中可能存在的正文既不解码也不复制到下一轮
|
||||
let account_id = payload
|
||||
.get("account_id")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or_else(protocol_not_sent)?
|
||||
.to_owned();
|
||||
let session_id = match payload.get("session_id") {
|
||||
Some(Value::String(value)) => Some(value.clone()),
|
||||
Some(Value::Null) | None => None,
|
||||
Some(_) => return Err(protocol_not_sent()),
|
||||
};
|
||||
Ok(XaiSessionState {
|
||||
account_id,
|
||||
session_id,
|
||||
})
|
||||
})
|
||||
.transpose()
|
||||
}
|
||||
|
||||
pub(super) fn encode_xai_session_state(
|
||||
state: XaiSessionState,
|
||||
) -> Result<Option<ProviderSessionState>, ProviderError> {
|
||||
let value = serde_json::to_value(state).map_err(|_| protocol_sent())?;
|
||||
if serde_json::to_vec(&value)
|
||||
.map_err(|_| protocol_sent())?
|
||||
.len()
|
||||
> XAI_SESSION_STATE_MAX_BYTES
|
||||
{
|
||||
return Ok(None);
|
||||
}
|
||||
let Value::Object(payload) = value else {
|
||||
return Err(protocol_sent());
|
||||
};
|
||||
ProviderSessionState::new(XAI_PROVIDER_NAME, payload)
|
||||
.map(Some)
|
||||
.map_err(|_| protocol_sent())
|
||||
) -> Result<ProviderSessionState, ProviderError> {
|
||||
ProviderSessionState::new(
|
||||
XAI_PROVIDER_NAME,
|
||||
Map::from_iter([
|
||||
("account_id".to_owned(), state.account_id.into()),
|
||||
("session_id".to_owned(), state.session_id.into()),
|
||||
]),
|
||||
)
|
||||
.map_err(|_| protocol_not_sent())
|
||||
}
|
||||
|
||||
pub(super) fn continuation_account(
|
||||
context: &AttemptContext,
|
||||
previous_session: Option<&XaiSessionState>,
|
||||
) -> Result<Option<gateway_core::account::ProviderAccountId>, ProviderError> {
|
||||
let Some(continuation) = context.continuation() else {
|
||||
return Ok(None);
|
||||
};
|
||||
match (context.continuation_attempt(), continuation) {
|
||||
(ContinuationAttempt::Native, ContinuationBinding::Pinned(pin)) => {
|
||||
if pin.provider().as_str() != XAI_PROVIDER_NAME {
|
||||
return Err(invalid_continuation());
|
||||
}
|
||||
) -> Result<Option<ProviderAccountId>, ProviderError> {
|
||||
match (context.continuation_attempt(), context.continuation()) {
|
||||
(ContinuationAttempt::None, None) => Ok(None),
|
||||
(ContinuationAttempt::Native, Some(ContinuationBinding::Pinned(pin)))
|
||||
if pin.provider().as_str() == XAI_PROVIDER_NAME =>
|
||||
{
|
||||
Ok(Some(pin.account().clone()))
|
||||
}
|
||||
(ContinuationAttempt::Native, ContinuationBinding::External(_)) => {
|
||||
Err(invalid_continuation())
|
||||
}
|
||||
(ContinuationAttempt::ReplayOwner, _) => {
|
||||
let previous = previous_session.ok_or_else(invalid_continuation)?;
|
||||
gateway_core::account::ProviderAccountId::new(previous.account_id.clone())
|
||||
.map(Some)
|
||||
.map_err(|_| invalid_continuation())
|
||||
}
|
||||
(ContinuationAttempt::ReplayAny, _) => Ok(None),
|
||||
(ContinuationAttempt::None | ContinuationAttempt::RotateForClientReplay(_), _) => {
|
||||
Err(invalid_continuation())
|
||||
}
|
||||
// 原生续接失效时不从网关拼装历史,也不把增量请求发给其他账号
|
||||
_ => Err(invalid_continuation()),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn apply_continuation(
|
||||
request: &mut GrokResponsesRequest,
|
||||
previous_session: Option<&XaiSessionState>,
|
||||
context: &AttemptContext,
|
||||
account: &gateway_core::account::ProviderAccountId,
|
||||
current_input: &[Value],
|
||||
account: &ProviderAccountId,
|
||||
) -> Result<(), ProviderError> {
|
||||
let Some(continuation) = context.continuation() else {
|
||||
return Ok(());
|
||||
};
|
||||
match context.continuation_attempt() {
|
||||
ContinuationAttempt::Native => {
|
||||
let ContinuationBinding::Pinned(pin) = continuation else {
|
||||
return Err(invalid_continuation());
|
||||
};
|
||||
let provider = ProviderKind::new(XAI_PROVIDER_NAME).map_err(|_| protocol_not_sent())?;
|
||||
if !pin.matches(&provider, account) {
|
||||
return Err(invalid_continuation());
|
||||
}
|
||||
if previous_session.is_some_and(|state| !state.response_stored)
|
||||
|| request.instructions()
|
||||
!= previous_session.and_then(|state| state.instructions.as_ref())
|
||||
{
|
||||
let previous = previous_session.ok_or_else(invalid_continuation)?;
|
||||
return apply_replay(request, previous, account, current_input);
|
||||
}
|
||||
// Grok 原生续接继承首轮指令,不允许同时提交 instructions
|
||||
request.clear_instructions();
|
||||
request.set_previous_response_id(Some(pin.upstream_response_id().as_str().to_owned()));
|
||||
Ok(())
|
||||
}
|
||||
ContinuationAttempt::ReplayOwner | ContinuationAttempt::ReplayAny => {
|
||||
let previous = previous_session.ok_or_else(invalid_continuation)?;
|
||||
if context.continuation_attempt() == ContinuationAttempt::ReplayOwner
|
||||
&& previous.account_id != account.as_str()
|
||||
{
|
||||
return Err(invalid_continuation());
|
||||
}
|
||||
apply_replay(request, previous, account, current_input)
|
||||
}
|
||||
ContinuationAttempt::None | ContinuationAttempt::RotateForClientReplay(_) => {
|
||||
Err(invalid_continuation())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_replay(
|
||||
request: &mut GrokResponsesRequest,
|
||||
previous: &XaiSessionState,
|
||||
account: &gateway_core::account::ProviderAccountId,
|
||||
current_input: &[Value],
|
||||
) -> Result<(), ProviderError> {
|
||||
let mut input = replay_input_for_account(previous, account.as_str());
|
||||
input.reserve(current_input.len());
|
||||
input.extend(current_input.iter().cloned());
|
||||
request.set_replay_input(input);
|
||||
request.set_previous_response_id(None);
|
||||
request.inherit_session(None);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn replay_input_for_account(state: &XaiSessionState, account_id: &str) -> Vec<Value> {
|
||||
state
|
||||
.transcript
|
||||
.iter()
|
||||
.filter_map(|item| match item {
|
||||
XaiReplayItem::ClientInput(value) => Some(value.clone()),
|
||||
XaiReplayItem::SanitizedOutput(value) => Some(value.clone()),
|
||||
XaiReplayItem::AccountOutput {
|
||||
account_id: owner,
|
||||
item,
|
||||
} if owner == account_id => Some(item.clone()),
|
||||
XaiReplayItem::AccountOutput { item, .. } => output_for_another_account(item.clone()),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(super) fn project_transcript_to_account(transcript: &mut Vec<XaiReplayItem>, account_id: &str) {
|
||||
*transcript = transcript
|
||||
.drain(..)
|
||||
.filter_map(|item| match item {
|
||||
XaiReplayItem::AccountOutput {
|
||||
account_id: owner,
|
||||
item,
|
||||
} if owner != account_id => {
|
||||
output_for_another_account(item).map(XaiReplayItem::SanitizedOutput)
|
||||
}
|
||||
item => Some(item),
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
|
||||
fn output_for_another_account(mut item: Value) -> Option<Value> {
|
||||
let Value::Object(object) = &mut item else {
|
||||
return None;
|
||||
let ContinuationBinding::Pinned(pin) = continuation else {
|
||||
return Err(invalid_continuation());
|
||||
};
|
||||
let is_reasoning = object.get("type").and_then(Value::as_str) == Some("reasoning");
|
||||
if !matches!(
|
||||
object.get("type").and_then(Value::as_str),
|
||||
Some("reasoning" | "message" | "function_call" | "custom_tool_call")
|
||||
) {
|
||||
return None;
|
||||
let provider = ProviderKind::new(XAI_PROVIDER_NAME).map_err(|_| protocol_not_sent())?;
|
||||
if context.continuation_attempt() != ContinuationAttempt::Native
|
||||
|| !pin.matches(&provider, account)
|
||||
{
|
||||
return Err(invalid_continuation());
|
||||
}
|
||||
object.remove("id");
|
||||
object.remove("status");
|
||||
if is_reasoning {
|
||||
object.remove("encrypted_content");
|
||||
if object.get("encrypted_content").is_none() && !has_readable_reasoning(object) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
Some(item)
|
||||
}
|
||||
|
||||
pub(super) fn has_readable_reasoning(item: &Map<String, Value>) -> bool {
|
||||
["summary", "content"].into_iter().any(|field| {
|
||||
item.get(field)
|
||||
.and_then(Value::as_array)
|
||||
.is_some_and(|parts| {
|
||||
parts.iter().any(|part| {
|
||||
part.get("text")
|
||||
.and_then(Value::as_str)
|
||||
.is_some_and(|text| !text.trim().is_empty())
|
||||
})
|
||||
})
|
||||
})
|
||||
request.set_previous_response_id(pin.upstream_response_id().as_str());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn attach_xai_session_update(
|
||||
events: &mut [ProviderEvent],
|
||||
capture: &mut Option<GrokSessionCapture>,
|
||||
) -> Result<(), ProviderError> {
|
||||
if capture.is_none() {
|
||||
return Ok(());
|
||||
}
|
||||
let mut terminal_index = None;
|
||||
for (index, event) in events.iter().enumerate() {
|
||||
if let Some(capture) = capture.as_mut() {
|
||||
capture_output_item(event, capture);
|
||||
}
|
||||
if event
|
||||
state: &mut Option<ProviderSessionState>,
|
||||
) {
|
||||
if let Some(terminal) = events.iter_mut().find(|event| {
|
||||
event
|
||||
.canonical_facts()
|
||||
.iter()
|
||||
.any(|fact| matches!(fact, GatewayEvent::Completed(_)))
|
||||
{
|
||||
terminal_index = Some(index);
|
||||
}
|
||||
}
|
||||
let Some(terminal_index) = terminal_index else {
|
||||
return Ok(());
|
||||
};
|
||||
let Some(mut capture) = capture.take() else {
|
||||
return Ok(());
|
||||
};
|
||||
let mut transcript = capture
|
||||
.previous
|
||||
.take()
|
||||
.map(|state| state.transcript)
|
||||
.unwrap_or_default();
|
||||
project_transcript_to_account(&mut transcript, &capture.account_id);
|
||||
transcript.extend(
|
||||
capture
|
||||
.request_input
|
||||
.into_iter()
|
||||
.map(XaiReplayItem::ClientInput),
|
||||
);
|
||||
transcript.extend(capture.output_items.into_values().map(|item| {
|
||||
XaiReplayItem::AccountOutput {
|
||||
account_id: capture.account_id.clone(),
|
||||
item,
|
||||
}
|
||||
}));
|
||||
let state = XaiSessionState {
|
||||
account_id: capture.account_id,
|
||||
session_id: capture.session_id,
|
||||
transcript,
|
||||
instructions: capture.instructions,
|
||||
response_stored: capture.response_stored,
|
||||
};
|
||||
if let Some(update) = encode_xai_session_state(state)? {
|
||||
events[terminal_index].attach_session_update(update);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn capture_output_item(event: &ProviderEvent, capture: &mut GrokSessionCapture) {
|
||||
let Some(wire) = event.wire_event() else {
|
||||
return;
|
||||
};
|
||||
let event_type = wire
|
||||
.event_type()
|
||||
.or_else(|| wire.data().get("type").and_then(Value::as_str));
|
||||
if event_type == Some("response.output_item.done")
|
||||
&& capture.output_items.len() < XAI_SESSION_OUTPUT_LIMIT
|
||||
&& let Some(item) = wire
|
||||
.data()
|
||||
.get("item")
|
||||
.filter(|item| item.is_object())
|
||||
.cloned()
|
||||
}) && let Some(state) = state.take()
|
||||
{
|
||||
let index = wire
|
||||
.data()
|
||||
.get("output_index")
|
||||
.and_then(Value::as_u64)
|
||||
.and_then(|value| u32::try_from(value).ok())
|
||||
.unwrap_or_else(|| u32::try_from(capture.output_items.len()).unwrap_or(u32::MAX));
|
||||
capture.output_items.insert(index, item);
|
||||
}
|
||||
if matches!(
|
||||
event_type,
|
||||
Some("response.completed" | "response.incomplete")
|
||||
) && let Some(output) = wire
|
||||
.data()
|
||||
.get("response")
|
||||
.and_then(Value::as_object)
|
||||
.and_then(|response| response.get("output"))
|
||||
.and_then(Value::as_array)
|
||||
.filter(|output| !output.is_empty())
|
||||
{
|
||||
for (index, item) in output.iter().take(XAI_SESSION_OUTPUT_LIMIT).enumerate() {
|
||||
let Some(index) = u32::try_from(index).ok() else {
|
||||
break;
|
||||
};
|
||||
if capture.output_items.contains_key(&index) {
|
||||
continue;
|
||||
}
|
||||
if item.is_object() {
|
||||
capture.output_items.insert(index, item.clone());
|
||||
}
|
||||
}
|
||||
terminal.attach_session_update(state);
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn invalid_continuation() -> ProviderError {
|
||||
ProviderError::new(
|
||||
ProviderErrorKind::InvalidRequest,
|
||||
UpstreamSendState::NotSent,
|
||||
)
|
||||
.with_continuation_failure(ContinuationFailure::HistoryUnavailable)
|
||||
.with_continuation_recovery_disposition(ContinuationRecoveryDisposition::ClientReplayRequired)
|
||||
ProviderError::responses_replay_required("history_unavailable", UpstreamSendState::NotSent)
|
||||
}
|
||||
|
||||
pub(super) fn protocol_not_sent() -> ProviderError {
|
||||
provider_error(ProviderErrorKind::Protocol, UpstreamSendState::NotSent)
|
||||
}
|
||||
|
||||
pub(super) fn protocol_sent() -> ProviderError {
|
||||
provider_error(ProviderErrorKind::Protocol, UpstreamSendState::Sent)
|
||||
}
|
||||
|
||||
@@ -318,15 +318,19 @@ pub(super) fn map_continuation_failure(
|
||||
&& error.kind() == ProviderErrorKind::InvalidRequest
|
||||
&& error.upstream_status() == Some(404)
|
||||
&& error.upstream_code().is_some_and(|code| {
|
||||
code.as_str()
|
||||
.trim()
|
||||
.eq_ignore_ascii_case(RESPONSE_NOT_FOUND_CODE)
|
||||
RESPONSE_NOT_FOUND_CODES
|
||||
.iter()
|
||||
.any(|known| code.as_str().trim().eq_ignore_ascii_case(known))
|
||||
});
|
||||
if is_reasoning_decode_failure || is_missing_native_response {
|
||||
error
|
||||
.with_continuation_failure(ContinuationFailure::HistoryUnavailable)
|
||||
.with_continuation_recovery_disposition(
|
||||
ContinuationRecoveryDisposition::ProviderReplayAllowed,
|
||||
ContinuationRecoveryDisposition::ClientReplayRequired,
|
||||
)
|
||||
.with_continuation_unavailable_reason("history_unavailable")
|
||||
.with_client_visible_upstream_error(
|
||||
ClientVisibleUpstreamError::previous_response_not_found(),
|
||||
)
|
||||
.with_replay_safe()
|
||||
} else {
|
||||
|
||||
@@ -40,7 +40,6 @@ use gateway_core::task::{
|
||||
};
|
||||
use gateway_core::upstream::{UpstreamSendState, UpstreamTransport};
|
||||
use gateway_protocol::openai::OPENAI_PROTOCOL;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Map, Value};
|
||||
use url::Url;
|
||||
|
||||
@@ -51,9 +50,9 @@ use crate::credential::{
|
||||
GrokCredentialRefreshService, GrokQuotaError,
|
||||
};
|
||||
use crate::profile::{GROK_CLI_RELEASE_POLL_INTERVAL, GrokCliReleaseService};
|
||||
use crate::transport::canonical::GrokCanonicalDecoder;
|
||||
use crate::transport::config::XAI_PROVIDER_NAME;
|
||||
use crate::transport::headers::{GrokClientIdentity, build_grok_headers};
|
||||
use crate::transport::response::GrokResponseDecoder;
|
||||
use crate::transport::{
|
||||
GROK_RESPONSES_URL, GrokCredentialFailure, GrokInferenceRequest, GrokInferenceResponse,
|
||||
GrokInferenceTransport, GrokInferenceTransportError, GrokInferenceTransportErrorKind,
|
||||
@@ -77,10 +76,8 @@ use failure::*;
|
||||
use stream::*;
|
||||
|
||||
const HTTP_SSE_TRANSPORT: &str = "http_sse";
|
||||
const XAI_SESSION_STATE_MAX_BYTES: usize = 8 * 1024 * 1024;
|
||||
const XAI_SESSION_OUTPUT_LIMIT: usize = 4_096;
|
||||
const REASONING_DECODE_FAILED_CODE: &str = "reasoning_decode_failed";
|
||||
const RESPONSE_NOT_FOUND_CODE: &str = "not_found";
|
||||
const RESPONSE_NOT_FOUND_CODES: [&str; 2] = ["not-found", "not_found"];
|
||||
|
||||
/// 官方 Grok Build Provider;会话选择与 HTTP SSE transport 均由外部注入
|
||||
///
|
||||
@@ -377,7 +374,7 @@ impl GrokBuildProvider {
|
||||
));
|
||||
}
|
||||
let previous_session = decode_xai_session_state(&generate)?;
|
||||
let operation_account = continuation_account(&context, previous_session.as_ref())?;
|
||||
let operation_account = continuation_account(&context)?;
|
||||
let operation_account = merge_frozen_account_owner(&context, operation_account)?;
|
||||
validate_selected_grok_account(&selected, &context, operation_account.as_ref())?;
|
||||
let prepared = PreparedGrokAttempt {
|
||||
@@ -418,35 +415,20 @@ impl GrokBuildProvider {
|
||||
.to_owned(),
|
||||
)
|
||||
.map_err(|_| protocol_not_sent())?;
|
||||
let request_input = upstream_request.input_items();
|
||||
let instructions = upstream_request.instructions().cloned();
|
||||
if let Some(previous) = previous_session.as_ref() {
|
||||
if context.continuation().is_some()
|
||||
&& let Some(previous) = previous_session.as_ref()
|
||||
{
|
||||
upstream_request.inherit_session(previous.session_id.as_deref());
|
||||
}
|
||||
apply_continuation(
|
||||
&mut upstream_request,
|
||||
previous_session.as_ref(),
|
||||
&context,
|
||||
selected.account_id(),
|
||||
request_input.as_slice(),
|
||||
)?;
|
||||
let session_capture = (!matches!(
|
||||
context.continuation(),
|
||||
Some(ContinuationBinding::Pinned(_) | ContinuationBinding::External(_))
|
||||
) || previous_session.is_some())
|
||||
.then(|| GrokSessionCapture {
|
||||
previous: previous_session,
|
||||
request_input,
|
||||
instructions,
|
||||
response_stored: upstream_request
|
||||
.body()
|
||||
.get("store")
|
||||
.and_then(Value::as_bool)
|
||||
!= Some(false),
|
||||
apply_continuation(&mut upstream_request, &context, selected.account_id())?;
|
||||
let session_state = Some(encode_xai_session_state(XaiSessionState {
|
||||
account_id: selected.account_id().as_str().to_owned(),
|
||||
session_id: upstream_request.session_id().map(str::to_owned),
|
||||
output_items: BTreeMap::new(),
|
||||
});
|
||||
})?);
|
||||
let account_switch = account_switched(&context, &selected)
|
||||
|| previous_session
|
||||
.as_ref()
|
||||
.is_some_and(|previous| previous.account_id != selected.account_id().as_str());
|
||||
let selected = Arc::new(selected);
|
||||
let allows_account_state_mutation = selected.allows_account_state_mutation();
|
||||
let metadata =
|
||||
@@ -460,11 +442,13 @@ impl GrokBuildProvider {
|
||||
credential_recovery: Arc::clone(&self.credential_recovery),
|
||||
responses_url: self.responses_url.clone(),
|
||||
request: upstream_request,
|
||||
request_headers: crate::transport::headers::request_headers(&generate),
|
||||
account_switch,
|
||||
middleware_headers,
|
||||
upstream_model: wire_upstream_model,
|
||||
context,
|
||||
session: Arc::clone(&selected),
|
||||
session_capture,
|
||||
session_state,
|
||||
},
|
||||
);
|
||||
let stream = ProviderStream::new(metadata, events, selected);
|
||||
@@ -485,6 +469,12 @@ fn native_request_requirements(request: &GenerateRequest) -> CapabilityRequireme
|
||||
.capability_requirements()
|
||||
}
|
||||
|
||||
fn account_switched(context: &AttemptContext, selected: &SelectedGrokSession) -> bool {
|
||||
context.account_state_owner().is_some_and(|owner| {
|
||||
owner.provider().as_str() != XAI_PROVIDER_NAME || owner.account() != selected.account_id()
|
||||
})
|
||||
}
|
||||
|
||||
struct GrokSelectionFacts {
|
||||
model: UpstreamModelId,
|
||||
account: Option<ProviderAccountId>,
|
||||
@@ -497,14 +487,9 @@ fn grok_selection_facts(
|
||||
context: &AttemptContext,
|
||||
adapted: bool,
|
||||
) -> Result<GrokSelectionFacts, ProviderError> {
|
||||
let previous_session = if adapted {
|
||||
None
|
||||
} else {
|
||||
decode_xai_session_state(generate)?
|
||||
};
|
||||
let native_source = !adapted && generate.protocol_payload().protocol() == OPENAI_PROTOCOL;
|
||||
let (selection_model, operation_account, affinity) = if native_source {
|
||||
let operation_account = continuation_account(context, previous_session.as_ref())?;
|
||||
let operation_account = continuation_account(context)?;
|
||||
let request = GrokResponsesRequest::encode(
|
||||
generate,
|
||||
upstream_model.as_str(),
|
||||
@@ -523,7 +508,7 @@ fn grok_selection_facts(
|
||||
} else {
|
||||
// 源协议由转换插件拥有;这里只使用冻结的候选模型与 Core 账号 owner,
|
||||
// 不把未知 JSON 中的同名字段解释为 xAI 会话或亲和事实
|
||||
let operation_account = continuation_account(context, previous_session.as_ref())?;
|
||||
let operation_account = continuation_account(context)?;
|
||||
(
|
||||
upstream_model.as_str().to_owned(),
|
||||
merge_frozen_account_owner(context, operation_account)?,
|
||||
@@ -676,7 +661,7 @@ fn tool_support(evidence: GrokCatalogCapabilityEvidence) -> SupportLevel {
|
||||
GrokCatalogCapabilityEvidence::DeclaredNative => SupportLevel::Native,
|
||||
GrokCatalogCapabilityEvidence::DeclaredUnsupported => SupportLevel::Unsupported,
|
||||
// catalog 省略该可选字段时,Grok Build 的 Responses 工具协议仍可用;
|
||||
// 请求 adapter 会在发送前规范化仅客户端侧的工具结构
|
||||
// Chat 由直接适配器装配工具,原生工具声明交给上游校验
|
||||
GrokCatalogCapabilityEvidence::Unknown => SupportLevel::Emulated,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,11 +8,13 @@ pub(super) struct GrokStreamAttempt {
|
||||
pub(super) credential_recovery: Arc<dyn GrokCredentialRecovery>,
|
||||
pub(super) responses_url: Url,
|
||||
pub(super) request: GrokResponsesRequest,
|
||||
pub(super) request_headers: Vec<MiddlewareHeader>,
|
||||
pub(super) account_switch: bool,
|
||||
pub(super) middleware_headers: Vec<MiddlewareHeader>,
|
||||
pub(super) upstream_model: UpstreamModelId,
|
||||
pub(super) context: AttemptContext,
|
||||
pub(super) session: Arc<SelectedGrokSession>,
|
||||
pub(super) session_capture: Option<GrokSessionCapture>,
|
||||
pub(super) session_state: Option<ProviderSessionState>,
|
||||
}
|
||||
|
||||
// xAI 的首字要求真实语义输出,结构事件只记首事件时间
|
||||
@@ -28,17 +30,45 @@ fn observe_output_timings(
|
||||
let mut timings = previous;
|
||||
let elapsed_ms = u64::try_from(started_at.elapsed().as_millis()).unwrap_or(u64::MAX);
|
||||
timings.first_event_ms.get_or_insert(elapsed_ms);
|
||||
for event in events.iter().flat_map(ProviderEvent::canonical_facts) {
|
||||
match event {
|
||||
GatewayEvent::ReasoningDelta(delta) if !delta.text.is_empty() => {
|
||||
for wire in events.iter().filter_map(ProviderEvent::wire_event) {
|
||||
let value = wire.data();
|
||||
let event_type = value
|
||||
.get("type")
|
||||
.and_then(Value::as_str)
|
||||
.or(wire.event_type())
|
||||
.unwrap_or_default();
|
||||
let has_delta = value
|
||||
.get("delta")
|
||||
.and_then(Value::as_str)
|
||||
.is_some_and(|delta| !delta.is_empty());
|
||||
match event_type {
|
||||
"response.reasoning_summary_text.delta" | "response.reasoning_text.delta"
|
||||
if has_delta =>
|
||||
{
|
||||
timings.first_reasoning_ms.get_or_insert(elapsed_ms);
|
||||
timings.first_token_ms.get_or_insert(elapsed_ms);
|
||||
}
|
||||
GatewayEvent::TextDelta(delta) if !delta.text.is_empty() => {
|
||||
"response.output_text.delta" | "response.refusal.delta" if has_delta => {
|
||||
timings.first_text_ms.get_or_insert(elapsed_ms);
|
||||
timings.first_token_ms.get_or_insert(elapsed_ms);
|
||||
}
|
||||
GatewayEvent::ToolCallDelta(delta) if !delta.arguments_delta.is_empty() => {
|
||||
"response.function_call_arguments.delta" | "response.custom_tool_call_input.delta"
|
||||
if has_delta =>
|
||||
{
|
||||
timings.first_token_ms.get_or_insert(elapsed_ms);
|
||||
}
|
||||
"response.output_item.done"
|
||||
if value.get("item").is_some_and(|item| {
|
||||
matches!(
|
||||
item.get("type").and_then(Value::as_str),
|
||||
Some("function_call" | "custom_tool_call")
|
||||
) && item
|
||||
.get("arguments")
|
||||
.or_else(|| item.get("input"))
|
||||
.and_then(Value::as_str)
|
||||
.is_some_and(|args| !args.is_empty())
|
||||
}) =>
|
||||
{
|
||||
timings.first_token_ms.get_or_insert(elapsed_ms);
|
||||
}
|
||||
_ => {}
|
||||
@@ -51,26 +81,6 @@ fn observe_output_timings(
|
||||
true
|
||||
}
|
||||
|
||||
fn append_middleware_grok_headers(
|
||||
target: &mut Vec<crate::transport::GrokHeader>,
|
||||
headers: &[MiddlewareHeader],
|
||||
) -> Result<(), ProviderError> {
|
||||
let mut replaced = std::collections::HashSet::new();
|
||||
for header in headers {
|
||||
if replaced.insert(header.name().to_ascii_lowercase()) {
|
||||
target.retain(|existing| !existing.name().eq_ignore_ascii_case(header.name()));
|
||||
}
|
||||
let value = std::str::from_utf8(header.value())
|
||||
.map_err(|_| provider_error(ProviderErrorKind::Protocol, UpstreamSendState::NotSent))?;
|
||||
// 插件可写任意字段,值不进入 Debug;transport 仍读取完整原值
|
||||
target.push(crate::transport::GrokHeader::sensitive(
|
||||
header.name().to_owned(),
|
||||
crate::SecretValue::new(value),
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn cold_http_sse_stream(
|
||||
selector: Arc<dyn GrokSessionSelector>,
|
||||
transport: Arc<dyn GrokInferenceTransport>,
|
||||
@@ -82,11 +92,13 @@ pub(super) fn cold_http_sse_stream(
|
||||
credential_recovery,
|
||||
responses_url,
|
||||
request,
|
||||
request_headers,
|
||||
account_switch,
|
||||
middleware_headers,
|
||||
upstream_model,
|
||||
context,
|
||||
session,
|
||||
mut session_capture,
|
||||
mut session_state,
|
||||
} = attempt;
|
||||
Box::pin(async_stream::try_stream! {
|
||||
if context.cancellation().is_cancelled() {
|
||||
@@ -95,16 +107,15 @@ pub(super) fn cold_http_sse_stream(
|
||||
UpstreamSendState::NotSent,
|
||||
))?;
|
||||
}
|
||||
let mut headers = build_grok_headers(
|
||||
let headers = build_grok_headers(
|
||||
&wire_profile,
|
||||
&session,
|
||||
&client_identity,
|
||||
context.request_id(),
|
||||
request.session_id(),
|
||||
None,
|
||||
request.conversation_group_id(),
|
||||
&upstream_model,
|
||||
);
|
||||
append_middleware_grok_headers(&mut headers, &middleware_headers)?;
|
||||
let cancellation = context.cancellation().clone();
|
||||
let response = {
|
||||
let body = request.to_json_bytes().map_err(map_request_error)?;
|
||||
@@ -113,7 +124,8 @@ pub(super) fn cold_http_sse_stream(
|
||||
headers,
|
||||
body,
|
||||
session.binding().clone(),
|
||||
).with_trace(context.trace());
|
||||
).with_request_headers(request_headers, middleware_headers, account_switch)
|
||||
.with_trace(context.trace());
|
||||
let inference_request = super::outbound::prepare_request(
|
||||
inference_request, &context, &session, &upstream_model,
|
||||
).await?;
|
||||
@@ -167,7 +179,7 @@ pub(super) fn cold_http_sse_stream(
|
||||
yield ProviderEvent::observation(observation.clone());
|
||||
|
||||
let mut body = response.into_body();
|
||||
let mut decoder = GrokCanonicalDecoder::for_request(upstream_model.as_str(), &request)
|
||||
let mut decoder = GrokResponseDecoder::for_request(upstream_model.as_str(), &request)
|
||||
.with_pricing(context.pricing().get("xai").and_then(|p| p.get(upstream_model.as_str())).cloned());
|
||||
loop {
|
||||
if context.deadline().is_elapsed() {
|
||||
@@ -229,7 +241,7 @@ pub(super) fn cold_http_sse_stream(
|
||||
.iter()
|
||||
.flat_map(ProviderEvent::canonical_facts)
|
||||
.any(|event| matches!(event, GatewayEvent::Completed(_)));
|
||||
attach_xai_session_update(&mut events, &mut session_capture)?;
|
||||
attach_xai_session_update(&mut events, &mut session_state);
|
||||
if completed && session.allows_account_state_mutation() {
|
||||
selector.record_success(&session).await;
|
||||
}
|
||||
@@ -269,7 +281,7 @@ pub(super) fn cold_http_sse_stream(
|
||||
observation = observation.with_service_tier_if_valid(tier.to_owned());
|
||||
yield ProviderEvent::observation(observation.clone());
|
||||
}
|
||||
attach_xai_session_update(&mut final_events, &mut session_capture)?;
|
||||
attach_xai_session_update(&mut final_events, &mut session_state);
|
||||
if completed && session.allows_account_state_mutation() {
|
||||
selector.record_success(&session).await;
|
||||
}
|
||||
|
||||
@@ -2,14 +2,93 @@
|
||||
|
||||
use std::fmt;
|
||||
|
||||
use base64::{Engine as _, engine::general_purpose::STANDARD};
|
||||
use gateway_core::engine::ModelRequestId;
|
||||
use gateway_core::engine::middleware::MiddlewareHeader;
|
||||
use gateway_core::operation::GenerateRequest;
|
||||
use gateway_core::routing::UpstreamModelId;
|
||||
use gateway_protocol::http::{
|
||||
is_downstream_environment_request_header, is_transport_managed_request_header,
|
||||
};
|
||||
use serde_json::Value;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::{SecretValue, XaiWireProfileState};
|
||||
|
||||
use super::SelectedGrokSession;
|
||||
|
||||
pub(crate) fn request_headers(request: &GenerateRequest) -> Vec<MiddlewareHeader> {
|
||||
request
|
||||
.protocol_payload()
|
||||
.context()
|
||||
.get("opaque_request_headers")
|
||||
.and_then(Value::as_array)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|entry| {
|
||||
let pair = entry.as_array().filter(|pair| pair.len() == 2)?;
|
||||
let name = pair[0].as_str()?;
|
||||
let value = STANDARD.decode(pair[1].as_str()?).ok()?;
|
||||
reqwest::header::HeaderName::from_bytes(name.as_bytes()).ok()?;
|
||||
reqwest::header::HeaderValue::from_bytes(&value).ok()?;
|
||||
Some(MiddlewareHeader::new(name, value.into()))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// 只过滤客户端原始透传头,受信中间件的显式改写由调用方按合同另行合并
|
||||
pub(crate) fn managed_header(name: &str) -> bool {
|
||||
let name = name.to_ascii_lowercase();
|
||||
is_transport_managed_request_header(&name)
|
||||
|| is_downstream_environment_request_header(&name)
|
||||
// Grok 的认证、账号和画像由所选 OAuth 会话生成,业务扩展与正文不在此处理
|
||||
|| matches!(
|
||||
name.as_str(),
|
||||
"authorization"
|
||||
| "cookie"
|
||||
| "cookie2"
|
||||
| "x-api-key"
|
||||
| "x-goog-api-key"
|
||||
| "content-type"
|
||||
| "accept"
|
||||
| "user-agent"
|
||||
| "originator"
|
||||
| "version"
|
||||
| "chatgpt-account-id"
|
||||
| "chatgpt-project-id"
|
||||
| "openai-organization"
|
||||
| "openai-project"
|
||||
| "x-openai-actor-authorization"
|
||||
| "x-codex-installation-id"
|
||||
| "x-oai-attestation"
|
||||
| "x-oai-is"
|
||||
| "x-oai-is-update"
|
||||
| "x-xai-token-auth"
|
||||
| "x-authenticateresponse"
|
||||
| "x-grok-user-id"
|
||||
| "x-userid"
|
||||
| "x-email"
|
||||
| "x-grok-client-version"
|
||||
| "x-grok-client-mode"
|
||||
| "x-grok-client-identifier"
|
||||
| "x-grok-agent-id"
|
||||
| "x-grok-conv-id"
|
||||
| "x-grok-session-id"
|
||||
| "x-grok-conv-group-id"
|
||||
| "x-grok-req-id"
|
||||
| "x-grok-model-override"
|
||||
| "x-grok-experiments"
|
||||
| "idempotency-key"
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn tracing_header(name: &str) -> bool {
|
||||
matches!(
|
||||
name.to_ascii_lowercase().as_str(),
|
||||
"traceparent" | "tracestate" | "sentry-trace" | "baggage"
|
||||
)
|
||||
}
|
||||
|
||||
/// 进程级 Grok Build 客户端身份;请求级身份在构造 headers 时单独生成
|
||||
#[derive(Clone)]
|
||||
pub struct GrokClientIdentity(SecretValue);
|
||||
@@ -107,7 +186,7 @@ pub fn build_grok_headers(
|
||||
client_identity: &GrokClientIdentity,
|
||||
request_id: &ModelRequestId,
|
||||
upstream_session_id: Option<&str>,
|
||||
turn_index: Option<&str>,
|
||||
conversation_group_id: Option<&str>,
|
||||
model: &UpstreamModelId,
|
||||
) -> Vec<GrokHeader> {
|
||||
let upstream_request_id = Uuid::new_v4().hyphenated().to_string();
|
||||
@@ -147,9 +226,12 @@ pub fn build_grok_headers(
|
||||
"x-grok-session-id",
|
||||
SecretValue::new(upstream_session_id.to_owned()),
|
||||
));
|
||||
if let Some(turn_index) = turn_index {
|
||||
headers.push(GrokHeader::public("x-grok-turn-idx", turn_index));
|
||||
}
|
||||
}
|
||||
if let Some(group) = conversation_group_id {
|
||||
headers.push(GrokHeader::sensitive(
|
||||
"x-grok-conv-group-id",
|
||||
SecretValue::new(group),
|
||||
));
|
||||
}
|
||||
headers
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user