mirror of
https://github.com/zyycn/codex-proxy-rs.git
synced 2026-11-07 08:05:32 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
80f7d53085 | ||
|
|
2f2c1787be | ||
|
|
d679d5e708 | ||
|
|
0f214c3e25 | ||
|
|
736eca6593 | ||
|
|
be5b6d199e | ||
|
|
53e1e9cfb8 | ||
|
|
e03851e23f | ||
|
|
7cd17aff42 | ||
|
|
005466bcb0 | ||
|
|
a6031310f1 | ||
|
|
1ac2a4eac3 | ||
|
|
790a643020 | ||
|
|
1fa37ac92f | ||
|
|
0ceac908f4 | ||
|
|
86a27bed94 | ||
|
|
60f8f1ee80 | ||
|
|
7b6a204889 | ||
|
|
47d30474af | ||
|
|
f1d5b73255 | ||
|
|
18c75132c3 | ||
|
|
a48139b4c2 | ||
|
|
dd529d07ec | ||
|
|
19fbb5da75 | ||
|
|
9296885cce | ||
|
|
af9790ac37 | ||
|
|
c58e280739 | ||
|
|
e33f50ec09 | ||
|
|
1db8b0e319 | ||
|
|
8c8618aa0f | ||
|
|
c43a8872db | ||
|
|
51c5caed0e | ||
|
|
a7f95c3a78 | ||
|
|
421e37896a | ||
|
|
1d1ccda42a | ||
|
|
e38cf31323 | ||
|
|
614c81c375 | ||
|
|
f0484c4e11 | ||
|
|
dffc417b9f | ||
|
|
2d4294c3c9 | ||
|
|
3d9906facf | ||
|
|
da9c2b92b0 | ||
|
|
de5c10c4e4 | ||
|
|
939cb99985 | ||
|
|
2bb8ebc01c | ||
|
|
6a5300a7b5 | ||
|
|
2c5b8b5c1a | ||
|
|
0a87ac7f76 | ||
|
|
3ac9d5f6f8 | ||
|
|
e7e5b659cd | ||
|
|
b225b3732d | ||
|
|
9dca763ea4 |
@@ -20,7 +20,7 @@ description: Codex Proxy RS 开发、修复、排障、代码审查和文档修
|
||||
| 模块或调用链变更 | [Workspace 边界](../../../docs/architecture.md#3-workspace-边界)及所属模块章节,不通读整份架构 |
|
||||
| 新增、调整、清理或审查测试 | 下方[测试维护](#测试维护),按当前行为、职责归属与已有覆盖判断保留、合并或删除 |
|
||||
| 修改部署行为、`deploy/` 配置或数据库迁移 | 按范围读取[部署](../../../deploy/README.md)、[迁移](../../../backend/migrations/README.md)对应章节 |
|
||||
| 修改或审查文档 | [文档检查](references/documentation.md)及目标章节,不默认读取代码开发、页面验收或发布流程 |
|
||||
| 修改或审查文档;实现或审查用法、公开合同、职责、约束或运维操作的变化 | [文档检查](references/documentation.md)及相关章节,尚无文档差异时也检查是否漏更;纯文档任务不默认读取代码开发、页面验收或发布流程 |
|
||||
| 代码审查,包括 PR 审查 | [审查标准](../../../CONTRIBUTING.md#审查标准),叠加被审查行为所属领域的规范;审查默认只读 |
|
||||
| PR / Issue / 发版 | 按当前意图选 [PR](../cpr-github-pr/SKILL.md)、[Issue](../cpr-github-issue/SKILL.md)或[发版](../cpr-release/SKILL.md),普通提交不创建 PR |
|
||||
|
||||
@@ -36,7 +36,7 @@ description: Codex Proxy RS 开发、修复、排障、代码审查和文档修
|
||||
|
||||
1. 遵守已提供的 [AGENTS.md](../../../AGENTS.md),按其 CodeGraph 约定定位代码;确认工作区、任务范围与已有改动,找到事实归属、同类实现和调用链,补齐上表命中规范及[项目约定](../../../CONTRIBUTING.md#项目约定)对应条目后再修改
|
||||
2. 以最终差异重新匹配上表,补齐新增领域的规范并检查实际实现,再处理本次引入的职责越界、重复规则、冗余状态与无依据分支;删除或替换功能时一并清理失效的配置、类型、调用、测试与文档,已部署数据和公开合同仍遵守所属迁移及兼容规则;仅审查时报告,不自行修复
|
||||
3. 常规文档只写当前状态;有文档差异时执行[文档检查](references/documentation.md),没有时只确认现有说明是否失真,普通开发不自动修改 `release/notes.md`
|
||||
3. 按最终行为执行[文档检查](references/documentation.md),核对所属正文及相关概述、示例和引用,在本任务内完成必要同步;不以尚无文档差异跳过检查。内部重构等未改变文档所述事实时无需改文档;常规文档只写当前状态,普通开发不自动修改 `release/notes.md`
|
||||
4. 按变更范围执行[验证](../../../CONTRIBUTING.md#验证)及其停止条件,后端命令见[验证命令](../../../docs/architecture.md#验证命令);沿用本轮有效证据与用户已确定的验收分工,区分通过、失败、跳过与未执行;提交时补读[提交约定](../../../CONTRIBUTING.md#项目约定)
|
||||
5. 交付实际结果与验证缺口;前端按[前端流程](references/frontend.md)核对最终差异和运行证据,后端按上表检查生命周期,不把构建通过当作行为验收
|
||||
|
||||
|
||||
@@ -1,14 +1,22 @@
|
||||
# 文档检查
|
||||
|
||||
修改或审查文档时完整读取本流程,并读取 [文档职责与更新条件](../../../../CONTRIBUTING.md#文档职责与更新条件)的完整章节,覆盖内容归属与层次行文
|
||||
修改或审查文档,以及实现或审查涉及文档更新条件的行为变化时,完整读取本流程和 [文档职责与更新条件](../../../../CONTRIBUTING.md#文档职责与更新条件),覆盖内容归属与层次行文
|
||||
|
||||
## 核实与同步范围
|
||||
|
||||
- 以当前目标分支及任务内工作区的实现、配置和有效运行证据核实行为;提交记录用于发现待核实的主题,不能直接当作现行事实或按提交顺序组织正文。按 [CodeGraph 约定](../../../../AGENTS.md#codegraph)同步索引后定位,证据不足时报告缺口,不把计划或推测写成已支持能力
|
||||
- 开发任务按最终行为检查哪些用法、合同、职责、约束或运维操作需要同步,即使尚无 Markdown 差异也要检查;独立文档更新按用户范围核对现行说明,不等到发版时再补普通开发所需的文档
|
||||
- 沿同一事实查找所属正文及相关概述、示例和引用,重点核对“支持/不支持”等能力声明、默认值、配置模板和命令。概述保留必要摘要并链接详细合同;不能只更新详细章节,留下 README 或示例中的矛盾说明,也不扩展为无关全仓改写
|
||||
|
||||
## 写之前
|
||||
|
||||
先确定读者、必须说明的当前事实与所属章节,再决定是否需要修改及详略;文档职责与更新条件按上节核对。涉及合同或职责说明时,补读所属架构、API 或 SDK 的对应条款,核实事实;不因文档提及实现而执行无关的开发与构建流程
|
||||
|
||||
在所属章节就地替换失效说明,先组织读者现在需要的操作、结果和限制,不从变更摘要改写正文。仅介绍被替代实现、修复动机或修改经过的段落直接删除;删掉“新增”“此前”“不再”等词后仍在回答变更经过的内容,也不保留
|
||||
|
||||
## 逐段验收
|
||||
|
||||
检查工作区和暂存区中本任务的最终文档差异,按内容用途处理,不只搜索关键词:
|
||||
检查工作区和暂存区中本任务的最终文档差异,并连同受影响章节及相关概述、示例通读,按内容用途处理,不只搜索关键词:
|
||||
|
||||
| 段落回答的问题 | 处理 |
|
||||
| --- | --- |
|
||||
@@ -26,6 +34,6 @@
|
||||
|
||||
- 完成上述逐段验收及[行文检查](../../../../CONTRIBUTING.md#层次与行文),发现问题先处理,未完成内容审查不能称文档已检查
|
||||
- 检查相对链接、章节锚点、表格与命令示例,`git diff --check` 或构建通过不能代替内容审查
|
||||
- 报告实际覆盖和缺口即可,不把检查记录写进常规文档
|
||||
- 交付时简述已同步的文档范围;涉及更新条件却未改文档时,说明现有内容为何仍准确或还有什么缺口。仅报告实际核对范围,不把链接检查通过称为事实核实,也不把检查记录写进常规文档
|
||||
|
||||
只有明确的发布说明任务才进入 `cpr-release`;发布说明与常规文档的边界按[内容归属](../../../../CONTRIBUTING.md#内容归属)执行
|
||||
|
||||
@@ -108,7 +108,7 @@ jobs:
|
||||
components: rustfmt,clippy
|
||||
|
||||
- name: Cache Rust
|
||||
uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2
|
||||
uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
|
||||
with:
|
||||
workspaces: backend -> target
|
||||
save-if: ${{ github.event_name == 'push' && github.ref == 'refs/heads/main' }}
|
||||
@@ -122,7 +122,7 @@ jobs:
|
||||
run: cargo clippy --all-targets --all-features --locked -- -D warnings
|
||||
|
||||
- name: Setup nextest
|
||||
uses: taiki-e/install-action@8cca0918f8471c33515202b73f56ab27f2bed283 # v2.87.29
|
||||
uses: taiki-e/install-action@1e29709c0ec63babbe8f266397a465f29a825f91 # v2.87.31
|
||||
with:
|
||||
tool: cargo-nextest@0.9.143
|
||||
fallback: none
|
||||
|
||||
@@ -29,7 +29,6 @@ jobs:
|
||||
backend: ${{ steps.filter.outputs.backend }}
|
||||
frontend: ${{ steps.filter.outputs.frontend }}
|
||||
container: ${{ steps.filter.outputs.container }}
|
||||
source: ${{ steps.filter.outputs.source }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
@@ -41,7 +40,7 @@ jobs:
|
||||
id: filter
|
||||
uses: dorny/paths-filter@ceb8a2b8f2d89434be7ff52d3de7ec3738c5cc9d # v4.0.3
|
||||
with:
|
||||
# 目录规则取并集,再统一排除说明文档,保留隐藏配置与子模块指针
|
||||
# 目录规则取并集,再统一排除说明文档,保留隐藏配置
|
||||
predicate-quantifier: some-with-excludes
|
||||
filters: |
|
||||
backend:
|
||||
@@ -61,17 +60,6 @@ jobs:
|
||||
- '.github/workflows/ci.yml'
|
||||
- '.github/workflows/_quality.yml'
|
||||
- '!**/*.md'
|
||||
source:
|
||||
- '.github/scripts/toolchains.rb'
|
||||
- 'backend/rust-toolchain.toml'
|
||||
- 'deploy/Dockerfile'
|
||||
- '.gitmodules'
|
||||
- 'modules/ui'
|
||||
- 'modules/plugins'
|
||||
- 'frontend/**'
|
||||
- 'backend/crates/gateway-plugin/sdk/**'
|
||||
- '.github/workflows/ci.yml'
|
||||
- '!**/*.md'
|
||||
container:
|
||||
- 'backend/**'
|
||||
- 'frontend/**'
|
||||
@@ -101,56 +89,3 @@ jobs:
|
||||
uses: ./.github/workflows/_container.yml
|
||||
with:
|
||||
ref: ${{ github.event.pull_request.head.sha || github.sha }}
|
||||
|
||||
source-development:
|
||||
needs: changes
|
||||
if: needs.changes.outputs.source == 'true'
|
||||
runs-on: ubuntu-26.04
|
||||
timeout-minutes: 20
|
||||
steps:
|
||||
- name: Checkout with development modules
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
ref: ${{ github.event.pull_request.head.sha || github.sha }}
|
||||
submodules: recursive
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0
|
||||
with:
|
||||
package_json_file: frontend/package.json
|
||||
- name: Read build toolchains
|
||||
id: toolchains
|
||||
run: ruby .github/scripts/toolchains.rb >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
|
||||
with:
|
||||
node-version: ${{ steps.toolchains.outputs.node }}
|
||||
- name: Setup Rust
|
||||
uses: dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8 # master
|
||||
with:
|
||||
toolchain: ${{ steps.toolchains.outputs.rust }}
|
||||
- name: Install development dependencies
|
||||
run: |
|
||||
pnpm --dir modules/ui install --frozen-lockfile
|
||||
pnpm --dir frontend install --frozen-lockfile
|
||||
pnpm --dir modules/plugins/examples/workbench/frontend install --frozen-lockfile
|
||||
- name: Check UI source integration
|
||||
run: |
|
||||
pnpm --dir frontend build:source
|
||||
pnpm --dir modules/plugins/examples/workbench/frontend build:source
|
||||
- name: Check local SDK integration
|
||||
env:
|
||||
RUST_MIN_STACK: 16777216
|
||||
CARGO_TARGET_DIR: ${{ github.workspace }}/backend/target/plugin-development
|
||||
run: |
|
||||
sdk_check_dir="$RUNNER_TEMP/plugin-source"
|
||||
mkdir -p "$sdk_check_dir/backend"
|
||||
cp modules/plugins/examples/workbench/backend/Cargo.{toml,lock} "$sdk_check_dir/backend/"
|
||||
cp -R modules/plugins/examples/workbench/backend/{src,tests} "$sdk_check_dir/backend/"
|
||||
cp modules/plugins/examples/workbench/plugin.json "$sdk_check_dir/"
|
||||
cargo test --manifest-path "$sdk_check_dir/backend/Cargo.toml" \
|
||||
--config "patch.\"https://github.com/zyycn/codex-proxy-rs.git\".gateway-plugin-sdk.path=\"$GITHUB_WORKSPACE/backend/crates/gateway-plugin/sdk\""
|
||||
- name: Ensure source checks preserve lockfiles
|
||||
run: |
|
||||
git diff --exit-code -- frontend/package.json frontend/pnpm-lock.yaml backend/Cargo.lock
|
||||
git -C modules/plugins diff --exit-code -- examples/workbench/frontend/package.json examples/workbench/frontend/pnpm-lock.yaml examples/workbench/backend/Cargo.lock
|
||||
|
||||
@@ -312,7 +312,7 @@ jobs:
|
||||
uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1
|
||||
|
||||
- name: Login to GHCR
|
||||
uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4.6.0
|
||||
uses: docker/login-action@81c6f93d4bc991e510b342a00b419b3bb4efc5c6 # v4.7.0
|
||||
with:
|
||||
registry: ${{ env.REGISTRY }}
|
||||
username: ${{ github.actor }}
|
||||
@@ -409,7 +409,7 @@ jobs:
|
||||
uses: sigstore/cosign-installer@6f9f17788090df1f26f669e9d70d6ae9567deba6 # v4.1.2
|
||||
|
||||
- name: Login to GHCR
|
||||
uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4.6.0
|
||||
uses: docker/login-action@81c6f93d4bc991e510b342a00b419b3bb4efc5c6 # v4.7.0
|
||||
with:
|
||||
registry: ${{ env.REGISTRY }}
|
||||
username: ${{ github.actor }}
|
||||
|
||||
@@ -28,7 +28,7 @@ jobs:
|
||||
ref: ${{ github.event.pull_request.head.sha || github.sha }}
|
||||
|
||||
- name: Install cargo-audit
|
||||
uses: taiki-e/install-action@8cca0918f8471c33515202b73f56ab27f2bed283 # v2.87.29
|
||||
uses: taiki-e/install-action@1e29709c0ec63babbe8f266397a465f29a825f91 # v2.87.31
|
||||
with:
|
||||
tool: cargo-audit@0.22.2
|
||||
fallback: none
|
||||
|
||||
@@ -34,6 +34,7 @@ Thumbs.db
|
||||
|
||||
# Local tools and worktrees
|
||||
/.codegraph/
|
||||
/.playwright-cli/
|
||||
/.codex-ws-audit/
|
||||
/.reasonix/
|
||||
/.claude
|
||||
|
||||
@@ -28,6 +28,7 @@ Issue 和 PR 回复统一按 [GitHub 回复口吻](CONTRIBUTING.md#github-回复
|
||||
|
||||
In repositories indexed by CodeGraph (a `.codegraph/` directory exists at the repo root), reach for it BEFORE grep/find or reading files when you need to understand or locate code:
|
||||
|
||||
- **Index freshness**: Run `codegraph sync` from the repository root before the first code query in a task. After pulling updates, switching branches, or changing code, run it again before the next query so symbols and call paths match the working tree. If synchronization fails, report the failure and verify against current source rather than treating the index as current.
|
||||
- **MCP tools** (when available): `codegraph_explore` answers most code questions in one call — the relevant symbols' verbatim source plus the call paths between them. `codegraph_node` returns one symbol's source + callers, or reads a whole file with line numbers. If the tools are listed but deferred, load them by name via tool search.
|
||||
- **Shell** (always works): `codegraph explore "<symbol names or question>"` and `codegraph node <symbol-or-file>` print the same output.
|
||||
|
||||
|
||||
+1
-1
@@ -228,7 +228,7 @@ git diff --check
|
||||
|
||||
## 自动检查与合并条件
|
||||
|
||||
[CI](.github/workflows/ci.yml) 按变更范围调用质量检查,Markdown 不触发后端、前端、容器和源码联调任务,工作流语法检查独立执行
|
||||
[CI](.github/workflows/ci.yml) 按变更范围调用质量检查,Markdown 不触发后端、前端和容器任务,工作流语法检查独立执行
|
||||
|
||||
后端 CI 使用 nextest 执行 `main` 集成测试,默认 Redis 密码模式执行完整测试集,ACL 用户模式复用同一批构建产物执行 Store 的 Redis 测试;本地验证命令见 [架构文档](docs/architecture.md#验证命令)
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
</div>
|
||||
|
||||
> [!NOTE]
|
||||
> 本项目提供 Responses API,不支持 `/v1/chat/completions`,接入前请确认客户端支持 Responses 协议
|
||||
> 本项目提供 Responses API 和 Chat Completions API;Chat Completions 请求通过 Responses 链路执行,支持范围见 [API 参考](docs/api.md#chat-completions-请求)
|
||||
|
||||
## 快速预览
|
||||
|
||||
@@ -97,7 +97,7 @@ API Key 持有者可在登录页切换身份,查看自己的用量与额度,
|
||||
|
||||
完整步骤、生图配置与排障见[客户端配置](deploy/README.md#客户端配置)
|
||||
|
||||
**其他 Responses API 客户端**:填写以下信息:
|
||||
**其他 Responses / Chat Completions API 客户端**:填写以下信息:
|
||||
|
||||
| 配置 | 值 |
|
||||
| --- | --- |
|
||||
|
||||
Generated
+96
-106
@@ -147,9 +147,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "async-compression"
|
||||
version = "0.4.50"
|
||||
version = "0.4.51"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ee19bd99b43e3691acbad4e840420a4881cea6c0b66a208125a824f8fd53f5a1"
|
||||
checksum = "9d5755640120b24961f8231e05892e4a4f7e0d04e8aeca161508c9c397946970"
|
||||
dependencies = [
|
||||
"compression-codecs",
|
||||
"compression-core",
|
||||
@@ -224,9 +224,9 @@ checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
|
||||
|
||||
[[package]]
|
||||
name = "aws-credential-types"
|
||||
version = "1.3.0"
|
||||
version = "1.3.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e93964ffdaf57857f544be3666a5f57570bb699e934700f11b49708f61bb556e"
|
||||
checksum = "576e8da35751dc85409ec1cd15999f692c277a1fbe9336780fe6f15e49dd637d"
|
||||
dependencies = [
|
||||
"aws-smithy-async",
|
||||
"aws-smithy-runtime-api",
|
||||
@@ -260,9 +260,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "aws-runtime"
|
||||
version = "1.10.0"
|
||||
version = "1.10.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2b8a9911551b4ea6ca13805ef52ed96f7d2bbb43cc3b4a14cb0776a71f33cfaa"
|
||||
checksum = "9a0cc2144962cc5e358467b16e3d82981b1d424a7c3d34602be0036103814a1a"
|
||||
dependencies = [
|
||||
"aws-credential-types",
|
||||
"aws-sigv4",
|
||||
@@ -286,9 +286,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "aws-sdk-s3"
|
||||
version = "1.152.0"
|
||||
version = "1.155.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "004d5acbd6850ab58789a43822e0a2ef23927a46b012c17f8fa51253103db9f8"
|
||||
checksum = "5a542f0e9261b9ce56708d591a62062079fa3c58a362ffbf49a2e48a4f6ced16"
|
||||
dependencies = [
|
||||
"arc-swap",
|
||||
"aws-credential-types",
|
||||
@@ -322,9 +322,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "aws-sigv4"
|
||||
version = "1.6.0"
|
||||
version = "1.6.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2312577f088c9fbf4206dfdb884cf1de9407b43e1a923cbed5237775116fc24b"
|
||||
checksum = "9d3d48355cb86b15ccbb38b8bc6b87500c824ee4ed8cbc10a961b435242b5e16"
|
||||
dependencies = [
|
||||
"aws-credential-types",
|
||||
"aws-smithy-eventstream",
|
||||
@@ -344,9 +344,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "aws-smithy-async"
|
||||
version = "1.3.0"
|
||||
version = "1.3.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f02e407fb3b54891734224b9ffac8a71fdd35f542500fa1af95754a6b2beb316"
|
||||
checksum = "de681a9df7ff79823b759ee17061076ec049cd61a8fa28ece4293d89c9f6964e"
|
||||
dependencies = [
|
||||
"futures-util",
|
||||
"pin-project-lite",
|
||||
@@ -376,9 +376,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "aws-smithy-eventstream"
|
||||
version = "0.61.4"
|
||||
version = "0.61.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "80c2051c2f1016fb8e6548dd07b8bc2ac9c3fe583721444b92f515e856d31609"
|
||||
checksum = "14c8a643d0e114cae39e45415e3225793a6396698b7779a0c9e3ede731d8fc71"
|
||||
dependencies = [
|
||||
"aws-smithy-types",
|
||||
"bytes",
|
||||
@@ -387,9 +387,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "aws-smithy-http"
|
||||
version = "0.64.1"
|
||||
version = "0.64.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "639b4d8f8555f24a9be649811c3eb0b4d4616f4d61daf0c32e28873bc1ea9af1"
|
||||
checksum = "ba8960956e0ee0ca3f3161e62913a61bc65a7ef638ca3ef1d4c7159f8443e398"
|
||||
dependencies = [
|
||||
"aws-smithy-eventstream",
|
||||
"aws-smithy-runtime-api",
|
||||
@@ -403,15 +403,14 @@ dependencies = [
|
||||
"http-body-util",
|
||||
"percent-encoding",
|
||||
"pin-project-lite",
|
||||
"pin-utils",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "aws-smithy-http-client"
|
||||
version = "1.5.0"
|
||||
version = "1.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "51c89cc3f1f281d659a67a519a1b5c6d445b5ce09fa7e5aee40c2c2707e9509d"
|
||||
checksum = "aeca69f65362f7375891008ea525fd440ad6db1836458ac188c87b126804114e"
|
||||
dependencies = [
|
||||
"aws-smithy-async",
|
||||
"aws-smithy-runtime-api",
|
||||
@@ -433,9 +432,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "aws-smithy-json"
|
||||
version = "0.63.1"
|
||||
version = "0.65.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3385d469edbe8b60cc72002784652b5efca39178192aa9cc4b44c9875c6bdc18"
|
||||
checksum = "9f6835fb38bc6fc8c91e584b0366eb4ff595e5c485134dbf4f0bdeaa18856666"
|
||||
dependencies = [
|
||||
"aws-smithy-runtime-api",
|
||||
"aws-smithy-schema",
|
||||
@@ -453,9 +452,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "aws-smithy-runtime"
|
||||
version = "1.16.0"
|
||||
version = "1.16.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d6e302ac1d88b99652489df31abdec6ac42a2ab2ac3982ad0ac49f64dfaf28ba"
|
||||
checksum = "79cef0c41e8ca40f74f68ed8ee4d1ddbde12bb847b95ef9b3c025681ddfae58a"
|
||||
dependencies = [
|
||||
"aws-smithy-async",
|
||||
"aws-smithy-http",
|
||||
@@ -470,16 +469,15 @@ dependencies = [
|
||||
"http-body",
|
||||
"http-body-util",
|
||||
"pin-project-lite",
|
||||
"pin-utils",
|
||||
"tokio",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "aws-smithy-runtime-api"
|
||||
version = "1.19.0"
|
||||
version = "1.19.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c0730c16f91124c6a2abb4932c77e299288b3dd9f967ea2e9ec48cc6731e87a4"
|
||||
checksum = "06788004dea79018413f381891da6dcca23196acd79c4d51b767fbdacc76eae4"
|
||||
dependencies = [
|
||||
"aws-smithy-async",
|
||||
"aws-smithy-runtime-api-macros",
|
||||
@@ -505,9 +503,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "aws-smithy-schema"
|
||||
version = "0.2.1"
|
||||
version = "1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e8f395d93304280b64b7632fea798d177e74897fe7f063416ce627cd6fa24829"
|
||||
checksum = "bec8dae1015a6d959a5faf86fbdf77486cfe19e4ccb6ee009d8a46efc45028a4"
|
||||
dependencies = [
|
||||
"aws-smithy-runtime-api",
|
||||
"aws-smithy-types",
|
||||
@@ -516,9 +514,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "aws-smithy-types"
|
||||
version = "1.8.1"
|
||||
version = "1.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "69bb407740a197147da48238ecc94498493c9e85445732360cec180296ca45f1"
|
||||
checksum = "55752025c39c0e094962fd73f1c57014b191f678612e517f219468e575af9822"
|
||||
dependencies = [
|
||||
"base64-simd",
|
||||
"bytes",
|
||||
@@ -530,7 +528,6 @@ dependencies = [
|
||||
"itoa",
|
||||
"num-integer",
|
||||
"pin-project-lite",
|
||||
"pin-utils",
|
||||
"ryu",
|
||||
"serde",
|
||||
"time",
|
||||
@@ -540,9 +537,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "aws-smithy-xml"
|
||||
version = "0.62.1"
|
||||
version = "0.64.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0b932c8d6dc127fc980eecd78f8694ae9b9551b69a93a7def2a199c1c0033daf"
|
||||
checksum = "a6581618a2fd006159016d1c36881d94d61b4a017f4a8d631310875e18252413"
|
||||
dependencies = [
|
||||
"aws-smithy-runtime-api",
|
||||
"aws-smithy-schema",
|
||||
@@ -552,9 +549,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "aws-types"
|
||||
version = "1.6.0"
|
||||
version = "1.7.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "209f3a6d82a6e9e5f94abbed94c7a26e1c052341002bf57a5fb5481f625896fc"
|
||||
checksum = "6ba0d970d3947bb064d2ae1d823efa186c1dbde88f88afa8f6549946e5d8deee"
|
||||
dependencies = [
|
||||
"aws-credential-types",
|
||||
"aws-smithy-async",
|
||||
@@ -945,9 +942,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "compression-codecs"
|
||||
version = "0.4.45"
|
||||
version = "0.4.46"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "98fc98460ba0ad5317075d3632b8dfc45d0be8c4a49347c2a38272019717614a"
|
||||
checksum = "cae36683101b2899f48bd31f8db9839437356188e3b1ff23096e73dab09ba8fe"
|
||||
dependencies = [
|
||||
"compression-core",
|
||||
"flate2",
|
||||
@@ -956,9 +953,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "compression-core"
|
||||
version = "0.4.33"
|
||||
version = "0.4.34"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6e8ccc4ea9f6acc32d102c0f6d471d11d913ad15f20c04de743374861fa1d414"
|
||||
checksum = "2ebdda89edc534bf8d5dd2857562633b6495557e5846552ade994b99ed13c36a"
|
||||
|
||||
[[package]]
|
||||
name = "config"
|
||||
@@ -1084,9 +1081,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "crc32fast"
|
||||
version = "1.5.2"
|
||||
version = "1.5.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "01a7799fd6b852db0e61728dde9a204c423b44d689dbd432522543614b490e78"
|
||||
checksum = "0ba106e844045ddc02c20768ac4b0b7cb45f2cc2ecbd833ac9f5dacb183c2055"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
]
|
||||
@@ -1166,14 +1163,14 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cssparser"
|
||||
version = "0.37.0"
|
||||
version = "0.38.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8c9cdaae01d5ed7882b04d795e7f752f46ff52d2fa3b50a20d28c464510bba98"
|
||||
checksum = "11119743ad110e8c1bdccd930d7f5c30c99e5fc76a7b63ec9807e84eef0c5f59"
|
||||
dependencies = [
|
||||
"cssparser-macros",
|
||||
"dtoa-short",
|
||||
"itoa",
|
||||
"phf 0.13.1",
|
||||
"phf 0.14.0",
|
||||
"smallvec",
|
||||
]
|
||||
|
||||
@@ -2125,12 +2122,13 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "html5ever"
|
||||
version = "0.39.0"
|
||||
version = "0.40.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "46a1761807faccc9a19e86944bbf40610014066306f96edcdedc2fb714bcb7b8"
|
||||
checksum = "456a1a377e608e555d22ddab27ac0114bc7a7b4199078108e34c2aeae6c9b130"
|
||||
dependencies = [
|
||||
"log",
|
||||
"markup5ever",
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2483,9 +2481,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "jsonschema"
|
||||
version = "0.58.6"
|
||||
version = "0.60.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f622c574a29fb3034a0a90645afee194dfedc75fc124228801b6e77041075bd1"
|
||||
checksum = "7e7305938cac5ee144352ceb71583ffc6cfeac7d20fcb20ef865a4d5c314e499"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"bytecount",
|
||||
@@ -2511,23 +2509,24 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "jsonschema-regex"
|
||||
version = "0.58.6"
|
||||
version = "0.60.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a968fffd387b2ab005bf00c1851f5d26e90df05b6f7ad609ed0d620033cca5e7"
|
||||
checksum = "6f8a848331614144c03e815fb931f238c9e342bd7ab501b29e35d647e7cd5688"
|
||||
dependencies = [
|
||||
"regex-syntax",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "jsonschema-value"
|
||||
version = "0.58.6"
|
||||
version = "0.60.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "39b7670345e5ce87371339d13705dbb9276b7e3e934bbe1efa2c6734a1f65a96"
|
||||
checksum = "5a5a947ef798eeacacb43edf29b1d0ab64bdf5e2c9fbcaad10ee8663d922b544"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"bytecount",
|
||||
"fraction",
|
||||
"getrandom 0.3.4",
|
||||
"memchr",
|
||||
"num-cmp",
|
||||
"num-traits",
|
||||
"serde_json",
|
||||
@@ -2642,9 +2641,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "markup5ever"
|
||||
version = "0.39.0"
|
||||
version = "0.40.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7122d987ec5f704ee56f6e5b41a7d93722e9aae27ae07cafa4036c4d3f9757de"
|
||||
checksum = "0ab3dc68ac4a0f5719e560136778c1ee716e296030d75dbd4484e37e39e3a842"
|
||||
dependencies = [
|
||||
"log",
|
||||
"tendril",
|
||||
@@ -3101,23 +3100,23 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "phf"
|
||||
version = "0.13.1"
|
||||
version = "0.14.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf"
|
||||
checksum = "010378780309880b08997fae13be7834dba947d36393bd372f2b1556deb2a2f6"
|
||||
dependencies = [
|
||||
"phf_macros 0.13.1",
|
||||
"phf_shared 0.13.1",
|
||||
"phf_macros 0.14.0",
|
||||
"phf_shared 0.14.0",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "phf_codegen"
|
||||
version = "0.13.1"
|
||||
version = "0.14.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "49aa7f9d80421bca176ca8dbfebe668cc7a2684708594ec9f3c0db0805d5d6e1"
|
||||
checksum = "41b585a510fb76fdebead6897982ef2a03a21d8e6cbcca904999742a4afc6ffe"
|
||||
dependencies = [
|
||||
"phf_generator 0.13.1",
|
||||
"phf_shared 0.13.1",
|
||||
"phf_generator 0.14.0",
|
||||
"phf_shared 0.14.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3132,12 +3131,12 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "phf_generator"
|
||||
version = "0.13.1"
|
||||
version = "0.14.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "135ace3a761e564ec88c03a77317a7c6b80bb7f7135ef2544dbe054243b89737"
|
||||
checksum = "aeb62e0959d5a1bebc965f4d15d9e2b7cea002b6b0f5ba8cde6cc26738467100"
|
||||
dependencies = [
|
||||
"fastrand",
|
||||
"phf_shared 0.13.1",
|
||||
"phf_shared 0.14.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3155,12 +3154,12 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "phf_macros"
|
||||
version = "0.13.1"
|
||||
version = "0.14.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "812f032b54b1e759ccd5f8b6677695d5268c588701effba24601f6932f8269ef"
|
||||
checksum = "5fa8d0ca26d424d27630da600c6624696e7dec8bf7b3b492b383c5dc49e5e085"
|
||||
dependencies = [
|
||||
"phf_generator 0.13.1",
|
||||
"phf_shared 0.13.1",
|
||||
"phf_generator 0.14.0",
|
||||
"phf_shared 0.14.0",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
@@ -3186,9 +3185,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "phf_shared"
|
||||
version = "0.13.1"
|
||||
version = "0.14.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e57fef6bc5981e38c2ce2d63bfa546861309f875b8a75f092d1d54ae2d64f266"
|
||||
checksum = "c6fd9027e2d9319be6349febd1db4e8d02aa544921200c9b777720ac34a3aa89"
|
||||
dependencies = [
|
||||
"siphasher",
|
||||
]
|
||||
@@ -3199,12 +3198,6 @@ version = "0.2.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
|
||||
|
||||
[[package]]
|
||||
name = "pin-utils"
|
||||
version = "0.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184"
|
||||
|
||||
[[package]]
|
||||
name = "pkcs8"
|
||||
version = "0.11.0"
|
||||
@@ -3636,9 +3629,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "referencing"
|
||||
version = "0.58.6"
|
||||
version = "0.60.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "558f3855529c0a7e78a48e409fa653456e55f1b167eab4109c16a255b7727e3f"
|
||||
checksum = "922268812b6f9e20b4ab0f1efe8e07036958eed7346ceddb31c777b5531fd11f"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"fluent-uri",
|
||||
@@ -3875,9 +3868,9 @@ checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
|
||||
|
||||
[[package]]
|
||||
name = "scraper"
|
||||
version = "0.27.0"
|
||||
version = "0.29.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bdd0be4d296f048bfb06dd01bbc80ef789ddd2e55583e8d2e6b804942abfabc2"
|
||||
checksum = "6844b5f49a5579f12ba4f89d9f7eec6d71889e4aa0bc7181821040ce66f08fff"
|
||||
dependencies = [
|
||||
"cssparser",
|
||||
"ego-tree",
|
||||
@@ -3885,7 +3878,6 @@ dependencies = [
|
||||
"html5ever",
|
||||
"precomputed-hash",
|
||||
"selectors",
|
||||
"tendril",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3950,17 +3942,15 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "selectors"
|
||||
version = "0.38.0"
|
||||
version = "0.41.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8adfa1c298912827b8a28b223b3b874357397ae706e6190acd9bf28cee99114d"
|
||||
checksum = "8322aebea94a6cc288ff884e8a49bdbceef60206c400c6c46d22e62fc4fd91a6"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"cssparser",
|
||||
"derive_more",
|
||||
"log",
|
||||
"new_debug_unreachable",
|
||||
"phf 0.13.1",
|
||||
"phf_codegen",
|
||||
"precomputed-hash",
|
||||
"rustc-hash",
|
||||
"servo_arc",
|
||||
@@ -4067,9 +4057,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "servo_arc"
|
||||
version = "0.4.3"
|
||||
version = "0.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "170fb83ab34de17dc69aa7c67482b22218ddb85da56546f9bd6b929e32a05930"
|
||||
checksum = "b4eceb519ec34d8290aaf6e46f435102f2bfa63f22b05a144fb16ab266d3b198"
|
||||
dependencies = [
|
||||
"stable_deref_trait",
|
||||
]
|
||||
@@ -4401,24 +4391,24 @@ checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"
|
||||
|
||||
[[package]]
|
||||
name = "string_cache"
|
||||
version = "0.9.0"
|
||||
version = "0.11.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a18596f8c785a729f2819c0f6a7eae6ebeebdfffbfe4214ae6b087f690e31901"
|
||||
checksum = "ffa8a5dbe8b3f0bbe29d4c3225daafaeead63afdc1b65fc4c01a1384166038e6"
|
||||
dependencies = [
|
||||
"new_debug_unreachable",
|
||||
"parking_lot",
|
||||
"phf_shared 0.13.1",
|
||||
"phf_shared 0.14.0",
|
||||
"precomputed-hash",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "string_cache_codegen"
|
||||
version = "0.6.1"
|
||||
version = "0.11.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "585635e46db231059f76c5849798146164652513eb9e8ab2685939dd90f29b69"
|
||||
checksum = "928dcdf75e47626b3617a976ec205d9f057584c371c1f23b782129268d0e6edc"
|
||||
dependencies = [
|
||||
"phf_generator 0.13.1",
|
||||
"phf_shared 0.13.1",
|
||||
"phf_generator 0.14.0",
|
||||
"phf_shared 0.14.0",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
]
|
||||
@@ -5214,11 +5204,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "web_atoms"
|
||||
version = "0.2.6"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ba8b815c1b593dc0baf78dd0f4fc8fdb2de53198fb1163738093e9a311c33fb3"
|
||||
checksum = "7572660c8890448ba236b7376f27e389c6a7e1c70195622faced601f855c0ada"
|
||||
dependencies = [
|
||||
"phf 0.13.1",
|
||||
"phf 0.14.0",
|
||||
"phf_codegen",
|
||||
"string_cache",
|
||||
"string_cache_codegen",
|
||||
@@ -5651,9 +5641,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "zip"
|
||||
version = "9.0.4"
|
||||
version = "9.0.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a954114b47a54df49f83d2722814e86b23d4bb1b54a1b90fb7d92b41619ddc22"
|
||||
checksum = "6e04976da629d3b04204ba8105b396a193af8ad2583b2c79bfb3ab8af580a11e"
|
||||
dependencies = [
|
||||
"crc32fast",
|
||||
"flate2",
|
||||
@@ -5677,27 +5667,27 @@ checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
|
||||
|
||||
[[package]]
|
||||
name = "zstd"
|
||||
version = "0.13.3"
|
||||
version = "0.14.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e91ee311a569c327171651566e07972200e76fcfe2242a4fa446149a3881c08a"
|
||||
checksum = "db3ae9bf90af6e40197bef767eeefc46ad6397420fe873830bd85e5fbbfb3c70"
|
||||
dependencies = [
|
||||
"zstd-safe",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zstd-safe"
|
||||
version = "7.2.4"
|
||||
version = "8.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8f49c4d5f0abb602a93fb8736af2a4f4dd9512e36f7f570d66e65ff867ed3b9d"
|
||||
checksum = "ded520f16b29e1a9b771c722221b2b0a0398c2316d9bb3c42b458a5414d7434b"
|
||||
dependencies = [
|
||||
"zstd-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zstd-sys"
|
||||
version = "2.0.16+zstd.1.5.7"
|
||||
version = "2.1.2+zstd.1.5.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "91e19ebc2adc8f83e43039e79776e3fda8ca919132d68a1fed6a5faca2683748"
|
||||
checksum = "481ada9c543b2323cbb7bbdbb5249177fbf0188ed959ed2c15e4b22421c84ed3"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"pkg-config",
|
||||
|
||||
@@ -103,6 +103,10 @@ async fn execute(
|
||||
let management = ManagementPorts::new(&store, providers.admin.clone(), core.snapshot_control());
|
||||
or_shutdown!(plugin_runtime, management.bind(&plugin_runtime));
|
||||
let core = or_shutdown!(plugin_runtime, core.activate().await);
|
||||
or_shutdown!(
|
||||
plugin_runtime,
|
||||
plugin_runtime.bind_client_identity_port(&core.client_identity_port())
|
||||
);
|
||||
let nested_models = core.nested_model_execution_port();
|
||||
let affinity_lookup = core.affinity_lookup_port();
|
||||
or_shutdown!(
|
||||
|
||||
@@ -38,6 +38,10 @@ pub async fn run() -> Result<(), BootstrapError> {
|
||||
let management = ManagementPorts::new(&store, providers.admin.clone(), core.snapshot_control());
|
||||
or_shutdown!(plugin_runtime, management.bind(&plugin_runtime));
|
||||
let mut core = or_shutdown!(plugin_runtime, core.activate().await);
|
||||
or_shutdown!(
|
||||
plugin_runtime,
|
||||
plugin_runtime.bind_client_identity_port(&core.client_identity_port())
|
||||
);
|
||||
let nested_models = core.nested_model_execution_port();
|
||||
let affinity_lookup = core.affinity_lookup_port();
|
||||
or_shutdown!(
|
||||
|
||||
@@ -370,10 +370,28 @@ fn config_loader_should_reject_zero_server_port() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn config_loader_should_validate_openai_residency() {
|
||||
fn config_loader_should_accept_optional_openai_routing_strings() {
|
||||
for value in [
|
||||
serde_json::Value::Null,
|
||||
serde_json::json!("us"),
|
||||
serde_json::json!("custom-value"),
|
||||
serde_json::json!(""),
|
||||
] {
|
||||
let mut document = valid_config_document();
|
||||
document["openai"]["residency"] = value.clone();
|
||||
document["openai"]["account_routing_override"] = value;
|
||||
parse_config(&document.to_string()).expect("optional routing strings");
|
||||
}
|
||||
let mut document = valid_config_document();
|
||||
document["openai"]["residency"] = serde_json::json!("invalid");
|
||||
assert_rejected(document.to_string());
|
||||
document["openai"]
|
||||
.as_object_mut()
|
||||
.unwrap()
|
||||
.remove("residency");
|
||||
document["openai"]
|
||||
.as_object_mut()
|
||||
.unwrap()
|
||||
.remove("account_routing_override");
|
||||
parse_config(&document.to_string()).expect("omitted routing strings");
|
||||
}
|
||||
|
||||
fn assert_rejected(config: String) {
|
||||
|
||||
@@ -1,9 +1,4 @@
|
||||
//! 容量熔断冻结的恢复编排:到期探测、失败顺延与自适应并发下调
|
||||
//!
|
||||
//! 冻结事实保存在可丢失的 Redis 冷却中,本服务只组合 Admin 端口:
|
||||
//! 观测(`AccountRuntimeStore`)、探测(`AccountsService`)与写回
|
||||
//! (原子降低并发 / 按冻结代次结束探测)
|
||||
//! 旧观测不会覆盖管理员操作
|
||||
//! 账号错误保护的到期探测与按冻结快照恢复
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::Arc;
|
||||
@@ -11,7 +6,7 @@ use std::time::{Duration, SystemTime};
|
||||
|
||||
use chrono::{DateTime, Utc};
|
||||
use futures::StreamExt as _;
|
||||
use gateway_core::account::{AccountConcurrencyLimit, ProviderAccountId};
|
||||
use gateway_core::account::{AccountErrorProtection, ProviderAccountId};
|
||||
use gateway_core::routing::UpstreamModelId;
|
||||
use gateway_core::task::{ScheduledTask, WorkerCycleContext, WorkerTaskError};
|
||||
use tracing::warn;
|
||||
@@ -19,14 +14,9 @@ use tracing::warn;
|
||||
use crate::model::accounts::{
|
||||
AccountConnectionTestEvent, AccountFreeze, AccountPageItem, AccountRuntimeSnapshot,
|
||||
};
|
||||
use crate::model::{MutationActor, MutationContext};
|
||||
use crate::ports::store::{AccountRuntimeStore, AccountStore, SettingsStore};
|
||||
use crate::use_case::accounts::AccountsService;
|
||||
|
||||
/// 自适应并发下调保留系数:下调到观测在途峰值的 80%
|
||||
const ADAPTIVE_CONCURRENCY_FACTOR: f64 = 0.8;
|
||||
/// 自适应并发下限:过低的并发让账号几乎不可用,宁可保持冻结
|
||||
const ADAPTIVE_CONCURRENCY_FLOOR: u32 = 2;
|
||||
/// worker 周期;冷却观测与探测都依赖该节奏
|
||||
pub const FREEZE_RECOVERY_INTERVAL: Duration = Duration::from_secs(30);
|
||||
pub const FREEZE_RECOVERY_WORKER_OWNER: &str = "account-freeze-recovery";
|
||||
@@ -34,9 +24,6 @@ pub const WORKER_INITIAL_BACKOFF: Duration = Duration::from_secs(1);
|
||||
pub const WORKER_MAXIMUM_BACKOFF: Duration = Duration::from_secs(60);
|
||||
pub const WORKER_LEASE_TTL: Duration = Duration::from_secs(15 * 60);
|
||||
pub const WORKER_LEASE_RENEWAL: Duration = Duration::from_secs(5 * 60);
|
||||
/// 系统审计上下文的固定请求 ID;账号并发更新审计由此溯源到自动冻结编排
|
||||
const SYSTEM_REQUEST_ID: &str = "account-freeze-recovery";
|
||||
|
||||
/// 冻结恢复所需的管理端口组合
|
||||
#[derive(Clone)]
|
||||
pub struct FreezeRecoveryDeps {
|
||||
@@ -55,26 +42,12 @@ impl FreezeRecoveryTask {
|
||||
Self { deps }
|
||||
}
|
||||
|
||||
fn system_context() -> MutationContext {
|
||||
MutationContext {
|
||||
actor: MutationActor::System,
|
||||
request_id: SYSTEM_REQUEST_ID.to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
/// 读取冻结策略;读取或校验失败跳过本轮,不能把未知配置当作允许解冻
|
||||
async fn freeze_policy(&self) -> Option<gateway_core::provider_ports::ProviderFreezePolicy> {
|
||||
/// 无法读取或校验配置时跳过本轮,不能把未知状态当作允许解冻
|
||||
async fn freeze_policy(&self) -> Option<AccountErrorProtection> {
|
||||
let settings = self.deps.settings.load_runtime_settings().await.ok()?;
|
||||
gateway_core::provider_ports::ProviderFreezePolicy::try_new(
|
||||
settings.values.account_auto_freeze_enabled,
|
||||
settings.values.account_auto_freeze_threshold,
|
||||
settings.values.account_auto_freeze_window_seconds,
|
||||
settings.values.account_auto_freeze_duration_seconds,
|
||||
settings.values.account_auto_freeze_probe_enabled,
|
||||
settings.values.account_auto_freeze_probe_model,
|
||||
settings.values.account_auto_freeze_adaptive_concurrency,
|
||||
)
|
||||
.ok()
|
||||
let policy = settings.values.account_error_protection;
|
||||
policy.validate().ok()?;
|
||||
Some(policy)
|
||||
}
|
||||
|
||||
async fn active_freezes(&self) -> BTreeMap<String, AccountFreeze> {
|
||||
@@ -89,55 +62,9 @@ impl FreezeRecoveryTask {
|
||||
if freezes.is_empty() {
|
||||
return;
|
||||
}
|
||||
if policy.enabled() && policy.adaptive_concurrency() {
|
||||
self.adapt_concurrency_limits(&freezes, &policy).await;
|
||||
}
|
||||
self.recover_due_freezes(&freezes, &policy).await;
|
||||
}
|
||||
|
||||
/// 对冻结中的账号执行自适应并发下调:目标为观测在途峰值的 80%(下限 2),
|
||||
/// 只降不升;未观测到峰值证据的账号保持现状
|
||||
async fn adapt_concurrency_limits(
|
||||
&self,
|
||||
freezes: &BTreeMap<String, AccountFreeze>,
|
||||
policy: &gateway_core::provider_ports::ProviderFreezePolicy,
|
||||
) {
|
||||
let account_ids = freezes.keys().cloned().collect::<Vec<_>>();
|
||||
let Ok(peaks) = self.deps.runtime.capacity_peaks(&account_ids).await else {
|
||||
return;
|
||||
};
|
||||
for (account_id, peak) in peaks {
|
||||
let Some(target) = adaptive_target(peak) else {
|
||||
continue;
|
||||
};
|
||||
let Ok(account) = ProviderAccountId::new(account_id.clone()) else {
|
||||
continue;
|
||||
};
|
||||
let Some(limit) = AccountConcurrencyLimit::new(target) else {
|
||||
continue;
|
||||
};
|
||||
match self
|
||||
.deps
|
||||
.accounts
|
||||
.lower_concurrency_limit(&Self::system_context(), account, limit)
|
||||
.await
|
||||
{
|
||||
Ok(Some(_)) => {
|
||||
tracing::info!(
|
||||
account_id,
|
||||
adapted_limit = target,
|
||||
freeze_seconds = policy.freeze_duration().as_secs(),
|
||||
"容量熔断:按观测在途峰值下调账号并发上限",
|
||||
);
|
||||
}
|
||||
Ok(None) => {}
|
||||
Err(error) => {
|
||||
warn!(account_id, error = %error, "自适应并发下调失败");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn load_account(&self, account_id: &str) -> Option<Option<AccountPageItem>> {
|
||||
let account_id = ProviderAccountId::new(account_id.to_owned()).ok()?;
|
||||
self.deps
|
||||
@@ -151,13 +78,13 @@ impl FreezeRecoveryTask {
|
||||
async fn recover_due_freezes(
|
||||
&self,
|
||||
freezes: &BTreeMap<String, AccountFreeze>,
|
||||
policy: &gateway_core::provider_ports::ProviderFreezePolicy,
|
||||
policy: &AccountErrorProtection,
|
||||
) {
|
||||
for (account_id, freeze) in freezes {
|
||||
if freeze.until > Utc::now() {
|
||||
continue;
|
||||
}
|
||||
if policy.enabled() && policy.probe_enabled() && freeze.requires_probe {
|
||||
if policy.enabled && policy.probe_enabled && freeze.requires_probe {
|
||||
self.probe_and_recover(account_id, freeze, policy).await;
|
||||
} else if let Err(error) = self
|
||||
.deps
|
||||
@@ -174,11 +101,19 @@ impl FreezeRecoveryTask {
|
||||
&self,
|
||||
account_id: &str,
|
||||
freeze: &AccountFreeze,
|
||||
policy: &gateway_core::provider_ports::ProviderFreezePolicy,
|
||||
policy: &AccountErrorProtection,
|
||||
) {
|
||||
let Some(Some(item)) = self.load_account(account_id).await else {
|
||||
return;
|
||||
};
|
||||
if item.account.credential_revision != freeze.credential_revision {
|
||||
let _ = self
|
||||
.deps
|
||||
.runtime
|
||||
.finish_freeze(account_id, freeze, None)
|
||||
.await;
|
||||
return;
|
||||
}
|
||||
if !item.account.enabled {
|
||||
// 停用账号没有自动恢复意义;解冻交给管理员手动恢复
|
||||
return;
|
||||
@@ -186,7 +121,7 @@ impl FreezeRecoveryTask {
|
||||
let Ok(account) = ProviderAccountId::new(account_id.to_owned()) else {
|
||||
return;
|
||||
};
|
||||
let Some(model) = self.resolve_probe_model(&account, policy).await else {
|
||||
let Some(model) = self.resolve_probe_model(&account, freeze, policy).await else {
|
||||
// 没有可用探测模型时按失败处理,顺延冻结等待下一轮
|
||||
self.postpone(&account, freeze, policy).await;
|
||||
return;
|
||||
@@ -224,9 +159,23 @@ impl FreezeRecoveryTask {
|
||||
&self,
|
||||
account: &ProviderAccountId,
|
||||
freeze: &AccountFreeze,
|
||||
policy: &gateway_core::provider_ports::ProviderFreezePolicy,
|
||||
policy: &AccountErrorProtection,
|
||||
) {
|
||||
let Some(until) = SystemTime::now().checked_add(policy.freeze_duration()) else {
|
||||
// 探测期间关闭保护或探测时,不再把已经到期的冻结向后延长
|
||||
let Some(current) = self.freeze_policy().await else {
|
||||
return;
|
||||
};
|
||||
if !current.enabled || !current.probe_enabled {
|
||||
let _ = self
|
||||
.deps
|
||||
.runtime
|
||||
.finish_freeze(account.as_str(), freeze, None)
|
||||
.await;
|
||||
return;
|
||||
}
|
||||
let Some(until) = SystemTime::now().checked_add(Duration::from_secs(
|
||||
freeze.duration_seconds.unwrap_or(policy.duration_seconds),
|
||||
)) else {
|
||||
return;
|
||||
};
|
||||
let until = DateTime::<Utc>::from(until);
|
||||
@@ -239,7 +188,10 @@ impl FreezeRecoveryTask {
|
||||
Ok(true) => {
|
||||
tracing::info!(
|
||||
account_id = account.as_str(),
|
||||
postpone_seconds = policy.freeze_duration().as_secs(),
|
||||
postpone_seconds = Duration::from_secs(
|
||||
freeze.duration_seconds.unwrap_or(policy.duration_seconds)
|
||||
)
|
||||
.as_secs(),
|
||||
"冻结恢复探测失败:账号冻结顺延",
|
||||
);
|
||||
}
|
||||
@@ -257,9 +209,14 @@ impl FreezeRecoveryTask {
|
||||
async fn resolve_probe_model(
|
||||
&self,
|
||||
account: &ProviderAccountId,
|
||||
policy: &gateway_core::provider_ports::ProviderFreezePolicy,
|
||||
freeze: &AccountFreeze,
|
||||
policy: &AccountErrorProtection,
|
||||
) -> Option<UpstreamModelId> {
|
||||
if let Some(model) = policy.probe_model() {
|
||||
if let Some(model) = if freeze.duration_seconds.is_some() {
|
||||
freeze.probe_model.as_deref()
|
||||
} else {
|
||||
policy.probe_model.as_deref()
|
||||
} {
|
||||
return UpstreamModelId::new(model.to_owned()).ok();
|
||||
}
|
||||
let models = self.deps.accounts.models(account, false).await.ok()?;
|
||||
@@ -282,15 +239,6 @@ impl ScheduledTask for FreezeRecoveryTask {
|
||||
}
|
||||
}
|
||||
|
||||
/// 自适应目标并发:观测峰值 × 0.8 向下取整,下限 2;无证据(峰值为 0)不调整
|
||||
fn adaptive_target(peak_in_flight: u32) -> Option<u32> {
|
||||
if peak_in_flight == 0 {
|
||||
return None;
|
||||
}
|
||||
let scaled = (f64::from(peak_in_flight) * ADAPTIVE_CONCURRENCY_FACTOR).floor() as u32;
|
||||
Some(scaled.max(ADAPTIVE_CONCURRENCY_FLOOR))
|
||||
}
|
||||
|
||||
/// 消耗连接测试事件流并返回是否以 `Completed` 终止
|
||||
async fn drain_probe(mut events: crate::model::accounts::AccountConnectionTestEventStream) -> bool {
|
||||
let mut completed = false;
|
||||
|
||||
@@ -81,6 +81,7 @@ pub struct AccountListQuery {
|
||||
/// Admin query service 从运行态存储取得的当前账号冷却快照
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct AccountRuntimeSnapshot {
|
||||
pub protection_rules: BTreeMap<String, Vec<gateway_core::account::AccountProtectionMatch>>,
|
||||
pub cooldown: BTreeMap<String, gateway_core::account::AccountCooldown>,
|
||||
/// `None` 表示实时 lease 存储不可用;`Some` 中未出现的账号当前使用量为零
|
||||
pub in_flight: Option<BTreeMap<String, u64>>,
|
||||
@@ -93,6 +94,9 @@ pub struct AccountFreeze {
|
||||
pub until: DateTime<Utc>,
|
||||
pub generation: String,
|
||||
pub requires_probe: bool,
|
||||
pub duration_seconds: Option<u64>,
|
||||
pub probe_model: Option<String>,
|
||||
pub protection_rules: Vec<gateway_core::account::AccountProtectionMatch>,
|
||||
}
|
||||
|
||||
/// 可选的账号分组成员筛选条件
|
||||
@@ -203,6 +207,7 @@ pub struct AccountPage {
|
||||
/// 同一状态快照下的账号事实与唯一状态投影
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct AccountPageItem {
|
||||
pub protection_rules: Vec<gateway_core::account::AccountProtectionMatch>,
|
||||
pub account: AccountRecord,
|
||||
pub projection: AccountStatusProjection,
|
||||
pub capacity: AccountCapacity,
|
||||
|
||||
@@ -2,7 +2,9 @@
|
||||
|
||||
use chrono::{DateTime, Utc};
|
||||
|
||||
use super::observability::{DecimalAmount, RequestMetricPoint, UsageOverview};
|
||||
use super::observability::{
|
||||
DecimalAmount, RequestMetricPoint, UsageConcurrencyPoint, UsageOverview,
|
||||
};
|
||||
|
||||
/// 数据可见性状态,不以缺失投影冒充零统计
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
@@ -57,9 +59,10 @@ pub struct UsageProjectedCostPoint {
|
||||
}
|
||||
|
||||
/// 同一数据库快照内的完整洞察输入
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct UsageInsightsObservation {
|
||||
pub overview: UsageOverview,
|
||||
pub trend: Vec<RequestMetricPoint>,
|
||||
pub costs: Vec<UsageProjectedCostPoint>,
|
||||
pub concurrency: Vec<UsageConcurrencyPoint>,
|
||||
}
|
||||
|
||||
@@ -23,7 +23,6 @@ pub enum MutationAuditOperation {
|
||||
BackupDelete,
|
||||
BackupConnectionTest,
|
||||
BackupDownloadUrl,
|
||||
ProviderAccountAdaptConcurrency,
|
||||
ProviderAccountRecover,
|
||||
ProviderAccountBatchUpdate,
|
||||
ProviderAccountDelete,
|
||||
@@ -84,7 +83,6 @@ impl MutationAuditOperation {
|
||||
Self::BackupDelete => ("backup.delete_requested", "backup"),
|
||||
Self::BackupConnectionTest => ("backup.s3_connection_tested", "backup_settings"),
|
||||
Self::BackupDownloadUrl => ("backup.download_url_created", "backup"),
|
||||
Self::ProviderAccountAdaptConcurrency => ("adapt_concurrency", "provider_account"),
|
||||
Self::ProviderAccountRecover => ("recover", "provider_account"),
|
||||
Self::ProviderAccountBatchUpdate => ("batch_update", "provider_account"),
|
||||
Self::ProviderAccountDelete => ("delete", "provider_account"),
|
||||
|
||||
@@ -653,6 +653,7 @@ pub struct DashboardAccountUsage {
|
||||
pub authentication_kind: String,
|
||||
pub name: String,
|
||||
pub email: Option<String>,
|
||||
pub notes: Option<String>,
|
||||
pub plan_type: Option<String>,
|
||||
/// Admin 按 Provider 补齐的套餐展示名称
|
||||
pub plan_type_display: Option<String>,
|
||||
@@ -1260,38 +1261,44 @@ pub struct UsageInsightsHealth {
|
||||
pub points: Vec<UsageInsightsHealthPoint>,
|
||||
}
|
||||
|
||||
/// 一个时间桶内按重叠时长加权的逻辑请求并发
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct UsageConcurrencyPoint {
|
||||
pub bucket_start: DateTime<Utc>,
|
||||
pub average_concurrency: f64,
|
||||
pub peak_concurrency: u64,
|
||||
}
|
||||
|
||||
/// 请求并发与调度等待的负载指标
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct UsageInsightsLoad {
|
||||
pub average_concurrency: f64,
|
||||
pub peak_concurrency: u64,
|
||||
pub admission_decision_p95_ms: Option<PercentileMilliseconds>,
|
||||
pub account_selection_wait_p95_ms: Option<PercentileMilliseconds>,
|
||||
}
|
||||
|
||||
/// 洞察性能时间点
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct UsageInsightsPerformancePoint {
|
||||
pub bucket_start: DateTime<Utc>,
|
||||
pub latency_percentiles: LatencyPercentiles,
|
||||
pub first_token_latency_percentiles: LatencyPercentiles,
|
||||
pub admission_decision_percentiles: LatencyPercentiles,
|
||||
pub account_selection_wait_percentiles: LatencyPercentiles,
|
||||
pub output_throughput_p10: Option<u64>,
|
||||
pub output_throughput_p50: Option<u64>,
|
||||
pub output_throughput_p90: Option<u64>,
|
||||
pub capacity_utilization_avg_basis_points: Option<u64>,
|
||||
pub capacity_utilization_p95_basis_points: Option<u64>,
|
||||
pub load: UsageInsightsLoad,
|
||||
}
|
||||
|
||||
/// 洞察性能汇总与可观测覆盖率
|
||||
/// 洞察性能汇总
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct UsageInsightsPerformance {
|
||||
pub latency_percentiles: LatencyPercentiles,
|
||||
pub first_token_latency_percentiles: LatencyPercentiles,
|
||||
pub latency_coverage: f64,
|
||||
pub first_token_coverage: f64,
|
||||
pub admission_decision_percentiles: LatencyPercentiles,
|
||||
pub account_selection_wait_percentiles: LatencyPercentiles,
|
||||
pub admission_decision_coverage: f64,
|
||||
pub account_selection_wait_coverage: f64,
|
||||
pub output_throughput_p10: Option<u64>,
|
||||
pub output_throughput_p50: Option<u64>,
|
||||
pub output_throughput_p90: Option<u64>,
|
||||
pub capacity_utilization_avg_basis_points: Option<u64>,
|
||||
pub capacity_utilization_p95_basis_points: Option<u64>,
|
||||
pub capacity_coverage: f64,
|
||||
pub load: UsageInsightsLoad,
|
||||
pub points: Vec<UsageInsightsPerformancePoint>,
|
||||
}
|
||||
|
||||
|
||||
@@ -84,6 +84,7 @@ pub struct PluginInstanceMutation {
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum PluginInstanceRuntimeStatus {
|
||||
Disabled,
|
||||
Unknown,
|
||||
AwaitingPublication,
|
||||
Preparing,
|
||||
Running,
|
||||
@@ -108,6 +109,21 @@ pub struct PluginInstanceRuntime {
|
||||
pub actual_artifact_sha256: Option<String>,
|
||||
pub failure: Option<PluginInstanceRuntimeFailure>,
|
||||
pub draining_revisions: Vec<u64>,
|
||||
pub load: Option<PluginInstanceRuntimeLoad>,
|
||||
}
|
||||
|
||||
/// 当前发布会话的资源占用采样,计数可以重叠且不构成原子快照
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct PluginInstanceRuntimeLoad {
|
||||
/// 总在途名额,包含排队、取消确认和仍由响应流持有的调用
|
||||
pub active_calls: usize,
|
||||
pub executing_calls: usize,
|
||||
pub queued_calls: usize,
|
||||
pub resuming_calls: usize,
|
||||
/// 包含已返回但尚未由插件消费的回调结果
|
||||
pub pending_callbacks: usize,
|
||||
/// 已交付首结果但尚未收到 End 的流
|
||||
pub active_streams: usize,
|
||||
}
|
||||
|
||||
/// 可继续运行的旧接口提示,与无法启用的兼容性错误分开
|
||||
@@ -136,6 +152,8 @@ pub struct PluginInstanceView {
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct ConfigurePluginInstance {
|
||||
/// 只随本次启动请求传递,不写入实例配置
|
||||
pub compatibility_confirmation: Option<PluginCompatibilityConfirmation>,
|
||||
/// 创建草稿固定一个 UUID,重试复用同一配置,不能作为编辑已有配置的入口
|
||||
pub creation_id: Option<String>,
|
||||
/// 编辑时检查用户看到的配置版本,避免覆盖另一窗口已经保存的内容
|
||||
@@ -159,6 +177,16 @@ pub struct PluginInstanceReplacement {
|
||||
pub expected_revision: u64,
|
||||
}
|
||||
|
||||
/// 管理员确认的宿主、实例配置与目标包;不构成永久兼容豁免
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct PluginCompatibilityConfirmation {
|
||||
pub host_fingerprint: String,
|
||||
pub instance_id: String,
|
||||
pub instance_revision: u64,
|
||||
pub artifact_sha256: String,
|
||||
}
|
||||
|
||||
/// 恢复已安装旧版本的配置快照,并重新通过目标版本校验
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
@@ -196,6 +224,9 @@ pub struct PluginVersionConfiguration {
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PluginVersionPlan {
|
||||
pub compatibility_warning: Option<String>,
|
||||
pub compatibility_confirmation: Option<PluginCompatibilityConfirmation>,
|
||||
pub load_error: Option<String>,
|
||||
pub instance_revision: u64,
|
||||
pub artifact_sha256: String,
|
||||
pub configuration: serde_json::Value,
|
||||
|
||||
@@ -62,6 +62,48 @@ impl PluginHostCompatibility {
|
||||
.iter()
|
||||
.any(|entry| entry.capability == capability && entry.versions.contains(&version))
|
||||
}
|
||||
|
||||
/// 启动和升级预检共用比较规则,只检查插件声明的能力
|
||||
#[must_use]
|
||||
pub fn incompatibilities(
|
||||
&self,
|
||||
requirements: &PluginCompatibilityRequirements,
|
||||
host: &semver::Version,
|
||||
) -> Vec<String> {
|
||||
let mut reasons = Vec::new();
|
||||
if !self
|
||||
.manifest_schema_versions
|
||||
.contains(&requirements.manifest_schema_version)
|
||||
{
|
||||
reasons.push(format!(
|
||||
"清单 v{} 不在宿主支持范围内",
|
||||
requirements.manifest_schema_version
|
||||
));
|
||||
}
|
||||
if !self
|
||||
.protocol_versions
|
||||
.contains(&requirements.protocol_version)
|
||||
{
|
||||
reasons.push(format!(
|
||||
"RPC v{} 不在宿主支持范围内",
|
||||
requirements.protocol_version
|
||||
));
|
||||
}
|
||||
if !semver::VersionReq::parse(&requirements.host_version)
|
||||
.is_ok_and(|range| range.matches(host))
|
||||
{
|
||||
reasons.push(format!(
|
||||
"插件声明的宿主范围为 {},当前为 {host}",
|
||||
requirements.host_version
|
||||
));
|
||||
}
|
||||
for (capability, version) in &requirements.capabilities {
|
||||
if !self.supports_capability(capability, *version) {
|
||||
reasons.push(format!("{capability} v{version} 不在宿主支持范围内"));
|
||||
}
|
||||
}
|
||||
reasons
|
||||
}
|
||||
}
|
||||
|
||||
fn valid_versions(versions: &[u32]) -> bool {
|
||||
|
||||
@@ -1246,6 +1246,7 @@ impl fmt::Debug for ProviderExport {
|
||||
/// 统一账号目录的一行完整结果
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct AccountDirectoryItem {
|
||||
pub protection_rules: Vec<gateway_core::account::AccountProtectionMatch>,
|
||||
pub account: AccountRecord,
|
||||
pub capacity: super::accounts::AccountCapacity,
|
||||
pub capabilities: super::accounts::ProviderAccountCapabilities,
|
||||
|
||||
@@ -65,13 +65,7 @@ pub struct RuntimeSettingsValues {
|
||||
pub usage_retention_days: u32,
|
||||
pub ops_event_retention_days: u32,
|
||||
pub audit_retention_days: u32,
|
||||
pub account_auto_freeze_enabled: bool,
|
||||
pub account_auto_freeze_threshold: u32,
|
||||
pub account_auto_freeze_window_seconds: u64,
|
||||
pub account_auto_freeze_duration_seconds: u64,
|
||||
pub account_auto_freeze_probe_enabled: bool,
|
||||
pub account_auto_freeze_probe_model: Option<String>,
|
||||
pub account_auto_freeze_adaptive_concurrency: bool,
|
||||
pub account_error_protection: gateway_core::account::AccountErrorProtection,
|
||||
pub account_warmup_enabled: bool,
|
||||
pub account_warmup_schedule_time: String,
|
||||
pub account_warmup_model: Option<String>,
|
||||
@@ -232,12 +226,7 @@ impl RuntimeSettingsValues {
|
||||
self.ops_event_retention_days,
|
||||
self.audit_retention_days,
|
||||
)?;
|
||||
gateway_core::provider_ports::ProviderFreezePolicy::validate_values(
|
||||
self.account_auto_freeze_threshold,
|
||||
self.account_auto_freeze_window_seconds,
|
||||
self.account_auto_freeze_duration_seconds,
|
||||
self.account_auto_freeze_probe_model.as_deref(),
|
||||
)?;
|
||||
self.account_error_protection.validate()?;
|
||||
gateway_core::provider_ports::ProviderWarmupPolicy::validate_values(
|
||||
self.account_warmup_enabled,
|
||||
&self.account_warmup_schedule_time,
|
||||
|
||||
@@ -46,6 +46,15 @@ pub trait PluginPreparation: PluginRuntimeDiagnostics + PluginStateLifecycle {
|
||||
&self,
|
||||
snapshot: PluginInstanceSnapshot,
|
||||
) -> Result<ExtensionSetReference, AdminError>;
|
||||
|
||||
/// 确认由 Admin 校验配置版本,Runtime 复核宿主并仅放行目标实例
|
||||
async fn prepare_confirmed(
|
||||
&self,
|
||||
_snapshot: PluginInstanceSnapshot,
|
||||
_confirmation: crate::model::plugins::instances::PluginCompatibilityConfirmation,
|
||||
) -> Result<ExtensionSetReference, AdminError> {
|
||||
Err(AdminError::invalid("插件运行时不支持确认启动"))
|
||||
}
|
||||
}
|
||||
|
||||
/// 运行诊断独立于发布准备;没有进程事实时显式返回 None
|
||||
@@ -175,6 +184,10 @@ pub trait PluginDistribution: Send + Sync {
|
||||
/// Runtime 只解释插件包格式;安装事务与来源选择归 Admin
|
||||
#[async_trait]
|
||||
pub trait PluginPackageInspector: Send + Sync {
|
||||
/// 当前宿主版本、兼容声明与平台的稳定身份,不含敏感信息
|
||||
fn compatibility_host_fingerprint(&self) -> Result<String, AdminError> {
|
||||
Err(AdminError::internal("宿主兼容声明不可用"))
|
||||
}
|
||||
/// 完整校验包并返回版本范围诊断;校验失败与可加载但未经宿主承诺的提醒分开
|
||||
async fn compatibility_warning(
|
||||
&self,
|
||||
|
||||
@@ -209,14 +209,6 @@ pub trait AccountStore:
|
||||
context: &MutationContext,
|
||||
) -> AdminStoreResult<AccountUpdateResult>;
|
||||
|
||||
/// 在事务内按最新启用状态、账号上限和全局默认值判断,只降低并发上限
|
||||
async fn lower_concurrency_limit(
|
||||
&self,
|
||||
account_id: &gateway_core::account::ProviderAccountId,
|
||||
limit: gateway_core::account::AccountConcurrencyLimit,
|
||||
context: &MutationContext,
|
||||
) -> AdminStoreResult<Option<AccountUpdateResult>>;
|
||||
|
||||
async fn recover_account(
|
||||
&self,
|
||||
account_id: &gateway_core::account::ProviderAccountId,
|
||||
@@ -259,17 +251,11 @@ pub trait AccountRuntimeStore: Send + Sync {
|
||||
account_ids: &[String],
|
||||
) -> AdminStoreResult<AccountRuntimeSnapshot>;
|
||||
|
||||
/// 容量熔断自动冻结中的账号与其冻结截止时间;429 临时限流不包含在内
|
||||
/// 账号错误保护中的账号与其冻结快照;临时限流不包含在内
|
||||
async fn active_freezes(
|
||||
&self,
|
||||
) -> AdminStoreResult<BTreeMap<String, crate::model::accounts::AccountFreeze>>;
|
||||
|
||||
/// 读取容量失败窗口内观测到的在途并发峰值(自适应并发下调的证据)
|
||||
async fn capacity_peaks(
|
||||
&self,
|
||||
account_ids: &[String],
|
||||
) -> AdminStoreResult<BTreeMap<String, u32>>;
|
||||
|
||||
/// 仅当冻结快照仍匹配时解除或顺延;旧探测不得覆盖手动恢复或新一轮冻结
|
||||
async fn finish_freeze(
|
||||
&self,
|
||||
|
||||
@@ -88,13 +88,6 @@ pub trait AccountsService: Send + Sync {
|
||||
command: UpdateAccount,
|
||||
) -> Result<AccountUpdateResult, AdminError>;
|
||||
|
||||
async fn lower_concurrency_limit(
|
||||
&self,
|
||||
context: &MutationContext,
|
||||
account_id: ProviderAccountId,
|
||||
limit: gateway_core::account::AccountConcurrencyLimit,
|
||||
) -> Result<Option<AccountUpdateResult>, AdminError>;
|
||||
|
||||
async fn batch_update(
|
||||
&self,
|
||||
context: &MutationContext,
|
||||
@@ -474,6 +467,7 @@ impl DefaultAccountsService {
|
||||
.and_then(|(window, _)| window.local_usage.clone())
|
||||
});
|
||||
Ok(AccountDirectoryItem {
|
||||
protection_rules: stored.protection_rules,
|
||||
capacity: stored.capacity,
|
||||
capabilities: provider
|
||||
.account_capabilities(account_id, &stored.account.authentication_kind),
|
||||
@@ -583,6 +577,7 @@ impl AccountsService for DefaultAccountsService {
|
||||
.and_then(|(window, _)| window.local_usage.clone())
|
||||
});
|
||||
Ok(AccountDirectoryItem {
|
||||
protection_rules: item.protection_rules,
|
||||
capacity: crate::model::accounts::AccountCapacity {
|
||||
used_slots: in_flight
|
||||
.as_ref()
|
||||
@@ -766,27 +761,6 @@ impl AccountsService for DefaultAccountsService {
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
async fn lower_concurrency_limit(
|
||||
&self,
|
||||
context: &MutationContext,
|
||||
account_id: ProviderAccountId,
|
||||
limit: gateway_core::account::AccountConcurrencyLimit,
|
||||
) -> Result<Option<AccountUpdateResult>, AdminError> {
|
||||
let (_, provider) = self.provider_for_account(&account_id).await?;
|
||||
let result = self
|
||||
.accounts
|
||||
.lower_concurrency_limit(&account_id, limit, context)
|
||||
.await
|
||||
.map_err(|error| map_store_error(error, "provider account"))?;
|
||||
if let Some(result) = &result {
|
||||
provider
|
||||
.account_facts_changed(std::slice::from_ref(&account_id))
|
||||
.await;
|
||||
publish_committed(self.snapshot.as_ref(), result.config_revision).await?;
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
async fn batch_update(
|
||||
&self,
|
||||
context: &MutationContext,
|
||||
|
||||
@@ -20,9 +20,10 @@ use crate::{
|
||||
HealthTimeline, HealthTimelinePoint, OpsErrorPage, OpsErrorQuery, ProviderBillingInput,
|
||||
RequestMetricPoint, RequestMetrics, TimeRange, Trend, TrendKind, TrendPoint,
|
||||
TrendSummary, UsageBilling, UsageBillingProjection, UsageCalculatedBillingFact,
|
||||
UsageDetail, UsageFilter, UsageInsights, UsageInsightsCost, UsageInsightsCostPoint,
|
||||
UsageInsightsHealth, UsageInsightsHealthPoint, UsageInsightsPerformance,
|
||||
UsageInsightsPerformancePoint, UsageOverview, UsagePage, UsageQuery, UsageSummary,
|
||||
UsageConcurrencyPoint, UsageDetail, UsageFilter, UsageInsights, UsageInsightsCost,
|
||||
UsageInsightsCostPoint, UsageInsightsHealth, UsageInsightsHealthPoint,
|
||||
UsageInsightsLoad, UsageInsightsPerformance, UsageInsightsPerformancePoint,
|
||||
UsageOverview, UsagePage, UsageQuery, UsageSummary,
|
||||
},
|
||||
provider_credentials::ProviderQuotaRequest,
|
||||
},
|
||||
@@ -304,7 +305,7 @@ impl ObservabilityService for DefaultObservabilityService {
|
||||
}
|
||||
let overview = observation.overview;
|
||||
let trend = observation.trend;
|
||||
build_usage_insights(overview, trend, standard_costs)
|
||||
build_usage_insights(overview, trend, standard_costs, observation.concurrency)
|
||||
}
|
||||
|
||||
async fn diagnostics(
|
||||
@@ -385,6 +386,7 @@ fn build_usage_insights(
|
||||
overview: UsageOverview,
|
||||
trend: Vec<RequestMetricPoint>,
|
||||
standard_costs: UsageCostScenarios,
|
||||
concurrency: Vec<UsageConcurrencyPoint>,
|
||||
) -> Result<UsageInsights, AdminError> {
|
||||
let granularity = trend.first().map_or(
|
||||
crate::model::observability::Granularity::FifteenMinutes,
|
||||
@@ -432,49 +434,69 @@ fn build_usage_insights(
|
||||
})
|
||||
.collect(),
|
||||
};
|
||||
let concurrency_by_bucket = concurrency
|
||||
.iter()
|
||||
.map(|point| (point.bucket_start, point))
|
||||
.collect::<BTreeMap<_, _>>();
|
||||
let mut weighted_concurrency_micros = 0.0;
|
||||
let mut effective_micros = 0_i64;
|
||||
for (index, point) in concurrency.iter().enumerate() {
|
||||
let start = point.bucket_start.max(overview.range.start);
|
||||
let end = concurrency
|
||||
.get(index + 1)
|
||||
.map_or(overview.range.end, |next| next.bucket_start)
|
||||
.min(overview.range.end);
|
||||
let micros = (end - start).num_microseconds().unwrap_or(0).max(0);
|
||||
effective_micros = effective_micros.saturating_add(micros);
|
||||
weighted_concurrency_micros += point.average_concurrency * micros as f64;
|
||||
}
|
||||
let average_concurrency = if effective_micros > 0 {
|
||||
weighted_concurrency_micros / effective_micros as f64
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
let peak_concurrency = concurrency
|
||||
.iter()
|
||||
.map(|point| point.peak_concurrency)
|
||||
.max()
|
||||
.unwrap_or(0);
|
||||
let performance = UsageInsightsPerformance {
|
||||
latency_percentiles: requests.latency_percentiles,
|
||||
first_token_latency_percentiles: requests.first_token_latency_percentiles,
|
||||
latency_coverage: rate_or_zero(requests.latency_count, requests.request_count),
|
||||
first_token_coverage: rate_or_zero(
|
||||
requests.first_token_latency_count,
|
||||
requests.request_count,
|
||||
),
|
||||
admission_decision_percentiles: requests.admission_decision_percentiles,
|
||||
account_selection_wait_percentiles: requests.account_selection_wait_percentiles,
|
||||
admission_decision_coverage: rate_or_zero(
|
||||
requests.admission_decision_count,
|
||||
requests.request_count,
|
||||
),
|
||||
account_selection_wait_coverage: rate_or_zero(
|
||||
requests.account_selection_wait_count,
|
||||
requests.request_count,
|
||||
),
|
||||
output_throughput_p10: requests.output_throughput_p10,
|
||||
output_throughput_p50: requests.output_throughput_p50,
|
||||
output_throughput_p90: requests.output_throughput_p90,
|
||||
capacity_utilization_avg_basis_points: requests.capacity_utilization_avg_basis_points,
|
||||
capacity_utilization_p95_basis_points: requests.capacity_utilization_p95_basis_points,
|
||||
capacity_coverage: rate_or_zero(requests.capacity_sample_count, requests.request_count),
|
||||
load: UsageInsightsLoad {
|
||||
average_concurrency,
|
||||
peak_concurrency,
|
||||
admission_decision_p95_ms: requests.admission_decision_percentiles.p95_ms,
|
||||
account_selection_wait_p95_ms: requests.account_selection_wait_percentiles.p95_ms,
|
||||
},
|
||||
points: trend
|
||||
.iter()
|
||||
.map(|point| UsageInsightsPerformancePoint {
|
||||
bucket_start: point.bucket_start,
|
||||
latency_percentiles: point.metrics.latency_percentiles,
|
||||
first_token_latency_percentiles: point.metrics.first_token_latency_percentiles,
|
||||
admission_decision_percentiles: point.metrics.admission_decision_percentiles,
|
||||
account_selection_wait_percentiles: point
|
||||
.metrics
|
||||
.account_selection_wait_percentiles,
|
||||
output_throughput_p10: point.metrics.output_throughput_p10,
|
||||
output_throughput_p50: point.metrics.output_throughput_p50,
|
||||
output_throughput_p90: point.metrics.output_throughput_p90,
|
||||
capacity_utilization_avg_basis_points: point
|
||||
.metrics
|
||||
.capacity_utilization_avg_basis_points,
|
||||
capacity_utilization_p95_basis_points: point
|
||||
.metrics
|
||||
.capacity_utilization_p95_basis_points,
|
||||
.map(|point| {
|
||||
let concurrency = concurrency_by_bucket.get(&point.bucket_start);
|
||||
UsageInsightsPerformancePoint {
|
||||
bucket_start: point.bucket_start,
|
||||
latency_percentiles: point.metrics.latency_percentiles,
|
||||
first_token_latency_percentiles: point.metrics.first_token_latency_percentiles,
|
||||
output_throughput_p10: point.metrics.output_throughput_p10,
|
||||
output_throughput_p50: point.metrics.output_throughput_p50,
|
||||
output_throughput_p90: point.metrics.output_throughput_p90,
|
||||
load: UsageInsightsLoad {
|
||||
average_concurrency: concurrency
|
||||
.map_or(0.0, |point| point.average_concurrency),
|
||||
peak_concurrency: concurrency.map_or(0, |point| point.peak_concurrency),
|
||||
admission_decision_p95_ms: point
|
||||
.metrics
|
||||
.admission_decision_percentiles
|
||||
.p95_ms,
|
||||
account_selection_wait_p95_ms: point
|
||||
.metrics
|
||||
.account_selection_wait_percentiles
|
||||
.p95_ms,
|
||||
},
|
||||
}
|
||||
})
|
||||
.collect(),
|
||||
};
|
||||
|
||||
@@ -161,53 +161,24 @@ impl PluginSystemUpdatePreflight {
|
||||
.await,
|
||||
) {
|
||||
(_, Err(error)) if error.kind() == AdminErrorKind::Invalid => {
|
||||
Some("插件包或协议与目标版本不兼容".to_owned())
|
||||
Some(error.message().to_owned())
|
||||
}
|
||||
(_, Err(error)) => return Err(map_inspection_error(error)),
|
||||
(None, _) => Some("无法确认插件与目标版本兼容".to_owned()),
|
||||
(Some(host), Ok(requirements)) => {
|
||||
if !semver::VersionReq::parse(&requirements.host_version)
|
||||
.is_ok_and(|versions| versions.matches(target))
|
||||
{
|
||||
Some(format!("要求网关版本 {}", requirements.host_version))
|
||||
} else if !host
|
||||
.manifest_schema_versions
|
||||
.contains(&requirements.manifest_schema_version)
|
||||
|| !host
|
||||
.protocol_versions
|
||||
.contains(&requirements.protocol_version)
|
||||
|| requirements
|
||||
.capabilities
|
||||
.iter()
|
||||
.any(|(capability, version)| {
|
||||
!host.supports_capability(capability, *version)
|
||||
})
|
||||
{
|
||||
Some("插件协议或能力与目标版本不兼容".to_owned())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
let reasons = host.incompatibilities(&requirements, target);
|
||||
(!reasons.is_empty()).then(|| reasons.join(","))
|
||||
}
|
||||
}
|
||||
} else {
|
||||
match self
|
||||
.inspector
|
||||
.inspect(
|
||||
artifact.archive.clone(),
|
||||
Some(instance.artifact_sha256.clone()),
|
||||
)
|
||||
.compatibility_warning(artifact.archive, instance.artifact_sha256.clone())
|
||||
.await
|
||||
{
|
||||
Ok(_) => self
|
||||
.inspector
|
||||
.compatibility_warning(
|
||||
artifact.archive,
|
||||
instance.artifact_sha256.clone(),
|
||||
)
|
||||
.await
|
||||
.map_err(map_inspection_error)?,
|
||||
Ok(warning) => warning,
|
||||
Err(error) if error.kind() == AdminErrorKind::Invalid => {
|
||||
Some("插件与当前宿主不兼容".to_owned())
|
||||
Some(error.message().to_owned())
|
||||
}
|
||||
Err(error) => return Err(map_inspection_error(error)),
|
||||
}
|
||||
|
||||
@@ -186,6 +186,8 @@ impl PluginsService {
|
||||
.configuration_ready(probe, &metadata)
|
||||
.await?;
|
||||
|
||||
let status = self.package_status(&metadata.sha256).await?;
|
||||
let compatible = status.warning.is_none() && status.load_error.is_none();
|
||||
// 其它管理员写入或同插件的并发安装可能推进全局 revision;稳定 creation ID
|
||||
// 配合每轮重新读取,既不会复制默认实例,也不会覆盖先完成的另一个版本
|
||||
for _ in 0..3 {
|
||||
@@ -207,12 +209,13 @@ impl PluginsService {
|
||||
}
|
||||
|
||||
let input = ConfigurePluginInstance {
|
||||
compatibility_confirmation: None,
|
||||
replace_instances: Vec::new(),
|
||||
creation_id: Some(creation_id.clone()),
|
||||
expected_revision: None,
|
||||
name: metadata.display_name.clone(),
|
||||
artifact_sha256: metadata.sha256.clone(),
|
||||
enabled: !configuration_required,
|
||||
enabled: !configuration_required && compatible,
|
||||
configuration: configuration.clone(),
|
||||
secrets: None,
|
||||
bindings: bindings.clone(),
|
||||
|
||||
@@ -1,773 +0,0 @@
|
||||
//! 插件实例的配置、停用、删除与私有状态迁移编排
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use gateway_core::{
|
||||
policy::ClientApiKeyId,
|
||||
routing::{AccountGroupId, extensions::ExtensionSetReference},
|
||||
};
|
||||
use secrecy::ExposeSecret;
|
||||
|
||||
use super::PluginsService;
|
||||
use crate::{
|
||||
model::{
|
||||
AdminError, AdminErrorKind, MutationContext, Revision,
|
||||
plugins::instances::{
|
||||
ConfigurePluginInstance, PluginInstance, PluginInstanceMutation,
|
||||
PluginInstanceReplacement, PluginInstanceRuntime, PluginInstanceRuntimeStatus,
|
||||
PluginInstanceSnapshot, PluginInstanceView,
|
||||
},
|
||||
plugins::state::{PluginStateCommit, PluginStateConfiguration},
|
||||
},
|
||||
use_case::{map_store_error, publish_committed},
|
||||
};
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
pub(super) struct PackageStatus {
|
||||
warning: Option<String>,
|
||||
load_error: Option<String>,
|
||||
}
|
||||
|
||||
impl PluginsService {
|
||||
/// 只校验固定包体,不启动插件;停用实例也需区分兼容性提醒与加载错误
|
||||
async fn package_status(&self, digest: &str) -> Result<PackageStatus, AdminError> {
|
||||
// 运行宿主和摘要固定,缓存纯静态结论,避免管理页轮询反复解包
|
||||
// 只缓存有限数量的确定结果,暂时性错误仍可重试
|
||||
let mut cache = self.compatibility.lock().await;
|
||||
if let Some(warning) = cache.get(digest) {
|
||||
return Ok(warning.clone());
|
||||
}
|
||||
let artifact = self
|
||||
.store
|
||||
.load_artifact(digest)
|
||||
.await
|
||||
.map_err(|error| map_store_error(error, "plugin"))?;
|
||||
let warning = match self
|
||||
.inspector
|
||||
.compatibility_warning(artifact.archive, digest.to_owned())
|
||||
.await
|
||||
{
|
||||
Ok(warning) => PackageStatus {
|
||||
warning,
|
||||
load_error: None,
|
||||
},
|
||||
Err(error) if error.kind() == AdminErrorKind::Invalid => PackageStatus {
|
||||
warning: None,
|
||||
load_error: Some(error.message().to_owned()),
|
||||
},
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
if cache.len() < 128 {
|
||||
cache.insert(digest.to_owned(), warning.clone());
|
||||
}
|
||||
Ok(warning)
|
||||
}
|
||||
|
||||
pub async fn instances(&self) -> Result<Vec<PluginInstanceView>, AdminError> {
|
||||
let snapshot = self
|
||||
.store
|
||||
.load_instances()
|
||||
.await
|
||||
.map_err(|e| map_store_error(e, "plugin"))?;
|
||||
let published = self.published.snapshot_for_diagnostics();
|
||||
let published_revision = published.as_ref().map(|snapshot| snapshot.revision().get());
|
||||
let published_ready = published
|
||||
.as_ref()
|
||||
.is_some_and(|snapshot| snapshot.extensions().is_none_or(|set| set.can_serve()));
|
||||
let mut diagnostics = self
|
||||
.preparation
|
||||
.runtime_diagnostics(
|
||||
&snapshot,
|
||||
published_revision,
|
||||
published
|
||||
.as_ref()
|
||||
.and_then(|snapshot| snapshot.extensions()),
|
||||
)
|
||||
.await
|
||||
.unwrap_or_default();
|
||||
let target_revision = snapshot.config_revision.get();
|
||||
let artifacts = self
|
||||
.list()
|
||||
.await?
|
||||
.into_iter()
|
||||
.map(|artifact| (artifact.metadata.sha256.clone(), artifact.metadata))
|
||||
.collect::<BTreeMap<_, _>>();
|
||||
let mut views = Vec::with_capacity(snapshot.instances.len());
|
||||
for instance in snapshot.instances {
|
||||
let metadata = artifacts
|
||||
.get(&instance.artifact_sha256)
|
||||
.ok_or_else(|| AdminError::not_found("插件制品不存在"))?;
|
||||
let package_status = self.package_status(&instance.artifact_sha256).await?;
|
||||
let configuration_required = package_status.load_error.is_none()
|
||||
&& !self
|
||||
.preparation
|
||||
.configuration_ready(instance.clone(), metadata)
|
||||
.await?;
|
||||
let runtime = diagnostics.remove(&instance.id).unwrap_or_else(|| {
|
||||
let running = instance.enabled
|
||||
&& published_ready
|
||||
&& published_revision == Some(target_revision);
|
||||
PluginInstanceRuntime {
|
||||
status: if !instance.enabled {
|
||||
PluginInstanceRuntimeStatus::Disabled
|
||||
} else if running {
|
||||
PluginInstanceRuntimeStatus::Running
|
||||
} else {
|
||||
PluginInstanceRuntimeStatus::AwaitingPublication
|
||||
},
|
||||
actual_revision: running.then_some(instance.revision.get()),
|
||||
actual_artifact_sha256: running.then(|| instance.artifact_sha256.clone()),
|
||||
failure: None,
|
||||
draining_revisions: Vec::new(),
|
||||
}
|
||||
});
|
||||
views.push(PluginInstanceView {
|
||||
api_deprecations: if package_status.load_error.is_none() {
|
||||
self.inspector.api_deprecations(metadata)?
|
||||
} else {
|
||||
Vec::new()
|
||||
},
|
||||
configuration_required,
|
||||
compatibility_warning: package_status.warning,
|
||||
load_error: package_status.load_error,
|
||||
running: runtime.status == PluginInstanceRuntimeStatus::Running,
|
||||
published_revision,
|
||||
runtime,
|
||||
instance,
|
||||
});
|
||||
}
|
||||
Ok(views)
|
||||
}
|
||||
|
||||
pub async fn configure_instance(
|
||||
&self,
|
||||
id: Option<&str>,
|
||||
input: ConfigurePluginInstance,
|
||||
context: &MutationContext,
|
||||
) -> Result<PluginInstanceMutation, AdminError> {
|
||||
if id.is_some() && input.creation_id.is_some() {
|
||||
return Err(AdminError::invalid("编辑配置不能使用创建标识"));
|
||||
}
|
||||
if id.is_none() && input.expected_revision.is_some() {
|
||||
return Err(AdminError::invalid("创建配置不能指定已有配置版本"));
|
||||
}
|
||||
if let Some(creation_id) = &input.creation_id {
|
||||
let parsed = uuid::Uuid::parse_str(creation_id)
|
||||
.map_err(|_| AdminError::invalid("配置创建标识必须是 UUID"))?;
|
||||
if parsed.to_string() != *creation_id {
|
||||
return Err(AdminError::invalid("配置创建标识必须使用标准 UUID 格式"));
|
||||
}
|
||||
}
|
||||
let snapshot = self
|
||||
.store
|
||||
.load_instances()
|
||||
.await
|
||||
.map_err(|e| map_store_error(e, "plugin"))?;
|
||||
let existing = match id {
|
||||
Some(id) => Some(
|
||||
snapshot
|
||||
.instances
|
||||
.iter()
|
||||
.find(|instance| instance.id == id)
|
||||
.cloned()
|
||||
.ok_or_else(|| AdminError::not_found("插件实例不存在"))?,
|
||||
),
|
||||
None => input.creation_id.as_ref().and_then(|creation_id| {
|
||||
snapshot
|
||||
.instances
|
||||
.iter()
|
||||
.find(|instance| instance.id == *creation_id)
|
||||
.cloned()
|
||||
}),
|
||||
};
|
||||
if let Some(existing) = &existing {
|
||||
if id.is_none() && !same_creation_request(existing, &input) {
|
||||
return Err(AdminError::conflict("此配置已创建,请加载最新配置后编辑"));
|
||||
}
|
||||
if input
|
||||
.expected_revision
|
||||
.is_some_and(|revision| revision != existing.revision.get())
|
||||
{
|
||||
return Err(AdminError::conflict("插件配置已变更,请加载最新配置后重试"));
|
||||
}
|
||||
}
|
||||
self.configure_from_snapshot(snapshot, existing, input, context)
|
||||
.await
|
||||
}
|
||||
|
||||
pub(super) async fn configure_from_snapshot(
|
||||
&self,
|
||||
mut snapshot: PluginInstanceSnapshot,
|
||||
existing: Option<PluginInstance>,
|
||||
input: ConfigurePluginInstance,
|
||||
context: &MutationContext,
|
||||
) -> Result<PluginInstanceMutation, AdminError> {
|
||||
let expected_revision = snapshot.config_revision;
|
||||
let candidate_revision = next_revision(expected_revision)?;
|
||||
let artifacts = self
|
||||
.store
|
||||
.list_artifacts()
|
||||
.await
|
||||
.map_err(|error| map_store_error(error, "plugin"))?;
|
||||
let artifact = artifacts
|
||||
.iter()
|
||||
.find(|artifact| artifact.metadata.sha256 == input.artifact_sha256)
|
||||
.ok_or_else(|| AdminError::not_found("插件制品不存在"))?;
|
||||
if artifact.accepted_at.is_none() {
|
||||
return Err(AdminError::invalid("请先安装并接受该版本声明的权限"));
|
||||
}
|
||||
if input.enabled
|
||||
&& let Some(warning) = self
|
||||
.package_status(&input.artifact_sha256)
|
||||
.await?
|
||||
.load_error
|
||||
{
|
||||
return Err(AdminError::invalid(format!(
|
||||
"{warning},无法启动,请安装兼容版本"
|
||||
)));
|
||||
}
|
||||
let same_plugin = |digest: &str| {
|
||||
artifacts.iter().any(|item| {
|
||||
item.metadata.sha256 == digest
|
||||
&& item.metadata.plugin_id == artifact.metadata.plugin_id
|
||||
})
|
||||
};
|
||||
if existing
|
||||
.as_ref()
|
||||
.is_some_and(|previous| !same_plugin(&previous.artifact_sha256))
|
||||
{
|
||||
return Err(AdminError::invalid("不能将已有配置切换为另一个插件"));
|
||||
}
|
||||
if input.enabled
|
||||
&& snapshot.instances.iter().any(|other| {
|
||||
other.enabled
|
||||
&& existing
|
||||
.as_ref()
|
||||
.is_none_or(|current| current.id != other.id)
|
||||
&& same_plugin(&other.artifact_sha256)
|
||||
&& !input
|
||||
.replace_instances
|
||||
.iter()
|
||||
.any(|replacement| replacement.id == other.id)
|
||||
})
|
||||
{
|
||||
return Err(AdminError::conflict(
|
||||
"此插件已有启用配置,请先切换或停用旧配置",
|
||||
));
|
||||
}
|
||||
let saved = if let Some(previous) = &existing
|
||||
&& previous.artifact_sha256 != input.artifact_sha256
|
||||
&& input.secrets.is_none()
|
||||
{
|
||||
self.store
|
||||
.load_version_configuration(&previous.id, &input.artifact_sha256)
|
||||
.await
|
||||
.map_err(|error| map_store_error(error, "plugin"))?
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let instance = PluginInstance {
|
||||
id: existing.as_ref().map_or_else(
|
||||
|| {
|
||||
input
|
||||
.creation_id
|
||||
.clone()
|
||||
.unwrap_or_else(|| uuid::Uuid::now_v7().to_string())
|
||||
},
|
||||
|instance| instance.id.clone(),
|
||||
),
|
||||
name: input.name.trim().to_owned(),
|
||||
artifact_sha256: input.artifact_sha256,
|
||||
enabled: input.enabled,
|
||||
trusted_process: true,
|
||||
configuration: input.configuration,
|
||||
secrets: input
|
||||
.secrets
|
||||
.or_else(|| saved.map(|saved| saved.secrets))
|
||||
.unwrap_or_else(|| {
|
||||
existing
|
||||
.as_ref()
|
||||
.map_or_else(Default::default, |instance| instance.secrets.clone())
|
||||
}),
|
||||
bindings: input.bindings,
|
||||
revision: candidate_revision,
|
||||
};
|
||||
validate_input(&instance)?;
|
||||
if existing
|
||||
.as_ref()
|
||||
.is_some_and(|previous| previous.artifact_sha256 != instance.artifact_sha256)
|
||||
&& !self
|
||||
.preparation
|
||||
.configuration_ready(instance.clone(), &artifact.metadata)
|
||||
.await?
|
||||
{
|
||||
return Err(AdminError::invalid(
|
||||
"目标版本仍缺少必填设置,请补充后再切换",
|
||||
));
|
||||
}
|
||||
|
||||
let replacements = input.replace_instances;
|
||||
if !replacements.is_empty() {
|
||||
if !instance.enabled || replacements.len() > 256 {
|
||||
return Err(AdminError::invalid(
|
||||
"仅启用配置时可以切换其他配置,单次最多 256 项",
|
||||
));
|
||||
}
|
||||
let mut ids = BTreeSet::new();
|
||||
for replacement in &replacements {
|
||||
if replacement.id == instance.id || !ids.insert(&replacement.id) {
|
||||
return Err(AdminError::invalid("停用列表不能重复或包含当前配置"));
|
||||
}
|
||||
let previous = snapshot
|
||||
.instances
|
||||
.iter()
|
||||
.find(|item| item.id == replacement.id)
|
||||
.ok_or_else(|| AdminError::conflict("待停用配置已变更,请重新确认"))?;
|
||||
if !previous.enabled || previous.revision.get() != replacement.expected_revision {
|
||||
return Err(AdminError::conflict("待停用配置已变更,请重新确认"));
|
||||
}
|
||||
if !artifacts.iter().any(|item| {
|
||||
item.metadata.sha256 == previous.artifact_sha256
|
||||
&& item.metadata.plugin_id == artifact.metadata.plugin_id
|
||||
}) {
|
||||
return Err(AdminError::invalid("只能切换同一插件的配置"));
|
||||
}
|
||||
}
|
||||
}
|
||||
let state = self.preparation.validate(instance.clone()).await?;
|
||||
if let Some(existing) = &existing
|
||||
&& self.state.transition_required(&existing.id, &state).await?
|
||||
{
|
||||
return self
|
||||
.configure_instance_with_state_transition(
|
||||
snapshot,
|
||||
existing.clone(),
|
||||
instance,
|
||||
state,
|
||||
&replacements,
|
||||
context,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
snapshot.instances.retain(|item| item.id != instance.id);
|
||||
snapshot.instances.push(instance.clone());
|
||||
snapshot.config_revision = candidate_revision;
|
||||
apply_replacements(&mut snapshot, &replacements);
|
||||
let prepared = self.preparation.prepare(snapshot.clone()).await?;
|
||||
let result = self
|
||||
.store
|
||||
.save_instance_replacing(
|
||||
instance,
|
||||
expected_revision,
|
||||
PluginStateCommit {
|
||||
configuration: state,
|
||||
transition_id: None,
|
||||
},
|
||||
&replacements,
|
||||
context,
|
||||
)
|
||||
.await
|
||||
.map_err(|e| map_store_error(e, "plugin"))?;
|
||||
self.publish_instance(snapshot, prepared, &result, &replacements)
|
||||
.await?;
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
async fn configure_instance_with_state_transition(
|
||||
&self,
|
||||
mut snapshot: PluginInstanceSnapshot,
|
||||
previous: PluginInstance,
|
||||
mut target: PluginInstance,
|
||||
target_state: PluginStateConfiguration,
|
||||
replacements: &[PluginInstanceReplacement],
|
||||
context: &MutationContext,
|
||||
) -> Result<PluginInstanceMutation, AdminError> {
|
||||
let previous_state = self.preparation.validate(previous.clone()).await?;
|
||||
let original_revision = snapshot.config_revision;
|
||||
// 即使最终保持停用,迁移也必须由目标制品的受控候选执行
|
||||
let mut migration_instance = target.clone();
|
||||
migration_instance.enabled = true;
|
||||
snapshot.config_revision = migration_instance.revision;
|
||||
snapshot
|
||||
.instances
|
||||
.retain(|instance| instance.id != migration_instance.id);
|
||||
snapshot.instances.push(migration_instance);
|
||||
apply_replacements(&mut snapshot, replacements);
|
||||
let migration_prepared = self.preparation.prepare(snapshot).await?;
|
||||
|
||||
let mut disabled_revision = None;
|
||||
let disabled = if previous.enabled {
|
||||
let mut disabled = previous.clone();
|
||||
disabled.enabled = false;
|
||||
let mutation = self
|
||||
.store
|
||||
.save_instance_with_state(
|
||||
disabled,
|
||||
original_revision,
|
||||
PluginStateCommit {
|
||||
configuration: previous_state.clone(),
|
||||
transition_id: None,
|
||||
},
|
||||
context,
|
||||
)
|
||||
.await
|
||||
.map_err(|error| map_store_error(error, "plugin"))?;
|
||||
publish_committed(self.snapshots.as_ref(), mutation.config_revision).await?;
|
||||
self.preparation
|
||||
.quiesce_instance(&previous.id, &previous.artifact_sha256, previous.revision)
|
||||
.await;
|
||||
disabled_revision = Some(mutation.config_revision);
|
||||
mutation.instance
|
||||
} else {
|
||||
previous.clone()
|
||||
};
|
||||
let expected_revision = disabled_revision.unwrap_or(original_revision);
|
||||
let transition = match self
|
||||
.state
|
||||
.begin_transition(
|
||||
&disabled.id,
|
||||
disabled.revision,
|
||||
&target.artifact_sha256,
|
||||
target_state.clone(),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(transition) => transition,
|
||||
Err(error) => {
|
||||
return Err(self
|
||||
.recover_failed_state_transition(
|
||||
None,
|
||||
&previous,
|
||||
&previous_state,
|
||||
disabled_revision,
|
||||
context,
|
||||
error,
|
||||
)
|
||||
.await);
|
||||
}
|
||||
};
|
||||
// 迁移开始后的所有提交前失败都走同一恢复出口;提交成功后不再回滚旧配置
|
||||
let committed = async {
|
||||
self.preparation
|
||||
.migrate_state(&migration_prepared, transition.clone())
|
||||
.await?;
|
||||
let mut current = self
|
||||
.store
|
||||
.load_instances()
|
||||
.await
|
||||
.map_err(|error| map_store_error(error, "plugin"))?;
|
||||
if current.config_revision != expected_revision {
|
||||
return Err(AdminError::conflict("迁移期间插件配置已发生变化"));
|
||||
}
|
||||
let candidate_revision = next_revision(expected_revision)?;
|
||||
target.revision = candidate_revision;
|
||||
current.instances.retain(|item| item.id != target.id);
|
||||
current.instances.push(target.clone());
|
||||
current.config_revision = candidate_revision;
|
||||
apply_replacements(&mut current, replacements);
|
||||
let prepared = self.preparation.prepare(current.clone()).await?;
|
||||
let result = self
|
||||
.store
|
||||
.save_instance_replacing(
|
||||
target,
|
||||
expected_revision,
|
||||
PluginStateCommit {
|
||||
configuration: target_state,
|
||||
transition_id: Some(transition.id.clone()),
|
||||
},
|
||||
replacements,
|
||||
context,
|
||||
)
|
||||
.await
|
||||
.map_err(|error| map_store_error(error, "plugin"))?;
|
||||
Ok((current, prepared, result))
|
||||
}
|
||||
.await;
|
||||
let (current, prepared, result) = match committed {
|
||||
Ok(committed) => committed,
|
||||
Err(error) => {
|
||||
return Err(self
|
||||
.recover_failed_state_transition(
|
||||
Some(&transition.id),
|
||||
&previous,
|
||||
&previous_state,
|
||||
disabled_revision,
|
||||
context,
|
||||
error,
|
||||
)
|
||||
.await);
|
||||
}
|
||||
};
|
||||
self.publish_instance(current, prepared, &result, replacements)
|
||||
.await?;
|
||||
drop(migration_prepared);
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
async fn recover_failed_state_transition(
|
||||
&self,
|
||||
transition_id: Option<&str>,
|
||||
previous: &PluginInstance,
|
||||
previous_state: &PluginStateConfiguration,
|
||||
disabled_revision: Option<Revision>,
|
||||
context: &MutationContext,
|
||||
original_error: AdminError,
|
||||
) -> AdminError {
|
||||
if let Some(transition_id) = transition_id {
|
||||
self.state.abort_transition(transition_id).await;
|
||||
}
|
||||
let Some(disabled_revision) = disabled_revision else {
|
||||
return original_error;
|
||||
};
|
||||
let restored = async {
|
||||
let mut snapshot = self
|
||||
.store
|
||||
.load_instances()
|
||||
.await
|
||||
.map_err(|error| map_store_error(error, "plugin"))?;
|
||||
if snapshot.config_revision != disabled_revision {
|
||||
return Err(AdminError::conflict(
|
||||
"状态迁移失败;实例已保持停用,且配置已被其他操作修改",
|
||||
));
|
||||
}
|
||||
let candidate_revision = next_revision(disabled_revision)?;
|
||||
let mut restore = previous.clone();
|
||||
restore.enabled = true;
|
||||
restore.revision = candidate_revision;
|
||||
snapshot.instances.retain(|item| item.id != restore.id);
|
||||
snapshot.instances.push(restore.clone());
|
||||
snapshot.config_revision = candidate_revision;
|
||||
let prepared = self.preparation.prepare(snapshot.clone()).await?;
|
||||
let mutation = self
|
||||
.store
|
||||
.save_instance_with_state(
|
||||
restore,
|
||||
disabled_revision,
|
||||
PluginStateCommit {
|
||||
configuration: previous_state.clone(),
|
||||
transition_id: None,
|
||||
},
|
||||
context,
|
||||
)
|
||||
.await
|
||||
.map_err(|error| map_store_error(error, "plugin"))?;
|
||||
self.publish_instance(snapshot, prepared, &mutation, &[])
|
||||
.await?;
|
||||
Ok::<(), AdminError>(())
|
||||
}
|
||||
.await;
|
||||
match restored {
|
||||
Ok(()) => original_error,
|
||||
Err(error) => {
|
||||
tracing::warn!(
|
||||
error_kind = ?error.kind(),
|
||||
"plugin state migration failed and the previous instance could not be restored"
|
||||
);
|
||||
AdminError::conflict("状态迁移失败;为避免覆盖并发配置,插件实例已保持停用")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 以事务返回的版本激活并发布,候选强引用必须覆盖整个提交后阶段
|
||||
async fn publish_instance(
|
||||
&self,
|
||||
mut snapshot: PluginInstanceSnapshot,
|
||||
prepared: ExtensionSetReference,
|
||||
mutation: &PluginInstanceMutation,
|
||||
replacements: &[PluginInstanceReplacement],
|
||||
) -> Result<(), AdminError> {
|
||||
let prepared = if mutation.config_revision == snapshot.config_revision
|
||||
&& mutation.instance.revision == snapshot.config_revision
|
||||
{
|
||||
prepared
|
||||
} else {
|
||||
snapshot.config_revision = mutation.config_revision;
|
||||
snapshot
|
||||
.instances
|
||||
.retain(|item| item.id != mutation.instance.id);
|
||||
snapshot.instances.push(mutation.instance.clone());
|
||||
apply_replacements(&mut snapshot, replacements);
|
||||
self.preparation.prepare(snapshot).await?
|
||||
};
|
||||
self.preparation
|
||||
.activate_state(&prepared, &mutation.instance)
|
||||
.await?;
|
||||
publish_committed(self.snapshots.as_ref(), mutation.config_revision).await?;
|
||||
drop(prepared);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn delete_instance(
|
||||
&self,
|
||||
id: &str,
|
||||
context: &MutationContext,
|
||||
) -> Result<Revision, AdminError> {
|
||||
let snapshot = self
|
||||
.store
|
||||
.load_instances()
|
||||
.await
|
||||
.map_err(|e| map_store_error(e, "plugin"))?;
|
||||
let instance = snapshot
|
||||
.instances
|
||||
.iter()
|
||||
.find(|instance| instance.id == id)
|
||||
.ok_or_else(|| AdminError::not_found("插件实例不存在"))?;
|
||||
if instance.enabled {
|
||||
return Err(AdminError::conflict("请先停用插件实例"));
|
||||
}
|
||||
let revision = self
|
||||
.store
|
||||
.delete_instance(id, snapshot.config_revision, context)
|
||||
.await
|
||||
.map_err(|e| map_store_error(e, "plugin"))?;
|
||||
publish_committed(self.snapshots.as_ref(), revision).await?;
|
||||
Ok(revision)
|
||||
}
|
||||
|
||||
/// 紧急管理修复不要求损坏插件成功准备;提交后沿用现有发布与暂停合同
|
||||
pub async fn disable_instance(
|
||||
&self,
|
||||
id: &str,
|
||||
context: &MutationContext,
|
||||
) -> Result<PluginInstanceMutation, AdminError> {
|
||||
let PluginInstanceSnapshot {
|
||||
config_revision,
|
||||
instances,
|
||||
} = self
|
||||
.store
|
||||
.load_instances()
|
||||
.await
|
||||
.map_err(|e| map_store_error(e, "plugin"))?;
|
||||
let mut instance = instances
|
||||
.into_iter()
|
||||
.find(|instance| instance.id == id)
|
||||
.ok_or_else(|| AdminError::not_found("插件实例不存在"))?;
|
||||
instance.enabled = false;
|
||||
let result = self
|
||||
.store
|
||||
.save_instance(instance, config_revision, context)
|
||||
.await
|
||||
.map_err(|e| map_store_error(e, "plugin"))?;
|
||||
publish_committed(self.snapshots.as_ref(), result.config_revision).await?;
|
||||
Ok(result)
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_replacements(
|
||||
snapshot: &mut PluginInstanceSnapshot,
|
||||
replacements: &[PluginInstanceReplacement],
|
||||
) {
|
||||
for instance in &mut snapshot.instances {
|
||||
if replacements.iter().any(|item| item.id == instance.id) {
|
||||
instance.enabled = false;
|
||||
instance.revision = snapshot.config_revision;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn same_creation_request(existing: &PluginInstance, input: &ConfigurePluginInstance) -> bool {
|
||||
let same_secrets = input
|
||||
.secrets
|
||||
.as_ref()
|
||||
.map_or(existing.secrets.is_empty(), |secrets| {
|
||||
secrets.len() == existing.secrets.len()
|
||||
&& secrets.iter().all(|(key, value)| {
|
||||
existing
|
||||
.secrets
|
||||
.get(key)
|
||||
.is_some_and(|current| current.expose_secret() == value.expose_secret())
|
||||
})
|
||||
});
|
||||
existing.name == input.name.trim()
|
||||
&& existing.artifact_sha256 == input.artifact_sha256
|
||||
&& existing.enabled == input.enabled
|
||||
&& existing.configuration == input.configuration
|
||||
&& existing.bindings == input.bindings
|
||||
&& same_secrets
|
||||
}
|
||||
|
||||
fn validate_input(instance: &PluginInstance) -> Result<(), AdminError> {
|
||||
if instance.name.is_empty()
|
||||
|| instance.name.len() > 128
|
||||
|| instance.name.chars().any(char::is_control)
|
||||
|| instance.artifact_sha256.len() != 64
|
||||
|| !instance
|
||||
.artifact_sha256
|
||||
.bytes()
|
||||
.all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
|
||||
|| !instance.configuration.is_object()
|
||||
|| serde_json::to_vec(&instance.configuration).map_or(true, |bytes| bytes.len() > 48 * 1024)
|
||||
|| instance.secrets.len() > 64
|
||||
|| instance.bindings.len() > 64
|
||||
{
|
||||
return Err(AdminError::invalid("插件实例配置不合法或超过大小限制"));
|
||||
}
|
||||
use secrecy::ExposeSecret as _;
|
||||
if instance
|
||||
.secrets
|
||||
.iter()
|
||||
.any(|(key, value)| key.len() > 64 || value.expose_secret().len() > 8192)
|
||||
|| instance
|
||||
.secrets
|
||||
.values()
|
||||
.map(|value| value.expose_secret().len())
|
||||
.sum::<usize>()
|
||||
> 48 * 1024
|
||||
{
|
||||
return Err(AdminError::invalid("插件敏感配置超过大小限制"));
|
||||
}
|
||||
if instance.bindings.iter().any(|binding| {
|
||||
binding.contribution.is_empty()
|
||||
|| binding.contribution.len() > 128
|
||||
|| !binding
|
||||
.contribution
|
||||
.bytes()
|
||||
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'-'))
|
||||
|| binding.client_key_ids.len() > 256
|
||||
|| binding.account_group_ids.len() > 256
|
||||
|| binding.client_key_ids.iter().collect::<BTreeSet<_>>().len()
|
||||
!= binding.client_key_ids.len()
|
||||
|| binding
|
||||
.account_group_ids
|
||||
.iter()
|
||||
.collect::<BTreeSet<_>>()
|
||||
.len()
|
||||
!= binding.account_group_ids.len()
|
||||
|| binding
|
||||
.client_key_ids
|
||||
.iter()
|
||||
.any(|id| ClientApiKeyId::new(id.clone()).is_err())
|
||||
|| binding
|
||||
.account_group_ids
|
||||
.iter()
|
||||
.any(|id| AccountGroupId::new(id.clone()).is_err())
|
||||
|| binding.identity_bindings.len() > 256
|
||||
|| binding
|
||||
.identity_bindings
|
||||
.iter()
|
||||
.map(|identity| &identity.principal)
|
||||
.collect::<BTreeSet<_>>()
|
||||
.len()
|
||||
!= binding.identity_bindings.len()
|
||||
|| binding.identity_bindings.iter().any(|identity| {
|
||||
identity.principal.trim() != identity.principal
|
||||
|| identity.principal.is_empty()
|
||||
|| identity.principal.len() > 256
|
||||
|| identity.principal.chars().any(char::is_control)
|
||||
|| ClientApiKeyId::new(identity.client_key_id.clone()).is_err()
|
||||
})
|
||||
}) {
|
||||
return Err(AdminError::invalid("插件绑定的范围或入口认证身份不合法"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn next_revision(revision: Revision) -> Result<Revision, AdminError> {
|
||||
Revision::new(
|
||||
revision
|
||||
.get()
|
||||
.checked_add(1)
|
||||
.ok_or_else(|| AdminError::internal("配置版本已耗尽"))?,
|
||||
)
|
||||
.map_err(|_| AdminError::internal("配置版本不合法"))
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
//! 插件配置的输入约束、创建幂等比较与候选快照变换
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use gateway_core::{policy::ClientApiKeyId, routing::AccountGroupId};
|
||||
use secrecy::ExposeSecret;
|
||||
|
||||
use crate::model::{
|
||||
AdminError, Revision,
|
||||
plugins::instances::{
|
||||
ConfigurePluginInstance, PluginInstance, PluginInstanceReplacement, PluginInstanceSnapshot,
|
||||
},
|
||||
};
|
||||
|
||||
pub(super) fn apply_replacements(
|
||||
snapshot: &mut PluginInstanceSnapshot,
|
||||
replacements: &[PluginInstanceReplacement],
|
||||
) {
|
||||
for instance in &mut snapshot.instances {
|
||||
if replacements.iter().any(|item| item.id == instance.id) {
|
||||
instance.enabled = false;
|
||||
instance.revision = snapshot.config_revision;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn same_creation_request(
|
||||
existing: &PluginInstance,
|
||||
input: &ConfigurePluginInstance,
|
||||
) -> bool {
|
||||
let same_secrets = input
|
||||
.secrets
|
||||
.as_ref()
|
||||
.map_or(existing.secrets.is_empty(), |secrets| {
|
||||
secrets.len() == existing.secrets.len()
|
||||
&& secrets.iter().all(|(key, value)| {
|
||||
existing
|
||||
.secrets
|
||||
.get(key)
|
||||
.is_some_and(|current| current.expose_secret() == value.expose_secret())
|
||||
})
|
||||
});
|
||||
existing.name == input.name.trim()
|
||||
&& existing.artifact_sha256 == input.artifact_sha256
|
||||
&& existing.enabled == input.enabled
|
||||
&& existing.configuration == input.configuration
|
||||
&& existing.bindings == input.bindings
|
||||
&& same_secrets
|
||||
}
|
||||
|
||||
pub(super) fn validate_input(instance: &PluginInstance) -> Result<(), AdminError> {
|
||||
if instance.name.is_empty()
|
||||
|| instance.name.len() > 128
|
||||
|| instance.name.chars().any(char::is_control)
|
||||
|| instance.artifact_sha256.len() != 64
|
||||
|| !instance
|
||||
.artifact_sha256
|
||||
.bytes()
|
||||
.all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
|
||||
|| !instance.configuration.is_object()
|
||||
|| serde_json::to_vec(&instance.configuration).map_or(true, |bytes| bytes.len() > 48 * 1024)
|
||||
|| instance.secrets.len() > 64
|
||||
|| instance.bindings.len() > 64
|
||||
{
|
||||
return Err(AdminError::invalid("插件实例配置不合法或超过大小限制"));
|
||||
}
|
||||
use secrecy::ExposeSecret as _;
|
||||
if instance
|
||||
.secrets
|
||||
.iter()
|
||||
.any(|(key, value)| key.len() > 64 || value.expose_secret().len() > 8192)
|
||||
|| instance
|
||||
.secrets
|
||||
.values()
|
||||
.map(|value| value.expose_secret().len())
|
||||
.sum::<usize>()
|
||||
> 48 * 1024
|
||||
{
|
||||
return Err(AdminError::invalid("插件敏感配置超过大小限制"));
|
||||
}
|
||||
if instance.bindings.iter().any(|binding| {
|
||||
binding.contribution.is_empty()
|
||||
|| binding.contribution.len() > 128
|
||||
|| !binding
|
||||
.contribution
|
||||
.bytes()
|
||||
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'-'))
|
||||
|| binding.client_key_ids.len() > 256
|
||||
|| binding.account_group_ids.len() > 256
|
||||
|| binding.client_key_ids.iter().collect::<BTreeSet<_>>().len()
|
||||
!= binding.client_key_ids.len()
|
||||
|| binding
|
||||
.account_group_ids
|
||||
.iter()
|
||||
.collect::<BTreeSet<_>>()
|
||||
.len()
|
||||
!= binding.account_group_ids.len()
|
||||
|| binding
|
||||
.client_key_ids
|
||||
.iter()
|
||||
.any(|id| ClientApiKeyId::new(id.clone()).is_err())
|
||||
|| binding
|
||||
.account_group_ids
|
||||
.iter()
|
||||
.any(|id| AccountGroupId::new(id.clone()).is_err())
|
||||
|| binding.identity_bindings.len() > 256
|
||||
|| binding
|
||||
.identity_bindings
|
||||
.iter()
|
||||
.map(|identity| &identity.principal)
|
||||
.collect::<BTreeSet<_>>()
|
||||
.len()
|
||||
!= binding.identity_bindings.len()
|
||||
|| binding.identity_bindings.iter().any(|identity| {
|
||||
identity.principal.trim() != identity.principal
|
||||
|| identity.principal.is_empty()
|
||||
|| identity.principal.len() > 256
|
||||
|| identity.principal.chars().any(char::is_control)
|
||||
|| ClientApiKeyId::new(identity.client_key_id.clone()).is_err()
|
||||
})
|
||||
}) {
|
||||
return Err(AdminError::invalid("插件绑定的范围或入口认证身份不合法"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn next_revision(revision: Revision) -> Result<Revision, AdminError> {
|
||||
Revision::new(
|
||||
revision
|
||||
.get()
|
||||
.checked_add(1)
|
||||
.ok_or_else(|| AdminError::internal("配置版本已耗尽"))?,
|
||||
)
|
||||
.map_err(|_| AdminError::internal("配置版本不合法"))
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
//! 插件私有状态迁移的排空、暂存提交与失败恢复编排
|
||||
|
||||
use super::{
|
||||
PluginsService,
|
||||
configuration::{apply_replacements, next_revision},
|
||||
};
|
||||
use crate::{
|
||||
model::{
|
||||
AdminError, MutationContext, Revision,
|
||||
plugins::{
|
||||
instances::{
|
||||
PluginCompatibilityConfirmation, PluginInstance, PluginInstanceMutation,
|
||||
PluginInstanceReplacement, PluginInstanceSnapshot,
|
||||
},
|
||||
state::{PluginStateCommit, PluginStateConfiguration},
|
||||
},
|
||||
},
|
||||
use_case::{map_store_error, publish_committed},
|
||||
};
|
||||
|
||||
impl PluginsService {
|
||||
pub(super) async fn configure_instance_with_state_transition(
|
||||
&self,
|
||||
mut snapshot: PluginInstanceSnapshot,
|
||||
mut target: PluginInstance,
|
||||
target_state: PluginStateConfiguration,
|
||||
replacements: &[PluginInstanceReplacement],
|
||||
confirmation: Option<&PluginCompatibilityConfirmation>,
|
||||
context: &MutationContext,
|
||||
) -> Result<PluginInstanceMutation, AdminError> {
|
||||
let previous = snapshot
|
||||
.instances
|
||||
.iter()
|
||||
.find(|instance| instance.id == target.id)
|
||||
.cloned()
|
||||
.ok_or_else(|| AdminError::not_found("插件实例不存在"))?;
|
||||
let previous_state = self.preparation.validate(previous.clone()).await?;
|
||||
let original_revision = snapshot.config_revision;
|
||||
// 即使最终保持停用,迁移也必须由目标制品的受控候选执行
|
||||
let mut migration_instance = target.clone();
|
||||
migration_instance.enabled = true;
|
||||
snapshot.config_revision = migration_instance.revision;
|
||||
snapshot
|
||||
.instances
|
||||
.retain(|instance| instance.id != migration_instance.id);
|
||||
snapshot.instances.push(migration_instance);
|
||||
apply_replacements(&mut snapshot, replacements);
|
||||
let migration_prepared = self
|
||||
.prepare_instance_candidate(snapshot, confirmation)
|
||||
.await?;
|
||||
|
||||
let mut disabled_revision = None;
|
||||
let disabled = if previous.enabled {
|
||||
let mut disabled = previous.clone();
|
||||
disabled.enabled = false;
|
||||
let mutation = self
|
||||
.store
|
||||
.save_instance_with_state(
|
||||
disabled,
|
||||
original_revision,
|
||||
PluginStateCommit {
|
||||
configuration: previous_state.clone(),
|
||||
transition_id: None,
|
||||
},
|
||||
context,
|
||||
)
|
||||
.await
|
||||
.map_err(|error| map_store_error(error, "plugin"))?;
|
||||
publish_committed(self.snapshots.as_ref(), mutation.config_revision).await?;
|
||||
self.preparation
|
||||
.quiesce_instance(&previous.id, &previous.artifact_sha256, previous.revision)
|
||||
.await;
|
||||
disabled_revision = Some(mutation.config_revision);
|
||||
mutation.instance
|
||||
} else {
|
||||
previous.clone()
|
||||
};
|
||||
let expected_revision = disabled_revision.unwrap_or(original_revision);
|
||||
let transition = match self
|
||||
.state
|
||||
.begin_transition(
|
||||
&disabled.id,
|
||||
disabled.revision,
|
||||
&target.artifact_sha256,
|
||||
target_state.clone(),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(transition) => transition,
|
||||
Err(error) => {
|
||||
return Err(self
|
||||
.recover_failed_state_transition(
|
||||
None,
|
||||
&previous,
|
||||
&previous_state,
|
||||
disabled_revision,
|
||||
context,
|
||||
error,
|
||||
)
|
||||
.await);
|
||||
}
|
||||
};
|
||||
// 迁移开始后的所有提交前失败都走同一恢复出口;提交成功后不再回滚旧配置
|
||||
let committed = async {
|
||||
self.preparation
|
||||
.migrate_state(&migration_prepared, transition.clone())
|
||||
.await?;
|
||||
let mut current = self
|
||||
.store
|
||||
.load_instances()
|
||||
.await
|
||||
.map_err(|error| map_store_error(error, "plugin"))?;
|
||||
if current.config_revision != expected_revision {
|
||||
return Err(AdminError::conflict("迁移期间插件配置已发生变化"));
|
||||
}
|
||||
let candidate_revision = next_revision(expected_revision)?;
|
||||
target.revision = candidate_revision;
|
||||
current.instances.retain(|item| item.id != target.id);
|
||||
current.instances.push(target.clone());
|
||||
current.config_revision = candidate_revision;
|
||||
apply_replacements(&mut current, replacements);
|
||||
let prepared = self
|
||||
.prepare_instance_candidate(current.clone(), confirmation)
|
||||
.await?;
|
||||
let result = self
|
||||
.store
|
||||
.save_instance_replacing(
|
||||
target,
|
||||
expected_revision,
|
||||
PluginStateCommit {
|
||||
configuration: target_state,
|
||||
transition_id: Some(transition.id.clone()),
|
||||
},
|
||||
replacements,
|
||||
context,
|
||||
)
|
||||
.await
|
||||
.map_err(|error| map_store_error(error, "plugin"))?;
|
||||
Ok((current, prepared, result))
|
||||
}
|
||||
.await;
|
||||
let (current, prepared, result) = match committed {
|
||||
Ok(committed) => committed,
|
||||
Err(error) => {
|
||||
return Err(self
|
||||
.recover_failed_state_transition(
|
||||
Some(&transition.id),
|
||||
&previous,
|
||||
&previous_state,
|
||||
disabled_revision,
|
||||
context,
|
||||
error,
|
||||
)
|
||||
.await);
|
||||
}
|
||||
};
|
||||
self.publish_instance(current, prepared, &result, replacements, confirmation)
|
||||
.await?;
|
||||
drop(migration_prepared);
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
async fn recover_failed_state_transition(
|
||||
&self,
|
||||
transition_id: Option<&str>,
|
||||
previous: &PluginInstance,
|
||||
previous_state: &PluginStateConfiguration,
|
||||
disabled_revision: Option<Revision>,
|
||||
context: &MutationContext,
|
||||
original_error: AdminError,
|
||||
) -> AdminError {
|
||||
if let Some(transition_id) = transition_id {
|
||||
self.state.abort_transition(transition_id).await;
|
||||
}
|
||||
let Some(disabled_revision) = disabled_revision else {
|
||||
return original_error;
|
||||
};
|
||||
let restored = async {
|
||||
let mut snapshot = self
|
||||
.store
|
||||
.load_instances()
|
||||
.await
|
||||
.map_err(|error| map_store_error(error, "plugin"))?;
|
||||
if snapshot.config_revision != disabled_revision {
|
||||
return Err(AdminError::conflict(
|
||||
"状态迁移失败;实例已保持停用,且配置已被其他操作修改",
|
||||
));
|
||||
}
|
||||
let candidate_revision = next_revision(disabled_revision)?;
|
||||
let mut restore = previous.clone();
|
||||
restore.enabled = true;
|
||||
restore.revision = candidate_revision;
|
||||
snapshot.instances.retain(|item| item.id != restore.id);
|
||||
snapshot.instances.push(restore.clone());
|
||||
snapshot.config_revision = candidate_revision;
|
||||
let prepared = self.preparation.prepare(snapshot.clone()).await?;
|
||||
let mutation = self
|
||||
.store
|
||||
.save_instance_with_state(
|
||||
restore,
|
||||
disabled_revision,
|
||||
PluginStateCommit {
|
||||
configuration: previous_state.clone(),
|
||||
transition_id: None,
|
||||
},
|
||||
context,
|
||||
)
|
||||
.await
|
||||
.map_err(|error| map_store_error(error, "plugin"))?;
|
||||
self.publish_instance(snapshot, prepared, &mutation, &[], None)
|
||||
.await?;
|
||||
Ok::<(), AdminError>(())
|
||||
}
|
||||
.await;
|
||||
match restored {
|
||||
Ok(()) => original_error,
|
||||
Err(error) => {
|
||||
tracing::warn!(
|
||||
error_kind = ?error.kind(),
|
||||
"plugin state migration failed and the previous instance could not be restored"
|
||||
);
|
||||
AdminError::conflict("状态迁移失败;为避免覆盖并发配置,插件实例已保持停用")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
//! 插件实例用例的职责边界与静态检查结果
|
||||
|
||||
mod configuration;
|
||||
mod migration;
|
||||
mod mutations;
|
||||
mod publication;
|
||||
mod queries;
|
||||
|
||||
use super::PluginsService;
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
pub(super) struct PackageStatus {
|
||||
pub(super) warning: Option<String>,
|
||||
pub(super) load_error: Option<String>,
|
||||
}
|
||||
@@ -0,0 +1,333 @@
|
||||
//! 插件实例的配置提交、发布、停用与删除用例
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use super::{
|
||||
PluginsService,
|
||||
configuration::{apply_replacements, next_revision, same_creation_request, validate_input},
|
||||
};
|
||||
use crate::{
|
||||
model::{
|
||||
AdminError, MutationContext, Revision,
|
||||
plugins::{
|
||||
instances::{
|
||||
ConfigurePluginInstance, PluginInstance, PluginInstanceMutation,
|
||||
PluginInstanceSnapshot,
|
||||
},
|
||||
state::PluginStateCommit,
|
||||
},
|
||||
},
|
||||
use_case::{map_store_error, publish_committed},
|
||||
};
|
||||
|
||||
impl PluginsService {
|
||||
pub async fn configure_instance(
|
||||
&self,
|
||||
id: Option<&str>,
|
||||
input: ConfigurePluginInstance,
|
||||
context: &MutationContext,
|
||||
) -> Result<PluginInstanceMutation, AdminError> {
|
||||
if id.is_some() && input.creation_id.is_some() {
|
||||
return Err(AdminError::invalid("编辑配置不能使用创建标识"));
|
||||
}
|
||||
if id.is_none() && input.expected_revision.is_some() {
|
||||
return Err(AdminError::invalid("创建配置不能指定已有配置版本"));
|
||||
}
|
||||
if let Some(creation_id) = &input.creation_id {
|
||||
let parsed = uuid::Uuid::parse_str(creation_id)
|
||||
.map_err(|_| AdminError::invalid("配置创建标识必须是 UUID"))?;
|
||||
if parsed.to_string() != *creation_id {
|
||||
return Err(AdminError::invalid("配置创建标识必须使用标准 UUID 格式"));
|
||||
}
|
||||
}
|
||||
let snapshot = self
|
||||
.store
|
||||
.load_instances()
|
||||
.await
|
||||
.map_err(|e| map_store_error(e, "plugin"))?;
|
||||
let existing = match id {
|
||||
Some(id) => Some(
|
||||
snapshot
|
||||
.instances
|
||||
.iter()
|
||||
.find(|instance| instance.id == id)
|
||||
.cloned()
|
||||
.ok_or_else(|| AdminError::not_found("插件实例不存在"))?,
|
||||
),
|
||||
None => input.creation_id.as_ref().and_then(|creation_id| {
|
||||
snapshot
|
||||
.instances
|
||||
.iter()
|
||||
.find(|instance| instance.id == *creation_id)
|
||||
.cloned()
|
||||
}),
|
||||
};
|
||||
if let Some(existing) = &existing {
|
||||
if id.is_none() && !same_creation_request(existing, &input) {
|
||||
return Err(AdminError::conflict("此配置已创建,请加载最新配置后编辑"));
|
||||
}
|
||||
if input
|
||||
.expected_revision
|
||||
.is_some_and(|revision| revision != existing.revision.get())
|
||||
{
|
||||
return Err(AdminError::conflict("插件配置已变更,请加载最新配置后重试"));
|
||||
}
|
||||
}
|
||||
self.configure_from_snapshot(snapshot, existing, input, context)
|
||||
.await
|
||||
}
|
||||
|
||||
pub(in crate::use_case::plugins) async fn configure_from_snapshot(
|
||||
&self,
|
||||
mut snapshot: PluginInstanceSnapshot,
|
||||
existing: Option<PluginInstance>,
|
||||
input: ConfigurePluginInstance,
|
||||
context: &MutationContext,
|
||||
) -> Result<PluginInstanceMutation, AdminError> {
|
||||
let expected_revision = snapshot.config_revision;
|
||||
let candidate_revision = next_revision(expected_revision)?;
|
||||
let artifacts = self
|
||||
.store
|
||||
.list_artifacts()
|
||||
.await
|
||||
.map_err(|error| map_store_error(error, "plugin"))?;
|
||||
let artifact = artifacts
|
||||
.iter()
|
||||
.find(|artifact| artifact.metadata.sha256 == input.artifact_sha256)
|
||||
.ok_or_else(|| AdminError::not_found("插件制品不存在"))?;
|
||||
if artifact.accepted_at.is_none() {
|
||||
return Err(AdminError::invalid("请先安装并确认完整信任该版本"));
|
||||
}
|
||||
let confirmation = input.compatibility_confirmation.as_ref();
|
||||
if let Some(confirmed) = confirmation
|
||||
&& (!input.enabled
|
||||
|| existing.as_ref().is_none_or(|instance| {
|
||||
instance.id != confirmed.instance_id
|
||||
|| instance.revision.get() != confirmed.instance_revision
|
||||
})
|
||||
|| input.artifact_sha256 != confirmed.artifact_sha256
|
||||
|| self.inspector.compatibility_host_fingerprint()? != confirmed.host_fingerprint)
|
||||
{
|
||||
return Err(AdminError::conflict(
|
||||
"宿主、插件包或配置已变化,请重新确认启动风险",
|
||||
));
|
||||
}
|
||||
if input.enabled {
|
||||
let status = self.package_status(&input.artifact_sha256).await?;
|
||||
if let Some(reason) = status.load_error {
|
||||
return Err(AdminError::invalid(format!(
|
||||
"{reason},无法启动,请安装兼容版本"
|
||||
)));
|
||||
}
|
||||
if let Some(reason) = status.warning
|
||||
&& confirmation.is_none()
|
||||
{
|
||||
return Err(AdminError::conflict(format!(
|
||||
"插件版本不兼容:{reason};请先确认启动风险"
|
||||
)));
|
||||
}
|
||||
}
|
||||
let same_plugin = |digest: &str| {
|
||||
artifacts.iter().any(|item| {
|
||||
item.metadata.sha256 == digest
|
||||
&& item.metadata.plugin_id == artifact.metadata.plugin_id
|
||||
})
|
||||
};
|
||||
if existing
|
||||
.as_ref()
|
||||
.is_some_and(|previous| !same_plugin(&previous.artifact_sha256))
|
||||
{
|
||||
return Err(AdminError::invalid("不能将已有配置切换为另一个插件"));
|
||||
}
|
||||
if input.enabled
|
||||
&& snapshot.instances.iter().any(|other| {
|
||||
other.enabled
|
||||
&& existing
|
||||
.as_ref()
|
||||
.is_none_or(|current| current.id != other.id)
|
||||
&& same_plugin(&other.artifact_sha256)
|
||||
&& !input
|
||||
.replace_instances
|
||||
.iter()
|
||||
.any(|replacement| replacement.id == other.id)
|
||||
})
|
||||
{
|
||||
return Err(AdminError::conflict(
|
||||
"此插件已有启用配置,请先切换或停用旧配置",
|
||||
));
|
||||
}
|
||||
let saved = if let Some(previous) = &existing
|
||||
&& previous.artifact_sha256 != input.artifact_sha256
|
||||
&& input.secrets.is_none()
|
||||
{
|
||||
self.store
|
||||
.load_version_configuration(&previous.id, &input.artifact_sha256)
|
||||
.await
|
||||
.map_err(|error| map_store_error(error, "plugin"))?
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let instance = PluginInstance {
|
||||
id: existing.as_ref().map_or_else(
|
||||
|| {
|
||||
input
|
||||
.creation_id
|
||||
.clone()
|
||||
.unwrap_or_else(|| uuid::Uuid::now_v7().to_string())
|
||||
},
|
||||
|instance| instance.id.clone(),
|
||||
),
|
||||
name: input.name.trim().to_owned(),
|
||||
artifact_sha256: input.artifact_sha256,
|
||||
enabled: input.enabled,
|
||||
trusted_process: true,
|
||||
configuration: input.configuration,
|
||||
secrets: input
|
||||
.secrets
|
||||
.or_else(|| saved.map(|saved| saved.secrets))
|
||||
.unwrap_or_else(|| {
|
||||
existing
|
||||
.as_ref()
|
||||
.map_or_else(Default::default, |instance| instance.secrets.clone())
|
||||
}),
|
||||
bindings: input.bindings,
|
||||
revision: candidate_revision,
|
||||
};
|
||||
validate_input(&instance)?;
|
||||
if existing
|
||||
.as_ref()
|
||||
.is_some_and(|previous| previous.artifact_sha256 != instance.artifact_sha256)
|
||||
&& !self
|
||||
.preparation
|
||||
.configuration_ready(instance.clone(), &artifact.metadata)
|
||||
.await?
|
||||
{
|
||||
return Err(AdminError::invalid(
|
||||
"目标版本仍缺少必填设置,请补充后再切换",
|
||||
));
|
||||
}
|
||||
|
||||
let replacements = input.replace_instances;
|
||||
if !replacements.is_empty() {
|
||||
if !instance.enabled || replacements.len() > 256 {
|
||||
return Err(AdminError::invalid(
|
||||
"仅启用配置时可以切换其他配置,单次最多 256 项",
|
||||
));
|
||||
}
|
||||
let mut ids = BTreeSet::new();
|
||||
for replacement in &replacements {
|
||||
if replacement.id == instance.id || !ids.insert(&replacement.id) {
|
||||
return Err(AdminError::invalid("停用列表不能重复或包含当前配置"));
|
||||
}
|
||||
let previous = snapshot
|
||||
.instances
|
||||
.iter()
|
||||
.find(|item| item.id == replacement.id)
|
||||
.ok_or_else(|| AdminError::conflict("待停用配置已变更,请重新确认"))?;
|
||||
if !previous.enabled || previous.revision.get() != replacement.expected_revision {
|
||||
return Err(AdminError::conflict("待停用配置已变更,请重新确认"));
|
||||
}
|
||||
if !artifacts.iter().any(|item| {
|
||||
item.metadata.sha256 == previous.artifact_sha256
|
||||
&& item.metadata.plugin_id == artifact.metadata.plugin_id
|
||||
}) {
|
||||
return Err(AdminError::invalid("只能切换同一插件的配置"));
|
||||
}
|
||||
}
|
||||
}
|
||||
let state = self.preparation.validate(instance.clone()).await?;
|
||||
if let Some(existing) = &existing
|
||||
&& self.state.transition_required(&existing.id, &state).await?
|
||||
{
|
||||
return self
|
||||
.configure_instance_with_state_transition(
|
||||
snapshot,
|
||||
instance,
|
||||
state,
|
||||
&replacements,
|
||||
confirmation,
|
||||
context,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
snapshot.instances.retain(|item| item.id != instance.id);
|
||||
snapshot.instances.push(instance.clone());
|
||||
snapshot.config_revision = candidate_revision;
|
||||
apply_replacements(&mut snapshot, &replacements);
|
||||
let prepared = self
|
||||
.prepare_instance_candidate(snapshot.clone(), confirmation)
|
||||
.await?;
|
||||
let result = self
|
||||
.store
|
||||
.save_instance_replacing(
|
||||
instance,
|
||||
expected_revision,
|
||||
PluginStateCommit {
|
||||
configuration: state,
|
||||
transition_id: None,
|
||||
},
|
||||
&replacements,
|
||||
context,
|
||||
)
|
||||
.await
|
||||
.map_err(|e| map_store_error(e, "plugin"))?;
|
||||
self.publish_instance(snapshot, prepared, &result, &replacements, confirmation)
|
||||
.await?;
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
pub async fn delete_instance(
|
||||
&self,
|
||||
id: &str,
|
||||
context: &MutationContext,
|
||||
) -> Result<Revision, AdminError> {
|
||||
let snapshot = self
|
||||
.store
|
||||
.load_instances()
|
||||
.await
|
||||
.map_err(|e| map_store_error(e, "plugin"))?;
|
||||
let instance = snapshot
|
||||
.instances
|
||||
.iter()
|
||||
.find(|instance| instance.id == id)
|
||||
.ok_or_else(|| AdminError::not_found("插件实例不存在"))?;
|
||||
if instance.enabled {
|
||||
return Err(AdminError::conflict("请先停用插件实例"));
|
||||
}
|
||||
let revision = self
|
||||
.store
|
||||
.delete_instance(id, snapshot.config_revision, context)
|
||||
.await
|
||||
.map_err(|e| map_store_error(e, "plugin"))?;
|
||||
publish_committed(self.snapshots.as_ref(), revision).await?;
|
||||
Ok(revision)
|
||||
}
|
||||
|
||||
/// 紧急管理修复不要求损坏插件成功准备;提交后沿用现有发布与暂停合同
|
||||
pub async fn disable_instance(
|
||||
&self,
|
||||
id: &str,
|
||||
context: &MutationContext,
|
||||
) -> Result<PluginInstanceMutation, AdminError> {
|
||||
let PluginInstanceSnapshot {
|
||||
config_revision,
|
||||
instances,
|
||||
} = self
|
||||
.store
|
||||
.load_instances()
|
||||
.await
|
||||
.map_err(|e| map_store_error(e, "plugin"))?;
|
||||
let mut instance = instances
|
||||
.into_iter()
|
||||
.find(|instance| instance.id == id)
|
||||
.ok_or_else(|| AdminError::not_found("插件实例不存在"))?;
|
||||
instance.enabled = false;
|
||||
let result = self
|
||||
.store
|
||||
.save_instance(instance, config_revision, context)
|
||||
.await
|
||||
.map_err(|e| map_store_error(e, "plugin"))?;
|
||||
publish_committed(self.snapshots.as_ref(), result.config_revision).await?;
|
||||
Ok(result)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
//! 配置提交与迁移恢复共用的状态激活和发布收尾
|
||||
|
||||
use gateway_core::routing::extensions::ExtensionSetReference;
|
||||
|
||||
use super::{PluginsService, configuration::apply_replacements};
|
||||
use crate::{
|
||||
model::{
|
||||
AdminError,
|
||||
plugins::instances::{
|
||||
PluginCompatibilityConfirmation, PluginInstanceMutation, PluginInstanceReplacement,
|
||||
PluginInstanceSnapshot,
|
||||
},
|
||||
},
|
||||
use_case::publish_committed,
|
||||
};
|
||||
|
||||
impl PluginsService {
|
||||
pub(super) async fn prepare_instance_candidate(
|
||||
&self,
|
||||
snapshot: PluginInstanceSnapshot,
|
||||
confirmation: Option<&PluginCompatibilityConfirmation>,
|
||||
) -> Result<ExtensionSetReference, AdminError> {
|
||||
match confirmation {
|
||||
Some(confirmation) => {
|
||||
self.preparation
|
||||
.prepare_confirmed(snapshot, confirmation.clone())
|
||||
.await
|
||||
}
|
||||
None => self.preparation.prepare(snapshot).await,
|
||||
}
|
||||
}
|
||||
|
||||
/// 以事务返回的版本激活并发布,候选强引用必须覆盖整个提交后阶段
|
||||
pub(super) async fn publish_instance(
|
||||
&self,
|
||||
mut snapshot: PluginInstanceSnapshot,
|
||||
prepared: ExtensionSetReference,
|
||||
mutation: &PluginInstanceMutation,
|
||||
replacements: &[PluginInstanceReplacement],
|
||||
confirmation: Option<&PluginCompatibilityConfirmation>,
|
||||
) -> Result<(), AdminError> {
|
||||
let prepared = if mutation.config_revision == snapshot.config_revision
|
||||
&& mutation.instance.revision == snapshot.config_revision
|
||||
{
|
||||
prepared
|
||||
} else {
|
||||
snapshot.config_revision = mutation.config_revision;
|
||||
snapshot
|
||||
.instances
|
||||
.retain(|item| item.id != mutation.instance.id);
|
||||
snapshot.instances.push(mutation.instance.clone());
|
||||
apply_replacements(&mut snapshot, replacements);
|
||||
self.prepare_instance_candidate(snapshot, confirmation)
|
||||
.await?
|
||||
};
|
||||
self.preparation
|
||||
.activate_state(&prepared, &mutation.instance)
|
||||
.await?;
|
||||
publish_committed(self.snapshots.as_ref(), mutation.config_revision).await?;
|
||||
drop(prepared);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
//! 插件实例列表与静态包检查的只读投影,不从发布事实推断进程状态
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use super::{PackageStatus, PluginsService};
|
||||
use crate::{
|
||||
model::{
|
||||
AdminError, AdminErrorKind,
|
||||
plugins::instances::{
|
||||
PluginInstanceRuntime, PluginInstanceRuntimeStatus, PluginInstanceView,
|
||||
},
|
||||
},
|
||||
use_case::map_store_error,
|
||||
};
|
||||
|
||||
impl PluginsService {
|
||||
/// 只校验固定包体,不启动插件;停用实例也需区分兼容性提醒与加载错误
|
||||
pub(in crate::use_case::plugins) async fn package_status(
|
||||
&self,
|
||||
digest: &str,
|
||||
) -> Result<PackageStatus, AdminError> {
|
||||
// 运行宿主和摘要固定,缓存纯静态结论,避免管理页轮询反复解包
|
||||
// 只缓存有限数量的确定结果,暂时性错误仍可重试
|
||||
if let Some(status) = self.compatibility.lock().await.get(digest).cloned() {
|
||||
return Ok(status);
|
||||
}
|
||||
let artifact = self
|
||||
.store
|
||||
.load_artifact(digest)
|
||||
.await
|
||||
.map_err(|error| map_store_error(error, "plugin"))?;
|
||||
let status = match self
|
||||
.inspector
|
||||
.compatibility_warning(artifact.archive, digest.to_owned())
|
||||
.await
|
||||
{
|
||||
Ok(warning) => PackageStatus {
|
||||
warning,
|
||||
load_error: None,
|
||||
},
|
||||
Err(error) if error.kind() == AdminErrorKind::Invalid => PackageStatus {
|
||||
warning: None,
|
||||
load_error: Some(error.message().to_owned()),
|
||||
},
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
let mut cache = self.compatibility.lock().await;
|
||||
if cache.len() < 128 {
|
||||
cache.insert(digest.to_owned(), status.clone());
|
||||
}
|
||||
Ok(status)
|
||||
}
|
||||
|
||||
pub async fn instances(&self) -> Result<Vec<PluginInstanceView>, AdminError> {
|
||||
let snapshot = self
|
||||
.store
|
||||
.load_instances()
|
||||
.await
|
||||
.map_err(|e| map_store_error(e, "plugin"))?;
|
||||
let published = self.published.snapshot_for_diagnostics();
|
||||
let published_revision = published.as_ref().map(|snapshot| snapshot.revision().get());
|
||||
let mut diagnostics = self
|
||||
.preparation
|
||||
.runtime_diagnostics(
|
||||
&snapshot,
|
||||
published_revision,
|
||||
published
|
||||
.as_ref()
|
||||
.and_then(|snapshot| snapshot.extensions()),
|
||||
)
|
||||
.await
|
||||
.unwrap_or_default();
|
||||
let artifacts = self
|
||||
.list()
|
||||
.await?
|
||||
.into_iter()
|
||||
.map(|artifact| (artifact.metadata.sha256.clone(), artifact.metadata))
|
||||
.collect::<BTreeMap<_, _>>();
|
||||
let mut views = Vec::with_capacity(snapshot.instances.len());
|
||||
for instance in snapshot.instances {
|
||||
let metadata = artifacts
|
||||
.get(&instance.artifact_sha256)
|
||||
.ok_or_else(|| AdminError::not_found("插件制品不存在"))?;
|
||||
let package_status = self.package_status(&instance.artifact_sha256).await?;
|
||||
let configuration_required = package_status.load_error.is_none()
|
||||
&& !self
|
||||
.preparation
|
||||
.configuration_ready(instance.clone(), metadata)
|
||||
.await?;
|
||||
let runtime =
|
||||
diagnostics
|
||||
.remove(&instance.id)
|
||||
.unwrap_or_else(|| PluginInstanceRuntime {
|
||||
status: if !instance.enabled {
|
||||
PluginInstanceRuntimeStatus::Disabled
|
||||
} else {
|
||||
PluginInstanceRuntimeStatus::Unknown
|
||||
},
|
||||
actual_revision: None,
|
||||
actual_artifact_sha256: None,
|
||||
failure: None,
|
||||
draining_revisions: Vec::new(),
|
||||
load: None,
|
||||
});
|
||||
views.push(PluginInstanceView {
|
||||
api_deprecations: if package_status.load_error.is_none() {
|
||||
self.inspector.api_deprecations(metadata)?
|
||||
} else {
|
||||
Vec::new()
|
||||
},
|
||||
configuration_required,
|
||||
compatibility_warning: package_status.warning,
|
||||
load_error: package_status.load_error,
|
||||
running: runtime.status == PluginInstanceRuntimeStatus::Running,
|
||||
published_revision,
|
||||
runtime,
|
||||
instance,
|
||||
});
|
||||
}
|
||||
Ok(views)
|
||||
}
|
||||
}
|
||||
@@ -10,9 +10,9 @@ use crate::{
|
||||
plugins::{
|
||||
PluginArtifactMetadata,
|
||||
instances::{
|
||||
ConfigurePluginInstance, PluginInstance, PluginInstanceMutation,
|
||||
PluginRollbackPlan, PluginRollbackTarget, PluginVersionConfiguration,
|
||||
PluginVersionPlan, RollbackPluginInstance,
|
||||
ConfigurePluginInstance, PluginCompatibilityConfirmation, PluginInstance,
|
||||
PluginInstanceMutation, PluginRollbackPlan, PluginRollbackTarget,
|
||||
PluginVersionConfiguration, PluginVersionPlan, RollbackPluginInstance,
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -61,6 +61,7 @@ impl PluginsService {
|
||||
AdminError::invalid("该版本没有可恢复的配置,请通过版本切换检查当前设置")
|
||||
})?;
|
||||
let configuration = ConfigurePluginInstance {
|
||||
compatibility_confirmation: None,
|
||||
creation_id: None,
|
||||
expected_revision: None,
|
||||
replace_instances: Vec::new(),
|
||||
@@ -142,7 +143,21 @@ impl PluginsService {
|
||||
.find(|instance| instance.id == id)
|
||||
.ok_or_else(|| AdminError::not_found("插件实例不存在"))?;
|
||||
let (configuration, restored) = self.version_configuration(instance, digest).await?;
|
||||
let status = self.package_status(digest).await?;
|
||||
let compatibility_confirmation = if status.warning.is_some() {
|
||||
Some(PluginCompatibilityConfirmation {
|
||||
host_fingerprint: self.inspector.compatibility_host_fingerprint()?,
|
||||
instance_id: instance.id.clone(),
|
||||
instance_revision: instance.revision.get(),
|
||||
artifact_sha256: digest.to_owned(),
|
||||
})
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Ok(PluginVersionPlan {
|
||||
compatibility_warning: status.warning,
|
||||
compatibility_confirmation,
|
||||
load_error: status.load_error,
|
||||
instance_revision: instance.revision.get(),
|
||||
artifact_sha256: digest.to_owned(),
|
||||
configuration: configuration.configuration,
|
||||
@@ -179,6 +194,7 @@ impl PluginsService {
|
||||
.version_configuration(&existing, &input.artifact_sha256)
|
||||
.await?;
|
||||
let request = ConfigurePluginInstance {
|
||||
compatibility_confirmation: None,
|
||||
creation_id: None,
|
||||
expected_revision: Some(existing.revision.get()),
|
||||
replace_instances: Vec::new(),
|
||||
|
||||
@@ -315,6 +315,7 @@ impl AccountRuntimeStore for FakeRuntimeStore {
|
||||
) -> AdminStoreResult<AccountRuntimeSnapshot> {
|
||||
*self.requested_accounts.lock().expect("requested accounts") = account_ids.to_vec();
|
||||
Ok(AccountRuntimeSnapshot {
|
||||
protection_rules: std::collections::BTreeMap::new(),
|
||||
cooldown: BTreeMap::from([(
|
||||
"acct_limited".to_owned(),
|
||||
std::time::SystemTime::from(Utc::now() + Duration::minutes(5)).into(),
|
||||
@@ -329,13 +330,6 @@ impl AccountRuntimeStore for FakeRuntimeStore {
|
||||
Ok(BTreeMap::new())
|
||||
}
|
||||
|
||||
async fn capacity_peaks(
|
||||
&self,
|
||||
_account_ids: &[String],
|
||||
) -> AdminStoreResult<BTreeMap<String, u32>> {
|
||||
Ok(BTreeMap::new())
|
||||
}
|
||||
|
||||
async fn finish_freeze(
|
||||
&self,
|
||||
_account_id: &str,
|
||||
|
||||
@@ -617,7 +617,6 @@ pub(super) struct FakeAccountStore {
|
||||
automations: Mutex<
|
||||
BTreeMap<String, gateway_admin::model::reset_credit_automation::ResetCreditAutomation>,
|
||||
>,
|
||||
pub(super) lowered_limits: Mutex<Vec<(String, u32)>>,
|
||||
}
|
||||
|
||||
impl FakeAccountStore {
|
||||
@@ -638,7 +637,6 @@ impl FakeAccountStore {
|
||||
quota_window_queries: Mutex::new(Vec::new()),
|
||||
quota_forecast_history: Mutex::new(QuotaForecastHistory::default()),
|
||||
update_commands: Mutex::new(Vec::new()),
|
||||
lowered_limits: Mutex::new(Vec::new()),
|
||||
automations: Mutex::default(),
|
||||
})
|
||||
}
|
||||
@@ -720,6 +718,7 @@ impl FakeAccountStore {
|
||||
last_error_message: account.last_error_message.clone(),
|
||||
};
|
||||
AccountPageItem {
|
||||
protection_rules: Vec::new(),
|
||||
capacity: gateway_admin::model::accounts::AccountCapacity {
|
||||
used_slots: None,
|
||||
total_slots: account
|
||||
@@ -1036,35 +1035,6 @@ impl AccountStore for FakeAccountStore {
|
||||
})
|
||||
}
|
||||
|
||||
async fn lower_concurrency_limit(
|
||||
&self,
|
||||
account_id: &ProviderAccountId,
|
||||
limit: gateway_core::account::AccountConcurrencyLimit,
|
||||
_: &MutationContext,
|
||||
) -> AdminStoreResult<Option<AccountUpdateResult>> {
|
||||
let mut accounts = self.accounts.lock().expect("accounts");
|
||||
let Some(account) = accounts
|
||||
.iter_mut()
|
||||
.find(|account| account.id == account_id.as_str())
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
if !account.enabled
|
||||
|| account.concurrency_limit.map_or(5, |value| value.get()) <= limit.get()
|
||||
{
|
||||
return Ok(None);
|
||||
}
|
||||
account.concurrency_limit = Some(limit);
|
||||
self.lowered_limits
|
||||
.lock()
|
||||
.expect("lowered limits")
|
||||
.push((account.id.clone(), limit.get()));
|
||||
Ok(Some(AccountUpdateResult {
|
||||
config_revision: revision(2),
|
||||
account_id: account_id.clone(),
|
||||
}))
|
||||
}
|
||||
|
||||
async fn recover_account(
|
||||
&self,
|
||||
account_id: &ProviderAccountId,
|
||||
@@ -1189,13 +1159,7 @@ impl SettingsStore for StaticSettingsStore {
|
||||
usage_retention_days: 30,
|
||||
ops_event_retention_days: 30,
|
||||
audit_retention_days: 30,
|
||||
account_auto_freeze_enabled: true,
|
||||
account_auto_freeze_threshold: 12,
|
||||
account_auto_freeze_window_seconds: 600,
|
||||
account_auto_freeze_duration_seconds: 7_200,
|
||||
account_auto_freeze_probe_enabled: true,
|
||||
account_auto_freeze_probe_model: None,
|
||||
account_auto_freeze_adaptive_concurrency: true,
|
||||
account_error_protection: gateway_core::account::AccountErrorProtection::default(),
|
||||
account_warmup_enabled: false,
|
||||
account_warmup_schedule_time: "08:00".to_owned(),
|
||||
account_warmup_model: None,
|
||||
@@ -3680,6 +3644,7 @@ impl AccountRuntimeStore for CapacityRuntime {
|
||||
return Err(store_unavailable());
|
||||
}
|
||||
Ok(AccountRuntimeSnapshot {
|
||||
protection_rules: std::collections::BTreeMap::new(),
|
||||
in_flight: self.counts.clone(),
|
||||
..Default::default()
|
||||
})
|
||||
@@ -3691,10 +3656,6 @@ impl AccountRuntimeStore for CapacityRuntime {
|
||||
Ok(BTreeMap::new())
|
||||
}
|
||||
|
||||
async fn capacity_peaks(&self, _: &[String]) -> AdminStoreResult<BTreeMap<String, u32>> {
|
||||
Ok(BTreeMap::new())
|
||||
}
|
||||
|
||||
async fn finish_freeze(
|
||||
&self,
|
||||
_: &str,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! 容量熔断冻结恢复编排回归:到期探测、失败顺延与自适应并发下调
|
||||
//! 账号保护恢复编排:到期探测、快照参数与失败顺延
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::{Arc, Mutex};
|
||||
@@ -24,7 +24,7 @@ use gateway_core::task::{
|
||||
use super::AdminHarness;
|
||||
use super::accounts::{FakeAccountStore, FakeProviderAdmin, account_record, events, revision};
|
||||
|
||||
fn runtime_settings(enabled: bool, probe_enabled: bool, adaptive: bool) -> RuntimeSettings {
|
||||
fn runtime_settings(enabled: bool, probe_enabled: bool) -> RuntimeSettings {
|
||||
RuntimeSettings {
|
||||
request_profiles: Default::default(),
|
||||
config_revision: revision(1),
|
||||
@@ -52,13 +52,22 @@ fn runtime_settings(enabled: bool, probe_enabled: bool, adaptive: bool) -> Runti
|
||||
usage_retention_days: 31,
|
||||
ops_event_retention_days: 30,
|
||||
audit_retention_days: 90,
|
||||
account_auto_freeze_enabled: enabled,
|
||||
account_auto_freeze_threshold: 12,
|
||||
account_auto_freeze_window_seconds: 600,
|
||||
account_auto_freeze_duration_seconds: 7_200,
|
||||
account_auto_freeze_probe_enabled: probe_enabled,
|
||||
account_auto_freeze_probe_model: Some("gpt-5.5".to_owned()),
|
||||
account_auto_freeze_adaptive_concurrency: adaptive,
|
||||
account_error_protection: gateway_core::account::AccountErrorProtection {
|
||||
enabled,
|
||||
probe_enabled,
|
||||
probe_model: Some("gpt-5.5".to_owned()),
|
||||
rules: vec![gateway_core::account::AccountErrorRule {
|
||||
id: "sample".into(),
|
||||
name: "示例".into(),
|
||||
conditions: vec![gateway_core::account::AccountErrorCondition {
|
||||
field: gateway_core::account::AccountErrorField::Code,
|
||||
operator: gateway_core::account::AccountErrorOperator::Equals,
|
||||
values: vec![Some("custom_failure".into())],
|
||||
ignore_case: false,
|
||||
}],
|
||||
}],
|
||||
..Default::default()
|
||||
},
|
||||
account_warmup_enabled: false,
|
||||
account_warmup_schedule_time: "08:00".to_owned(),
|
||||
account_warmup_model: None,
|
||||
@@ -131,19 +140,17 @@ fn store_unavailable() -> AdminStoreError {
|
||||
)
|
||||
}
|
||||
|
||||
/// 记录解冻/顺延调用的运行态 fake;冻结与峰值证据由测试预置
|
||||
/// 记录解冻与顺延调用,冻结快照由测试预置
|
||||
struct FreezeRuntimeStore {
|
||||
freezes: BTreeMap<String, AccountFreeze>,
|
||||
peaks: BTreeMap<String, u32>,
|
||||
cleared: Mutex<Vec<String>>,
|
||||
extended: Mutex<Vec<(String, DateTime<Utc>)>>,
|
||||
}
|
||||
|
||||
impl FreezeRuntimeStore {
|
||||
fn new(freezes: BTreeMap<String, AccountFreeze>, peaks: BTreeMap<String, u32>) -> Arc<Self> {
|
||||
fn new(freezes: BTreeMap<String, AccountFreeze>) -> Arc<Self> {
|
||||
Arc::new(Self {
|
||||
freezes,
|
||||
peaks,
|
||||
cleared: Mutex::new(Vec::new()),
|
||||
extended: Mutex::new(Vec::new()),
|
||||
})
|
||||
@@ -188,16 +195,6 @@ impl AccountRuntimeStore for FreezeRuntimeStore {
|
||||
Ok(self.freezes.clone())
|
||||
}
|
||||
|
||||
async fn capacity_peaks(
|
||||
&self,
|
||||
account_ids: &[String],
|
||||
) -> AdminStoreResult<BTreeMap<String, u32>> {
|
||||
Ok(account_ids
|
||||
.iter()
|
||||
.filter_map(|id| self.peaks.get(id).map(|peak| (id.clone(), *peak)))
|
||||
.collect())
|
||||
}
|
||||
|
||||
async fn finish_freeze(
|
||||
&self,
|
||||
account_id: &str,
|
||||
@@ -241,9 +238,10 @@ struct FailingProbe;
|
||||
impl AccountProbe for FailingProbe {
|
||||
fn probe(
|
||||
&self,
|
||||
_: AccountProbeRequest,
|
||||
request: AccountProbeRequest,
|
||||
_: Option<Arc<gateway_core::routing::RuntimeSnapshot>>,
|
||||
) -> futures::future::BoxFuture<'_, Result<AccountProbeResult, AccountProbeError>> {
|
||||
assert_eq!(request.upstream_model.as_str(), "snapshot-model");
|
||||
Box::pin(async {
|
||||
Err(AccountProbeError::new(
|
||||
gateway_core::error::GatewayError::new(
|
||||
@@ -317,6 +315,9 @@ fn freeze_until(until: DateTime<Utc>) -> BTreeMap<String, AccountFreeze> {
|
||||
BTreeMap::from([(
|
||||
"acct_test".to_owned(),
|
||||
AccountFreeze {
|
||||
duration_seconds: None,
|
||||
probe_model: None,
|
||||
protection_rules: Vec::new(),
|
||||
credential_revision: revision(1),
|
||||
until,
|
||||
generation: "freeze-generation".to_owned(),
|
||||
@@ -331,9 +332,9 @@ fn freeze_due() -> BTreeMap<String, AccountFreeze> {
|
||||
|
||||
#[tokio::test]
|
||||
async fn probe_success_clears_freeze() {
|
||||
let runtime = FreezeRuntimeStore::new(freeze_due(), BTreeMap::new());
|
||||
let runtime = FreezeRuntimeStore::new(freeze_due());
|
||||
let (task, _store) = recovery_task(
|
||||
runtime_settings(true, true, false),
|
||||
runtime_settings(true, true),
|
||||
Arc::clone(&runtime),
|
||||
Arc::new(SuccessfulProbe),
|
||||
)
|
||||
@@ -346,10 +347,13 @@ async fn probe_success_clears_freeze() {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn probe_failure_postpones_freeze() {
|
||||
let runtime = FreezeRuntimeStore::new(freeze_due(), BTreeMap::new());
|
||||
async fn probe_failure_postpones_using_the_freeze_snapshot() {
|
||||
let mut freezes = freeze_due();
|
||||
freezes.get_mut("acct_test").unwrap().duration_seconds = Some(300);
|
||||
freezes.get_mut("acct_test").unwrap().probe_model = Some("snapshot-model".into());
|
||||
let runtime = FreezeRuntimeStore::new(freezes);
|
||||
let (task, _store) = recovery_task(
|
||||
runtime_settings(true, true, false),
|
||||
runtime_settings(true, true),
|
||||
Arc::clone(&runtime),
|
||||
Arc::new(FailingProbe),
|
||||
)
|
||||
@@ -364,16 +368,16 @@ async fn probe_failure_postpones_freeze() {
|
||||
assert_eq!(account_id, "acct_test");
|
||||
let remaining = until.timestamp_millis() - Utc::now().timestamp_millis();
|
||||
assert!(
|
||||
remaining > 7_000_000 && remaining <= 7_200_000,
|
||||
"postponed freeze should be about 2 hours, got {remaining}ms"
|
||||
remaining > 290_000 && remaining <= 300_000,
|
||||
"postponed freeze should use the frozen 5-minute duration, got {remaining}ms"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn disabled_policy_releases_due_freeze_without_probing() {
|
||||
let runtime = FreezeRuntimeStore::new(freeze_due(), BTreeMap::new());
|
||||
let runtime = FreezeRuntimeStore::new(freeze_due());
|
||||
let (task, _store) = recovery_task(
|
||||
runtime_settings(false, true, false),
|
||||
runtime_settings(false, true),
|
||||
Arc::clone(&runtime),
|
||||
Arc::new(SuccessfulProbe),
|
||||
)
|
||||
@@ -385,59 +389,12 @@ async fn disabled_policy_releases_due_freeze_without_probing() {
|
||||
assert!(runtime.extended().is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn adaptive_concurrency_lowers_limit_to_observed_peak() {
|
||||
let runtime = FreezeRuntimeStore::new(
|
||||
freeze_until(Utc::now() + TimeDelta::hours(1)),
|
||||
BTreeMap::from([("acct_test".to_owned(), 4_u32)]),
|
||||
);
|
||||
let (task, store) = recovery_task(
|
||||
runtime_settings(true, false, true),
|
||||
Arc::clone(&runtime),
|
||||
Arc::new(SuccessfulProbe),
|
||||
)
|
||||
.await;
|
||||
|
||||
run_cycle(task.as_ref()).await;
|
||||
|
||||
// 峰值 4 × 0.8 = 3(不低于下限 2),低于全局默认 5,应下调到 3
|
||||
assert_eq!(
|
||||
*store.lowered_limits.lock().expect("lowered limits"),
|
||||
vec![("acct_test".to_owned(), 3)]
|
||||
);
|
||||
assert!(store.update_commands().is_empty());
|
||||
assert!(runtime.extended().is_empty());
|
||||
assert!(runtime.cleared().is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn adaptive_concurrency_never_raises_limit() {
|
||||
let runtime = FreezeRuntimeStore::new(
|
||||
freeze_until(Utc::now() + TimeDelta::hours(1)),
|
||||
BTreeMap::from([("acct_test".to_owned(), 40_u32)]),
|
||||
);
|
||||
let (task, store) = recovery_task(
|
||||
runtime_settings(true, false, true),
|
||||
Arc::clone(&runtime),
|
||||
Arc::new(SuccessfulProbe),
|
||||
)
|
||||
.await;
|
||||
|
||||
run_cycle(task.as_ref()).await;
|
||||
|
||||
// 峰值 40 的目标 32 高于全局默认 5;只降不升,不下发任何更新
|
||||
assert!(store.update_commands().is_empty());
|
||||
}
|
||||
|
||||
/// 到期时间还早(超过探测提前量)的冻结不发起探测
|
||||
#[tokio::test]
|
||||
async fn probe_skips_freezes_far_from_expiry() {
|
||||
let runtime = FreezeRuntimeStore::new(
|
||||
freeze_until(Utc::now() + TimeDelta::hours(1)),
|
||||
BTreeMap::new(),
|
||||
);
|
||||
let runtime = FreezeRuntimeStore::new(freeze_until(Utc::now() + TimeDelta::hours(1)));
|
||||
let (task, _store) = recovery_task(
|
||||
runtime_settings(true, true, false),
|
||||
runtime_settings(true, true),
|
||||
Arc::clone(&runtime),
|
||||
Arc::new(SuccessfulProbe),
|
||||
)
|
||||
@@ -449,13 +406,10 @@ async fn probe_skips_freezes_far_from_expiry() {
|
||||
assert!(runtime.extended().is_empty());
|
||||
}
|
||||
|
||||
/// 停用账号不参与探测恢复;并发下调同样跳过
|
||||
/// 停用账号不参与探测恢复
|
||||
#[tokio::test]
|
||||
async fn disabled_accounts_are_skipped() {
|
||||
let runtime = FreezeRuntimeStore::new(
|
||||
freeze_due(),
|
||||
BTreeMap::from([("acct_test".to_owned(), 4_u32)]),
|
||||
);
|
||||
let runtime = FreezeRuntimeStore::new(freeze_due());
|
||||
let mut record = account_record("openai");
|
||||
record.enabled = false;
|
||||
let store = FakeAccountStore::with_account(record, events());
|
||||
@@ -463,7 +417,7 @@ async fn disabled_accounts_are_skipped() {
|
||||
.accounts(Arc::clone(&store) as Arc<dyn AccountStore>)
|
||||
.account_runtime(Arc::clone(&runtime) as Arc<dyn AccountRuntimeStore>)
|
||||
.settings(Arc::new(FreezeSettingsStore {
|
||||
settings: runtime_settings(true, true, true),
|
||||
settings: runtime_settings(true, true),
|
||||
}))
|
||||
.provider(FakeProviderAdmin::new("openai", events()))
|
||||
.probe(Arc::new(SuccessfulProbe))
|
||||
|
||||
@@ -614,15 +614,6 @@ impl AccountStore for UnavailableStore {
|
||||
Err(unavailable("account enabled"))
|
||||
}
|
||||
|
||||
async fn lower_concurrency_limit(
|
||||
&self,
|
||||
_: &gateway_core::account::ProviderAccountId,
|
||||
_: gateway_core::account::AccountConcurrencyLimit,
|
||||
_: &MutationContext,
|
||||
) -> AdminStoreResult<Option<gateway_admin::model::accounts::AccountUpdateResult>> {
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
async fn recover_account(
|
||||
&self,
|
||||
_: &ProviderAccountId,
|
||||
@@ -685,13 +676,6 @@ impl AccountRuntimeStore for UnavailableStore {
|
||||
Ok(BTreeMap::new())
|
||||
}
|
||||
|
||||
async fn capacity_peaks(
|
||||
&self,
|
||||
_account_ids: &[String],
|
||||
) -> AdminStoreResult<BTreeMap<String, u32>> {
|
||||
Ok(BTreeMap::new())
|
||||
}
|
||||
|
||||
async fn finish_freeze(
|
||||
&self,
|
||||
_account_id: &str,
|
||||
|
||||
@@ -22,8 +22,9 @@ use gateway_admin::{
|
||||
DiagnosticDimension, DiagnosticObservation, DiagnosticsObservation, Granularity,
|
||||
HealthStatus, LatencyPercentiles, ObservabilityPageSize, OpsErrorPage, OpsErrorQuery,
|
||||
PercentileMilliseconds, RequestMetricPoint, RequestMetrics, TimeRange, TrendKind,
|
||||
UsageBilling, UsageDetail, UsageFilter, UsageInsightsObservation, UsageListRecord,
|
||||
UsageOverview, UsagePage, UsageProjectedCostPoint, UsageQuery, UsageSummaryObservation,
|
||||
UsageBilling, UsageConcurrencyPoint, UsageDetail, UsageFilter,
|
||||
UsageInsightsObservation, UsageListRecord, UsageOverview, UsagePage,
|
||||
UsageProjectedCostPoint, UsageQuery, UsageSummaryObservation,
|
||||
},
|
||||
settings::{
|
||||
AdminApiKey, AdminApiKeyMutation, ReplaceRuntimeSettings, RotationStrategy,
|
||||
@@ -678,10 +679,26 @@ async fn observability_services_should_calculate_usage_insights_and_diagnostic_s
|
||||
assert_eq!(insights.health.success_rate, 0.75);
|
||||
assert_eq!(insights.health.completion_rate, 1.0);
|
||||
assert_eq!(insights.granularity, Granularity::FifteenMinutes);
|
||||
assert_eq!(insights.performance.latency_coverage, 0.5);
|
||||
assert_eq!(insights.performance.admission_decision_coverage, 1.0);
|
||||
assert_eq!(insights.performance.account_selection_wait_coverage, 0.8);
|
||||
assert_eq!(insights.performance.capacity_coverage, 0.8);
|
||||
assert_eq!(
|
||||
insights
|
||||
.performance
|
||||
.load
|
||||
.admission_decision_p95_ms
|
||||
.map(|value| value.as_f64()),
|
||||
Some(5.0)
|
||||
);
|
||||
assert_eq!(
|
||||
insights
|
||||
.performance
|
||||
.load
|
||||
.account_selection_wait_p95_ms
|
||||
.map(|value| value.as_f64()),
|
||||
Some(40.0)
|
||||
);
|
||||
assert_eq!(
|
||||
insights.performance.points[0].load,
|
||||
insights.performance.load
|
||||
);
|
||||
assert_eq!(insights.performance.output_throughput_p50, Some(50));
|
||||
assert_eq!(insights.cost.tokens_per_request, 100.0);
|
||||
assert_eq!(
|
||||
@@ -742,6 +759,52 @@ async fn observability_services_should_calculate_usage_insights_and_diagnostic_s
|
||||
assert_eq!(diagnostics.items[1].request_share, 0.25);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn usage_insights_should_weight_concurrency_by_effective_bucket_duration() {
|
||||
let bucket_start = DateTime::parse_from_rfc3339("2026-09-01T10:00:00Z")
|
||||
.unwrap()
|
||||
.with_timezone(&Utc);
|
||||
let range = TimeRange::new(
|
||||
bucket_start + Duration::minutes(5),
|
||||
bucket_start + Duration::minutes(20),
|
||||
)
|
||||
.unwrap();
|
||||
let store = Arc::new(FixtureObservabilityStore::new(range));
|
||||
store.replace_trend(vec![
|
||||
health_metric_point(bucket_start, RequestMetrics::default()),
|
||||
health_metric_point(
|
||||
bucket_start + Duration::minutes(15),
|
||||
RequestMetrics::default(),
|
||||
),
|
||||
]);
|
||||
*store.concurrency.lock().unwrap() = vec![
|
||||
UsageConcurrencyPoint {
|
||||
bucket_start,
|
||||
average_concurrency: 1.0,
|
||||
peak_concurrency: 1,
|
||||
},
|
||||
UsageConcurrencyPoint {
|
||||
bucket_start: bucket_start + Duration::minutes(15),
|
||||
average_concurrency: 3.0,
|
||||
peak_concurrency: 4,
|
||||
},
|
||||
];
|
||||
|
||||
let insights = observability_services(store)
|
||||
.await
|
||||
.observability()
|
||||
.usage_insights(range, UsageFilter::default())
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert!((insights.performance.load.average_concurrency - 5.0 / 3.0).abs() < 1e-10);
|
||||
assert_eq!(insights.performance.load.peak_concurrency, 4);
|
||||
assert_eq!(insights.performance.points[0].load.average_concurrency, 1.0);
|
||||
assert_eq!(insights.performance.points[0].load.peak_concurrency, 1);
|
||||
assert_eq!(insights.performance.points[1].load.average_concurrency, 3.0);
|
||||
assert_eq!(insights.performance.points[1].load.peak_concurrency, 4);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn diagnostics_should_preserve_request_order_when_a_small_sample_fails() {
|
||||
let now = Utc::now();
|
||||
@@ -937,6 +1000,7 @@ async fn dashboard_should_preserve_provider_plan_names() {
|
||||
authentication_kind: "oauth".to_owned(),
|
||||
name: (*plan).to_owned(),
|
||||
email: None,
|
||||
notes: None,
|
||||
plan_type: Some((*plan).to_owned()),
|
||||
plan_type_display: None,
|
||||
request_count: 0,
|
||||
@@ -987,6 +1051,7 @@ struct FixtureObservabilityStore {
|
||||
trend: Mutex<Vec<RequestMetricPoint>>,
|
||||
overview: Mutex<UsageOverview>,
|
||||
projected_costs: Mutex<Vec<UsageProjectedCostPoint>>,
|
||||
concurrency: Mutex<Vec<UsageConcurrencyPoint>>,
|
||||
insights_fail: AtomicBool,
|
||||
summary_fail: AtomicBool,
|
||||
diagnostics: Mutex<DiagnosticsObservation>,
|
||||
@@ -1014,6 +1079,7 @@ impl FixtureObservabilityStore {
|
||||
providers: Vec::new(),
|
||||
}),
|
||||
projected_costs: Mutex::new(Vec::new()),
|
||||
concurrency: Mutex::new(Vec::new()),
|
||||
insights_fail: AtomicBool::new(false),
|
||||
summary_fail: AtomicBool::new(false),
|
||||
diagnostics: Mutex::new(DiagnosticsObservation::default()),
|
||||
@@ -1144,6 +1210,7 @@ impl ObservabilityStore for FixtureObservabilityStore {
|
||||
.lock()
|
||||
.expect("projected costs")
|
||||
.clone(),
|
||||
concurrency: self.concurrency.lock().expect("concurrency").clone(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1253,13 +1320,7 @@ impl SettingsStore for FixtureSettingsStore {
|
||||
usage_retention_days: 31,
|
||||
ops_event_retention_days: 30,
|
||||
audit_retention_days: 30,
|
||||
account_auto_freeze_enabled: true,
|
||||
account_auto_freeze_threshold: 12,
|
||||
account_auto_freeze_window_seconds: 600,
|
||||
account_auto_freeze_duration_seconds: 7_200,
|
||||
account_auto_freeze_probe_enabled: true,
|
||||
account_auto_freeze_probe_model: None,
|
||||
account_auto_freeze_adaptive_concurrency: true,
|
||||
account_error_protection: gateway_core::account::AccountErrorProtection::default(),
|
||||
account_warmup_enabled: false,
|
||||
account_warmup_schedule_time: "08:00".to_owned(),
|
||||
account_warmup_model: None,
|
||||
|
||||
@@ -39,6 +39,7 @@ struct FixtureData {
|
||||
artifact: InstalledPluginArtifact,
|
||||
snapshot: PluginInstanceSnapshot,
|
||||
saves: usize,
|
||||
compatibility_warning: Option<String>,
|
||||
publications: Vec<u64>,
|
||||
}
|
||||
|
||||
@@ -61,6 +62,7 @@ impl Fixture {
|
||||
instances: existing.into_iter().collect(),
|
||||
},
|
||||
saves: 0,
|
||||
compatibility_warning: None,
|
||||
publications: Vec::new(),
|
||||
}),
|
||||
})
|
||||
@@ -89,6 +91,14 @@ impl SnapshotControl for Fixture {
|
||||
|
||||
#[async_trait]
|
||||
impl gateway_admin::ports::plugins::PluginPackageInspector for Fixture {
|
||||
async fn compatibility_warning(
|
||||
&self,
|
||||
_: Arc<[u8]>,
|
||||
_: String,
|
||||
) -> Result<Option<String>, AdminError> {
|
||||
Ok(self.data.lock().unwrap().compatibility_warning.clone())
|
||||
}
|
||||
|
||||
async fn inspect(
|
||||
&self,
|
||||
archive: Arc<[u8]>,
|
||||
@@ -488,3 +498,20 @@ fn context() -> MutationContext {
|
||||
fn store_error(kind: AdminStoreErrorKind) -> AdminStoreError {
|
||||
AdminStoreError::new(kind, "plugin", "install fixture")
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn installing_an_incompatible_package_keeps_the_default_instance_stopped() {
|
||||
let fixture = Fixture::new(metadata(true), None);
|
||||
fixture.data.lock().unwrap().compatibility_warning = Some("宿主范围不匹配".into());
|
||||
let result = fixture
|
||||
.service()
|
||||
.accept_artifact(DIGEST, &context())
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(!result.configuration_required);
|
||||
let data = fixture.data.lock().unwrap();
|
||||
assert_eq!(data.snapshot.instances.len(), 1);
|
||||
assert!(!data.snapshot.instances[0].enabled);
|
||||
assert!(!data.snapshot.instances[0].bindings.is_empty());
|
||||
assert!(data.artifact.accepted_at.is_some());
|
||||
}
|
||||
|
||||
+103
-44
@@ -49,6 +49,8 @@ use serde_json::json;
|
||||
|
||||
use super::TestPluginPorts;
|
||||
|
||||
mod queries;
|
||||
|
||||
const OLD_ARTIFACT: &str = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
|
||||
const NEW_ARTIFACT: &str = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb";
|
||||
|
||||
@@ -61,6 +63,10 @@ enum MigrationBehavior {
|
||||
|
||||
#[async_trait]
|
||||
impl gateway_admin::ports::plugins::PluginPackageInspector for LifecycleFixture {
|
||||
fn compatibility_host_fingerprint(&self) -> Result<String, AdminError> {
|
||||
Ok("test-host".into())
|
||||
}
|
||||
|
||||
fn api_deprecations(
|
||||
&self,
|
||||
metadata: &PluginArtifactMetadata,
|
||||
@@ -88,6 +94,11 @@ impl gateway_admin::ports::plugins::PluginPackageInspector for LifecycleFixture
|
||||
archive: Arc<[u8]>,
|
||||
digest: String,
|
||||
) -> Result<Option<String>, AdminError> {
|
||||
let gate = self.inspection_gate.lock().unwrap().clone();
|
||||
if let Some(gate) = gate.filter(|gate| gate.digest == digest) {
|
||||
gate.started.notify_one();
|
||||
gate.release.notified().await;
|
||||
}
|
||||
self.inspect(archive, Some(digest)).await?;
|
||||
Ok(self.data.lock().unwrap().compatibility_warning.clone())
|
||||
}
|
||||
@@ -143,11 +154,19 @@ struct LifecycleFixture {
|
||||
behavior: MigrationBehavior,
|
||||
data: Mutex<FixtureData>,
|
||||
next_prepared: AtomicU64,
|
||||
inspection_gate: Mutex<Option<Arc<InspectionGate>>>,
|
||||
}
|
||||
|
||||
struct InspectionGate {
|
||||
digest: String,
|
||||
started: tokio::sync::Notify,
|
||||
release: tokio::sync::Notify,
|
||||
}
|
||||
|
||||
impl LifecycleFixture {
|
||||
fn new(behavior: MigrationBehavior) -> Arc<Self> {
|
||||
Arc::new(Self {
|
||||
inspection_gate: Mutex::new(None),
|
||||
behavior,
|
||||
data: Mutex::new(FixtureData {
|
||||
snapshot: PluginInstanceSnapshot {
|
||||
@@ -267,6 +286,22 @@ impl ExtensionSetLease for Lease {
|
||||
|
||||
#[async_trait]
|
||||
impl PluginPreparation for LifecycleFixture {
|
||||
async fn prepare_confirmed(
|
||||
&self,
|
||||
snapshot: PluginInstanceSnapshot,
|
||||
confirmation: gateway_admin::model::plugins::instances::PluginCompatibilityConfirmation,
|
||||
) -> Result<ExtensionSetReference, AdminError> {
|
||||
assert_eq!(confirmation.host_fingerprint, "test-host");
|
||||
assert!(
|
||||
snapshot
|
||||
.instances
|
||||
.iter()
|
||||
.any(|instance| instance.id == confirmation.instance_id
|
||||
&& instance.artifact_sha256 == confirmation.artifact_sha256)
|
||||
);
|
||||
self.prepare(snapshot).await
|
||||
}
|
||||
|
||||
async fn configuration_ready(
|
||||
&self,
|
||||
instance: PluginInstance,
|
||||
@@ -716,6 +751,7 @@ fn rollback_input() -> RollbackPluginInstance {
|
||||
|
||||
fn input() -> ConfigurePluginInstance {
|
||||
ConfigurePluginInstance {
|
||||
compatibility_confirmation: None,
|
||||
replace_instances: Vec::new(),
|
||||
creation_id: None,
|
||||
expected_revision: None,
|
||||
@@ -970,49 +1006,6 @@ fn state_unavailable<T>() -> PluginStateStoreResult<T> {
|
||||
))
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn instance_list_uses_runtime_diagnostics_and_keeps_running_compatibility_derived() {
|
||||
let fixture = LifecycleFixture::new(MigrationBehavior::Succeed);
|
||||
let expected = PluginInstanceRuntime {
|
||||
status: PluginInstanceRuntimeStatus::PreparationFailed,
|
||||
actual_revision: Some(9),
|
||||
actual_artifact_sha256: Some(OLD_ARTIFACT.into()),
|
||||
failure: Some(PluginInstanceRuntimeFailure {
|
||||
code: "unavailable".into(),
|
||||
message: "插件候选准备失败".into(),
|
||||
}),
|
||||
draining_revisions: vec![8],
|
||||
};
|
||||
fixture.data.lock().unwrap().diagnostics = Some(BTreeMap::from([(
|
||||
"00000000-0000-7000-8000-000000000001".into(),
|
||||
expected.clone(),
|
||||
)]));
|
||||
|
||||
let views = service(fixture, Arc::new(Published::default()))
|
||||
.instances()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(views.len(), 1);
|
||||
assert!(!views[0].running);
|
||||
assert_eq!(views[0].runtime, expected);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn instance_list_falls_back_without_inventing_runtime_failures() {
|
||||
let fixture = LifecycleFixture::new(MigrationBehavior::Succeed);
|
||||
let views = service(fixture, Arc::new(Published::default()))
|
||||
.instances()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(views.len(), 1);
|
||||
assert_eq!(
|
||||
views[0].runtime.status,
|
||||
PluginInstanceRuntimeStatus::AwaitingPublication
|
||||
);
|
||||
assert!(!views[0].running);
|
||||
assert!(views[0].runtime.failure.is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn incompatible_state_upgrade_quiesces_migrates_and_promotes_the_target() {
|
||||
let fixture = LifecycleFixture::new(MigrationBehavior::Succeed);
|
||||
@@ -1644,7 +1637,7 @@ async fn transient_compatibility_check_failure_can_be_retried() {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn compatibility_warning_allows_enabling_and_persists_after_success() {
|
||||
async fn incompatible_start_requires_confirmation_and_preserves_the_warning() {
|
||||
let fixture = LifecycleFixture::new(MigrationBehavior::Succeed);
|
||||
{
|
||||
let mut data = fixture.data.lock().unwrap();
|
||||
@@ -1657,6 +1650,21 @@ async fn compatibility_warning_allows_enabling_and_persists_after_success() {
|
||||
assert!(view.load_error.is_none());
|
||||
let mut request = input();
|
||||
request.artifact_sha256 = OLD_ARTIFACT.into();
|
||||
let error = service
|
||||
.configure_instance(Some(&view.instance.id), request, &context())
|
||||
.await
|
||||
.err()
|
||||
.unwrap();
|
||||
assert_eq!(error.kind(), AdminErrorKind::Conflict);
|
||||
assert!(fixture.data.lock().unwrap().saves.is_empty());
|
||||
assert!(fixture.data.lock().unwrap().prepared_snapshots.is_empty());
|
||||
let plan = service
|
||||
.version_plan(&view.instance.id, OLD_ARTIFACT)
|
||||
.await
|
||||
.unwrap();
|
||||
let mut request = input();
|
||||
request.artifact_sha256 = OLD_ARTIFACT.into();
|
||||
request.compatibility_confirmation = plan.compatibility_confirmation;
|
||||
let result = service
|
||||
.configure_instance(Some(&view.instance.id), request, &context())
|
||||
.await
|
||||
@@ -1667,3 +1675,54 @@ async fn compatibility_warning_allows_enabling_and_persists_after_success() {
|
||||
assert!(view.compatibility_warning.is_some());
|
||||
assert!(view.load_error.is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn incompatible_start_rejects_stale_confirmations_and_unloadable_packages() {
|
||||
for mismatch in ["host", "instance", "revision", "artifact", "unloadable"] {
|
||||
let fixture = LifecycleFixture::new(MigrationBehavior::Succeed);
|
||||
{
|
||||
let mut data = fixture.data.lock().unwrap();
|
||||
data.snapshot.instances[0].enabled = false;
|
||||
data.compatibility_warning = Some("middleware v2 未声明兼容".into());
|
||||
if mismatch == "unloadable" {
|
||||
data.inspection_error = Some(AdminErrorKind::Invalid);
|
||||
}
|
||||
}
|
||||
let service = service(fixture.clone(), Arc::new(Published::default()));
|
||||
let previous = fixture.data.lock().unwrap().snapshot.instances[0].clone();
|
||||
let mut confirmation =
|
||||
gateway_admin::model::plugins::instances::PluginCompatibilityConfirmation {
|
||||
host_fingerprint: "test-host".into(),
|
||||
instance_id: previous.id.clone(),
|
||||
instance_revision: previous.revision.get(),
|
||||
artifact_sha256: OLD_ARTIFACT.into(),
|
||||
};
|
||||
match mismatch {
|
||||
"host" => confirmation.host_fingerprint = "another-host".into(),
|
||||
"instance" => confirmation.instance_id = "another-instance".into(),
|
||||
"revision" => confirmation.instance_revision += 1,
|
||||
"artifact" => confirmation.artifact_sha256 = NEW_ARTIFACT.into(),
|
||||
_ => {}
|
||||
}
|
||||
let mut request = input();
|
||||
request.artifact_sha256 = OLD_ARTIFACT.into();
|
||||
request.compatibility_confirmation = Some(confirmation);
|
||||
let error = service
|
||||
.configure_instance(Some(&previous.id), request, &context())
|
||||
.await
|
||||
.err()
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
error.kind(),
|
||||
if mismatch == "unloadable" {
|
||||
AdminErrorKind::Invalid
|
||||
} else {
|
||||
AdminErrorKind::Conflict
|
||||
}
|
||||
);
|
||||
let data = fixture.data.lock().unwrap();
|
||||
assert!(data.saves.is_empty(), "{mismatch}");
|
||||
assert!(data.prepared_snapshots.is_empty(), "{mismatch}");
|
||||
assert!(!data.snapshot.instances[0].enabled);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
//! 实例运行诊断与包检查缓存的查询回归测试
|
||||
|
||||
use super::*;
|
||||
use gateway_admin::model::plugins::instances::PluginInstanceRuntimeLoad;
|
||||
|
||||
#[tokio::test]
|
||||
async fn instance_list_uses_runtime_diagnostics_and_keeps_running_compatibility_derived() {
|
||||
let fixture = LifecycleFixture::new(MigrationBehavior::Succeed);
|
||||
let expected = PluginInstanceRuntime {
|
||||
status: PluginInstanceRuntimeStatus::PreparationFailed,
|
||||
actual_revision: Some(9),
|
||||
actual_artifact_sha256: Some(OLD_ARTIFACT.into()),
|
||||
failure: Some(PluginInstanceRuntimeFailure {
|
||||
code: "unavailable".into(),
|
||||
message: "插件候选准备失败".into(),
|
||||
}),
|
||||
draining_revisions: vec![8],
|
||||
load: Some(PluginInstanceRuntimeLoad {
|
||||
active_calls: 3,
|
||||
executing_calls: 1,
|
||||
queued_calls: 1,
|
||||
resuming_calls: 1,
|
||||
pending_callbacks: 2,
|
||||
active_streams: 0,
|
||||
}),
|
||||
};
|
||||
fixture.data.lock().unwrap().diagnostics = Some(BTreeMap::from([(
|
||||
"00000000-0000-7000-8000-000000000001".into(),
|
||||
expected.clone(),
|
||||
)]));
|
||||
|
||||
let views = service(fixture, Arc::new(Published::default()))
|
||||
.instances()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(views.len(), 1);
|
||||
assert!(!views[0].running);
|
||||
assert_eq!(views[0].runtime, expected);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn instance_list_falls_back_without_inventing_runtime_failures() {
|
||||
let fixture = LifecycleFixture::new(MigrationBehavior::Succeed);
|
||||
let views = service(fixture, Arc::new(Published::default()))
|
||||
.instances()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(views.len(), 1);
|
||||
assert_eq!(
|
||||
views[0].runtime.status,
|
||||
PluginInstanceRuntimeStatus::Unknown
|
||||
);
|
||||
assert!(!views[0].running);
|
||||
assert!(views[0].runtime.failure.is_none());
|
||||
assert!(views[0].runtime.actual_revision.is_none());
|
||||
assert!(views[0].runtime.load.is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn disabled_instance_without_runtime_diagnostics_has_a_known_disabled_status() {
|
||||
let fixture = LifecycleFixture::new(MigrationBehavior::Succeed);
|
||||
fixture.data.lock().unwrap().snapshot.instances[0].enabled = false;
|
||||
let views = service(fixture, Arc::new(Published::default()))
|
||||
.instances()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
views[0].runtime.status,
|
||||
PluginInstanceRuntimeStatus::Disabled
|
||||
);
|
||||
assert!(!views[0].running);
|
||||
assert!(views[0].runtime.failure.is_none());
|
||||
assert!(views[0].runtime.load.is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn matching_publication_without_process_diagnostics_does_not_imply_running() {
|
||||
for diagnostics in [None, Some(BTreeMap::new())] {
|
||||
let fixture = LifecycleFixture::new(MigrationBehavior::Succeed);
|
||||
fixture.data.lock().unwrap().diagnostics = diagnostics;
|
||||
let revision = fixture.snapshot().config_revision.get();
|
||||
let published = RuntimeSnapshotHandle::new(
|
||||
gateway_core::routing::RuntimeSnapshot::new(
|
||||
ConfigRevision::new(revision).unwrap(),
|
||||
gateway_core::settings::SettingsValues::new(
|
||||
1,
|
||||
"round_robin",
|
||||
BTreeMap::new(),
|
||||
None,
|
||||
None,
|
||||
),
|
||||
Vec::new(),
|
||||
Vec::new(),
|
||||
Vec::new(),
|
||||
)
|
||||
.unwrap(),
|
||||
);
|
||||
let service = PluginsService::new(
|
||||
fixture.clone(),
|
||||
fixture.clone(),
|
||||
PluginDistributionPorts::new(Arc::new(TestPluginPorts), Arc::new(TestPluginPorts)),
|
||||
Arc::new(Published::default()),
|
||||
fixture.clone(),
|
||||
published,
|
||||
fixture,
|
||||
);
|
||||
let view = service.instances().await.unwrap().remove(0);
|
||||
assert_eq!(view.published_revision, Some(revision));
|
||||
assert_eq!(view.runtime.status, PluginInstanceRuntimeStatus::Unknown);
|
||||
assert!(!view.running);
|
||||
assert!(view.runtime.actual_revision.is_none());
|
||||
assert!(view.runtime.actual_artifact_sha256.is_none());
|
||||
assert!(view.runtime.failure.is_none());
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cached_package_query_is_not_blocked_by_another_package_inspection() {
|
||||
let fixture = LifecycleFixture::new(MigrationBehavior::Succeed);
|
||||
let service = Arc::new(service(fixture.clone(), Arc::new(Published::default())));
|
||||
service.instances().await.unwrap();
|
||||
let gate = Arc::new(InspectionGate {
|
||||
digest: NEW_ARTIFACT.into(),
|
||||
started: tokio::sync::Notify::new(),
|
||||
release: tokio::sync::Notify::new(),
|
||||
});
|
||||
*fixture.inspection_gate.lock().unwrap() = Some(gate.clone());
|
||||
fixture.data.lock().unwrap().snapshot.instances[0].artifact_sha256 = NEW_ARTIFACT.into();
|
||||
let inspecting = {
|
||||
let service = service.clone();
|
||||
tokio::spawn(async move { service.instances().await })
|
||||
};
|
||||
tokio::time::timeout(std::time::Duration::from_secs(1), gate.started.notified())
|
||||
.await
|
||||
.expect("another package inspection started");
|
||||
|
||||
fixture.data.lock().unwrap().snapshot.instances[0].artifact_sha256 = OLD_ARTIFACT.into();
|
||||
let cached =
|
||||
tokio::time::timeout(std::time::Duration::from_millis(100), service.instances()).await;
|
||||
gate.release.notify_one();
|
||||
inspecting.await.unwrap().unwrap();
|
||||
assert_eq!(
|
||||
cached
|
||||
.expect("cached query must not wait for inspection")
|
||||
.unwrap()[0]
|
||||
.instance
|
||||
.artifact_sha256,
|
||||
OLD_ARTIFACT
|
||||
);
|
||||
assert_eq!(fixture.data.lock().unwrap().archive_reads, 2);
|
||||
}
|
||||
@@ -213,6 +213,16 @@ fn sdk_settings_contract_matches_host_declarations() {
|
||||
let mut types = Vec::new();
|
||||
let mut replacement_fields = Vec::new();
|
||||
for (path, names) in [
|
||||
(
|
||||
"../gateway-core/src/account/error_protection.rs",
|
||||
&[
|
||||
"AccountErrorProtection",
|
||||
"AccountErrorRule",
|
||||
"AccountErrorCondition",
|
||||
"AccountErrorField",
|
||||
"AccountErrorOperator",
|
||||
][..],
|
||||
),
|
||||
(
|
||||
"../gateway-core/src/settings/privacy.rs",
|
||||
&[
|
||||
|
||||
@@ -345,13 +345,8 @@ async fn settings_should_reject_zero_refresh_margin_before_store_call() {
|
||||
usage_retention_days: 31,
|
||||
ops_event_retention_days: 30,
|
||||
audit_retention_days: 30,
|
||||
account_auto_freeze_enabled: true,
|
||||
account_auto_freeze_threshold: 12,
|
||||
account_auto_freeze_window_seconds: 600,
|
||||
account_auto_freeze_duration_seconds: 7_200,
|
||||
account_auto_freeze_probe_enabled: true,
|
||||
account_auto_freeze_probe_model: None,
|
||||
account_auto_freeze_adaptive_concurrency: true,
|
||||
account_error_protection:
|
||||
gateway_core::account::AccountErrorProtection::default(),
|
||||
account_warmup_enabled: false,
|
||||
account_warmup_schedule_time: "08:00".to_owned(),
|
||||
account_warmup_model: None,
|
||||
|
||||
@@ -37,7 +37,7 @@ tower-http = { version = "0.7.0", features = ["compression-gzip", "cors", "fs",
|
||||
tracing = "0.1.44"
|
||||
url = "2.5.8"
|
||||
uuid = { version = "1.23.3", features = ["v7"] }
|
||||
zstd = "=0.13.3"
|
||||
zstd = "=0.14.3"
|
||||
zip = { version = "9.0.4", default-features = false, features = ["deflate-flate2"] }
|
||||
|
||||
[dev-dependencies]
|
||||
|
||||
@@ -72,6 +72,7 @@ pub(super) fn account_view(
|
||||
projection,
|
||||
usage,
|
||||
quota,
|
||||
protection_rules,
|
||||
} = item;
|
||||
let status = projection.status.as_str().to_owned();
|
||||
let cooldown = projection.cooldown;
|
||||
@@ -86,7 +87,8 @@ pub(super) fn account_view(
|
||||
if account.authentication_kind == "api_key" {
|
||||
usage.window_kind = AccountUsageWindowKind::General;
|
||||
}
|
||||
let (quota, refresh_token_expires_at) = account_quota_view(quota, cooldown, now, time);
|
||||
let (mut quota, refresh_token_expires_at) = account_quota_view(quota, cooldown, now, time);
|
||||
quota.protection_rules = protection_rules;
|
||||
AccountView {
|
||||
capabilities: capabilities.into(),
|
||||
id: account.id.clone(),
|
||||
@@ -232,8 +234,8 @@ pub(super) fn account_quota_view(
|
||||
}
|
||||
});
|
||||
let rate_limit_reason = cooldown.map(|value| {
|
||||
if value.kind.is_capacity_freeze() {
|
||||
"capacity_freeze".to_owned()
|
||||
if value.kind.is_error_protection() {
|
||||
"error_protection".to_owned()
|
||||
} else {
|
||||
"upstream_rate_limit".to_owned()
|
||||
}
|
||||
@@ -251,6 +253,7 @@ pub(super) fn account_quota_view(
|
||||
rate_limit_recovery_display,
|
||||
rate_limit_reason,
|
||||
recovery_probe_required,
|
||||
protection_rules: Vec::new(),
|
||||
windows,
|
||||
credits: quota.credits.map(|credits| AccountQuotaCreditsView {
|
||||
has_credits: credits.has_credits,
|
||||
|
||||
@@ -394,6 +394,7 @@ pub struct AccountQuotaView {
|
||||
pub rate_limit_recovery_display: Option<String>,
|
||||
pub rate_limit_reason: Option<String>,
|
||||
pub recovery_probe_required: bool,
|
||||
pub protection_rules: Vec<gateway_core::account::AccountProtectionMatch>,
|
||||
pub windows: Vec<AccountQuotaWindowView>,
|
||||
pub credits: Option<AccountQuotaCreditsView>,
|
||||
}
|
||||
|
||||
@@ -41,10 +41,6 @@ pub(crate) fn display_rate(value: f64) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
fn basis_points_rate(value: u64) -> f64 {
|
||||
value as f64 / 10_000.0
|
||||
}
|
||||
|
||||
pub(crate) fn outcome_name(outcome: &domain::RequestOutcome) -> &str {
|
||||
outcome.as_str()
|
||||
}
|
||||
@@ -930,6 +926,7 @@ pub(crate) fn dashboard_view(
|
||||
.email
|
||||
.clone()
|
||||
.unwrap_or_else(|| credential.name.clone()),
|
||||
notes: credential.notes,
|
||||
plan_type: credential.plan_type.clone(),
|
||||
plan_type_display: credential
|
||||
.plan_type_display
|
||||
@@ -1050,6 +1047,17 @@ pub(crate) fn usage_summary_view(
|
||||
}
|
||||
}
|
||||
|
||||
fn overview_load_view(load: &domain::UsageInsightsLoad) -> OverviewLoadView {
|
||||
OverviewLoadView {
|
||||
average_concurrency: load.average_concurrency,
|
||||
peak_concurrency: load.peak_concurrency,
|
||||
admission_decision_p95_ms: load.admission_decision_p95_ms.map(|value| value.as_f64()),
|
||||
account_selection_wait_p95_ms: load
|
||||
.account_selection_wait_p95_ms
|
||||
.map(|value| value.as_f64()),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn usage_insights_view(
|
||||
insights: domain::UsageInsights,
|
||||
time: crate::time::TimePresenter,
|
||||
@@ -1092,31 +1100,10 @@ pub(crate) fn usage_insights_view(
|
||||
.first_token_latency_percentiles
|
||||
.p99_ms
|
||||
.map(|value| value.as_f64()),
|
||||
admission_decision_p50_ms: point
|
||||
.admission_decision_percentiles
|
||||
.p50_ms
|
||||
.map(|value| value.as_f64()),
|
||||
admission_decision_p95_ms: point
|
||||
.admission_decision_percentiles
|
||||
.p95_ms
|
||||
.map(|value| value.as_f64()),
|
||||
account_selection_wait_p50_ms: point
|
||||
.account_selection_wait_percentiles
|
||||
.p50_ms
|
||||
.map(|value| value.as_f64()),
|
||||
account_selection_wait_p95_ms: point
|
||||
.account_selection_wait_percentiles
|
||||
.p95_ms
|
||||
.map(|value| value.as_f64()),
|
||||
output_throughput_p10: point.output_throughput_p10,
|
||||
output_throughput_p50: point.output_throughput_p50,
|
||||
output_throughput_p90: point.output_throughput_p90,
|
||||
capacity_utilization: point
|
||||
.capacity_utilization_avg_basis_points
|
||||
.map(basis_points_rate),
|
||||
capacity_utilization_p95: point
|
||||
.capacity_utilization_p95_basis_points
|
||||
.map(basis_points_rate),
|
||||
load: overview_load_view(&point.load),
|
||||
})
|
||||
.collect();
|
||||
let cost_points = insights
|
||||
@@ -1185,42 +1172,10 @@ pub(crate) fn usage_insights_view(
|
||||
.first_token_latency_percentiles
|
||||
.p99_ms
|
||||
.map(|value| value.as_f64()),
|
||||
admission_decision_p50_ms: insights
|
||||
.performance
|
||||
.admission_decision_percentiles
|
||||
.p50_ms
|
||||
.map(|value| value.as_f64()),
|
||||
admission_decision_p95_ms: insights
|
||||
.performance
|
||||
.admission_decision_percentiles
|
||||
.p95_ms
|
||||
.map(|value| value.as_f64()),
|
||||
account_selection_wait_p50_ms: insights
|
||||
.performance
|
||||
.account_selection_wait_percentiles
|
||||
.p50_ms
|
||||
.map(|value| value.as_f64()),
|
||||
account_selection_wait_p95_ms: insights
|
||||
.performance
|
||||
.account_selection_wait_percentiles
|
||||
.p95_ms
|
||||
.map(|value| value.as_f64()),
|
||||
output_throughput_p10: insights.performance.output_throughput_p10,
|
||||
output_throughput_p50: insights.performance.output_throughput_p50,
|
||||
output_throughput_p90: insights.performance.output_throughput_p90,
|
||||
capacity_utilization: insights
|
||||
.performance
|
||||
.capacity_utilization_avg_basis_points
|
||||
.map(basis_points_rate),
|
||||
capacity_utilization_p95: insights
|
||||
.performance
|
||||
.capacity_utilization_p95_basis_points
|
||||
.map(basis_points_rate),
|
||||
latency_coverage: insights.performance.latency_coverage,
|
||||
first_token_coverage: insights.performance.first_token_coverage,
|
||||
admission_decision_coverage: insights.performance.admission_decision_coverage,
|
||||
account_selection_wait_coverage: insights.performance.account_selection_wait_coverage,
|
||||
capacity_coverage: insights.performance.capacity_coverage,
|
||||
load: overview_load_view(&insights.performance.load),
|
||||
points: performance_points,
|
||||
},
|
||||
cost: OverviewCostView {
|
||||
|
||||
@@ -406,6 +406,7 @@ pub struct DashboardAccountUsageView {
|
||||
pub provider: String,
|
||||
pub authentication_kind: String,
|
||||
pub email: String,
|
||||
pub notes: Option<String>,
|
||||
pub plan_type: Option<String>,
|
||||
pub plan_type_display: String,
|
||||
pub tokens: String,
|
||||
@@ -648,6 +649,16 @@ pub struct OverviewHealthView {
|
||||
pub points: Vec<OverviewHealthPointView>,
|
||||
}
|
||||
|
||||
/// 并发与调度等待的负载指标
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct OverviewLoadView {
|
||||
pub average_concurrency: f64,
|
||||
pub peak_concurrency: u64,
|
||||
pub admission_decision_p95_ms: Option<f64>,
|
||||
pub account_selection_wait_p95_ms: Option<f64>,
|
||||
}
|
||||
|
||||
/// 洞察性能趋势点
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -660,15 +671,10 @@ pub struct OverviewPerformancePointView {
|
||||
pub first_token_p50_ms: Option<f64>,
|
||||
pub first_token_p95_ms: Option<f64>,
|
||||
pub first_token_p99_ms: Option<f64>,
|
||||
pub admission_decision_p50_ms: Option<f64>,
|
||||
pub admission_decision_p95_ms: Option<f64>,
|
||||
pub account_selection_wait_p50_ms: Option<f64>,
|
||||
pub account_selection_wait_p95_ms: Option<f64>,
|
||||
pub output_throughput_p10: Option<u64>,
|
||||
pub output_throughput_p50: Option<u64>,
|
||||
pub output_throughput_p90: Option<u64>,
|
||||
pub capacity_utilization: Option<f64>,
|
||||
pub capacity_utilization_p95: Option<f64>,
|
||||
pub load: OverviewLoadView,
|
||||
}
|
||||
|
||||
/// 洞察性能摘要
|
||||
@@ -681,20 +687,10 @@ pub struct OverviewPerformanceView {
|
||||
pub first_token_p50_ms: Option<f64>,
|
||||
pub first_token_p95_ms: Option<f64>,
|
||||
pub first_token_p99_ms: Option<f64>,
|
||||
pub admission_decision_p50_ms: Option<f64>,
|
||||
pub admission_decision_p95_ms: Option<f64>,
|
||||
pub account_selection_wait_p50_ms: Option<f64>,
|
||||
pub account_selection_wait_p95_ms: Option<f64>,
|
||||
pub output_throughput_p10: Option<u64>,
|
||||
pub output_throughput_p50: Option<u64>,
|
||||
pub output_throughput_p90: Option<u64>,
|
||||
pub capacity_utilization: Option<f64>,
|
||||
pub capacity_utilization_p95: Option<f64>,
|
||||
pub latency_coverage: f64,
|
||||
pub first_token_coverage: f64,
|
||||
pub admission_decision_coverage: f64,
|
||||
pub account_selection_wait_coverage: f64,
|
||||
pub capacity_coverage: f64,
|
||||
pub load: OverviewLoadView,
|
||||
pub points: Vec<OverviewPerformancePointView>,
|
||||
}
|
||||
|
||||
|
||||
@@ -9,8 +9,8 @@ use axum::{
|
||||
};
|
||||
use gateway_admin::model::plugins::instances::{
|
||||
ConfigurePluginInstance, PluginCapabilityBinding, PluginInstance, PluginInstanceRuntime,
|
||||
PluginInstanceRuntimeFailure, PluginInstanceRuntimeStatus, PluginInstanceView,
|
||||
RollbackPluginInstance,
|
||||
PluginInstanceRuntimeFailure, PluginInstanceRuntimeLoad, PluginInstanceRuntimeStatus,
|
||||
PluginInstanceView, RollbackPluginInstance,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
@@ -70,6 +70,7 @@ struct InstanceView {
|
||||
#[serde(rename_all = "snake_case")]
|
||||
enum InstanceRuntimeStatus {
|
||||
Disabled,
|
||||
Unknown,
|
||||
AwaitingPublication,
|
||||
Preparing,
|
||||
Running,
|
||||
@@ -83,6 +84,7 @@ impl From<PluginInstanceRuntimeStatus> for InstanceRuntimeStatus {
|
||||
fn from(value: PluginInstanceRuntimeStatus) -> Self {
|
||||
match value {
|
||||
PluginInstanceRuntimeStatus::Disabled => Self::Disabled,
|
||||
PluginInstanceRuntimeStatus::Unknown => Self::Unknown,
|
||||
PluginInstanceRuntimeStatus::AwaitingPublication => Self::AwaitingPublication,
|
||||
PluginInstanceRuntimeStatus::Preparing => Self::Preparing,
|
||||
PluginInstanceRuntimeStatus::Running => Self::Running,
|
||||
@@ -118,6 +120,31 @@ struct InstanceRuntimeView {
|
||||
actual_artifact_sha256: Option<String>,
|
||||
failure: Option<InstanceRuntimeFailure>,
|
||||
draining_revisions: Vec<u64>,
|
||||
load: Option<InstanceRuntimeLoad>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct InstanceRuntimeLoad {
|
||||
active_calls: usize,
|
||||
executing_calls: usize,
|
||||
queued_calls: usize,
|
||||
resuming_calls: usize,
|
||||
pending_callbacks: usize,
|
||||
active_streams: usize,
|
||||
}
|
||||
|
||||
impl From<PluginInstanceRuntimeLoad> for InstanceRuntimeLoad {
|
||||
fn from(value: PluginInstanceRuntimeLoad) -> Self {
|
||||
Self {
|
||||
active_calls: value.active_calls,
|
||||
executing_calls: value.executing_calls,
|
||||
queued_calls: value.queued_calls,
|
||||
resuming_calls: value.resuming_calls,
|
||||
pending_callbacks: value.pending_callbacks,
|
||||
active_streams: value.active_streams,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<PluginInstanceRuntime> for InstanceRuntimeView {
|
||||
@@ -128,6 +155,7 @@ impl From<PluginInstanceRuntime> for InstanceRuntimeView {
|
||||
actual_artifact_sha256: value.actual_artifact_sha256,
|
||||
failure: value.failure.map(Into::into),
|
||||
draining_revisions: value.draining_revisions,
|
||||
load: value.load.map(Into::into),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -56,13 +56,7 @@ pub struct RuntimeSettingsFields {
|
||||
pub usage_retention_days: u64,
|
||||
pub ops_event_retention_days: u64,
|
||||
pub audit_retention_days: u64,
|
||||
pub account_auto_freeze_enabled: bool,
|
||||
pub account_auto_freeze_threshold: u64,
|
||||
pub account_auto_freeze_window_seconds: u64,
|
||||
pub account_auto_freeze_duration_seconds: u64,
|
||||
pub account_auto_freeze_probe_enabled: bool,
|
||||
pub account_auto_freeze_probe_model: Option<String>,
|
||||
pub account_auto_freeze_adaptive_concurrency: bool,
|
||||
pub account_error_protection: gateway_core::account::AccountErrorProtection,
|
||||
pub account_warmup_enabled: bool,
|
||||
pub account_warmup_schedule_time: String,
|
||||
pub account_warmup_model: Option<String>,
|
||||
@@ -593,11 +587,6 @@ fn map_wire_error(error: WireValidationError) -> AdminError {
|
||||
"settingsOpsRetentionOverflow" => "opsEventRetentionDays 不合法".to_owned(),
|
||||
"settingsAuditRetentionOverflow" => "auditRetentionDays 不合法".to_owned(),
|
||||
"requestLocation" => "请求位置不合法,请检查国家代码、地区和城市".to_owned(),
|
||||
"settingsFreezeThresholdOverflow" => "accountAutoFreezeThreshold 不合法".to_owned(),
|
||||
"accountAutoFreezeThreshold" => "账号自动冻结阈值应为 2~1000 的整数".to_owned(),
|
||||
"accountAutoFreezeWindowSeconds" => "账号自动冻结统计窗口应为 60~3600 秒".to_owned(),
|
||||
"accountAutoFreezeDurationSeconds" => "账号自动冻结时长应为 300~604800 秒".to_owned(),
|
||||
"accountAutoFreezeProbeModel" => "探测模型格式不合法".to_owned(),
|
||||
"providerRequestProfiles" => "Provider 请求画像格式不合法或字段冲突".to_owned(),
|
||||
"minCodexDesktopVersion" => "Codex Desktop 最低版本格式不合法".to_owned(),
|
||||
"minCodexCliVersion" => "Codex CLI 最低版本格式不合法".to_owned(),
|
||||
@@ -776,14 +765,7 @@ impl RuntimeSettingsFields {
|
||||
.map_err(|_| WireValidationError::new("settingsOpsRetentionOverflow"))?,
|
||||
audit_retention_days: u32::try_from(self.audit_retention_days)
|
||||
.map_err(|_| WireValidationError::new("settingsAuditRetentionOverflow"))?,
|
||||
account_auto_freeze_enabled: self.account_auto_freeze_enabled,
|
||||
account_auto_freeze_threshold: u32::try_from(self.account_auto_freeze_threshold)
|
||||
.map_err(|_| WireValidationError::new("settingsFreezeThresholdOverflow"))?,
|
||||
account_auto_freeze_window_seconds: self.account_auto_freeze_window_seconds,
|
||||
account_auto_freeze_duration_seconds: self.account_auto_freeze_duration_seconds,
|
||||
account_auto_freeze_probe_enabled: self.account_auto_freeze_probe_enabled,
|
||||
account_auto_freeze_probe_model: self.account_auto_freeze_probe_model,
|
||||
account_auto_freeze_adaptive_concurrency: self.account_auto_freeze_adaptive_concurrency,
|
||||
account_error_protection: self.account_error_protection,
|
||||
account_warmup_enabled: self.account_warmup_enabled,
|
||||
account_warmup_schedule_time: self.account_warmup_schedule_time,
|
||||
account_warmup_model: self.account_warmup_model,
|
||||
@@ -819,14 +801,7 @@ impl From<gateway_admin::model::settings::RuntimeSettingsValues> for RuntimeSett
|
||||
usage_retention_days: u64::from(settings.usage_retention_days),
|
||||
ops_event_retention_days: u64::from(settings.ops_event_retention_days),
|
||||
audit_retention_days: u64::from(settings.audit_retention_days),
|
||||
account_auto_freeze_enabled: settings.account_auto_freeze_enabled,
|
||||
account_auto_freeze_threshold: u64::from(settings.account_auto_freeze_threshold),
|
||||
account_auto_freeze_window_seconds: settings.account_auto_freeze_window_seconds,
|
||||
account_auto_freeze_duration_seconds: settings.account_auto_freeze_duration_seconds,
|
||||
account_auto_freeze_probe_enabled: settings.account_auto_freeze_probe_enabled,
|
||||
account_auto_freeze_probe_model: settings.account_auto_freeze_probe_model,
|
||||
account_auto_freeze_adaptive_concurrency: settings
|
||||
.account_auto_freeze_adaptive_concurrency,
|
||||
account_error_protection: settings.account_error_protection,
|
||||
account_warmup_enabled: settings.account_warmup_enabled,
|
||||
account_warmup_schedule_time: settings.account_warmup_schedule_time,
|
||||
account_warmup_model: settings.account_warmup_model,
|
||||
@@ -839,13 +814,7 @@ impl From<gateway_admin::model::settings::RuntimeSettingsValues> for RuntimeSett
|
||||
|
||||
fn settings_validation_error(field: &'static str) -> WireValidationError {
|
||||
WireValidationError::new(match field {
|
||||
"account_auto_freeze_adaptive_concurrency" => "accountAutoFreezeAdaptiveConcurrency",
|
||||
"account_auto_freeze_duration_seconds" => "accountAutoFreezeDurationSeconds",
|
||||
"account_auto_freeze_enabled" => "accountAutoFreezeEnabled",
|
||||
"account_auto_freeze_probe_enabled" => "accountAutoFreezeProbeEnabled",
|
||||
"account_auto_freeze_probe_model" => "accountAutoFreezeProbeModel",
|
||||
"account_auto_freeze_threshold" => "accountAutoFreezeThreshold",
|
||||
"account_auto_freeze_window_seconds" => "accountAutoFreezeWindowSeconds",
|
||||
"account_error_protection" => "accountErrorProtection",
|
||||
"account_warmup_enabled" => "accountWarmupEnabled",
|
||||
"account_warmup_model" => "accountWarmupModel",
|
||||
"reset_credit_lead_minutes" => "resetCreditLeadMinutes",
|
||||
|
||||
@@ -153,6 +153,19 @@ pub(crate) fn client_access_error_response(error: ClientAccessError) -> Response
|
||||
#[must_use]
|
||||
pub fn identify_codex_client(headers: &HeaderMap) -> Option<IdentifiedCodexClient> {
|
||||
const MAXIMUM_HEADER_LENGTH: usize = 4096;
|
||||
// 官方 CLI、IDE、SDK 与 App Server 的 UA 产品版本均来自所运行的 Codex Core
|
||||
const CORE_CLIENT_PRODUCTS: &[&str] = &[
|
||||
"codex_cli_rs",
|
||||
"codex-cli",
|
||||
"codex-tui",
|
||||
"codex_exec",
|
||||
"codex_vscode",
|
||||
"codex_sdk_ts",
|
||||
"codex_python_sdk",
|
||||
"codex-app-server",
|
||||
"codex-app-server-sdk",
|
||||
"codex_mcp_server",
|
||||
];
|
||||
|
||||
let originator = bounded_ascii_header(headers, "originator", MAXIMUM_HEADER_LENGTH);
|
||||
let user_agent = bounded_ascii_header(headers, "user-agent", MAXIMUM_HEADER_LENGTH);
|
||||
@@ -186,22 +199,17 @@ pub fn identify_codex_client(headers: &HeaderMap) -> Option<IdentifiedCodexClien
|
||||
for product in user_agent.split(|character: char| {
|
||||
character.is_ascii_whitespace() || matches!(character, '(' | ')' | ';' | ',' | '[' | ']')
|
||||
}) {
|
||||
for prefix in ["codex_cli_rs", "codex-cli"] {
|
||||
if product.eq_ignore_ascii_case(prefix) {
|
||||
return Some(IdentifiedCodexClient {
|
||||
kind: CodexClientKind::Cli,
|
||||
version: None,
|
||||
});
|
||||
}
|
||||
let Some((name, version)) = product.split_once('/') else {
|
||||
continue;
|
||||
};
|
||||
if name.eq_ignore_ascii_case(prefix) {
|
||||
return Some(IdentifiedCodexClient {
|
||||
kind: CodexClientKind::Cli,
|
||||
version: CodexClientVersion::parse(version).ok(),
|
||||
});
|
||||
}
|
||||
let (name, version) = product
|
||||
.split_once('/')
|
||||
.map_or((product, None), |(name, version)| (name, Some(version)));
|
||||
if CORE_CLIENT_PRODUCTS
|
||||
.iter()
|
||||
.any(|known| name.eq_ignore_ascii_case(known))
|
||||
{
|
||||
return Some(IdentifiedCodexClient {
|
||||
kind: CodexClientKind::Cli,
|
||||
version: version.and_then(|value| CodexClientVersion::parse(value).ok()),
|
||||
});
|
||||
}
|
||||
}
|
||||
None
|
||||
|
||||
@@ -0,0 +1,319 @@
|
||||
//! Chat 出口持有协议投影缓冲 提交与资源回收始终委托原受管正文
|
||||
|
||||
use std::collections::VecDeque;
|
||||
|
||||
use axum::body::to_bytes;
|
||||
use bytes::Bytes;
|
||||
use futures::future::BoxFuture;
|
||||
use gateway_core::{
|
||||
engine::middleware::{
|
||||
MiddlewareBody, MiddlewareError, MiddlewareFrame, MiddlewareFraming, MiddlewareHeader,
|
||||
MiddlewareResponse,
|
||||
},
|
||||
error::{GatewayError, GatewayErrorKind},
|
||||
};
|
||||
use gateway_protocol::openai::sse::{DONE_SSE_FRAME, SseEvent, SseEventDecoder, sse_frame_is_done};
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::openai::{middleware::error_response, responses::ProtocolErrorBody};
|
||||
|
||||
use super::response::{ChatIdentity, ChatStreamEncoder, project_response};
|
||||
|
||||
pub(super) fn project_middleware_response(
|
||||
response: MiddlewareResponse,
|
||||
identity: ChatIdentity,
|
||||
streaming: bool,
|
||||
include_usage: bool,
|
||||
) -> MiddlewareResponse {
|
||||
if !(200..300).contains(&response.status_code()) {
|
||||
return response;
|
||||
}
|
||||
let (protocol, status, mut headers, body, envelope) = response.into_parts();
|
||||
// 投影改变正文长度和表示形式 不继承 Responses 的实体长度或编码
|
||||
headers.retain(|header| {
|
||||
!["content-length", "content-type", "content-encoding"]
|
||||
.iter()
|
||||
.any(|name| header.name().eq_ignore_ascii_case(name))
|
||||
});
|
||||
headers.push(MiddlewareHeader::new(
|
||||
"content-type",
|
||||
Bytes::from_static(if streaming {
|
||||
b"text/event-stream"
|
||||
} else {
|
||||
b"application/json"
|
||||
}),
|
||||
));
|
||||
let projection = if streaming {
|
||||
Projection::Stream(Box::new(StreamProjection {
|
||||
encoder: ChatStreamEncoder::new(identity, include_usage),
|
||||
decoder: SseEventDecoder::default(),
|
||||
done_received: false,
|
||||
}))
|
||||
} else {
|
||||
Projection::Json(identity)
|
||||
};
|
||||
let mut response = MiddlewareResponse::new(
|
||||
protocol,
|
||||
status,
|
||||
headers,
|
||||
Box::new(ChatBody {
|
||||
inner: Some(body),
|
||||
projection,
|
||||
pending: VecDeque::new(),
|
||||
committed: false,
|
||||
finished: false,
|
||||
}),
|
||||
);
|
||||
if let Some(envelope) = envelope {
|
||||
response = response.with_envelope(envelope);
|
||||
}
|
||||
response
|
||||
}
|
||||
|
||||
pub(super) fn chat_error_frame(data: &Value) -> Bytes {
|
||||
let error = data
|
||||
.pointer("/response/error")
|
||||
.or_else(|| data.get("error"));
|
||||
Bytes::from(format!("data: {}\n\n", serde_json::json!({"error": error})))
|
||||
}
|
||||
|
||||
enum Projection {
|
||||
Json(ChatIdentity),
|
||||
Stream(Box<StreamProjection>),
|
||||
}
|
||||
|
||||
impl Projection {
|
||||
fn terminal_seen(&self) -> bool {
|
||||
matches!(self, Self::Stream(stream) if stream.terminal_seen())
|
||||
}
|
||||
}
|
||||
|
||||
struct StreamProjection {
|
||||
encoder: ChatStreamEncoder,
|
||||
decoder: SseEventDecoder,
|
||||
done_received: bool,
|
||||
}
|
||||
|
||||
impl StreamProjection {
|
||||
fn terminal_seen(&self) -> bool {
|
||||
self.encoder.is_completed() || self.encoder.has_wire_failure()
|
||||
}
|
||||
|
||||
fn project(&mut self, events: Vec<SseEvent>) -> Result<Vec<Bytes>, MiddlewareError> {
|
||||
let mut output = Vec::new();
|
||||
for event in events {
|
||||
if self.done_received {
|
||||
return Err(invalid_response());
|
||||
}
|
||||
let data = serde_json::from_str(&event.data).map_err(|_| invalid_response())?;
|
||||
// codec 区分辅助事件与终态后的业务输出 交付层不再维护一份事件分类
|
||||
output.extend(
|
||||
self.encoder
|
||||
.push_event(event.event.as_deref(), &data)
|
||||
.map_err(projection_error)?,
|
||||
);
|
||||
}
|
||||
Ok(output)
|
||||
}
|
||||
}
|
||||
|
||||
struct ChatBody {
|
||||
inner: Option<Box<dyn MiddlewareBody>>,
|
||||
projection: Projection,
|
||||
pending: VecDeque<MiddlewareFrame>,
|
||||
committed: bool,
|
||||
finished: bool,
|
||||
}
|
||||
|
||||
impl ChatBody {
|
||||
async fn read_one(&mut self) -> Result<(), MiddlewareError> {
|
||||
let inner = self.inner.as_mut().ok_or(MiddlewareError::InvalidState)?;
|
||||
let Some(frame) = inner.next_frame().await? else {
|
||||
if let Projection::Stream(stream) = &mut self.projection {
|
||||
let events = stream.decoder.finish().map_err(|_| invalid_response())?;
|
||||
let frames = stream.project(events)?;
|
||||
if !frames.is_empty() || !stream.done_received || !inner.is_finalized() {
|
||||
return Err(invalid_response());
|
||||
}
|
||||
self.pending.push_back(done_frame());
|
||||
}
|
||||
self.finished = true;
|
||||
return Ok(());
|
||||
};
|
||||
let transformed = frame.transformed();
|
||||
let (bytes, framing, terminal, envelope) = frame.into_parts();
|
||||
let output = match &mut self.projection {
|
||||
Projection::Json(identity) => {
|
||||
if framing != MiddlewareFraming::JsonDocument || !terminal {
|
||||
return Err(invalid_response());
|
||||
}
|
||||
let value = serde_json::from_slice(&bytes).map_err(|_| invalid_response())?;
|
||||
let value = project_response(&value, identity).map_err(projection_error)?;
|
||||
vec![MiddlewareFrame::new(
|
||||
Bytes::from(serde_json::to_vec(&value).map_err(|_| invalid_response())?),
|
||||
MiddlewareFraming::JsonDocument,
|
||||
true,
|
||||
)]
|
||||
}
|
||||
Projection::Stream(stream) => {
|
||||
if framing != MiddlewareFraming::SseEvent {
|
||||
return Err(invalid_response());
|
||||
}
|
||||
let events = stream
|
||||
.decoder
|
||||
.push(&bytes)
|
||||
.map_err(|_| invalid_response())?;
|
||||
let output = stream.project(events)?;
|
||||
// 共用 SSE 解码器只返回业务事件 DONE 由受管正文的控制帧单独确认
|
||||
if std::str::from_utf8(&bytes).is_ok_and(sse_frame_is_done) {
|
||||
if stream.done_received || !stream.terminal_seen() {
|
||||
return Err(invalid_response());
|
||||
}
|
||||
stream.done_received = true;
|
||||
}
|
||||
if terminal && !stream.done_received {
|
||||
return Err(invalid_response());
|
||||
}
|
||||
output
|
||||
.into_iter()
|
||||
.map(|bytes| MiddlewareFrame::new(bytes, MiddlewareFraming::SseEvent, false))
|
||||
.collect()
|
||||
}
|
||||
};
|
||||
let mut output: VecDeque<_> = output
|
||||
.into_iter()
|
||||
.map(|frame| frame.with_transformed(transformed))
|
||||
.collect();
|
||||
if let Some(envelope) = envelope
|
||||
&& let Some(last) = output.pop_back()
|
||||
{
|
||||
output.push_back(last.with_envelope(envelope));
|
||||
}
|
||||
self.pending.extend(output);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn verify_terminal(&mut self) -> Result<(), MiddlewareError> {
|
||||
while !self.finished {
|
||||
self.read_one().await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn fail_stream(&mut self, error: MiddlewareError) {
|
||||
self.pending.clear();
|
||||
if let Some(inner) = self.inner.take() {
|
||||
inner.close().await;
|
||||
}
|
||||
let response = error_response(error);
|
||||
let bytes = to_bytes(response.into_body(), usize::MAX)
|
||||
.await
|
||||
.unwrap_or_default();
|
||||
let value = serde_json::from_slice(&bytes).unwrap_or_else(|_| {
|
||||
serde_json::json!({"error": {
|
||||
"type": "server_error", "code": "invalid_upstream_response",
|
||||
"message": "The gateway could not deliver the Chat response."
|
||||
}})
|
||||
});
|
||||
self.pending.push_back(MiddlewareFrame::new(
|
||||
chat_error_frame(&value),
|
||||
MiddlewareFraming::SseEvent,
|
||||
false,
|
||||
));
|
||||
self.pending.push_back(done_frame());
|
||||
self.finished = true;
|
||||
}
|
||||
}
|
||||
|
||||
impl MiddlewareBody for ChatBody {
|
||||
fn next_frame(&mut self) -> BoxFuture<'_, Result<Option<MiddlewareFrame>, MiddlewareError>> {
|
||||
Box::pin(async move {
|
||||
while self.pending.is_empty() && !self.finished {
|
||||
let result = match self.read_one().await {
|
||||
Ok(()) if self.committed && self.projection.terminal_seen() => {
|
||||
self.verify_terminal().await
|
||||
}
|
||||
result => result,
|
||||
};
|
||||
if let Err(error) = result {
|
||||
if !self.committed {
|
||||
return Err(error);
|
||||
}
|
||||
self.fail_stream(error).await;
|
||||
}
|
||||
}
|
||||
Ok(self.pending.pop_front())
|
||||
})
|
||||
}
|
||||
|
||||
fn commit_downstream(
|
||||
&mut self,
|
||||
client_status_code: Option<u16>,
|
||||
) -> BoxFuture<'_, Result<(), MiddlewareError>> {
|
||||
Box::pin(async move {
|
||||
self.inner
|
||||
.as_mut()
|
||||
.ok_or(MiddlewareError::InvalidState)?
|
||||
.commit_downstream(client_status_code)
|
||||
.await?;
|
||||
self.committed = true;
|
||||
// HTTP 尚未发送首帧 即使首批已经包含 finish 或 usage 也先确认原会话完成结算
|
||||
if self.projection.terminal_seen()
|
||||
&& let Err(error) = self.verify_terminal().await
|
||||
{
|
||||
// 原会话已提交 不能把已记录的 200 改成另一 HTTP 状态
|
||||
// 首个 Chat 帧为 role 或 error 成功终态仍在 pending 内可安全撤回
|
||||
self.fail_stream(error).await;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
fn record_client_status(&mut self, status: u16) -> BoxFuture<'_, Result<(), MiddlewareError>> {
|
||||
match self.inner.as_mut() {
|
||||
Some(inner) => inner.record_client_status(status),
|
||||
None => Box::pin(async { Ok(()) }),
|
||||
}
|
||||
}
|
||||
|
||||
fn is_finalized(&self) -> bool {
|
||||
self.inner.as_ref().is_none_or(|inner| inner.is_finalized())
|
||||
}
|
||||
|
||||
fn close(mut self: Box<Self>) -> BoxFuture<'static, ()> {
|
||||
let inner = self.inner.take();
|
||||
Box::pin(async move {
|
||||
if let Some(inner) = inner {
|
||||
inner.close().await;
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn projection_error(error: ProtocolErrorBody) -> MiddlewareError {
|
||||
MiddlewareError::Gateway(
|
||||
GatewayError::new(
|
||||
GatewayErrorKind::UpstreamUnavailable,
|
||||
"The gateway could not project the upstream response to Chat Completions.",
|
||||
)
|
||||
.with_client_code(error.error.code),
|
||||
)
|
||||
}
|
||||
|
||||
fn invalid_response() -> MiddlewareError {
|
||||
MiddlewareError::Gateway(
|
||||
GatewayError::new(
|
||||
GatewayErrorKind::UpstreamUnavailable,
|
||||
"The gateway could not deliver the Chat response.",
|
||||
)
|
||||
.with_client_code("invalid_upstream_response"),
|
||||
)
|
||||
}
|
||||
|
||||
fn done_frame() -> MiddlewareFrame {
|
||||
MiddlewareFrame::new(
|
||||
Bytes::from_static(DONE_SSE_FRAME.as_bytes()),
|
||||
MiddlewareFraming::SseEvent,
|
||||
true,
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
//! Chat HTTP 入口只规范化协议 共用 Responses 的执行与交付链路
|
||||
|
||||
use std::{net::SocketAddr, time::SystemTime};
|
||||
|
||||
use axum::{
|
||||
body::Bytes,
|
||||
extract::{Extension, State, connect_info::ConnectInfo},
|
||||
http::{HeaderMap, StatusCode, header::CONTENT_ENCODING},
|
||||
response::Response,
|
||||
};
|
||||
|
||||
use crate::ApiState;
|
||||
use crate::openai::{
|
||||
auth::{authenticate_client, client_access_error_response},
|
||||
error::{gateway_error_response, protocol_error_response},
|
||||
responses::{
|
||||
DecodedResponsesRequest, HttpResponseAdapter, RequestDecodeError, ResponsesHttpRequest,
|
||||
decode_request_with_headers, decompress_request_body, execute_prepared_response,
|
||||
},
|
||||
router::CHAT_COMPLETIONS_PATH,
|
||||
};
|
||||
|
||||
use super::{
|
||||
delivery::{chat_error_frame, project_middleware_response},
|
||||
request::convert_request,
|
||||
response::ChatIdentity,
|
||||
};
|
||||
|
||||
pub(in crate::openai) async fn chat_completions(
|
||||
State(state): State<ApiState>,
|
||||
connect_info: Option<Extension<ConnectInfo<SocketAddr>>>,
|
||||
ingress_id: Option<Extension<tower_http::request_id::RequestId>>,
|
||||
headers: HeaderMap,
|
||||
body: Bytes,
|
||||
) -> Response {
|
||||
let service = state.openai().clone();
|
||||
let client = match authenticate_client(&service, &headers).await {
|
||||
Ok(client) => client,
|
||||
Err(error) => return client_access_error_response(error),
|
||||
};
|
||||
let (decoded, middleware_body, include_usage) = match decode_request(
|
||||
&body,
|
||||
&headers,
|
||||
client.snapshot().responses_max_decompressed_body_bytes(),
|
||||
) {
|
||||
Ok(request) => request,
|
||||
Err(error) => {
|
||||
return protocol_error_response(StatusCode::BAD_REQUEST, error.protocol_body());
|
||||
}
|
||||
};
|
||||
let prepared = match service.execution().prepare_execution(client).await {
|
||||
Ok(prepared) => prepared,
|
||||
Err(error) => return gateway_error_response(&error),
|
||||
};
|
||||
let identity = ChatIdentity {
|
||||
id: format!("chatcmpl-{}", prepared.request_id().as_str()),
|
||||
created: SystemTime::now()
|
||||
.duration_since(SystemTime::UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_secs(),
|
||||
model: decoded.metadata().requested_model().to_owned(),
|
||||
};
|
||||
let streaming = decoded.metadata().stream();
|
||||
let adapter = HttpResponseAdapter {
|
||||
endpoint: CHAT_COMPLETIONS_PATH,
|
||||
wrap: Box::new(move |response| {
|
||||
project_middleware_response(response, identity, streaming, include_usage)
|
||||
}),
|
||||
stream_error: chat_error_frame,
|
||||
};
|
||||
execute_prepared_response(
|
||||
service,
|
||||
prepared,
|
||||
ResponsesHttpRequest {
|
||||
peer_address: connect_info.map(|Extension(ConnectInfo(address))| address),
|
||||
ingress_id,
|
||||
headers,
|
||||
decoded,
|
||||
middleware_body,
|
||||
},
|
||||
None,
|
||||
Some(adapter),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
fn decode_request(
|
||||
body: &[u8],
|
||||
headers: &HeaderMap,
|
||||
maximum_body_bytes: usize,
|
||||
) -> Result<(DecodedResponsesRequest, Bytes, bool), RequestDecodeError> {
|
||||
let body = decompress_request_body(body, headers, maximum_body_bytes)?;
|
||||
let converted = convert_request(&body)?;
|
||||
let body =
|
||||
serde_json::to_vec(&converted.body).map_err(|_| RequestDecodeError::MalformedJson)?;
|
||||
let mut decoded_headers = headers.clone();
|
||||
decoded_headers.remove(CONTENT_ENCODING);
|
||||
let decoded = decode_request_with_headers(&body, &decoded_headers, maximum_body_bytes)?;
|
||||
Ok((decoded, Bytes::from(body), converted.include_usage))
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
//! Chat Completions 与 Responses 之间的 API 协议适配
|
||||
|
||||
mod delivery;
|
||||
mod http;
|
||||
mod request;
|
||||
mod response;
|
||||
|
||||
pub(super) use http::chat_completions;
|
||||
@@ -0,0 +1,550 @@
|
||||
//! 将 Chat 请求转换为 Responses 正文,协议选项留在 API,业务 JSON 与上游兼容规则保持原有归属
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
use crate::openai::responses::RequestDecodeError;
|
||||
|
||||
pub(in crate::openai) struct ConvertedChatRequest {
|
||||
pub(in crate::openai) body: Map<String, Value>,
|
||||
pub(in crate::openai) include_usage: bool,
|
||||
}
|
||||
|
||||
pub(in crate::openai) fn convert_request(
|
||||
body: &[u8],
|
||||
) -> Result<ConvertedChatRequest, RequestDecodeError> {
|
||||
let value = serde_json::from_slice(body).map_err(|_| RequestDecodeError::MalformedJson)?;
|
||||
let Value::Object(mut chat) = value else {
|
||||
return Err(RequestDecodeError::ExpectedObject);
|
||||
};
|
||||
validate_options(&chat)?;
|
||||
let model = required_string(&mut chat, "model", "model", false)?;
|
||||
let stream = optional_bool(&mut chat, "stream", "stream")?.unwrap_or(false);
|
||||
let include_usage = stream_options(optional(&mut chat, "stream_options"), stream)?;
|
||||
let input = messages(required(&mut chat, "messages", "messages")?)?;
|
||||
let mut body = Map::from_iter([
|
||||
("model".into(), model.into()),
|
||||
("input".into(), input.into()),
|
||||
("stream".into(), stream.into()),
|
||||
("store".into(), false.into()),
|
||||
]);
|
||||
if let Some(value) = optional(&mut chat, "tools") {
|
||||
body.insert("tools".into(), function_tools(value)?.into());
|
||||
}
|
||||
if let Some(value) = optional(&mut chat, "tool_choice") {
|
||||
let choice = tool_choice(value, body.get("tools"))?;
|
||||
body.insert("tool_choice".into(), choice);
|
||||
}
|
||||
if let Some(value) = optional_bool(&mut chat, "parallel_tool_calls", "parallel_tool_calls")? {
|
||||
body.insert("parallel_tool_calls".into(), value.into());
|
||||
}
|
||||
|
||||
let mut text = Map::new();
|
||||
if let Some(value) = optional(&mut chat, "response_format") {
|
||||
text.insert("format".into(), response_format(value)?);
|
||||
}
|
||||
if let Some(value) = optional(&mut chat, "verbosity") {
|
||||
string(&value, "verbosity", false)?;
|
||||
text.insert("verbosity".into(), value);
|
||||
}
|
||||
if !text.is_empty() {
|
||||
body.insert("text".into(), text.into());
|
||||
}
|
||||
if let Some(value) = optional(&mut chat, "reasoning_effort") {
|
||||
string(&value, "reasoning_effort", false)?;
|
||||
body.insert("reasoning".into(), json!({"effort": value}));
|
||||
}
|
||||
for field in ["max_tokens", "max_completion_tokens"] {
|
||||
if let Some(value) = optional(&mut chat, field) {
|
||||
if !value.as_u64().is_some_and(|tokens| tokens > 0) {
|
||||
return Err(invalid(field));
|
||||
}
|
||||
// 新字段优先,具体上游是否接受长度控制仍由现有 Provider 决定
|
||||
body.insert("max_output_tokens".into(), value);
|
||||
}
|
||||
}
|
||||
for (field, maximum) in [("temperature", 2.0), ("top_p", 1.0)] {
|
||||
if let Some(value) = optional(&mut chat, field) {
|
||||
if !value
|
||||
.as_f64()
|
||||
.is_some_and(|number| (0.0..=maximum).contains(&number))
|
||||
{
|
||||
return Err(invalid(field));
|
||||
}
|
||||
body.insert(field.into(), value);
|
||||
}
|
||||
}
|
||||
for field in [
|
||||
"user",
|
||||
"safety_identifier",
|
||||
"service_tier",
|
||||
"prompt_cache_key",
|
||||
"prompt_cache_retention",
|
||||
] {
|
||||
if let Some(value) = optional(&mut chat, field) {
|
||||
string(&value, field, true)?;
|
||||
body.insert(field.into(), value);
|
||||
}
|
||||
}
|
||||
for field in ["metadata", "prompt_cache_options", "moderation"] {
|
||||
if let Some(value) = optional(&mut chat, field) {
|
||||
let object = object(value, field)?;
|
||||
body.insert(field.into(), object.into());
|
||||
}
|
||||
}
|
||||
// 未识别的客户端顶层扩展不等于 Responses 参数,不进入上游正文
|
||||
Ok(ConvertedChatRequest {
|
||||
body,
|
||||
include_usage,
|
||||
})
|
||||
}
|
||||
|
||||
fn validate_options(chat: &Map<String, Value>) -> Result<(), RequestDecodeError> {
|
||||
for (field, value) in chat.iter().filter(|(_, value)| !value.is_null()) {
|
||||
let supported = match field.as_str() {
|
||||
"n" => value.as_u64() == Some(1),
|
||||
"store" | "logprobs" => value == false,
|
||||
"frequency_penalty" | "presence_penalty" => value.as_f64() == Some(0.0),
|
||||
"top_logprobs" => value.as_u64() == Some(0),
|
||||
"logit_bias" => value.as_object().is_some_and(Map::is_empty),
|
||||
"functions" | "stop" => value.as_array().is_some_and(Vec::is_empty),
|
||||
"modalities" => value == &json!(["text"]),
|
||||
"audio"
|
||||
| "prediction"
|
||||
| "seed"
|
||||
| "function_call"
|
||||
| "web_search_options"
|
||||
| "reasoning_content"
|
||||
| "input"
|
||||
| "previous_response_id"
|
||||
| "conversation"
|
||||
| "instructions"
|
||||
| "reasoning"
|
||||
| "text"
|
||||
| "include"
|
||||
| "background"
|
||||
| "max_output_tokens" => false,
|
||||
_ => true,
|
||||
};
|
||||
if !supported {
|
||||
return Err(unsupported(field));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn stream_options(value: Option<Value>, stream: bool) -> Result<bool, RequestDecodeError> {
|
||||
let Some(value) = value else {
|
||||
return Ok(false);
|
||||
};
|
||||
if !stream {
|
||||
return Err(invalid("stream_options"));
|
||||
}
|
||||
let mut options = object(value, "stream_options")?;
|
||||
let include_usage = optional_bool(
|
||||
&mut options,
|
||||
"include_usage",
|
||||
"stream_options.include_usage",
|
||||
)?
|
||||
.unwrap_or(false);
|
||||
if optional_bool(
|
||||
&mut options,
|
||||
"include_obfuscation",
|
||||
"stream_options.include_obfuscation",
|
||||
)? == Some(true)
|
||||
{
|
||||
// Chat 重编码会改变帧长度,不能声称继承上游流的长度混淆保证
|
||||
return Err(unsupported("stream_options.include_obfuscation"));
|
||||
}
|
||||
Ok(include_usage)
|
||||
}
|
||||
|
||||
fn messages(value: Value) -> Result<Vec<Value>, RequestDecodeError> {
|
||||
let messages = array(value, "messages")?;
|
||||
if messages.is_empty() {
|
||||
return Err(RequestDecodeError::EmptyField {
|
||||
field: "messages".into(),
|
||||
});
|
||||
}
|
||||
let mut input = Vec::with_capacity(messages.len());
|
||||
for (index, value) in messages.into_iter().enumerate() {
|
||||
let path = format!("messages[{index}]");
|
||||
let mut message = object(value, &path)?;
|
||||
let role = required_string(&mut message, "role", &format!("{path}.role"), false)?;
|
||||
if !matches!(
|
||||
role.as_str(),
|
||||
"system" | "developer" | "user" | "assistant" | "tool"
|
||||
) {
|
||||
return Err(unsupported(&format!("{path}.role")));
|
||||
}
|
||||
if let Some(name) = optional(&mut message, "name")
|
||||
&& !string(&name, &format!("{path}.name"), true)?.is_empty()
|
||||
{
|
||||
return Err(unsupported(&format!("{path}.name")));
|
||||
}
|
||||
for field in ["function_call", "reasoning_content", "reasoning", "audio"] {
|
||||
if optional(&mut message, field).is_some() {
|
||||
return Err(unsupported(&format!("{path}.{field}")));
|
||||
}
|
||||
}
|
||||
for (field, allowed_role) in [
|
||||
("tool_calls", "assistant"),
|
||||
("refusal", "assistant"),
|
||||
("tool_call_id", "tool"),
|
||||
] {
|
||||
if role != allowed_role && message.get(field).is_some_and(|value| !value.is_null()) {
|
||||
return Err(invalid(&format!("{path}.{field}")));
|
||||
}
|
||||
}
|
||||
if role == "tool" {
|
||||
let call_id = required_string(
|
||||
&mut message,
|
||||
"tool_call_id",
|
||||
&format!("{path}.tool_call_id"),
|
||||
false,
|
||||
)?;
|
||||
let content_path = format!("{path}.content");
|
||||
let content = required(&mut message, "content", &content_path)?;
|
||||
let output = if content.is_string() {
|
||||
content
|
||||
} else {
|
||||
content_parts(content, &role, &content_path, false)?.into()
|
||||
};
|
||||
input.push(
|
||||
json!({"type": "function_call_output", "call_id": call_id, "output": output}),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
let calls = optional(&mut message, "tool_calls")
|
||||
.map(|value| tool_calls(value, &format!("{path}.tool_calls")))
|
||||
.transpose()?
|
||||
.unwrap_or_default();
|
||||
let refusal = optional(&mut message, "refusal");
|
||||
if let Some(value) = &refusal {
|
||||
string(value, &format!("{path}.refusal"), true)?;
|
||||
}
|
||||
let content = optional(&mut message, "content");
|
||||
if content.is_none() && refusal.is_none() && calls.is_empty() {
|
||||
return Err(invalid(&format!("{path}.content")));
|
||||
}
|
||||
let is_assistant = role == "assistant";
|
||||
let mut parts = content
|
||||
.map(|value| content_parts(value, &role, &format!("{path}.content"), is_assistant))
|
||||
.transpose()?;
|
||||
if let Some(refusal) = refusal {
|
||||
parts
|
||||
.get_or_insert_with(Vec::new)
|
||||
.push(json!({"type": "refusal", "refusal": refusal}));
|
||||
}
|
||||
if let Some(parts) = parts {
|
||||
let mut item = json!({"type": "message", "role": role, "content": parts});
|
||||
if is_assistant {
|
||||
// assistant 历史采用输出消息合同,普通文本和 refusal 都不能编码成 input_text
|
||||
item["id"] = format!("msg_chat_{index}").into();
|
||||
item["status"] = "completed".into();
|
||||
}
|
||||
input.push(item);
|
||||
}
|
||||
input.extend(calls);
|
||||
}
|
||||
Ok(input)
|
||||
}
|
||||
|
||||
fn content_parts(
|
||||
value: Value,
|
||||
role: &str,
|
||||
path: &str,
|
||||
is_assistant: bool,
|
||||
) -> Result<Vec<Value>, RequestDecodeError> {
|
||||
let parts = match value {
|
||||
Value::String(text) => return Ok(vec![text_part(text, is_assistant)]),
|
||||
Value::Array(parts) => parts,
|
||||
_ => return Err(invalid_type(path, "a string or an array")),
|
||||
};
|
||||
let mut result = Vec::with_capacity(parts.len());
|
||||
for (index, value) in parts.into_iter().enumerate() {
|
||||
let path = format!("{path}[{index}]");
|
||||
let mut part = object(value, &path)?;
|
||||
let kind = required_string(&mut part, "type", &format!("{path}.type"), false)?;
|
||||
let mut converted = match kind.as_str() {
|
||||
"text" => text_part(
|
||||
required_string(&mut part, "text", &format!("{path}.text"), true)?,
|
||||
is_assistant,
|
||||
),
|
||||
"image_url" if role == "user" => image_part(
|
||||
required(&mut part, "image_url", &format!("{path}.image_url"))?,
|
||||
&format!("{path}.image_url"),
|
||||
)?,
|
||||
"refusal" if role == "assistant" => json!({
|
||||
"type": "refusal",
|
||||
"refusal": required_string(&mut part, "refusal", &format!("{path}.refusal"), true)?,
|
||||
}),
|
||||
_ => return Err(unsupported(&format!("{path}.type"))),
|
||||
};
|
||||
if let Some(value) = optional(&mut part, "prompt_cache_breakpoint") {
|
||||
if is_assistant {
|
||||
return Err(unsupported(&format!("{path}.prompt_cache_breakpoint")));
|
||||
}
|
||||
converted["prompt_cache_breakpoint"] =
|
||||
object(value, &format!("{path}.prompt_cache_breakpoint"))?.into();
|
||||
}
|
||||
result.push(converted);
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
fn text_part(text: String, is_assistant: bool) -> Value {
|
||||
if is_assistant {
|
||||
json!({"type": "output_text", "text": text, "annotations": []})
|
||||
} else {
|
||||
json!({"type": "input_text", "text": text})
|
||||
}
|
||||
}
|
||||
|
||||
fn image_part(value: Value, path: &str) -> Result<Value, RequestDecodeError> {
|
||||
let mut image = object(value, path)?;
|
||||
let url = required_string(&mut image, "url", &format!("{path}.url"), false)?;
|
||||
let valid = url::Url::parse(&url).is_ok_and(|parsed| {
|
||||
matches!(parsed.scheme(), "http" | "https") && parsed.host_str().is_some()
|
||||
|| parsed.scheme() == "data"
|
||||
&& url.starts_with("data:image/")
|
||||
&& url
|
||||
.split_once(";base64,")
|
||||
.is_some_and(|(_, data)| !data.trim().is_empty())
|
||||
});
|
||||
if !valid {
|
||||
return Err(invalid(&format!("{path}.url")));
|
||||
}
|
||||
let mut converted = json!({"type": "input_image", "image_url": url});
|
||||
if let Some(detail) = optional(&mut image, "detail") {
|
||||
string(&detail, &format!("{path}.detail"), false)?;
|
||||
converted["detail"] = detail;
|
||||
}
|
||||
Ok(converted)
|
||||
}
|
||||
|
||||
fn tool_calls(value: Value, path: &str) -> Result<Vec<Value>, RequestDecodeError> {
|
||||
let calls = array(value, path)?;
|
||||
let mut result = Vec::with_capacity(calls.len());
|
||||
for (index, value) in calls.into_iter().enumerate() {
|
||||
let path = format!("{path}[{index}]");
|
||||
let mut call = object(value, &path)?;
|
||||
let id = required_string(&mut call, "id", &format!("{path}.id"), false)?;
|
||||
if required_string(&mut call, "type", &format!("{path}.type"), false)? != "function" {
|
||||
return Err(unsupported(&format!("{path}.type")));
|
||||
}
|
||||
let function_path = format!("{path}.function");
|
||||
let mut function = object(
|
||||
required(&mut call, "function", &function_path)?,
|
||||
&function_path,
|
||||
)?;
|
||||
let name = required_string(
|
||||
&mut function,
|
||||
"name",
|
||||
&format!("{function_path}.name"),
|
||||
false,
|
||||
)?;
|
||||
let arguments = required_string(
|
||||
&mut function,
|
||||
"arguments",
|
||||
&format!("{function_path}.arguments"),
|
||||
true,
|
||||
)?;
|
||||
result.push(
|
||||
json!({"type": "function_call", "call_id": id, "name": name, "arguments": arguments}),
|
||||
);
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
fn function_tools(value: Value) -> Result<Vec<Value>, RequestDecodeError> {
|
||||
array(value, "tools")?
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(index, value)| {
|
||||
let path = format!("tools[{index}]");
|
||||
let mut tool = object(value, &path)?;
|
||||
if required_string(&mut tool, "type", &format!("{path}.type"), false)? != "function" {
|
||||
return Err(unsupported(&format!("{path}.type")));
|
||||
}
|
||||
let function_path = format!("{path}.function");
|
||||
let mut function = object(
|
||||
required(&mut tool, "function", &function_path)?,
|
||||
&function_path,
|
||||
)?;
|
||||
let name = required_string(
|
||||
&mut function,
|
||||
"name",
|
||||
&format!("{function_path}.name"),
|
||||
false,
|
||||
)?;
|
||||
// Chat 的缺省是宽松函数 schema,不能让 Responses 的缺省收紧原始参数合同
|
||||
let strict =
|
||||
optional_bool(&mut function, "strict", &format!("{function_path}.strict"))?
|
||||
.unwrap_or(false);
|
||||
let mut converted = json!({"type": "function", "name": name, "strict": strict});
|
||||
if let Some(description) = optional(&mut function, "description") {
|
||||
string(&description, &format!("{function_path}.description"), true)?;
|
||||
converted["description"] = description;
|
||||
}
|
||||
if let Some(parameters) = optional(&mut function, "parameters") {
|
||||
converted["parameters"] = parameters;
|
||||
}
|
||||
Ok(converted)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn tool_choice(value: Value, tools: Option<&Value>) -> Result<Value, RequestDecodeError> {
|
||||
let tools = tools.and_then(Value::as_array);
|
||||
if let Value::String(choice) = &value {
|
||||
return match choice.as_str() {
|
||||
"auto" | "none" => Ok(value),
|
||||
"required" if tools.is_some_and(|tools| !tools.is_empty()) => Ok(value),
|
||||
"required" => Err(invalid("tool_choice")),
|
||||
_ => Err(unsupported("tool_choice")),
|
||||
};
|
||||
}
|
||||
let mut choice = object(value, "tool_choice")?;
|
||||
if required_string(&mut choice, "type", "tool_choice.type", false)? != "function" {
|
||||
return Err(unsupported("tool_choice.type"));
|
||||
}
|
||||
let mut function = object(
|
||||
required(&mut choice, "function", "tool_choice.function")?,
|
||||
"tool_choice.function",
|
||||
)?;
|
||||
let name = required_string(&mut function, "name", "tool_choice.function.name", false)?;
|
||||
if !tools.is_some_and(|tools| {
|
||||
tools
|
||||
.iter()
|
||||
.any(|tool| tool.get("name").and_then(Value::as_str) == Some(name.as_str()))
|
||||
}) {
|
||||
return Err(invalid("tool_choice.function.name"));
|
||||
}
|
||||
Ok(json!({"type": "function", "name": name}))
|
||||
}
|
||||
|
||||
fn response_format(value: Value) -> Result<Value, RequestDecodeError> {
|
||||
let mut format = object(value, "response_format")?;
|
||||
let kind = required_string(&mut format, "type", "response_format.type", false)?;
|
||||
match kind.as_str() {
|
||||
"text" | "json_object" => Ok(json!({"type": kind})),
|
||||
"json_schema" => {
|
||||
let mut schema = object(
|
||||
required(&mut format, "json_schema", "response_format.json_schema")?,
|
||||
"response_format.json_schema",
|
||||
)?;
|
||||
let name = required_string(
|
||||
&mut schema,
|
||||
"name",
|
||||
"response_format.json_schema.name",
|
||||
false,
|
||||
)?;
|
||||
let definition = required(&mut schema, "schema", "response_format.json_schema.schema")?;
|
||||
if definition.is_null() {
|
||||
return Err(invalid("response_format.json_schema.schema"));
|
||||
}
|
||||
let mut converted = json!({"type": "json_schema", "name": name, "schema": definition});
|
||||
if let Some(strict) =
|
||||
optional_bool(&mut schema, "strict", "response_format.json_schema.strict")?
|
||||
{
|
||||
converted["strict"] = strict.into();
|
||||
}
|
||||
if let Some(description) = optional(&mut schema, "description") {
|
||||
string(
|
||||
&description,
|
||||
"response_format.json_schema.description",
|
||||
true,
|
||||
)?;
|
||||
converted["description"] = description;
|
||||
}
|
||||
Ok(converted)
|
||||
}
|
||||
_ => Err(unsupported("response_format.type")),
|
||||
}
|
||||
}
|
||||
|
||||
fn optional(object: &mut Map<String, Value>, key: &str) -> Option<Value> {
|
||||
object.remove(key).filter(|value| !value.is_null())
|
||||
}
|
||||
|
||||
fn required(
|
||||
object: &mut Map<String, Value>,
|
||||
key: &str,
|
||||
path: &str,
|
||||
) -> Result<Value, RequestDecodeError> {
|
||||
object
|
||||
.remove(key)
|
||||
.ok_or_else(|| RequestDecodeError::MissingField { field: path.into() })
|
||||
}
|
||||
|
||||
fn object(value: Value, path: &str) -> Result<Map<String, Value>, RequestDecodeError> {
|
||||
match value {
|
||||
Value::Object(object) => Ok(object),
|
||||
_ => Err(invalid_type(path, "an object")),
|
||||
}
|
||||
}
|
||||
|
||||
fn array(value: Value, path: &str) -> Result<Vec<Value>, RequestDecodeError> {
|
||||
match value {
|
||||
Value::Array(array) => Ok(array),
|
||||
_ => Err(invalid_type(path, "an array")),
|
||||
}
|
||||
}
|
||||
|
||||
fn string<'a>(
|
||||
value: &'a Value,
|
||||
path: &str,
|
||||
allow_empty: bool,
|
||||
) -> Result<&'a str, RequestDecodeError> {
|
||||
let value = value
|
||||
.as_str()
|
||||
.ok_or_else(|| invalid_type(path, "a string"))?;
|
||||
if !allow_empty && value.trim().is_empty() {
|
||||
return Err(RequestDecodeError::EmptyField { field: path.into() });
|
||||
}
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
fn required_string(
|
||||
object: &mut Map<String, Value>,
|
||||
key: &str,
|
||||
path: &str,
|
||||
allow_empty: bool,
|
||||
) -> Result<String, RequestDecodeError> {
|
||||
let value = required(object, key, path)?;
|
||||
string(&value, path, allow_empty)?;
|
||||
match value {
|
||||
Value::String(value) => Ok(value),
|
||||
_ => Err(invalid_type(path, "a string")),
|
||||
}
|
||||
}
|
||||
|
||||
fn optional_bool(
|
||||
object: &mut Map<String, Value>,
|
||||
key: &str,
|
||||
path: &str,
|
||||
) -> Result<Option<bool>, RequestDecodeError> {
|
||||
optional(object, key)
|
||||
.map(|value| {
|
||||
value
|
||||
.as_bool()
|
||||
.ok_or_else(|| invalid_type(path, "a boolean"))
|
||||
})
|
||||
.transpose()
|
||||
}
|
||||
|
||||
fn invalid_type(path: &str, expected: &'static str) -> RequestDecodeError {
|
||||
RequestDecodeError::InvalidType {
|
||||
field: path.into(),
|
||||
expected,
|
||||
}
|
||||
}
|
||||
|
||||
fn invalid(path: &str) -> RequestDecodeError {
|
||||
RequestDecodeError::InvalidValue { field: path.into() }
|
||||
}
|
||||
|
||||
fn unsupported(path: &str) -> RequestDecodeError {
|
||||
RequestDecodeError::UnsupportedField { field: path.into() }
|
||||
}
|
||||
@@ -0,0 +1,664 @@
|
||||
//! 将实际 Responses wire 投影为 Chat JSON 和 SSE,不拥有执行、计费或终结生命周期
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use bytes::Bytes;
|
||||
use gateway_protocol::openai::events::{billable_usage_is_complete, extract_usage};
|
||||
use gateway_protocol::openai::sse::encode_sse_event;
|
||||
use serde::Serialize;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::openai::responses::{ProtocolError, ProtocolErrorBody};
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub(in crate::openai) struct ChatIdentity {
|
||||
pub id: String,
|
||||
pub created: u64,
|
||||
pub model: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct Envelope<'a> {
|
||||
#[serde(flatten)]
|
||||
identity: &'a ChatIdentity,
|
||||
object: &'static str,
|
||||
choices: Value,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
usage: Option<Value>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
metadata: Option<&'a Value>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
service_tier: Option<&'a Value>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
moderation: Option<Value>,
|
||||
}
|
||||
|
||||
/// 输入已由现有 Responses collector 聚合,投影不再恢复或重建缺失的 output
|
||||
pub(in crate::openai) fn project_response(
|
||||
response: &Value,
|
||||
identity: &ChatIdentity,
|
||||
) -> Result<Value, ProtocolErrorBody> {
|
||||
let output = response
|
||||
.get("output")
|
||||
.and_then(Value::as_array)
|
||||
.ok_or_else(invalid_response)?;
|
||||
validate_output_identities(output)?;
|
||||
let mut content = None;
|
||||
let mut refusal = None;
|
||||
let mut tools = Vec::new();
|
||||
for item in output {
|
||||
match required_str(item, "type")? {
|
||||
"message" => {
|
||||
for part in message_parts(item)? {
|
||||
let (kind, text) = part_text(part)?;
|
||||
let target = match kind {
|
||||
PartKind::Text => &mut content,
|
||||
PartKind::Refusal => &mut refusal,
|
||||
};
|
||||
target.get_or_insert_with(String::new).push_str(text);
|
||||
}
|
||||
}
|
||||
"function_call" => {
|
||||
let (id, name, arguments) = function_fields(item)?;
|
||||
tools.push(json!({
|
||||
"id": id, "type": "function",
|
||||
"function": {"name": name, "arguments": arguments}
|
||||
}));
|
||||
}
|
||||
"reasoning" => {}
|
||||
_ => return Err(invalid_response()),
|
||||
}
|
||||
}
|
||||
let finish_reason = finish_reason(response, !tools.is_empty())?;
|
||||
let mut message = json!({"role": "assistant", "content": content, "refusal": refusal});
|
||||
if !tools.is_empty() {
|
||||
message["tool_calls"] = Value::Array(tools);
|
||||
}
|
||||
serde_json::to_value(Envelope {
|
||||
identity,
|
||||
object: "chat.completion",
|
||||
choices: json!([{"index": 0, "message": message, "finish_reason": finish_reason, "logprobs": null}]),
|
||||
usage: chat_usage(response),
|
||||
metadata: response.get("metadata"),
|
||||
service_tier: response.get("service_tier"),
|
||||
moderation: project_moderation(response)?,
|
||||
})
|
||||
.map_err(|_| invalid_response())
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum PartKind {
|
||||
Text,
|
||||
Refusal,
|
||||
}
|
||||
|
||||
impl PartKind {
|
||||
const fn field(self) -> &'static str {
|
||||
match self {
|
||||
Self::Text => "content",
|
||||
Self::Refusal => "refusal",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Part {
|
||||
kind: PartKind,
|
||||
text: String,
|
||||
}
|
||||
|
||||
struct Tool {
|
||||
index: usize,
|
||||
call_id: String,
|
||||
name: String,
|
||||
arguments: String,
|
||||
}
|
||||
|
||||
enum Output {
|
||||
Message(BTreeMap<u64, Part>),
|
||||
Function(Tool),
|
||||
Reasoning,
|
||||
}
|
||||
|
||||
struct OutputItem {
|
||||
id: Option<String>,
|
||||
output: Output,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum Terminal {
|
||||
Completed,
|
||||
Failed,
|
||||
}
|
||||
|
||||
/// 只保存身份关联与快照去重所需内容;终态帧由外层受管 body 决定何时交付
|
||||
pub(in crate::openai) struct ChatStreamEncoder {
|
||||
identity: ChatIdentity,
|
||||
include_usage: bool,
|
||||
role_sent: bool,
|
||||
output: BTreeMap<u64, OutputItem>,
|
||||
terminal: Option<Terminal>,
|
||||
}
|
||||
|
||||
impl ChatStreamEncoder {
|
||||
pub(in crate::openai) fn new(identity: ChatIdentity, include_usage: bool) -> Self {
|
||||
Self {
|
||||
identity,
|
||||
include_usage,
|
||||
role_sent: false,
|
||||
output: BTreeMap::new(),
|
||||
terminal: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::openai) fn is_completed(&self) -> bool {
|
||||
self.terminal == Some(Terminal::Completed)
|
||||
}
|
||||
|
||||
pub(in crate::openai) fn has_wire_failure(&self) -> bool {
|
||||
self.terminal == Some(Terminal::Failed)
|
||||
}
|
||||
|
||||
pub(in crate::openai) fn push_event(
|
||||
&mut self,
|
||||
event_type: Option<&str>,
|
||||
data: &Value,
|
||||
) -> Result<Vec<Bytes>, ProtocolErrorBody> {
|
||||
let event_type = event_type.or_else(|| data.get("type").and_then(Value::as_str));
|
||||
if self.has_wire_failure() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let mut frames = Vec::new();
|
||||
match event_type {
|
||||
Some("response.created") => {
|
||||
self.require_open()?;
|
||||
if !self.role_sent {
|
||||
frames.push(self.delta(json!({"role": "assistant"}))?);
|
||||
self.role_sent = true;
|
||||
}
|
||||
}
|
||||
Some("response.output_text.delta" | "response.refusal.delta") => {
|
||||
self.require_open()?;
|
||||
let kind = if event_type == Some("response.refusal.delta") {
|
||||
PartKind::Refusal
|
||||
} else {
|
||||
PartKind::Text
|
||||
};
|
||||
let delta = required_str(data, "delta")?;
|
||||
let part = self.event_part(data, kind)?;
|
||||
part.text.push_str(delta);
|
||||
if !delta.is_empty() {
|
||||
frames.push(self.delta(json!({kind.field(): delta}))?);
|
||||
}
|
||||
}
|
||||
Some("response.output_text.done" | "response.refusal.done") => {
|
||||
self.require_open()?;
|
||||
let (kind, field) = if event_type == Some("response.refusal.done") {
|
||||
(PartKind::Refusal, "refusal")
|
||||
} else {
|
||||
(PartKind::Text, "text")
|
||||
};
|
||||
let text = required_str(data, field)?;
|
||||
let part = self.event_part(data, kind)?;
|
||||
let suffix = append_snapshot(&mut part.text, text)?;
|
||||
if !suffix.is_empty() {
|
||||
frames.push(self.delta(json!({kind.field(): suffix}))?);
|
||||
}
|
||||
}
|
||||
Some("response.content_part.added" | "response.content_part.done") => {
|
||||
self.require_open()?;
|
||||
let part = data.get("part").ok_or_else(invalid_response)?;
|
||||
let (kind, text) = part_text(part)?;
|
||||
let part = self.event_part(data, kind)?;
|
||||
let suffix = append_snapshot(&mut part.text, text)?;
|
||||
if !suffix.is_empty() {
|
||||
frames.push(self.delta(json!({kind.field(): suffix}))?);
|
||||
}
|
||||
}
|
||||
Some("response.output_item.added" | "response.output_item.done") => {
|
||||
self.require_open()?;
|
||||
self.item_snapshot(
|
||||
required_index(data, "output_index")?,
|
||||
data.get("item").ok_or_else(invalid_response)?,
|
||||
false,
|
||||
&mut frames,
|
||||
)?;
|
||||
}
|
||||
Some(
|
||||
"response.function_call_arguments.delta" | "response.function_call_arguments.done",
|
||||
) => {
|
||||
self.require_open()?;
|
||||
let index = required_index(data, "output_index")?;
|
||||
let item = self.output.get_mut(&index).ok_or_else(invalid_response)?;
|
||||
bind_id(item, optional_id(data, "item_id")?)?;
|
||||
let Output::Function(tool) = &mut item.output else {
|
||||
return Err(invalid_response());
|
||||
};
|
||||
let delta = if event_type == Some("response.function_call_arguments.delta") {
|
||||
let delta = required_str(data, "delta")?;
|
||||
tool.arguments.push_str(delta);
|
||||
delta
|
||||
} else {
|
||||
append_snapshot(&mut tool.arguments, required_str(data, "arguments")?)?
|
||||
};
|
||||
let tool_index = tool.index;
|
||||
if !delta.is_empty() {
|
||||
frames.push(self.delta(json!({"tool_calls": [{"index": tool_index, "function": {"arguments": delta}}]}))?);
|
||||
}
|
||||
}
|
||||
Some("response.completed" | "response.incomplete") => {
|
||||
self.require_open()?;
|
||||
let response = data.get("response").ok_or_else(invalid_response)?;
|
||||
let status = required_str(response, "status")?;
|
||||
if (event_type == Some("response.completed") && status != "completed")
|
||||
|| (event_type == Some("response.incomplete") && status != "incomplete")
|
||||
{
|
||||
return Err(invalid_response());
|
||||
}
|
||||
if let Some(output) = response.get("output") {
|
||||
let output = output.as_array().ok_or_else(invalid_response)?;
|
||||
validate_output_identities(output)?;
|
||||
for (index, item) in output.iter().enumerate() {
|
||||
self.item_snapshot(index as u64, item, true, &mut frames)?;
|
||||
}
|
||||
} else if self.output.is_empty() {
|
||||
return Err(invalid_response());
|
||||
}
|
||||
let finish_reason = finish_reason(response, self.tool_count() > 0)?;
|
||||
frames.push(self.chunk(
|
||||
json!([{"index": 0, "delta": {}, "finish_reason": finish_reason, "logprobs": null}]),
|
||||
self.include_usage.then_some(Value::Null),
|
||||
Some(response),
|
||||
)?);
|
||||
if self.include_usage
|
||||
&& let Some(usage) = chat_usage(response)
|
||||
{
|
||||
frames.push(self.chunk(json!([]), Some(usage), None)?);
|
||||
}
|
||||
self.terminal = Some(Terminal::Completed);
|
||||
}
|
||||
Some("response.failed" | "error") => {
|
||||
self.require_open()?;
|
||||
let error = data
|
||||
.pointer("/response/error")
|
||||
.or_else(|| data.get("error"))
|
||||
.unwrap_or(data);
|
||||
required_str(error, "message")?;
|
||||
// 错误恢复信号和扩展由既有出口拥有,Chat 仅转换外层包装
|
||||
let mut error = error.clone();
|
||||
if error
|
||||
.get("type")
|
||||
.and_then(Value::as_str)
|
||||
.is_none_or(|kind| kind == "error")
|
||||
{
|
||||
error["type"] = json!("server_error");
|
||||
}
|
||||
frames.push(sse_frame(&json!({"error": error})));
|
||||
self.terminal = Some(Terminal::Failed);
|
||||
}
|
||||
// 辅助事件可随上游演进;实际 output item 和 content part 仍逐项检查可表达性
|
||||
_ => {}
|
||||
}
|
||||
// done-only 流也要提供完整 Chat 消息身份,辅助事件或私有推理不触发角色帧
|
||||
if !self.role_sent && !frames.is_empty() && !self.has_wire_failure() {
|
||||
frames.insert(0, self.delta(json!({"role": "assistant"}))?);
|
||||
self.role_sent = true;
|
||||
}
|
||||
Ok(frames)
|
||||
}
|
||||
|
||||
fn require_open(&self) -> Result<(), ProtocolErrorBody> {
|
||||
if self.terminal.is_some() {
|
||||
Err(invalid_response())
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn tool_count(&self) -> usize {
|
||||
self.output
|
||||
.values()
|
||||
.filter(|item| matches!(item.output, Output::Function(_)))
|
||||
.count()
|
||||
}
|
||||
|
||||
fn event_part(&mut self, data: &Value, kind: PartKind) -> Result<&mut Part, ProtocolErrorBody> {
|
||||
let index = required_index(data, "output_index")?;
|
||||
let content_index = required_index(data, "content_index")?;
|
||||
let id = optional_id(data, "item_id")?;
|
||||
let item = self.output.entry(index).or_insert_with(|| OutputItem {
|
||||
id: None,
|
||||
output: Output::Message(BTreeMap::new()),
|
||||
});
|
||||
bind_id(item, id)?;
|
||||
message_part(item, content_index, kind)
|
||||
}
|
||||
|
||||
fn item_snapshot(
|
||||
&mut self,
|
||||
index: u64,
|
||||
snapshot: &Value,
|
||||
terminal: bool,
|
||||
frames: &mut Vec<Bytes>,
|
||||
) -> Result<(), ProtocolErrorBody> {
|
||||
let id = optional_id(snapshot, "id")?;
|
||||
let kind = required_str(snapshot, "type")?;
|
||||
let call_id = if kind == "function_call" {
|
||||
Some(required_nonempty_str(snapshot, "call_id")?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let known_index = self.find_item(id, call_id)?;
|
||||
let index = match known_index {
|
||||
Some(known) if terminal || known == index => known,
|
||||
Some(_) => return Err(invalid_response()),
|
||||
None => index,
|
||||
};
|
||||
if !self.output.contains_key(&index) {
|
||||
let output = match kind {
|
||||
"message" => Output::Message(BTreeMap::new()),
|
||||
"reasoning" => Output::Reasoning,
|
||||
"function_call" => {
|
||||
let (call_id, name, _) = function_fields(snapshot)?;
|
||||
let tool_index = self.tool_count();
|
||||
frames.push(self.delta(json!({"tool_calls": [{"index": tool_index, "id": call_id, "type": "function", "function": {"name": name, "arguments": ""}}]}))?);
|
||||
Output::Function(Tool {
|
||||
index: tool_index,
|
||||
call_id: call_id.to_owned(),
|
||||
name: name.to_owned(),
|
||||
arguments: String::new(),
|
||||
})
|
||||
}
|
||||
_ => return Err(invalid_response()),
|
||||
};
|
||||
self.output.insert(index, OutputItem { id: None, output });
|
||||
}
|
||||
let item = self.output.get_mut(&index).ok_or_else(invalid_response)?;
|
||||
bind_id(item, id)?;
|
||||
match (&mut item.output, kind) {
|
||||
(Output::Message(parts), "message") => {
|
||||
for (index, part) in message_parts(snapshot)?.iter().enumerate() {
|
||||
let (kind, text) = part_text(part)?;
|
||||
let part = part_entry(parts, index as u64, kind)?;
|
||||
let suffix = append_snapshot(&mut part.text, text)?;
|
||||
if !suffix.is_empty() {
|
||||
frames.push(delta_frame(
|
||||
&self.identity,
|
||||
self.include_usage,
|
||||
json!({kind.field(): suffix}),
|
||||
)?);
|
||||
}
|
||||
}
|
||||
}
|
||||
(Output::Function(tool), "function_call") => {
|
||||
let (id, name, arguments) = function_fields(snapshot)?;
|
||||
if tool.call_id != id || tool.name != name {
|
||||
return Err(invalid_response());
|
||||
}
|
||||
let suffix = append_snapshot(&mut tool.arguments, arguments)?;
|
||||
if !suffix.is_empty() {
|
||||
frames.push(delta_frame(&self.identity, self.include_usage, json!({"tool_calls": [{"index": tool.index, "function": {"arguments": suffix}}]}))?);
|
||||
}
|
||||
}
|
||||
(Output::Reasoning, "reasoning") => {}
|
||||
_ => return Err(invalid_response()),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn find_item(
|
||||
&self,
|
||||
id: Option<&str>,
|
||||
call_id: Option<&str>,
|
||||
) -> Result<Option<u64>, ProtocolErrorBody> {
|
||||
let mut found = None;
|
||||
for (&index, item) in &self.output {
|
||||
let same_id = id.is_some() && item.id.as_deref() == id;
|
||||
let same_call = matches!(&item.output, Output::Function(tool) if call_id == Some(tool.call_id.as_str()));
|
||||
if same_id || same_call {
|
||||
if found.is_some_and(|previous| previous != index) {
|
||||
return Err(invalid_response());
|
||||
}
|
||||
found = Some(index);
|
||||
}
|
||||
}
|
||||
Ok(found)
|
||||
}
|
||||
|
||||
fn delta(&self, delta: Value) -> Result<Bytes, ProtocolErrorBody> {
|
||||
delta_frame(&self.identity, self.include_usage, delta)
|
||||
}
|
||||
|
||||
fn chunk(
|
||||
&self,
|
||||
choices: Value,
|
||||
usage: Option<Value>,
|
||||
response: Option<&Value>,
|
||||
) -> Result<Bytes, ProtocolErrorBody> {
|
||||
chunk_frame(&self.identity, choices, usage, response)
|
||||
}
|
||||
}
|
||||
|
||||
fn message_part(
|
||||
item: &mut OutputItem,
|
||||
index: u64,
|
||||
kind: PartKind,
|
||||
) -> Result<&mut Part, ProtocolErrorBody> {
|
||||
let Output::Message(parts) = &mut item.output else {
|
||||
return Err(invalid_response());
|
||||
};
|
||||
part_entry(parts, index, kind)
|
||||
}
|
||||
|
||||
fn part_entry(
|
||||
parts: &mut BTreeMap<u64, Part>,
|
||||
index: u64,
|
||||
kind: PartKind,
|
||||
) -> Result<&mut Part, ProtocolErrorBody> {
|
||||
let part = parts.entry(index).or_insert_with(|| Part {
|
||||
kind,
|
||||
text: String::new(),
|
||||
});
|
||||
if part.kind != kind {
|
||||
return Err(invalid_response());
|
||||
}
|
||||
Ok(part)
|
||||
}
|
||||
|
||||
fn bind_id(item: &mut OutputItem, id: Option<&str>) -> Result<(), ProtocolErrorBody> {
|
||||
if let Some(id) = id {
|
||||
if item.id.as_deref().is_some_and(|previous| previous != id) {
|
||||
return Err(invalid_response());
|
||||
}
|
||||
if item.id.is_none() {
|
||||
item.id = Some(id.to_owned());
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn append_snapshot<'a>(text: &mut String, snapshot: &'a str) -> Result<&'a str, ProtocolErrorBody> {
|
||||
let suffix = snapshot
|
||||
.strip_prefix(text.as_str())
|
||||
.ok_or_else(invalid_response)?;
|
||||
text.push_str(suffix);
|
||||
Ok(suffix)
|
||||
}
|
||||
|
||||
fn message_parts(item: &Value) -> Result<&[Value], ProtocolErrorBody> {
|
||||
if required_str(item, "role")? != "assistant" {
|
||||
return Err(invalid_response());
|
||||
}
|
||||
item.get("content")
|
||||
.and_then(Value::as_array)
|
||||
.map(Vec::as_slice)
|
||||
.ok_or_else(invalid_response)
|
||||
}
|
||||
|
||||
fn part_text(part: &Value) -> Result<(PartKind, &str), ProtocolErrorBody> {
|
||||
match required_str(part, "type")? {
|
||||
"output_text" => Ok((PartKind::Text, required_str(part, "text")?)),
|
||||
"refusal" => Ok((PartKind::Refusal, required_str(part, "refusal")?)),
|
||||
_ => Err(invalid_response()),
|
||||
}
|
||||
}
|
||||
|
||||
fn function_fields(item: &Value) -> Result<(&str, &str, &str), ProtocolErrorBody> {
|
||||
Ok((
|
||||
required_nonempty_str(item, "call_id")?,
|
||||
required_nonempty_str(item, "name")?,
|
||||
required_str(item, "arguments")?,
|
||||
))
|
||||
}
|
||||
|
||||
fn validate_output_identities(output: &[Value]) -> Result<(), ProtocolErrorBody> {
|
||||
let mut item_ids = BTreeSet::new();
|
||||
let mut call_ids = BTreeSet::new();
|
||||
for item in output {
|
||||
if let Some(id) = optional_id(item, "id")?
|
||||
&& !item_ids.insert(id)
|
||||
{
|
||||
return Err(invalid_response());
|
||||
}
|
||||
if item.get("type").and_then(Value::as_str) == Some("function_call")
|
||||
&& !call_ids.insert(required_nonempty_str(item, "call_id")?)
|
||||
{
|
||||
return Err(invalid_response());
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn finish_reason(response: &Value, has_tools: bool) -> Result<&'static str, ProtocolErrorBody> {
|
||||
if response.get("error").is_some_and(|value| !value.is_null()) {
|
||||
return Err(invalid_response());
|
||||
}
|
||||
match required_str(response, "status")? {
|
||||
"completed" => Ok(if has_tools { "tool_calls" } else { "stop" }),
|
||||
"incomplete" => match response
|
||||
.pointer("/incomplete_details/reason")
|
||||
.and_then(Value::as_str)
|
||||
{
|
||||
Some("max_output_tokens") => Ok("length"),
|
||||
Some("content_filter") => Ok("content_filter"),
|
||||
_ => Err(invalid_response()),
|
||||
},
|
||||
_ => Err(invalid_response()),
|
||||
}
|
||||
}
|
||||
|
||||
fn chat_usage(response: &Value) -> Option<Value> {
|
||||
let usage = extract_usage(response)?;
|
||||
if !billable_usage_is_complete(response, usage) {
|
||||
return None;
|
||||
}
|
||||
let mut result = json!({"prompt_tokens": usage.input_tokens, "completion_tokens": usage.output_tokens, "total_tokens": usage.total_tokens});
|
||||
if response
|
||||
.pointer("/usage/input_tokens_details/cached_tokens")
|
||||
.is_some()
|
||||
{
|
||||
result["prompt_tokens_details"] = json!({"cached_tokens": usage.cached_input_tokens});
|
||||
}
|
||||
if response
|
||||
.pointer("/usage/output_tokens_details/reasoning_tokens")
|
||||
.and_then(Value::as_u64)
|
||||
.is_some_and(|tokens| tokens <= usage.output_tokens)
|
||||
{
|
||||
result["completion_tokens_details"] =
|
||||
json!({"reasoning_tokens": usage.reasoning_output_tokens});
|
||||
}
|
||||
Some(result)
|
||||
}
|
||||
|
||||
fn project_moderation(response: &Value) -> Result<Option<Value>, ProtocolErrorBody> {
|
||||
let Some(moderation) = response.get("moderation").filter(|value| !value.is_null()) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let mut result = json!({});
|
||||
for side in ["input", "output"] {
|
||||
let value = moderation.get(side).ok_or_else(invalid_response)?;
|
||||
result[side] = match required_str(value, "type")? {
|
||||
"moderation_result" => {
|
||||
json!({"type": "moderation_results", "model": required_str(value, "model")?, "results": [value]})
|
||||
}
|
||||
"error" => value.clone(),
|
||||
_ => return Err(invalid_response()),
|
||||
};
|
||||
}
|
||||
Ok(Some(result))
|
||||
}
|
||||
|
||||
fn delta_frame(
|
||||
identity: &ChatIdentity,
|
||||
include_usage: bool,
|
||||
delta: Value,
|
||||
) -> Result<Bytes, ProtocolErrorBody> {
|
||||
chunk_frame(
|
||||
identity,
|
||||
json!([{"index": 0, "delta": delta, "finish_reason": null, "logprobs": null}]),
|
||||
include_usage.then_some(Value::Null),
|
||||
None,
|
||||
)
|
||||
}
|
||||
|
||||
fn chunk_frame(
|
||||
identity: &ChatIdentity,
|
||||
choices: Value,
|
||||
usage: Option<Value>,
|
||||
response: Option<&Value>,
|
||||
) -> Result<Bytes, ProtocolErrorBody> {
|
||||
let value = serde_json::to_value(Envelope {
|
||||
identity,
|
||||
object: "chat.completion.chunk",
|
||||
choices,
|
||||
usage,
|
||||
metadata: None,
|
||||
service_tier: response.and_then(|value| value.get("service_tier")),
|
||||
moderation: response.map(project_moderation).transpose()?.flatten(),
|
||||
})
|
||||
.map_err(|_| invalid_response())?;
|
||||
Ok(sse_frame(&value))
|
||||
}
|
||||
|
||||
fn sse_frame(value: &Value) -> Bytes {
|
||||
Bytes::from(encode_sse_event("", &value.to_string()))
|
||||
}
|
||||
|
||||
fn required_str<'a>(value: &'a Value, field: &str) -> Result<&'a str, ProtocolErrorBody> {
|
||||
value
|
||||
.get(field)
|
||||
.and_then(Value::as_str)
|
||||
.ok_or_else(invalid_response)
|
||||
}
|
||||
|
||||
fn required_nonempty_str<'a>(value: &'a Value, field: &str) -> Result<&'a str, ProtocolErrorBody> {
|
||||
let value = required_str(value, field)?;
|
||||
if value.is_empty() {
|
||||
return Err(invalid_response());
|
||||
}
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
fn optional_id<'a>(value: &'a Value, field: &str) -> Result<Option<&'a str>, ProtocolErrorBody> {
|
||||
value
|
||||
.get(field)
|
||||
.map(|_| required_nonempty_str(value, field))
|
||||
.transpose()
|
||||
}
|
||||
|
||||
fn required_index(value: &Value, field: &str) -> Result<u64, ProtocolErrorBody> {
|
||||
value
|
||||
.get(field)
|
||||
.and_then(Value::as_u64)
|
||||
.ok_or_else(invalid_response)
|
||||
}
|
||||
|
||||
fn invalid_response() -> ProtocolErrorBody {
|
||||
ProtocolErrorBody {
|
||||
error: ProtocolError {
|
||||
kind: "server_error",
|
||||
code: "invalid_upstream_response",
|
||||
message: "The upstream response cannot be represented as a Chat completion.".to_owned(),
|
||||
param: None,
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
//! OpenAI 客户端协议 adapter
|
||||
|
||||
pub mod auth;
|
||||
mod chat_completions;
|
||||
mod endpoint;
|
||||
pub mod error;
|
||||
pub mod images;
|
||||
|
||||
@@ -31,6 +31,7 @@ use gateway_core::event::{ProviderEvent, ProviderResponseHeader};
|
||||
use gateway_core::lifecycle::{CancellationToken, ConnectionGuard};
|
||||
use gateway_core::operation::OperationKind;
|
||||
use gateway_protocol::openai::sse::{DONE_SSE_FRAME, response_failed_sse_event_with_id};
|
||||
use serde_json::Value;
|
||||
use tokio::time::Instant;
|
||||
|
||||
use crate::ApiState;
|
||||
@@ -120,6 +121,23 @@ pub(crate) async fn execute_prepared_responses(
|
||||
prepared: PreparedRootExecution,
|
||||
request: ResponsesHttpRequest,
|
||||
authorization: Option<Arc<dyn ResponseAuthorization>>,
|
||||
) -> Response {
|
||||
execute_prepared_response(service, prepared, request, authorization, None).await
|
||||
}
|
||||
|
||||
/// 下游协议只投影出口字节 执行会话和计量仍归原 owner
|
||||
pub(in crate::openai) struct HttpResponseAdapter {
|
||||
pub endpoint: &'static str,
|
||||
pub wrap: Box<dyn FnOnce(MiddlewareResponse) -> MiddlewareResponse + Send>,
|
||||
pub stream_error: fn(&Value) -> Bytes,
|
||||
}
|
||||
|
||||
pub(in crate::openai) async fn execute_prepared_response(
|
||||
service: OpenAiService,
|
||||
prepared: PreparedRootExecution,
|
||||
request: ResponsesHttpRequest,
|
||||
authorization: Option<Arc<dyn ResponseAuthorization>>,
|
||||
adapter: Option<HttpResponseAdapter>,
|
||||
) -> Response {
|
||||
let ResponsesHttpRequest {
|
||||
peer_address,
|
||||
@@ -148,8 +166,14 @@ pub(crate) async fn execute_prepared_responses(
|
||||
// 中间件正文已经由入口按上限解压;传输编码和旧长度不能与改写后的正文混用
|
||||
middleware_headers.remove(CONTENT_ENCODING);
|
||||
middleware_headers.remove(CONTENT_LENGTH);
|
||||
let endpoint = adapter
|
||||
.as_ref()
|
||||
.map_or(crate::openai::router::RESPONSES_PATH, |adapter| {
|
||||
adapter.endpoint
|
||||
});
|
||||
let stream_error = adapter.as_ref().map(|adapter| adapter.stream_error);
|
||||
let input = RequestInput {
|
||||
endpoint: crate::openai::router::RESPONSES_PATH.to_owned(),
|
||||
endpoint: endpoint.to_owned(),
|
||||
protocol: OPENAI_PROTOCOL.to_owned(),
|
||||
operation: Some(OperationKind::Generate),
|
||||
transport,
|
||||
@@ -194,12 +218,7 @@ pub(crate) async fn execute_prepared_responses(
|
||||
None
|
||||
};
|
||||
let started = terminal_service
|
||||
.start_prepared_response(
|
||||
prepared,
|
||||
decoded,
|
||||
transport,
|
||||
crate::openai::router::RESPONSES_PATH,
|
||||
)
|
||||
.start_prepared_response(prepared, decoded, transport, endpoint)
|
||||
.await
|
||||
.map_err(MiddlewareError::Gateway)?;
|
||||
let _ = terminal_request_id.set(started.request_id.clone());
|
||||
@@ -242,17 +261,18 @@ pub(crate) async fn execute_prepared_responses(
|
||||
} else {
|
||||
response
|
||||
};
|
||||
into_http_response(
|
||||
validated_middleware_response(response, validation, stream),
|
||||
expected,
|
||||
)
|
||||
.await
|
||||
let response = validated_middleware_response(response, validation, stream);
|
||||
let response = match adapter {
|
||||
Some(adapter) => (adapter.wrap)(response),
|
||||
None => response,
|
||||
};
|
||||
into_http_response(response, expected).await
|
||||
}
|
||||
Err(error) => error_response(error),
|
||||
}
|
||||
};
|
||||
let response = if stream {
|
||||
super::keepalive::response(response, keepalive).await
|
||||
super::keepalive::response_with_encoder(response, keepalive, stream_error).await
|
||||
} else {
|
||||
response.await
|
||||
};
|
||||
|
||||
@@ -21,6 +21,14 @@ use crate::openai::middleware::{SSE_KEEPALIVE_FRAME, SSE_KEEPALIVE_INTERVAL};
|
||||
pub(super) async fn response(
|
||||
response: impl Future<Output = Response> + Send + 'static,
|
||||
admitted: oneshot::Receiver<ResponseCommit>,
|
||||
) -> Response {
|
||||
response_with_encoder(response, admitted, None).await
|
||||
}
|
||||
|
||||
pub(super) async fn response_with_encoder(
|
||||
response: impl Future<Output = Response> + Send + 'static,
|
||||
admitted: oneshot::Receiver<ResponseCommit>,
|
||||
error_encoder: Option<fn(&Value) -> Bytes>,
|
||||
) -> Response {
|
||||
let mut response = Box::pin(response);
|
||||
// 鉴权、模型门禁和准入失败仍保留原 HTTP 状态,不提前建立 SSE
|
||||
@@ -40,7 +48,7 @@ pub(super) async fn response(
|
||||
if !commit.record(Some(StatusCode::OK.as_u16())) {
|
||||
return response.await;
|
||||
}
|
||||
let pending = PendingResponse::Waiting(response);
|
||||
let pending = PendingResponse::Waiting(response, error_encoder);
|
||||
let stream = stream::once(async { Ok::<_, axum::Error>(SSE_KEEPALIVE_FRAME) })
|
||||
.chain(stream::try_unfold(pending, PendingResponse::next));
|
||||
let mut response = Response::new(Body::from_stream(stream));
|
||||
@@ -58,7 +66,7 @@ pub(super) async fn response(
|
||||
}
|
||||
|
||||
enum PendingResponse {
|
||||
Waiting(BoxFuture<'static, Response>),
|
||||
Waiting(BoxFuture<'static, Response>, Option<fn(&Value) -> Bytes>),
|
||||
Streaming(BodyDataStream),
|
||||
}
|
||||
|
||||
@@ -66,7 +74,7 @@ impl PendingResponse {
|
||||
async fn next(mut self) -> Result<Option<(Bytes, Self)>, axum::Error> {
|
||||
loop {
|
||||
match &mut self {
|
||||
Self::Waiting(response) => {
|
||||
Self::Waiting(response, error_encoder) => {
|
||||
// 心跳只轮询同一个 future,不取消重建首帧等待或插件调用
|
||||
let response = tokio::select! {
|
||||
biased;
|
||||
@@ -85,7 +93,7 @@ impl PendingResponse {
|
||||
let body = if sse {
|
||||
response.into_body()
|
||||
} else {
|
||||
stream_failure(response).await
|
||||
stream_failure(response, *error_encoder).await
|
||||
};
|
||||
// 正式响应的正文已经带有交付期心跳,后续只转交,不叠加定时器
|
||||
self = Self::Streaming(body.into_data_stream());
|
||||
@@ -102,7 +110,7 @@ impl PendingResponse {
|
||||
}
|
||||
}
|
||||
|
||||
async fn stream_failure(response: Response) -> Body {
|
||||
async fn stream_failure(response: Response, error_encoder: Option<fn(&Value) -> Bytes>) -> Body {
|
||||
let status = response.status();
|
||||
let retry_after = response
|
||||
.headers()
|
||||
@@ -145,7 +153,10 @@ async fn stream_failure(response: Response) -> Body {
|
||||
.entry("retry-after")
|
||||
.or_insert(Value::String(retry_after));
|
||||
}
|
||||
let mut event = encode_sse_event("response.failed", &data.to_string());
|
||||
event.push_str(DONE_SSE_FRAME);
|
||||
let mut event = match error_encoder {
|
||||
Some(encode) => encode(&data).to_vec(),
|
||||
None => encode_sse_event("response.failed", &data.to_string()).into_bytes(),
|
||||
};
|
||||
event.extend_from_slice(DONE_SSE_FRAME.as_bytes());
|
||||
Body::from(event)
|
||||
}
|
||||
|
||||
@@ -10,10 +10,12 @@ pub mod websocket;
|
||||
|
||||
pub(crate) use crate::request_context::request_client_context;
|
||||
pub use error::{ProtocolError, ProtocolErrorBody, RequestDecodeError, ResponseEncodeError};
|
||||
pub(in crate::openai) use http::{HttpResponseAdapter, execute_prepared_response};
|
||||
pub(crate) use http::{
|
||||
ResponseAuthorization, ResponsesHttpRequest, execute_prepared_responses, responses,
|
||||
};
|
||||
pub use http::{collect_execution_response, stream_execution_response};
|
||||
pub(in crate::openai) use request::decompress_request_body;
|
||||
pub use request::{
|
||||
ContinuationIntent, DecodedResponsesRequest, OpenAiRequestHeaders, ResponsesRequestMetadata,
|
||||
decode_request_with_headers,
|
||||
|
||||
@@ -371,7 +371,7 @@ const MAX_ZSTD_WINDOW_LOG: u32 = 26;
|
||||
/// 未压缩与 `identity` 借用原始正文;压缩正文在读取过程中限制展开大小,
|
||||
/// 避免先完整分配再检查
|
||||
/// 只接受单一编码,重复头和叠加编码不能只解释第一项
|
||||
fn decompress_request_body<'a>(
|
||||
pub(in crate::openai) fn decompress_request_body<'a>(
|
||||
body: &'a [u8],
|
||||
headers: &HeaderMap,
|
||||
max_decompressed_bytes: usize,
|
||||
|
||||
@@ -10,6 +10,8 @@ pub(super) const DOWNSTREAM_WRITE_TIMEOUT: Duration = Duration::from_secs(5 * 60
|
||||
pub(super) const DOWNSTREAM_CLOSE_TIMEOUT: Duration = Duration::from_secs(1);
|
||||
pub(super) const CONNECTION_MAX_AGE: Duration = Duration::from_secs(60 * 60);
|
||||
pub(super) const DOWNSTREAM_PING_INTERVAL: Duration = Duration::from_secs(25);
|
||||
pub(super) const DOWNSTREAM_PONG_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
pub(super) const DOWNSTREAM_PING_WRITE_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
|
||||
/// WebSocket pump 的写入与生命周期预算
|
||||
#[derive(Clone, Copy)]
|
||||
@@ -124,6 +126,7 @@ pub enum PumpExitReason {
|
||||
ReadError,
|
||||
WriteError,
|
||||
WriteTimeout,
|
||||
PongTimeout,
|
||||
LifecycleShutdown,
|
||||
ConnectionMaxAge,
|
||||
CoordinatorDropped,
|
||||
@@ -141,6 +144,7 @@ impl PumpExitReason {
|
||||
Self::ReadError => "read_error",
|
||||
Self::WriteError => "write_error",
|
||||
Self::WriteTimeout => "write_timeout",
|
||||
Self::PongTimeout => "pong_timeout",
|
||||
Self::LifecycleShutdown => "lifecycle_shutdown",
|
||||
Self::ConnectionMaxAge => "connection_max_age",
|
||||
Self::CoordinatorDropped => "coordinator_dropped",
|
||||
|
||||
@@ -30,6 +30,7 @@ use tokio::{
|
||||
pub struct ResponsesWebSocketConnection {
|
||||
connection_id: Arc<str>,
|
||||
opened_at: Instant,
|
||||
cancellation: CancellationToken,
|
||||
expired: Arc<AtomicBool>,
|
||||
commands: Option<mpsc::Sender<ConnectionCommand>>,
|
||||
incoming: mpsc::Receiver<PendingConnectionEvent>,
|
||||
@@ -266,7 +267,9 @@ impl ResponsesWebSocketConnection {
|
||||
}
|
||||
|
||||
fn terminate(&mut self, reason: PumpExitReason) {
|
||||
let reason = self.exited.try_recv().unwrap_or(reason);
|
||||
self.exit_reason.get_or_insert(reason);
|
||||
self.cancellation.cancel();
|
||||
self.commands.take();
|
||||
if let Some(task) = self.pump_task.take() {
|
||||
task.abort();
|
||||
@@ -306,6 +309,7 @@ impl ResponsesWebSocketConnection {
|
||||
|
||||
impl Drop for ResponsesWebSocketConnection {
|
||||
fn drop(&mut self) {
|
||||
self.cancellation.cancel();
|
||||
self.commands.take();
|
||||
if let Some(task) = self.pump_task.take() {
|
||||
task.abort();
|
||||
@@ -314,6 +318,7 @@ impl Drop for ResponsesWebSocketConnection {
|
||||
}
|
||||
|
||||
/// 为 WebSocket transport 启动包含冻结中间件计划的单 owner pump
|
||||
/// cancellation 必须属于本连接,连接退出或句柄释放时会取消它
|
||||
pub fn spawn_connection<S, E>(
|
||||
socket: S,
|
||||
connection_id: Arc<str>,
|
||||
@@ -341,7 +346,7 @@ where
|
||||
incoming_tx,
|
||||
exit_tx,
|
||||
Arc::clone(&connection_id),
|
||||
cancellation,
|
||||
cancellation.clone(),
|
||||
opened_at,
|
||||
Arc::clone(&expired),
|
||||
Arc::clone(&stats),
|
||||
@@ -353,6 +358,7 @@ where
|
||||
ResponsesWebSocketConnection {
|
||||
connection_id,
|
||||
opened_at,
|
||||
cancellation,
|
||||
expired,
|
||||
commands: Some(command_tx),
|
||||
incoming: incoming_rx,
|
||||
|
||||
@@ -19,7 +19,7 @@ use std::{
|
||||
},
|
||||
};
|
||||
use tokio::{
|
||||
sync::{Semaphore, mpsc, oneshot},
|
||||
sync::{Semaphore, mpsc, oneshot, watch},
|
||||
time::Instant,
|
||||
};
|
||||
|
||||
@@ -42,6 +42,7 @@ pub(super) async fn run_pump<S, E>(
|
||||
S: Stream<Item = Result<Message, E>> + Sink<Message, Error = E> + Unpin + Send + 'static,
|
||||
E: fmt::Display + Send + 'static,
|
||||
{
|
||||
let _connection_lifetime = middleware::CancelOnDrop(Some(cancellation.clone()));
|
||||
let context = Arc::new(PumpContext {
|
||||
extensions,
|
||||
connection_id,
|
||||
@@ -57,11 +58,13 @@ pub(super) async fn run_pump<S, E>(
|
||||
let (writer, mut reader) = socket.split();
|
||||
let writer = Arc::new(middleware::Writer::new(writer, context.clone()));
|
||||
let sender: Arc<dyn contract::Sender> = writer.clone();
|
||||
// 同一个受管任务同时驱动两侧;等待写入不能阻塞入站控制、关闭或取消
|
||||
let (activity, received_activity) = watch::channel(());
|
||||
// 心跳独立于业务写入等待,但共享唯一 writer,避免长写入或排队阻止失联检测
|
||||
let reason = tokio::select! {
|
||||
biased;
|
||||
reason = read_connection(&mut reader, &incoming, sender.clone(), &context) => reason,
|
||||
reason = read_connection(&mut reader, &incoming, sender.clone(), &activity, &context) => reason,
|
||||
reason = write_connection(writer.clone(), commands, &context) => reason,
|
||||
reason = heartbeat_connection(writer.clone(), received_activity, &context) => reason,
|
||||
};
|
||||
if matches!(reason, PumpExitReason::ClientClose) {
|
||||
if let Err(error) = writer.finish_peer_close(&cancellation).await {
|
||||
@@ -78,6 +81,7 @@ async fn read_connection<S, E>(
|
||||
socket: &mut S,
|
||||
incoming: &mpsc::Sender<PendingConnectionEvent>,
|
||||
sender: Arc<dyn contract::Sender>,
|
||||
activity: &watch::Sender<()>,
|
||||
context: &PumpContext,
|
||||
) -> PumpExitReason
|
||||
where
|
||||
@@ -103,6 +107,10 @@ where
|
||||
}
|
||||
message = socket.next() => {
|
||||
if matches!(&message, Some(Ok(_))) { context.stats.record_read(context.opened_at); }
|
||||
if matches!(&message, Some(Ok(message)) if !matches!(message, Message::Close(_))) {
|
||||
// 链路活动以真实入站为准,插件丢弃消息不应抹掉对端已经响应的事实
|
||||
activity.send_replace(());
|
||||
}
|
||||
let message = match message {
|
||||
Some(Ok(message)) => match middleware::transform(message, contract::Direction::Incoming, sender.clone(), context).await {
|
||||
Ok(Some(message)) => Some(Ok(message)),
|
||||
@@ -145,40 +153,22 @@ where
|
||||
S: Sink<Message, Error = E> + Unpin + Send + 'static,
|
||||
E: fmt::Display + Send + 'static,
|
||||
{
|
||||
let mut heartbeat = tokio::time::interval_at(
|
||||
context.opened_at + DOWNSTREAM_PING_INTERVAL,
|
||||
DOWNSTREAM_PING_INTERVAL,
|
||||
);
|
||||
heartbeat.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
|
||||
let mut ping_sequence = 0_u64;
|
||||
loop {
|
||||
let message = tokio::select! {
|
||||
let command = tokio::select! {
|
||||
biased;
|
||||
() = context.cancellation.cancelled() => return PumpExitReason::LifecycleShutdown,
|
||||
command = commands.recv() => {
|
||||
let Some(command) = command else { return PumpExitReason::CoordinatorDropped; };
|
||||
let ConnectionCommand { message, context: write_context, acknowledged } = command;
|
||||
let closing = matches!(message, Message::Close(_));
|
||||
let result = match middleware::transform(message, contract::Direction::Outgoing, writer.clone(), context).await {
|
||||
Ok(Some(message)) => writer.write(message).await.map(|()| WriteOutcome::Written),
|
||||
Ok(None) => Ok(WriteOutcome::Suppressed),
|
||||
Err(error) => Err(ConnectionWriteError::Transport { message: error.to_string() }),
|
||||
};
|
||||
let reason = result.as_ref().err().map(|error| write_exit_reason(error, context));
|
||||
if let Err(error) = &result {
|
||||
tracing::debug!(websocket_connection_id = %context.connection_id, request_id = write_context.request_id.as_deref().unwrap_or(""), frame_phase = write_context.phase.as_str(), error = %error, "Responses WebSocket pump transport write failed");
|
||||
}
|
||||
let _ = acknowledged.send(result);
|
||||
if let Some(reason) = reason { return reason; }
|
||||
if closing { return PumpExitReason::ServerClose; }
|
||||
continue;
|
||||
}
|
||||
_ = heartbeat.tick() => {
|
||||
ping_sequence = ping_sequence.wrapping_add(1);
|
||||
Message::Ping(ping_sequence.to_be_bytes().to_vec().into())
|
||||
}
|
||||
command = commands.recv() => command,
|
||||
};
|
||||
let message = match middleware::transform(
|
||||
let Some(command) = command else {
|
||||
return PumpExitReason::CoordinatorDropped;
|
||||
};
|
||||
let ConnectionCommand {
|
||||
message,
|
||||
context: write_context,
|
||||
acknowledged,
|
||||
} = command;
|
||||
let closing = matches!(message, Message::Close(_));
|
||||
let result = match middleware::transform(
|
||||
message,
|
||||
contract::Direction::Outgoing,
|
||||
writer.clone(),
|
||||
@@ -186,21 +176,125 @@ where
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(Some(message)) => message,
|
||||
Ok(None) => continue,
|
||||
Err(_) => return PumpExitReason::MiddlewareFailed,
|
||||
Ok(Some(message)) => writer.write(message).await.map(|()| WriteOutcome::Written),
|
||||
Ok(None) => Ok(WriteOutcome::Suppressed),
|
||||
Err(error) => Err(ConnectionWriteError::Transport {
|
||||
message: error.to_string(),
|
||||
}),
|
||||
};
|
||||
if let Err(error) = writer.write(message).await {
|
||||
tracing::info!(websocket_connection_id = %context.connection_id, error = %error, "Responses WebSocket control write failed");
|
||||
return write_exit_reason(&error, context);
|
||||
let reason = result
|
||||
.as_ref()
|
||||
.err()
|
||||
.map(|error| write_exit_reason(error, context));
|
||||
if let Err(error) = &result {
|
||||
tracing::debug!(websocket_connection_id = %context.connection_id, request_id = write_context.request_id.as_deref().unwrap_or(""), frame_phase = write_context.phase.as_str(), error = %error, "Responses WebSocket pump transport write failed");
|
||||
}
|
||||
let _ = acknowledged.send(result);
|
||||
if let Some(reason) = reason {
|
||||
return reason;
|
||||
}
|
||||
if closing {
|
||||
return PumpExitReason::ServerClose;
|
||||
}
|
||||
context
|
||||
.stats
|
||||
.ping_written_count
|
||||
.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
async fn heartbeat_connection<S, E>(
|
||||
writer: Arc<middleware::Writer<S>>,
|
||||
mut activity: watch::Receiver<()>,
|
||||
context: &PumpContext,
|
||||
) -> PumpExitReason
|
||||
where
|
||||
S: Sink<Message, Error = E> + Unpin + Send + 'static,
|
||||
E: fmt::Display + Send + 'static,
|
||||
{
|
||||
let mut heartbeat = tokio::time::interval_at(
|
||||
context.opened_at + DOWNSTREAM_PING_INTERVAL,
|
||||
DOWNSTREAM_PING_INTERVAL,
|
||||
);
|
||||
heartbeat.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
|
||||
let mut ping_sequence = 0_u64;
|
||||
let pong_deadline = tokio::time::sleep(DOWNSTREAM_PONG_TIMEOUT);
|
||||
tokio::pin!(pong_deadline);
|
||||
let mut pending_ping = false;
|
||||
loop {
|
||||
tokio::select! {
|
||||
biased;
|
||||
() = context.cancellation.cancelled() => return PumpExitReason::LifecycleShutdown,
|
||||
changed = activity.changed() => {
|
||||
if changed.is_err() { return PumpExitReason::PumpStopped; }
|
||||
pending_ping = false;
|
||||
continue;
|
||||
}
|
||||
() = &mut pong_deadline, if pending_ping => return PumpExitReason::PongTimeout,
|
||||
_ = heartbeat.tick() => {}
|
||||
}
|
||||
ping_sequence = ping_sequence.wrapping_add(1);
|
||||
let write = tokio::time::timeout(
|
||||
DOWNSTREAM_PING_WRITE_TIMEOUT,
|
||||
write_heartbeat(&writer, ping_sequence, context),
|
||||
);
|
||||
tokio::pin!(write);
|
||||
let mut received_during_write = false;
|
||||
loop {
|
||||
tokio::select! {
|
||||
biased;
|
||||
() = context.cancellation.cancelled() => return PumpExitReason::LifecycleShutdown,
|
||||
changed = activity.changed() => {
|
||||
if changed.is_err() { return PumpExitReason::PumpStopped; }
|
||||
pending_ping = false;
|
||||
received_during_write = true;
|
||||
}
|
||||
() = &mut pong_deadline, if pending_ping => return PumpExitReason::PongTimeout,
|
||||
result = &mut write => {
|
||||
match result {
|
||||
Ok(Ok(true)) => {
|
||||
context.stats.ping_written_count.fetch_add(1, Ordering::Relaxed);
|
||||
// 重复 Ping 不顺延截止,写入完成前已经收到的响应也不能丢失
|
||||
if !pending_ping && !received_during_write {
|
||||
pong_deadline.as_mut().reset(Instant::now() + DOWNSTREAM_PONG_TIMEOUT);
|
||||
pending_ping = true;
|
||||
}
|
||||
}
|
||||
Ok(Ok(false)) => {}
|
||||
Ok(Err(reason)) => return reason,
|
||||
Err(_) => return PumpExitReason::WriteTimeout,
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn write_heartbeat<S, E>(
|
||||
writer: &Arc<middleware::Writer<S>>,
|
||||
sequence: u64,
|
||||
context: &PumpContext,
|
||||
) -> Result<bool, PumpExitReason>
|
||||
where
|
||||
S: Sink<Message, Error = E> + Unpin + Send + 'static,
|
||||
E: fmt::Display + Send + 'static,
|
||||
{
|
||||
let message = middleware::transform(
|
||||
Message::Ping(sequence.to_be_bytes().to_vec().into()),
|
||||
contract::Direction::Outgoing,
|
||||
writer.clone(),
|
||||
context,
|
||||
)
|
||||
.await
|
||||
.map_err(|_| PumpExitReason::MiddlewareFailed)?;
|
||||
let Some(message) = message else {
|
||||
return Ok(false);
|
||||
};
|
||||
let is_ping = matches!(message, Message::Ping(_));
|
||||
writer.write(message).await.map_err(|error| {
|
||||
tracing::info!(websocket_connection_id = %context.connection_id, error = %error, "Responses WebSocket control write failed");
|
||||
write_exit_reason(&error, context)
|
||||
})?;
|
||||
Ok(is_ping)
|
||||
}
|
||||
|
||||
fn write_exit_reason(error: &ConnectionWriteError, context: &PumpContext) -> PumpExitReason {
|
||||
match error {
|
||||
ConnectionWriteError::Timeout { .. } => PumpExitReason::WriteTimeout,
|
||||
|
||||
@@ -181,13 +181,15 @@ async fn serve_responses_websocket(socket: WebSocket, session: ResponsesWebSocke
|
||||
"Responses WebSocket connected"
|
||||
);
|
||||
let _connection_guard = connection_guard;
|
||||
let cancellation = lifecycle.cancellation();
|
||||
let cancellation = lifecycle.cancellation().child_token();
|
||||
let _connection_cancellation =
|
||||
crate::middleware::websocket::CancelOnDrop(Some(cancellation.clone()));
|
||||
let request_headers =
|
||||
request_headers.with_downstream_websocket_connection_id(connection_id.clone());
|
||||
let mut connection = ResponsesWebSocketConnection::new(
|
||||
socket,
|
||||
connection_id,
|
||||
cancellation,
|
||||
cancellation.clone(),
|
||||
middleware,
|
||||
encode_headers(&raw_headers).into(),
|
||||
);
|
||||
@@ -299,7 +301,11 @@ async fn serve_responses_websocket(socket: WebSocket, session: ResponsesWebSocke
|
||||
}
|
||||
execution.prepare_execution(client).await
|
||||
};
|
||||
let prepared = match preparation.await {
|
||||
let prepared = match tokio::select! {
|
||||
biased;
|
||||
_ = connection.wait_for_exit() => break,
|
||||
prepared = preparation => prepared,
|
||||
} {
|
||||
Ok(prepared) => prepared,
|
||||
Err(error) => {
|
||||
trace_rejected_request(
|
||||
@@ -317,6 +323,7 @@ async fn serve_responses_websocket(socket: WebSocket, session: ResponsesWebSocke
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let prepared = prepared.with_connection_cancellation(cancellation.clone());
|
||||
let request_id = Arc::<str>::from(prepared.request_id().to_string());
|
||||
response_control = prepared.response_control();
|
||||
let capture = new_replay_capture();
|
||||
|
||||
@@ -7,6 +7,7 @@ use axum::{
|
||||
};
|
||||
|
||||
use super::{
|
||||
chat_completions::chat_completions,
|
||||
images::{image_edits, image_generations},
|
||||
live,
|
||||
models::{model_detail, models},
|
||||
@@ -19,6 +20,7 @@ use crate::ApiState;
|
||||
|
||||
// 公开协议路径由 API 层统一定义;Core 使用操作类型,不根据这些路径分派业务
|
||||
pub(super) const RESPONSES_PATH: &str = "/v1/responses";
|
||||
pub(super) const CHAT_COMPLETIONS_PATH: &str = "/v1/chat/completions";
|
||||
pub(super) const IMAGE_GENERATIONS_PATH: &str = "/v1/images/generations";
|
||||
pub(super) const IMAGE_EDITS_PATH: &str = "/v1/images/edits";
|
||||
pub(super) const SEARCH_PATH: &str = "/v1/alpha/search";
|
||||
@@ -33,6 +35,7 @@ pub(crate) fn router() -> Router<ApiState> {
|
||||
.route(IMAGE_EDITS_PATH, post(image_edits))
|
||||
.route(SEARCH_PATH, post(standalone_search))
|
||||
.route(RESPONSES_PATH, get(responses_websocket).post(responses))
|
||||
.route(CHAT_COMPLETIONS_PATH, post(chat_completions))
|
||||
.route(MODELS_PATH, get(models))
|
||||
// 官方 OpenAI 模型详情合同使用 path ID;它不属于 Admin API 约束
|
||||
.route(MODEL_DETAIL_PATH, get(model_detail))
|
||||
|
||||
@@ -91,17 +91,17 @@ async fn account_cooldown_returns_an_instant_and_server_formatted_recovery() {
|
||||
),
|
||||
(
|
||||
Some(7200),
|
||||
AccountCooldownKind::CapacityFreeze,
|
||||
AccountCooldownKind::ErrorProtection,
|
||||
Some("剩余 2 小时"),
|
||||
),
|
||||
(
|
||||
Some(7500),
|
||||
AccountCooldownKind::CapacityFreezeProbe,
|
||||
AccountCooldownKind::ErrorProtectionProbe,
|
||||
Some("剩余 2 小时 5 分"),
|
||||
),
|
||||
(
|
||||
Some(-60),
|
||||
AccountCooldownKind::CapacityFreezeProbe,
|
||||
AccountCooldownKind::ErrorProtectionProbe,
|
||||
Some("等待探测成功"),
|
||||
),
|
||||
(Some(20), AccountCooldownKind::RateLimit, None),
|
||||
@@ -121,7 +121,14 @@ async fn account_cooldown_returns_an_instant_and_server_formatted_recovery() {
|
||||
last_error_reason: None,
|
||||
last_error_message: None,
|
||||
};
|
||||
*fixture.account.lock().unwrap() = Some(account_page_item(facts, now, "oauth"));
|
||||
let mut item = account_page_item(facts, now, "oauth");
|
||||
if kind.is_error_protection() {
|
||||
item.protection_rules = vec![gateway_core::account::AccountProtectionMatch {
|
||||
id: "removed-rule".to_owned(),
|
||||
name: "触发时的规则名称".to_owned(),
|
||||
}];
|
||||
}
|
||||
*fixture.account.lock().unwrap() = Some(item);
|
||||
let response = admin::accounts::router::<AdminTestState>()
|
||||
.with_state(fixture.state())
|
||||
.oneshot(
|
||||
@@ -138,6 +145,17 @@ async fn account_cooldown_returns_an_instant_and_server_formatted_recovery() {
|
||||
let body = to_bytes(response.into_body(), 32768).await.unwrap();
|
||||
let value: serde_json::Value = serde_json::from_slice(&body).unwrap();
|
||||
let quota = &value["data"]["items"][0]["quota"];
|
||||
if kind.is_error_protection() {
|
||||
assert_eq!(quota["rateLimitReason"], "error_protection");
|
||||
assert_eq!(
|
||||
quota["protectionRules"],
|
||||
serde_json::json!([
|
||||
{"id":"removed-rule", "name":"触发时的规则名称"}
|
||||
])
|
||||
);
|
||||
} else {
|
||||
assert_eq!(quota["protectionRules"], serde_json::json!([]));
|
||||
}
|
||||
match until {
|
||||
Some(until) => {
|
||||
assert_eq!(
|
||||
@@ -256,6 +274,7 @@ fn account_page_item(
|
||||
use gateway_core::account::resolve_account_status;
|
||||
|
||||
AccountPageItem {
|
||||
protection_rules: Vec::new(),
|
||||
account: AccountRecord {
|
||||
outbound_proxy_id: None,
|
||||
outbound_proxy_enabled: true,
|
||||
|
||||
@@ -506,6 +506,7 @@ mod provider {
|
||||
last_error_message: None,
|
||||
};
|
||||
AccountPageItem {
|
||||
protection_rules: Vec::new(),
|
||||
capacity: gateway_admin::model::accounts::AccountCapacity {
|
||||
used_slots: None,
|
||||
total_slots: None,
|
||||
|
||||
@@ -647,13 +647,7 @@ impl SettingsStore for MemorySettingsStore {
|
||||
usage_retention_days: command.values.usage_retention_days,
|
||||
ops_event_retention_days: command.values.ops_event_retention_days,
|
||||
audit_retention_days: command.values.audit_retention_days,
|
||||
account_auto_freeze_enabled: true,
|
||||
account_auto_freeze_threshold: 12,
|
||||
account_auto_freeze_window_seconds: 600,
|
||||
account_auto_freeze_duration_seconds: 7_200,
|
||||
account_auto_freeze_probe_enabled: true,
|
||||
account_auto_freeze_probe_model: None,
|
||||
account_auto_freeze_adaptive_concurrency: true,
|
||||
account_error_protection: command.values.account_error_protection,
|
||||
account_warmup_enabled: false,
|
||||
account_warmup_schedule_time: "08:00".to_owned(),
|
||||
account_warmup_model: None,
|
||||
@@ -697,6 +691,7 @@ pub(super) struct MemoryClientKeyStore(Arc<Mutex<Option<ClientKeyRecord>>>);
|
||||
pub(super) struct MemoryObservations {
|
||||
pub summary: Option<UsageOverview>,
|
||||
pub trend: Option<Vec<RequestMetricPoint>>,
|
||||
pub concurrency: Vec<gateway_admin::model::observability::UsageConcurrencyPoint>,
|
||||
pub summaries: Vec<(TimeRange, UsageFilter)>,
|
||||
pub trends: Vec<(TimeRange, UsageFilter)>,
|
||||
pub records: Vec<UsageQuery>,
|
||||
@@ -1326,15 +1321,6 @@ impl AccountStore for UnusedStore {
|
||||
Err(unavailable("account enabled"))
|
||||
}
|
||||
|
||||
async fn lower_concurrency_limit(
|
||||
&self,
|
||||
_: &gateway_core::account::ProviderAccountId,
|
||||
_: gateway_core::account::AccountConcurrencyLimit,
|
||||
_: &MutationContext,
|
||||
) -> AdminStoreResult<Option<gateway_admin::model::accounts::AccountUpdateResult>> {
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
async fn recover_account(
|
||||
&self,
|
||||
_: &ProviderAccountId,
|
||||
@@ -1399,6 +1385,7 @@ impl AccountRuntimeStore for UnusedStore {
|
||||
async fn active_rate_limits(&self) -> AdminStoreResult<AccountRuntimeSnapshot> {
|
||||
Ok(AccountRuntimeSnapshot {
|
||||
cooldown: BTreeMap::new(),
|
||||
protection_rules: BTreeMap::new(),
|
||||
in_flight: Some(BTreeMap::new()),
|
||||
})
|
||||
}
|
||||
@@ -1406,6 +1393,7 @@ impl AccountRuntimeStore for UnusedStore {
|
||||
async fn account_runtime(&self, _: &[String]) -> AdminStoreResult<AccountRuntimeSnapshot> {
|
||||
Ok(AccountRuntimeSnapshot {
|
||||
cooldown: BTreeMap::new(),
|
||||
protection_rules: BTreeMap::new(),
|
||||
in_flight: Some(BTreeMap::new()),
|
||||
})
|
||||
}
|
||||
@@ -1416,13 +1404,6 @@ impl AccountRuntimeStore for UnusedStore {
|
||||
Ok(BTreeMap::new())
|
||||
}
|
||||
|
||||
async fn capacity_peaks(
|
||||
&self,
|
||||
_account_ids: &[String],
|
||||
) -> AdminStoreResult<BTreeMap<String, u32>> {
|
||||
Ok(BTreeMap::new())
|
||||
}
|
||||
|
||||
async fn finish_freeze(
|
||||
&self,
|
||||
_account_id: &str,
|
||||
@@ -1526,6 +1507,7 @@ impl ObservabilityStore for UnusedStore {
|
||||
.clone()
|
||||
.ok_or_else(|| unavailable("usage trend"))?,
|
||||
costs: Vec::new(),
|
||||
concurrency: data.concurrency.clone(),
|
||||
},
|
||||
)
|
||||
}
|
||||
@@ -1841,13 +1823,7 @@ fn test_runtime_settings() -> RuntimeSettings {
|
||||
usage_retention_days: 31,
|
||||
ops_event_retention_days: 30,
|
||||
audit_retention_days: 90,
|
||||
account_auto_freeze_enabled: true,
|
||||
account_auto_freeze_threshold: 12,
|
||||
account_auto_freeze_window_seconds: 600,
|
||||
account_auto_freeze_duration_seconds: 7_200,
|
||||
account_auto_freeze_probe_enabled: true,
|
||||
account_auto_freeze_probe_model: None,
|
||||
account_auto_freeze_adaptive_concurrency: true,
|
||||
account_error_protection: Default::default(),
|
||||
account_warmup_enabled: false,
|
||||
account_warmup_schedule_time: "08:00".to_owned(),
|
||||
account_warmup_model: None,
|
||||
|
||||
@@ -1286,6 +1286,102 @@ async fn calendar_query_rejects_an_anchor_outside_the_local_calendar() {
|
||||
assert!(fixture.dashboard_summary_range.lock().unwrap().is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn usage_insights_maps_load_summary_and_points_to_camel_case() {
|
||||
use crate::admin::{AdminTestFixture, AdminTestState};
|
||||
use axum::{
|
||||
body::{Body, to_bytes},
|
||||
http::{Request, StatusCode, header},
|
||||
};
|
||||
use chrono::Duration;
|
||||
use gateway_admin::model::observability::{
|
||||
Granularity, LatencyPercentiles, PercentileMilliseconds, RequestMetricPoint,
|
||||
RequestMetrics, TimeRange, UsageConcurrencyPoint, UsageOverview,
|
||||
};
|
||||
use gateway_api::admin::observability;
|
||||
use tower::ServiceExt as _;
|
||||
|
||||
let fixture = AdminTestFixture::new().await;
|
||||
fixture.auth.insert_session("valid-session");
|
||||
let now = Utc::now();
|
||||
let range = TimeRange::new(now - Duration::minutes(15), now).unwrap();
|
||||
let bucket = range.start;
|
||||
{
|
||||
let mut observations = fixture.observations.lock().unwrap();
|
||||
observations.summary = Some(UsageOverview {
|
||||
analytics: Default::default(),
|
||||
range,
|
||||
requests: RequestMetrics {
|
||||
admission_decision_percentiles: LatencyPercentiles {
|
||||
p95_ms: Some(PercentileMilliseconds::new(12.5).unwrap()),
|
||||
..Default::default()
|
||||
},
|
||||
account_selection_wait_percentiles: LatencyPercentiles {
|
||||
p95_ms: Some(PercentileMilliseconds::new(128.75).unwrap()),
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
},
|
||||
attempts: Default::default(),
|
||||
providers: Vec::new(),
|
||||
});
|
||||
observations.trend = Some(vec![RequestMetricPoint {
|
||||
bucket_start: bucket,
|
||||
granularity: Granularity::FifteenMinutes,
|
||||
metrics: RequestMetrics {
|
||||
admission_decision_percentiles: LatencyPercentiles {
|
||||
p95_ms: Some(PercentileMilliseconds::new(2.5).unwrap()),
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
},
|
||||
cost_coverage: Default::default(),
|
||||
costs: Vec::new(),
|
||||
}]);
|
||||
observations.concurrency = vec![UsageConcurrencyPoint {
|
||||
bucket_start: bucket,
|
||||
average_concurrency: 1.25,
|
||||
peak_concurrency: 3,
|
||||
}];
|
||||
}
|
||||
|
||||
let response = observability::router::<AdminTestState>()
|
||||
.with_state(fixture.state())
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.uri("/api/admin/usage/insights/overview")
|
||||
.header(header::COOKIE, "cpr_session=valid-session")
|
||||
.header("x-request-id", "req_usage_insights_load")
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let status = response.status();
|
||||
let body = to_bytes(response.into_body(), 1024 * 1024).await.unwrap();
|
||||
let value: serde_json::Value = serde_json::from_slice(&body).unwrap();
|
||||
assert_eq!(status, StatusCode::OK, "{value}");
|
||||
let performance = &value["data"]["performance"];
|
||||
assert_eq!(
|
||||
performance["load"],
|
||||
json!({
|
||||
"averageConcurrency": 1.25,
|
||||
"peakConcurrency": 3,
|
||||
"admissionDecisionP95Ms": 12.5,
|
||||
"accountSelectionWaitP95Ms": 128.75,
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
performance["points"][0]["load"],
|
||||
json!({
|
||||
"averageConcurrency": 1.25,
|
||||
"peakConcurrency": 3,
|
||||
"admissionDecisionP95Ms": 2.5,
|
||||
"accountSelectionWaitP95Ms": null,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn observability_queries_reject_group_filters_and_analytics_search() {
|
||||
use crate::admin::{AdminTestFixture, AdminTestState};
|
||||
@@ -1511,6 +1607,7 @@ async fn dashboard_summary_should_identify_metrics_without_localized_labels() {
|
||||
authentication_kind: "oauth".to_owned(),
|
||||
name: account_id.clone(),
|
||||
email: None,
|
||||
notes: None,
|
||||
plan_type: None,
|
||||
plan_type_display: None,
|
||||
request_count: 10,
|
||||
@@ -1709,6 +1806,7 @@ async fn dashboard_relative_time_preserves_server_anchor_boundaries_and_deployme
|
||||
authentication_kind: "oauth".to_owned(),
|
||||
name: "Relative time fixture".to_owned(),
|
||||
email: None,
|
||||
notes: None,
|
||||
plan_type: None,
|
||||
plan_type_display: None,
|
||||
request_count: 1,
|
||||
|
||||
@@ -322,6 +322,17 @@ async fn instance_list_serializes_safe_runtime_diagnostics() {
|
||||
assert_eq!(instance["running"], false);
|
||||
assert_eq!(instance["runtime"]["status"], "preparation_failed");
|
||||
assert_eq!(instance["runtime"]["actualRevision"], 6);
|
||||
assert_eq!(
|
||||
instance["runtime"]["load"],
|
||||
serde_json::json!({
|
||||
"activeCalls": 3,
|
||||
"executingCalls": 1,
|
||||
"queuedCalls": 1,
|
||||
"resumingCalls": 1,
|
||||
"pendingCallbacks": 2,
|
||||
"activeStreams": 0,
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
instance["runtime"]["drainingRevisions"],
|
||||
serde_json::json!([5])
|
||||
@@ -665,6 +676,14 @@ impl gateway_admin::ports::plugins::PluginRuntimeDiagnostics for TestPluginPorts
|
||||
message: "插件候选准备失败".into(),
|
||||
}),
|
||||
draining_revisions: vec![5],
|
||||
load: Some(gateway_admin::model::plugins::instances::PluginInstanceRuntimeLoad {
|
||||
active_calls: 3,
|
||||
executing_calls: 1,
|
||||
queued_calls: 1,
|
||||
resuming_calls: 1,
|
||||
pending_callbacks: 2,
|
||||
active_streams: 0,
|
||||
}),
|
||||
},
|
||||
)
|
||||
})
|
||||
|
||||
@@ -65,13 +65,7 @@ fn update_body() -> Value {
|
||||
"usageRetentionDays": 31,
|
||||
"opsEventRetentionDays": 31,
|
||||
"auditRetentionDays": 91,
|
||||
"accountAutoFreezeEnabled": true,
|
||||
"accountAutoFreezeThreshold": 12,
|
||||
"accountAutoFreezeWindowSeconds": 600,
|
||||
"accountAutoFreezeDurationSeconds": 7200,
|
||||
"accountAutoFreezeProbeEnabled": true,
|
||||
"accountAutoFreezeProbeModel": null,
|
||||
"accountAutoFreezeAdaptiveConcurrency": true,
|
||||
"accountErrorProtection": gateway_core::account::AccountErrorProtection::default(),
|
||||
"accountWarmupEnabled": false,
|
||||
"accountWarmupScheduleTime": "08:00",
|
||||
"accountWarmupModel": null,
|
||||
@@ -185,6 +179,87 @@ fn privacy_policy_is_required_and_rejects_unknown_contract_fields() {
|
||||
assert!(serde_json::from_value::<UpdateRuntimeSettingsRequest>(unknown).is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn error_protection_rules_round_trip_and_invalid_policy_does_not_replace_them() {
|
||||
let fixture = AdminTestFixture::new().await;
|
||||
fixture.auth.insert_session("valid-session");
|
||||
let mut body = update_body();
|
||||
let policy = json!({
|
||||
"enabled": true,
|
||||
"rules": [{
|
||||
"id": "custom-rejection", "name": "自定义上游拒绝",
|
||||
"conditions": [
|
||||
{"field": "provider", "operator": "equals", "values": ["openai", "xai"], "ignoreCase": false},
|
||||
{"field": "code", "operator": "equals", "values": ["custom_vendor_rejection", null], "ignoreCase": true},
|
||||
{"field": "message", "operator": "contains", "values": ["please pause"], "ignoreCase": false}
|
||||
]
|
||||
}],
|
||||
"threshold": 3, "windowSeconds": 120, "durationSeconds": 300,
|
||||
"probeEnabled": false, "probeModel": null
|
||||
});
|
||||
body["accountErrorProtection"] = policy.clone();
|
||||
let response = app(fixture.state())
|
||||
.oneshot(request(
|
||||
Method::POST,
|
||||
"/api/admin/settings/update",
|
||||
Some(body.clone()),
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
let saved = response_json(response).await;
|
||||
assert_eq!(saved["data"]["accountErrorProtection"], policy);
|
||||
body["configRevision"] = saved["data"]["configRevision"].clone();
|
||||
|
||||
let mut invalid_policies = Vec::new();
|
||||
let mut empty = policy.clone();
|
||||
empty["rules"] = json!([]);
|
||||
invalid_policies.push(empty);
|
||||
let mut provider_only = policy.clone();
|
||||
provider_only["rules"][0]["conditions"] = json!([
|
||||
{"field": "provider", "operator": "equals", "values": ["openai"], "ignoreCase": false}
|
||||
]);
|
||||
invalid_policies.push(provider_only);
|
||||
let mut empty_contains = policy.clone();
|
||||
empty_contains["rules"][0]["conditions"][2]["values"] = json!([" "]);
|
||||
invalid_policies.push(empty_contains);
|
||||
for invalid in invalid_policies {
|
||||
body["accountErrorProtection"] = invalid;
|
||||
let response = app(fixture.state())
|
||||
.oneshot(request(
|
||||
Method::POST,
|
||||
"/api/admin/settings/update",
|
||||
Some(body.clone()),
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
|
||||
}
|
||||
let response = app(fixture.state())
|
||||
.oneshot(request(Method::GET, "/api/admin/settings", None))
|
||||
.await
|
||||
.unwrap();
|
||||
let loaded = response_json(response).await;
|
||||
assert_eq!(loaded["data"]["accountErrorProtection"], policy);
|
||||
assert_eq!(
|
||||
loaded["data"]["configRevision"],
|
||||
saved["data"]["configRevision"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn error_protection_requires_an_explicit_policy_in_settings_replacement() {
|
||||
let mut missing = update_body();
|
||||
missing
|
||||
.as_object_mut()
|
||||
.unwrap()
|
||||
.remove("accountErrorProtection");
|
||||
assert!(serde_json::from_value::<UpdateRuntimeSettingsRequest>(missing).is_err());
|
||||
let mut unknown = update_body();
|
||||
unknown["accountErrorProtection"]["unknownField"] = json!(true);
|
||||
assert!(serde_json::from_value::<UpdateRuntimeSettingsRequest>(unknown).is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn smart_settings_round_trip_and_invalid_updates_leave_the_saved_value_intact() {
|
||||
let fixture = AdminTestFixture::new().await;
|
||||
@@ -400,13 +475,7 @@ fn settings_response_should_cover_the_full_runtime_settings_contract() {
|
||||
usage_retention_days: 31,
|
||||
ops_event_retention_days: 31,
|
||||
audit_retention_days: 91,
|
||||
account_auto_freeze_enabled: true,
|
||||
account_auto_freeze_threshold: 12,
|
||||
account_auto_freeze_window_seconds: 600,
|
||||
account_auto_freeze_duration_seconds: 7_200,
|
||||
account_auto_freeze_probe_enabled: true,
|
||||
account_auto_freeze_probe_model: None,
|
||||
account_auto_freeze_adaptive_concurrency: true,
|
||||
account_error_protection: Default::default(),
|
||||
account_warmup_enabled: false,
|
||||
account_warmup_schedule_time: "08:00".to_owned(),
|
||||
account_warmup_model: None,
|
||||
@@ -453,13 +522,7 @@ fn settings_response_should_cover_the_full_runtime_settings_contract() {
|
||||
"usageRetentionDays": 31,
|
||||
"opsEventRetentionDays": 31,
|
||||
"auditRetentionDays": 91,
|
||||
"accountAutoFreezeEnabled": true,
|
||||
"accountAutoFreezeThreshold": 12,
|
||||
"accountAutoFreezeWindowSeconds": 600,
|
||||
"accountAutoFreezeDurationSeconds": 7200,
|
||||
"accountAutoFreezeProbeEnabled": true,
|
||||
"accountAutoFreezeProbeModel": null,
|
||||
"accountAutoFreezeAdaptiveConcurrency": true,
|
||||
"accountErrorProtection": gateway_core::account::AccountErrorProtection::default(),
|
||||
"accountWarmupEnabled": false,
|
||||
"accountWarmupScheduleTime": "08:00",
|
||||
"accountWarmupModel": null,
|
||||
|
||||
@@ -229,29 +229,67 @@ fn desktop_headers_should_take_precedence_over_embedded_cli_marker() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cli_user_agent_should_expose_semver_or_recognized_missing_version() {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(
|
||||
"user-agent",
|
||||
HeaderValue::from_static("codex_cli_rs/0.39.0 (Linux; x86_64)"),
|
||||
);
|
||||
let identified = identify_codex_client(&headers).expect("recognized CLI");
|
||||
assert_eq!(identified.kind(), CodexClientKind::Cli);
|
||||
assert_eq!(
|
||||
identified.version().map(ToString::to_string).as_deref(),
|
||||
Some("0.39.0")
|
||||
);
|
||||
fn official_core_clients_should_use_the_core_version_instead_of_the_app_suffix() {
|
||||
for product in [
|
||||
"codex_cli_rs",
|
||||
"codex-cli",
|
||||
"codex-tui",
|
||||
"codex_exec",
|
||||
"codex_vscode",
|
||||
"codex_sdk_ts",
|
||||
"codex_python_sdk",
|
||||
"codex-app-server",
|
||||
"codex-app-server-sdk",
|
||||
"codex_mcp_server",
|
||||
"CoDeX-TuI",
|
||||
] {
|
||||
for (version, expected) in [
|
||||
(Some("0.158.0"), Some("0.158.0")),
|
||||
(
|
||||
Some("0.165.0-alpha.1+build.2"),
|
||||
Some("0.165.0-alpha.1+build.2"),
|
||||
),
|
||||
(Some("not-a-version"), None),
|
||||
(Some(""), None),
|
||||
(None, None),
|
||||
] {
|
||||
let prefix = version.map_or_else(|| product.to_owned(), |v| format!("{product}/{v}"));
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(
|
||||
"user-agent",
|
||||
HeaderValue::from_str(&format!(
|
||||
"{prefix} (Mac OS 26.6.2; arm64) Apple_Terminal ({product}; 0.165.0)"
|
||||
))
|
||||
.unwrap(),
|
||||
);
|
||||
let identified = identify_codex_client(&headers).expect("recognized official client");
|
||||
assert_eq!(identified.kind(), CodexClientKind::Cli, "{prefix}");
|
||||
assert_eq!(
|
||||
identified.version().map(ToString::to_string).as_deref(),
|
||||
expected,
|
||||
"{prefix}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
headers.insert(
|
||||
"user-agent",
|
||||
HeaderValue::from_static("codex-cli/not-a-version"),
|
||||
);
|
||||
assert!(
|
||||
identify_codex_client(&headers)
|
||||
.expect("recognized invalid CLI")
|
||||
.version()
|
||||
.is_none()
|
||||
);
|
||||
#[test]
|
||||
fn unknown_codex_like_products_should_remain_unrestricted() {
|
||||
for product in [
|
||||
"custom-codex-tui",
|
||||
"codex-tui-custom",
|
||||
"codex_cli_rs_custom",
|
||||
"codex_python_sdk_custom",
|
||||
"my_app",
|
||||
"deepseek-harness",
|
||||
] {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(
|
||||
"user-agent",
|
||||
HeaderValue::from_str(&format!("{product}/0.158.0 (Linux; x86_64)")).unwrap(),
|
||||
);
|
||||
assert_eq!(identify_codex_client(&headers), None, "{product}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,624 @@
|
||||
//! Chat HTTP 夹具和共享执行、鉴权、插件及终结边界
|
||||
|
||||
use std::{
|
||||
collections::VecDeque,
|
||||
io::Write as _,
|
||||
sync::{
|
||||
Arc, Mutex,
|
||||
atomic::{AtomicBool, AtomicUsize, Ordering},
|
||||
},
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use axum::{
|
||||
body::{Body, to_bytes},
|
||||
http::{Request, StatusCode},
|
||||
response::Response,
|
||||
};
|
||||
use bytes::Bytes;
|
||||
use futures::future::BoxFuture;
|
||||
use gateway_core::{
|
||||
engine::{
|
||||
CommitRequirement, CoordinatedEvent, EngineError, ModelRequestId,
|
||||
execution::{
|
||||
AuthenticatedClient, ClientAuthenticationError, ExecutionService, ExecutionSession,
|
||||
PreparedRootExecution, ResponseCommit, StartExecution, StartProviderExecution,
|
||||
StartedExecution,
|
||||
},
|
||||
middleware::{
|
||||
FrozenMiddlewarePlan, MiddlewareContext, MiddlewareError, MiddlewareNext,
|
||||
MiddlewarePlan, MiddlewareRequest, MiddlewareResponse,
|
||||
},
|
||||
},
|
||||
error::GatewayError,
|
||||
event::{ProviderEvent, ProviderResponseHeader},
|
||||
operation::Operation,
|
||||
routing::{
|
||||
PublicModelId,
|
||||
extensions::{ExtensionSetId, ExtensionSetLease, ExtensionSetReference},
|
||||
},
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
use tower::ServiceExt as _;
|
||||
|
||||
use super::{chat_request, completed, created, message};
|
||||
use crate::openai::{
|
||||
api_router, authenticated_client, authenticated_client_for_provider_with_limit,
|
||||
middleware::{RequestMiddleware, ResponseFrameAction},
|
||||
};
|
||||
|
||||
pub(super) const PATH: &str = "/v1/chat/completions";
|
||||
const KEY: &str = "sk_chat_fixture";
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct Trace {
|
||||
pub commits: AtomicUsize,
|
||||
pub discarded: AtomicUsize,
|
||||
pub cancelled: AtomicBool,
|
||||
pub finalized: AtomicBool,
|
||||
pub detached: AtomicUsize,
|
||||
response_commit: ResponseCommit,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) enum Finish {
|
||||
#[default]
|
||||
Success,
|
||||
Error,
|
||||
Pending,
|
||||
}
|
||||
|
||||
pub(super) struct Session {
|
||||
events: VecDeque<Vec<ProviderEvent>>,
|
||||
pub trace: Arc<Trace>,
|
||||
pub finish: Finish,
|
||||
pub delay: Option<Duration>,
|
||||
pub fail_commit: bool,
|
||||
pub response_headers: Vec<ProviderResponseHeader>,
|
||||
committed: bool,
|
||||
buffered: bool,
|
||||
}
|
||||
|
||||
impl Session {
|
||||
pub fn new(events: Vec<ProviderEvent>) -> Self {
|
||||
Self {
|
||||
events: events.into_iter().map(|event| vec![event]).collect(),
|
||||
trace: Arc::default(),
|
||||
finish: Finish::Success,
|
||||
delay: None,
|
||||
fail_commit: false,
|
||||
response_headers: Vec::new(),
|
||||
committed: false,
|
||||
buffered: false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_batch(mut self, events: Vec<ProviderEvent>) -> Self {
|
||||
self.events.push_back(events);
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl ExecutionSession for Session {
|
||||
fn response_commit(&self) -> ResponseCommit {
|
||||
self.trace.response_commit.clone()
|
||||
}
|
||||
|
||||
fn next_event(&mut self) -> BoxFuture<'_, Result<Option<CoordinatedEvent>, EngineError>> {
|
||||
Box::pin(async move {
|
||||
if let Some(delay) = self.delay.take() {
|
||||
tokio::time::sleep(delay).await;
|
||||
}
|
||||
if let Some(event) = self.events.pop_front() {
|
||||
let requirement = if self.committed {
|
||||
CommitRequirement::AlreadyCommitted
|
||||
} else {
|
||||
CommitRequirement::CommitBeforeDelivery
|
||||
};
|
||||
return CoordinatedEvent::try_batch(event, requirement).map(Some);
|
||||
}
|
||||
match self.finish {
|
||||
Finish::Success => {
|
||||
self.trace.finalized.store(true, Ordering::SeqCst);
|
||||
Ok(None)
|
||||
}
|
||||
Finish::Error => {
|
||||
self.trace.finalized.store(true, Ordering::SeqCst);
|
||||
Err(EngineError::ProviderMetadataMismatch)
|
||||
}
|
||||
Finish::Pending => futures::future::pending().await,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn collect_uncommitted(&mut self) -> BoxFuture<'_, Result<Vec<ProviderEvent>, EngineError>> {
|
||||
self.buffered = true;
|
||||
Box::pin(async move { Ok(self.events.drain(..).flatten().collect()) })
|
||||
}
|
||||
|
||||
fn response_headers(&self) -> &[ProviderResponseHeader] {
|
||||
&self.response_headers
|
||||
}
|
||||
|
||||
fn discard_pending_delivery(&mut self) -> Result<(), EngineError> {
|
||||
self.trace.discarded.fetch_add(1, Ordering::SeqCst);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn commit_downstream(&mut self, status: Option<u16>) -> BoxFuture<'_, Result<(), EngineError>> {
|
||||
Box::pin(async move {
|
||||
self.trace.commits.fetch_add(1, Ordering::SeqCst);
|
||||
if self.fail_commit {
|
||||
return Err(EngineError::ProviderMetadataMismatch);
|
||||
}
|
||||
self.trace.response_commit.record(status);
|
||||
self.committed = true;
|
||||
if self.buffered {
|
||||
self.trace.finalized.store(true, Ordering::SeqCst);
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
fn record_client_status(&mut self, status: u16) -> BoxFuture<'_, Result<(), EngineError>> {
|
||||
Box::pin(async move {
|
||||
self.trace.response_commit.record(Some(status));
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
fn is_finalized(&self) -> bool {
|
||||
self.trace.finalized.load(Ordering::SeqCst)
|
||||
}
|
||||
fn cancel(&self) {
|
||||
self.trace.cancelled.store(true, Ordering::SeqCst);
|
||||
}
|
||||
fn detach_finalize(self: Box<Self>) -> BoxFuture<'static, ()> {
|
||||
Box::pin(async move {
|
||||
self.trace.detached.fetch_add(1, Ordering::SeqCst);
|
||||
self.trace.finalized.store(true, Ordering::SeqCst);
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub(super) struct Captured {
|
||||
pub body: Value,
|
||||
pub context: Value,
|
||||
pub endpoint: String,
|
||||
}
|
||||
|
||||
pub(super) struct Execution {
|
||||
pub captured: Mutex<Option<Captured>>,
|
||||
pub client: AuthenticatedClient,
|
||||
pub middleware: Option<FrozenMiddlewarePlan>,
|
||||
session: Mutex<Option<Session>>,
|
||||
}
|
||||
|
||||
impl Execution {
|
||||
pub fn new(session: Session) -> Self {
|
||||
Self {
|
||||
captured: Mutex::default(),
|
||||
client: authenticated_client(KEY),
|
||||
middleware: None,
|
||||
session: Mutex::new(Some(session)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ExecutionService for Execution {
|
||||
fn authenticate(&self, key: &str) -> Result<AuthenticatedClient, ClientAuthenticationError> {
|
||||
if key == KEY {
|
||||
Ok(self.client.clone())
|
||||
} else {
|
||||
Err(ClientAuthenticationError::InvalidKey)
|
||||
}
|
||||
}
|
||||
fn public_models(&self, _: &AuthenticatedClient) -> Vec<PublicModelId> {
|
||||
Vec::new()
|
||||
}
|
||||
fn contains_public_model(&self, _: &AuthenticatedClient, _: &PublicModelId) -> bool {
|
||||
true
|
||||
}
|
||||
fn middleware_plan(&self, _: &PreparedRootExecution) -> Option<FrozenMiddlewarePlan> {
|
||||
self.middleware.clone()
|
||||
}
|
||||
fn start(
|
||||
&self,
|
||||
request: StartExecution,
|
||||
) -> BoxFuture<'_, Result<StartedExecution, GatewayError>> {
|
||||
Box::pin(async move {
|
||||
let Operation::Generate(generation) = request.operation else {
|
||||
panic!("Chat must generate")
|
||||
};
|
||||
*self.captured.lock().unwrap() = Some(Captured {
|
||||
body: Value::Object(generation.protocol_payload().body().clone()),
|
||||
context: Value::Object(generation.protocol_payload().context().clone()),
|
||||
endpoint: request.metadata.endpoint,
|
||||
});
|
||||
Ok(StartedExecution {
|
||||
request_id: ModelRequestId::new("req_chat_fixture").unwrap(),
|
||||
created_at: std::time::SystemTime::now(),
|
||||
stream: request.metadata.stream,
|
||||
session: Box::new(self.session.lock().unwrap().take().expect("one request")),
|
||||
})
|
||||
})
|
||||
}
|
||||
fn start_provider_endpoint(
|
||||
&self,
|
||||
_: StartProviderExecution,
|
||||
) -> BoxFuture<'_, Result<StartedExecution, GatewayError>> {
|
||||
Box::pin(async { panic!("Chat must use model execution") })
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) struct Fixture {
|
||||
pub router: axum::Router,
|
||||
pub execution: Arc<Execution>,
|
||||
pub trace: Arc<Trace>,
|
||||
}
|
||||
|
||||
impl Fixture {
|
||||
pub async fn new(session: Session) -> Self {
|
||||
Self::with_execution(Execution::new(session)).await
|
||||
}
|
||||
pub async fn with_execution(execution: Execution) -> Self {
|
||||
let trace = execution
|
||||
.session
|
||||
.lock()
|
||||
.unwrap()
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.trace
|
||||
.clone();
|
||||
let execution = Arc::new(execution);
|
||||
Self {
|
||||
router: api_router(execution.clone()).await,
|
||||
execution,
|
||||
trace,
|
||||
}
|
||||
}
|
||||
pub async fn post(&self, body: Value) -> Response {
|
||||
self.router.clone().oneshot(request(body)).await.unwrap()
|
||||
}
|
||||
pub fn captured(&self) -> Captured {
|
||||
self.execution
|
||||
.captured
|
||||
.lock()
|
||||
.unwrap()
|
||||
.clone()
|
||||
.expect("started request")
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn request(body: Value) -> Request<Body> {
|
||||
Request::post(PATH)
|
||||
.header("authorization", format!("Bearer {KEY}"))
|
||||
.header("content-type", "application/json")
|
||||
.body(Body::from(body.to_string()))
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
pub(super) async fn json_body(response: Response) -> Value {
|
||||
serde_json::from_slice(&to_bytes(response.into_body(), usize::MAX).await.unwrap()).unwrap()
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub(super) struct InspectMiddleware {
|
||||
pub inner: RequestMiddleware,
|
||||
pub requests: Mutex<Vec<Value>>,
|
||||
pub update: Option<fn(&mut Value)>,
|
||||
}
|
||||
|
||||
impl InspectMiddleware {
|
||||
pub fn frozen(self: &Arc<Self>) -> FrozenMiddlewarePlan {
|
||||
FrozenMiddlewarePlan::new(
|
||||
self.clone(),
|
||||
ExtensionSetReference::new(
|
||||
ExtensionSetId::new("chat-inspector".to_owned()).unwrap(),
|
||||
Arc::new(ReadyLease),
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
struct ReadyLease;
|
||||
impl ExtensionSetLease for ReadyLease {
|
||||
fn is_ready(&self) -> bool {
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
impl MiddlewarePlan for InspectMiddleware {
|
||||
fn handle(
|
||||
&self,
|
||||
context: MiddlewareContext,
|
||||
mut request: MiddlewareRequest,
|
||||
next: MiddlewareNext,
|
||||
) -> BoxFuture<'static, Result<MiddlewareResponse, MiddlewareError>> {
|
||||
let mut body: Value = serde_json::from_slice(request.body()).unwrap();
|
||||
self.requests.lock().unwrap().push(body.clone());
|
||||
if let Some(update) = self.update {
|
||||
update(&mut body);
|
||||
let headers = request.headers().to_vec();
|
||||
request = request
|
||||
.replace_parts(
|
||||
"openai".to_owned(),
|
||||
headers,
|
||||
Bytes::from(body.to_string()),
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
self.inner.handle(context, request, next)
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rejects_missing_authentication_before_decoding_or_execution() {
|
||||
let fixture = Fixture::new(Session::new(Vec::new())).await;
|
||||
for authorization in [None, Some("Bearer sk_invalid")] {
|
||||
let mut request = Request::post(PATH);
|
||||
if let Some(authorization) = authorization {
|
||||
request = request.header("authorization", authorization);
|
||||
}
|
||||
let response = fixture
|
||||
.router
|
||||
.clone()
|
||||
.oneshot(request.body(Body::from("broken json")).unwrap())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
|
||||
}
|
||||
assert!(fixture.execution.captured.lock().unwrap().is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn request_middleware_sees_responses_and_preserves_the_chat_endpoint() {
|
||||
let middleware = Arc::new(InspectMiddleware {
|
||||
inner: RequestMiddleware {
|
||||
expected_operation: Some(gateway_core::operation::OperationKind::Generate),
|
||||
..RequestMiddleware::default()
|
||||
},
|
||||
update: Some(|body| {
|
||||
body["input"] = json!("rewritten by request middleware");
|
||||
}),
|
||||
..InspectMiddleware::default()
|
||||
});
|
||||
let mut execution = Execution::new(Session::new(vec![completed(json!([message("ok")]))]));
|
||||
execution.middleware = Some(middleware.frozen());
|
||||
let fixture = Fixture::with_execution(execution).await;
|
||||
let response = fixture.post(chat_request(false)).await;
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
let downstream = json_body(response).await;
|
||||
assert_eq!(downstream["object"], "chat.completion");
|
||||
let observed = middleware.requests.lock().unwrap();
|
||||
assert!(observed[0].get("messages").is_none());
|
||||
assert_eq!(observed[0]["input"][0]["role"], "user");
|
||||
assert_eq!(
|
||||
middleware.inner.endpoints.lock().unwrap().as_slice(),
|
||||
[PATH]
|
||||
);
|
||||
let captured = fixture.captured();
|
||||
assert_eq!(captured.endpoint, PATH);
|
||||
assert_eq!(captured.body["input"], "rewritten by request middleware");
|
||||
assert_eq!(fixture.trace.commits.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn dropping_chat_body_cancels_and_finalizes_the_original_execution() {
|
||||
let mut session = Session::new(vec![created()]);
|
||||
session.finish = Finish::Pending;
|
||||
let fixture = Fixture::new(session).await;
|
||||
let response = fixture.post(chat_request(true)).await;
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
drop(response);
|
||||
for _ in 0..8 {
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
assert!(fixture.trace.cancelled.load(Ordering::SeqCst));
|
||||
assert_eq!(fixture.trace.detached.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn gzip_and_headers_reuse_the_responses_ingress_contract() {
|
||||
let mut session = Session::new(vec![completed(json!([message("ok")]))]);
|
||||
session.response_headers = vec![
|
||||
ProviderResponseHeader::new("x-future-multi", Bytes::from_static(b"first")),
|
||||
ProviderResponseHeader::new("x-future-multi", Bytes::from_static(b"second")),
|
||||
ProviderResponseHeader::new("connection", Bytes::from_static(b"x-hop-only")),
|
||||
ProviderResponseHeader::new("x-hop-only", Bytes::from_static(b"removed")),
|
||||
];
|
||||
let fixture = Fixture::new(session).await;
|
||||
let body = chat_request(false).to_string();
|
||||
let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast());
|
||||
encoder.write_all(body.as_bytes()).unwrap();
|
||||
let compressed = encoder.finish().unwrap();
|
||||
let request = Request::post(PATH)
|
||||
.header("authorization", format!("Bearer {KEY}"))
|
||||
.header("content-type", "application/json")
|
||||
.header("content-encoding", "gzip")
|
||||
.header("content-length", compressed.len())
|
||||
.header("session_id", "chat-session")
|
||||
.header("x-future-input", "first")
|
||||
.header("x-future-input", "second")
|
||||
.body(Body::from(compressed))
|
||||
.unwrap();
|
||||
let response = fixture.router.clone().oneshot(request).await.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
assert_eq!(
|
||||
response
|
||||
.headers()
|
||||
.get_all("x-future-multi")
|
||||
.iter()
|
||||
.map(|value| value.to_str().unwrap())
|
||||
.collect::<Vec<_>>(),
|
||||
["first", "second"]
|
||||
);
|
||||
assert!(!response.headers().contains_key("x-hop-only"));
|
||||
assert!(!response.headers().contains_key("content-encoding"));
|
||||
assert_eq!(
|
||||
json_body(response).await["choices"][0]["message"]["content"],
|
||||
"ok"
|
||||
);
|
||||
let captured = fixture.captured();
|
||||
assert_eq!(captured.context["session_id"], "chat-session");
|
||||
let headers = captured.context["opaque_request_headers"]
|
||||
.as_array()
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
headers
|
||||
.iter()
|
||||
.filter(|header| header[0] == "x-future-input")
|
||||
.count(),
|
||||
2
|
||||
);
|
||||
assert!(!headers.iter().any(|header| matches!(
|
||||
header[0].as_str(),
|
||||
Some("content-encoding" | "content-length" | "authorization")
|
||||
)));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn corrupt_or_oversized_compressed_chat_never_starts_execution() {
|
||||
let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast());
|
||||
encoder
|
||||
.write_all(chat_request(false).to_string().as_bytes())
|
||||
.unwrap();
|
||||
let valid_compressed = encoder.finish().unwrap();
|
||||
for bytes in [b"broken gzip".to_vec(), valid_compressed] {
|
||||
let mut execution = Execution::new(Session::new(Vec::new()));
|
||||
execution.client = authenticated_client_for_provider_with_limit(KEY, "openai", 16);
|
||||
let fixture = Fixture::with_execution(execution).await;
|
||||
let request = Request::post(PATH)
|
||||
.header("authorization", format!("Bearer {KEY}"))
|
||||
.header("content-encoding", "gzip")
|
||||
.body(Body::from(bytes))
|
||||
.unwrap();
|
||||
let response = fixture.router.clone().oneshot(request).await.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
|
||||
assert!(fixture.execution.captured.lock().unwrap().is_none());
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn response_middleware_is_validated_as_responses_before_chat_projection() {
|
||||
for matching_identity in [true, false] {
|
||||
let replacement = json!({"id":if matching_identity {"resp_chat_test"} else {"resp_other"},
|
||||
"status":"completed","output":[message("plugin text")]});
|
||||
let middleware = Arc::new(
|
||||
RequestMiddleware {
|
||||
expected_operation: Some(gateway_core::operation::OperationKind::Generate),
|
||||
..RequestMiddleware::default()
|
||||
}
|
||||
.with_response_actions(vec![ResponseFrameAction::Replace(Bytes::from(
|
||||
replacement.to_string(),
|
||||
))]),
|
||||
);
|
||||
let mut execution =
|
||||
Execution::new(Session::new(vec![completed(json!([message("original")]))]));
|
||||
execution.middleware = Some(middleware.frozen());
|
||||
let fixture = Fixture::with_execution(execution).await;
|
||||
let response = fixture.post(chat_request(false)).await;
|
||||
if matching_identity {
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
assert_eq!(
|
||||
json_body(response).await["choices"][0]["message"]["content"],
|
||||
"plugin text"
|
||||
);
|
||||
} else {
|
||||
assert_eq!(response.status(), StatusCode::BAD_GATEWAY);
|
||||
assert_eq!(
|
||||
json_body(response).await["error"]["code"],
|
||||
"middleware_failed"
|
||||
);
|
||||
assert_eq!(fixture.trace.commits.load(Ordering::SeqCst), 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn commit_failure_does_not_deliver_buffered_or_first_terminal_chat_success() {
|
||||
for streaming in [false, true] {
|
||||
let mut session = Session::new(vec![completed(json!([message("not delivered")]))]);
|
||||
session.fail_commit = true;
|
||||
let fixture = Fixture::new(session).await;
|
||||
let response = fixture.post(chat_request(streaming)).await;
|
||||
assert!(response.status().is_server_error());
|
||||
let body = json_body(response).await;
|
||||
assert!(body.get("error").is_some());
|
||||
assert!(body.get("choices").is_none());
|
||||
assert!(fixture.trace.cancelled.load(Ordering::SeqCst));
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_same_execution_fixture_finishes_native_responses_with_one_commit() {
|
||||
for already_started in [false, true] {
|
||||
let mut events = Vec::new();
|
||||
if already_started {
|
||||
events.push(created());
|
||||
}
|
||||
events.push(completed(json!([message("native baseline")])));
|
||||
let fixture = Fixture::new(Session::new(events)).await;
|
||||
let mut request = request(json!({"model":"model-a","input":"hello","stream":true}));
|
||||
*request.uri_mut() = "/v1/responses".parse().unwrap();
|
||||
let response = fixture.router.clone().oneshot(request).await.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
let bytes = to_bytes(response.into_body(), usize::MAX).await.unwrap();
|
||||
let text = String::from_utf8(bytes.to_vec()).unwrap();
|
||||
assert!(text.contains("event: response.completed"), "{text}");
|
||||
assert!(text.contains("native baseline"), "{text}");
|
||||
assert!(!text.contains("response.failed"), "{text}");
|
||||
assert_eq!(text.matches("data: [DONE]").count(), 1, "{text}");
|
||||
assert!(text.ends_with("data: [DONE]\n\n"), "{text}");
|
||||
assert!(fixture.trace.finalized.load(Ordering::SeqCst));
|
||||
assert_eq!(fixture.trace.commits.load(Ordering::SeqCst), 1);
|
||||
assert_eq!(fixture.trace.response_commit.status_code(), Some(200));
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn finalization_failure_never_leaks_success_finish_or_usage() {
|
||||
for already_started in [false, true] {
|
||||
let mut events = Vec::new();
|
||||
if already_started {
|
||||
events.push(created());
|
||||
}
|
||||
events.push(completed(json!([])));
|
||||
let mut session = Session::new(events);
|
||||
session.finish = Finish::Error;
|
||||
let fixture = Fixture::new(session).await;
|
||||
let mut body = chat_request(true);
|
||||
body["stream_options"] = json!({"include_usage":true});
|
||||
let response = fixture.post(body).await;
|
||||
// 原会话已经接受 200 提交,后续终结错误只能作为流内错误交付
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
let (_, chunks) = super::response::sse_body(response).await;
|
||||
assert!(chunks.iter().any(|chunk| chunk.get("error").is_some()));
|
||||
assert!(
|
||||
!chunks
|
||||
.iter()
|
||||
.any(|chunk| chunk["choices"][0]["finish_reason"].is_string())
|
||||
);
|
||||
assert!(!chunks.iter().any(|chunk| chunk["choices"] == json!([])));
|
||||
assert!(fixture.trace.finalized.load(Ordering::SeqCst));
|
||||
assert_eq!(fixture.trace.commits.load(Ordering::SeqCst), 1);
|
||||
assert_eq!(fixture.trace.response_commit.status_code(), Some(200));
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn error_after_admission_keepalive_uses_chat_error_encoding() {
|
||||
let mut session = Session::new(Vec::new());
|
||||
session.delay = Some(Duration::from_secs(31));
|
||||
session.finish = Finish::Error;
|
||||
let fixture = Fixture::new(session).await;
|
||||
let response = fixture.post(chat_request(true)).await;
|
||||
let (body, chunks) = super::response::sse_body(response).await;
|
||||
assert!(body.starts_with(": keep-alive\n\n"));
|
||||
assert!(chunks.iter().any(|chunk| chunk.get("error").is_some()));
|
||||
assert!(!body.contains("response.failed"));
|
||||
assert_eq!(fixture.trace.commits.load(Ordering::SeqCst), 0);
|
||||
assert_eq!(fixture.trace.response_commit.status_code(), Some(200));
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
//! Chat Completions 的请求转换、输出投影与 HTTP 生命周期测试
|
||||
|
||||
mod http;
|
||||
mod request;
|
||||
mod response;
|
||||
|
||||
use gateway_core::event::{ProtocolWireEvent, ProviderEvent};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
fn chat_request(stream: bool) -> Value {
|
||||
json!({"model":"model-a","messages":[{"role":"user","content":"hello"}],"stream":stream})
|
||||
}
|
||||
|
||||
fn wire(kind: &str, mut value: Value) -> ProviderEvent {
|
||||
value["type"] = json!(kind);
|
||||
ProviderEvent::wire(ProtocolWireEvent::json("openai", Some(kind.to_owned()), value).unwrap())
|
||||
}
|
||||
|
||||
fn completed(output: Value) -> ProviderEvent {
|
||||
wire(
|
||||
"response.completed",
|
||||
json!({"response":{
|
||||
"id":"resp_chat_test","object":"response","model":"upstream-model",
|
||||
"status":"completed","output":output,
|
||||
"usage":{"input_tokens":11,"output_tokens":7,"total_tokens":18,
|
||||
"input_tokens_details":{"cached_tokens":3},
|
||||
"output_tokens_details":{"reasoning_tokens":2}}
|
||||
}}),
|
||||
)
|
||||
}
|
||||
|
||||
fn message(text: &str) -> Value {
|
||||
json!({"id":"msg_chat_test","type":"message","role":"assistant","status":"completed",
|
||||
"content":[{"type":"output_text","text":text,"annotations":[]}]})
|
||||
}
|
||||
|
||||
fn created() -> ProviderEvent {
|
||||
wire(
|
||||
"response.created",
|
||||
json!({"response":{
|
||||
"id":"resp_chat_test","object":"response","model":"upstream-model",
|
||||
"status":"in_progress","output":[]
|
||||
}}),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
//! Chat 请求映射保留消息、工具和不透明业务数据的语义
|
||||
|
||||
use axum::http::StatusCode;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{
|
||||
chat_request, completed,
|
||||
http::{Fixture, Session, json_body},
|
||||
message,
|
||||
};
|
||||
|
||||
async fn convert(body: Value) -> Value {
|
||||
let fixture = Fixture::new(Session::new(vec![completed(json!([message("ok")]))])).await;
|
||||
let response = fixture.post(body).await;
|
||||
let status = response.status();
|
||||
let result = json_body(response).await;
|
||||
assert_eq!(status, StatusCode::OK, "{result}");
|
||||
fixture.captured().body
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn preserves_ordered_roles_images_and_modern_tool_round_trip() {
|
||||
let arguments = "{ \"city\" : \"北京\", \"store\":true }";
|
||||
let converted = convert(json!({"model":"model-a","messages":[
|
||||
{"role":"system","content":"system text"},
|
||||
{"role":"developer","content":"developer text"},
|
||||
{"role":"user","content":[{"type":"text","text":"describe"},
|
||||
{"type":"image_url","image_url":{"url":"data:image/png;base64,aGVsbG8=","detail":"high"}}]},
|
||||
{"role":"assistant","content":"checking","tool_calls":[
|
||||
{"id":"call-weather","type":"function","function":{"name":"weather","arguments":arguments}}]},
|
||||
{"role":"tool","tool_call_id":"call-weather","content":"{\"temperature\":25}"},
|
||||
{"role":"user","content":"continue"}
|
||||
]})).await;
|
||||
let input = converted["input"].as_array().unwrap();
|
||||
assert_eq!(
|
||||
input
|
||||
.iter()
|
||||
.filter_map(|item| item["role"].as_str())
|
||||
.collect::<Vec<_>>(),
|
||||
["system", "developer", "user", "assistant", "user"]
|
||||
);
|
||||
assert_eq!(
|
||||
input[2]["content"][1],
|
||||
json!({"type":"input_image","image_url":"data:image/png;base64,aGVsbG8=","detail":"high"})
|
||||
);
|
||||
assert_eq!(
|
||||
input[3]["content"],
|
||||
json!([{"type":"output_text","text":"checking","annotations":[]}])
|
||||
);
|
||||
assert_eq!(
|
||||
input[4],
|
||||
json!({"type":"function_call","call_id":"call-weather","name":"weather","arguments":arguments})
|
||||
);
|
||||
assert_eq!(
|
||||
input[5],
|
||||
json!({"type":"function_call_output","call_id":"call-weather","output":"{\"temperature\":25}"})
|
||||
);
|
||||
assert!(converted.get("previous_response_id").is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn assistant_history_uses_output_content_for_text_and_refusals() {
|
||||
for content in [
|
||||
json!("previous answer"),
|
||||
json!([{"type":"text","text":"previous answer"}]),
|
||||
json!([{"type":"text","text":"previous answer"},{"type":"refusal","refusal":"declined"}]),
|
||||
] {
|
||||
let converted = convert(json!({"model":"model-a","messages":[
|
||||
{"role":"user","content":"first turn"},
|
||||
{"role":"assistant","content":content},
|
||||
{"role":"user","content":"continue from the previous answer"}
|
||||
]}))
|
||||
.await;
|
||||
let history = &converted["input"][1];
|
||||
assert_eq!(history["role"], "assistant");
|
||||
assert_eq!(history["status"], "completed");
|
||||
assert!(!history["id"].as_str().unwrap().is_empty());
|
||||
assert_eq!(
|
||||
history["content"][0],
|
||||
json!({"type":"output_text","text":"previous answer","annotations":[]})
|
||||
);
|
||||
if content.is_array() && content.as_array().unwrap().len() == 2 {
|
||||
assert_eq!(
|
||||
history["content"][1],
|
||||
json!({"type":"refusal","refusal":"declined"})
|
||||
);
|
||||
}
|
||||
assert_eq!(converted["input"][2]["content"][0]["type"], "input_text");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn preserves_nested_schema_metadata_and_future_opaque_values() {
|
||||
let schema = json!({"type":"object","properties":{
|
||||
"messages":{"type":"string"},"store":{"type":"boolean"},
|
||||
"function_call":{"type":"string"},"future":{"x-extension":[1,2]}},
|
||||
"required":["messages"],"additionalProperties":true});
|
||||
let mut body = chat_request(false);
|
||||
body["model"] = json!("future-model-opaque:β");
|
||||
body["tools"] = json!([{"type":"function","function":{"name":"inspect","parameters":schema}}]);
|
||||
body["tool_choice"] = json!({"type":"function","function":{"name":"inspect"}});
|
||||
body["response_format"] = json!({"type":"json_schema","json_schema":{
|
||||
"name":"result","description":"preserve","strict":true,"schema":schema}});
|
||||
body["metadata"] = json!({"messages":"business data","future":"kept"});
|
||||
body["reasoning_effort"] = json!("future-effort");
|
||||
body["verbosity"] = json!("future-verbosity");
|
||||
body["service_tier"] = json!("future-tier");
|
||||
body["future_client_extension"] = json!({"opaque":true});
|
||||
let converted = convert(body).await;
|
||||
assert_eq!(converted["model"], "future-model-opaque:β");
|
||||
assert_eq!(converted["tools"][0]["parameters"], schema);
|
||||
assert_eq!(converted["tools"][0]["strict"], false);
|
||||
assert_eq!(
|
||||
converted["tool_choice"],
|
||||
json!({"type":"function","name":"inspect"})
|
||||
);
|
||||
assert_eq!(converted["text"]["format"]["schema"], schema);
|
||||
assert_eq!(converted["text"]["format"]["strict"], true);
|
||||
assert_eq!(
|
||||
converted["metadata"],
|
||||
json!({"messages":"business data","future":"kept"})
|
||||
);
|
||||
assert_eq!(converted["reasoning"]["effort"], "future-effort");
|
||||
assert_eq!(converted["text"]["verbosity"], "future-verbosity");
|
||||
assert_eq!(converted["service_tier"], "future-tier");
|
||||
assert!(converted.get("future_client_extension").is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn normalizes_neutral_defaults_without_dropping_shared_provider_parameters() {
|
||||
let mut body = chat_request(false);
|
||||
for name in [
|
||||
"stream",
|
||||
"store",
|
||||
"n",
|
||||
"functions",
|
||||
"function_call",
|
||||
"logprobs",
|
||||
"seed",
|
||||
] {
|
||||
body[name] = Value::Null;
|
||||
}
|
||||
body["frequency_penalty"] = json!(0);
|
||||
body["presence_penalty"] = json!(0);
|
||||
body["stop"] = json!([]);
|
||||
body["max_tokens"] = json!(12);
|
||||
body["max_completion_tokens"] = json!(24);
|
||||
body["temperature"] = json!(0.2);
|
||||
body["top_p"] = json!(0.9);
|
||||
body["prompt_cache_retention"] = json!("24h");
|
||||
let converted = convert(body).await;
|
||||
assert_eq!(converted["stream"], false);
|
||||
assert_eq!(converted["store"], false);
|
||||
assert_eq!(converted["max_output_tokens"], 24);
|
||||
assert_eq!(converted["temperature"], 0.2);
|
||||
assert_eq!(converted["top_p"], 0.9);
|
||||
assert_eq!(converted["prompt_cache_retention"], "24h");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn refuses_known_unrepresentable_features_before_starting_execution() {
|
||||
for (name, value) in [
|
||||
("n", json!(2)),
|
||||
("store", json!(true)),
|
||||
("stop", json!(["stop"])),
|
||||
("seed", json!(7)),
|
||||
("frequency_penalty", json!(0.3)),
|
||||
("logprobs", json!(true)),
|
||||
("functions", json!([{"name":"old"}])),
|
||||
("function_call", json!("auto")),
|
||||
("input", json!("not chat")),
|
||||
("previous_response_id", json!("resp_previous")),
|
||||
("audio", json!({"voice":"alloy","format":"wav"})),
|
||||
(
|
||||
"prediction",
|
||||
json!({"type":"content","content":"predicted"}),
|
||||
),
|
||||
] {
|
||||
let fixture = Fixture::new(Session::new(Vec::new())).await;
|
||||
let mut body = chat_request(false);
|
||||
body[name] = value;
|
||||
let response = fixture.post(body).await;
|
||||
assert_eq!(response.status(), StatusCode::BAD_REQUEST, "{name}");
|
||||
let body = json_body(response).await;
|
||||
assert_eq!(body["error"]["param"], name, "{body}");
|
||||
assert!(
|
||||
fixture.execution.captured.lock().unwrap().is_none(),
|
||||
"{name}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rejects_unmapped_message_content_and_identity_fields() {
|
||||
for message in [
|
||||
json!({"role":"user","name":"speaker","content":"hello"}),
|
||||
json!({"role":"user","content":[{"type":"file","file":{"file_id":"file-example"}}]}),
|
||||
json!({"role":"assistant","content":"hello","reasoning_content":"private"}),
|
||||
json!({"role":"assistant","content":[{"type":"text","text":"history","prompt_cache_breakpoint":{"type":"default"}}]}),
|
||||
json!({"role":"tool","content":"unassociated output"}),
|
||||
] {
|
||||
let fixture = Fixture::new(Session::new(Vec::new())).await;
|
||||
let response = fixture
|
||||
.post(json!({"model":"model-a","messages":[message]}))
|
||||
.await;
|
||||
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
|
||||
let body = json_body(response).await;
|
||||
assert!(
|
||||
body["error"]["param"]
|
||||
.as_str()
|
||||
.unwrap()
|
||||
.starts_with("messages")
|
||||
);
|
||||
assert!(fixture.execution.captured.lock().unwrap().is_none());
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn assistant_tool_history_keeps_arguments_opaque_and_cache_annotations_structural() {
|
||||
let cache = json!({"type":"default","future_setting":{"keep":true}});
|
||||
let arguments = "not valid JSON {\n \"raw\" : 🦀";
|
||||
let converted = convert(json!({"model":"model-a","messages":[
|
||||
{"role":"user","content":[{"type":"text","text":"cached","prompt_cache_breakpoint":cache}]},
|
||||
{"role":"assistant","content":null,"tool_calls":[{"id":"call-raw","type":"function",
|
||||
"function":{"name":"raw","arguments":arguments}}]},
|
||||
{"role":"tool","tool_call_id":"call-raw","content":[{"type":"text","text":"result"}]}
|
||||
],"prompt_cache_options":{"future":{"keep":true}},"moderation":{"future":{"keep":true}}}))
|
||||
.await;
|
||||
assert_eq!(
|
||||
converted["input"][0]["content"][0]["prompt_cache_breakpoint"],
|
||||
cache
|
||||
);
|
||||
assert_eq!(converted["input"][1]["arguments"], arguments);
|
||||
assert_eq!(
|
||||
converted["input"][2]["output"],
|
||||
json!([{"type":"input_text","text":"result"}])
|
||||
);
|
||||
assert_eq!(
|
||||
converted["prompt_cache_options"],
|
||||
json!({"future":{"keep":true}})
|
||||
);
|
||||
assert_eq!(converted["moderation"], json!({"future":{"keep":true}}));
|
||||
}
|
||||
@@ -0,0 +1,596 @@
|
||||
//! Chat JSON 与 SSE 的真实 wire 投影、去重和协议扩展边界
|
||||
|
||||
use axum::{body::to_bytes, http::StatusCode, response::Response};
|
||||
use serde_json::{Value, json};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use super::{
|
||||
chat_request, completed, created,
|
||||
http::{Fixture, Session, json_body},
|
||||
message, wire,
|
||||
};
|
||||
|
||||
pub(super) async fn sse_body(response: Response) -> (String, Vec<Value>) {
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
assert_eq!(response.headers()["content-type"], "text/event-stream");
|
||||
let bytes = to_bytes(response.into_body(), usize::MAX).await.unwrap();
|
||||
let text = String::from_utf8(bytes.to_vec()).unwrap();
|
||||
assert_eq!(text.matches("data: [DONE]").count(), 1, "{text}");
|
||||
assert!(text.ends_with("data: [DONE]\n\n"), "{text}");
|
||||
assert!(!text.contains("event: response."), "{text}");
|
||||
let chunks = text
|
||||
.lines()
|
||||
.filter_map(|line| line.strip_prefix("data: "))
|
||||
.filter(|data| *data != "[DONE]")
|
||||
.map(|data| serde_json::from_str(data).unwrap())
|
||||
.collect();
|
||||
(text, chunks)
|
||||
}
|
||||
|
||||
fn combined(chunks: &[Value], name: &str) -> String {
|
||||
chunks
|
||||
.iter()
|
||||
.filter_map(|value| value["choices"][0]["delta"][name].as_str())
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn tool(id: &str, call_id: &str, name: &str, arguments: &str) -> Value {
|
||||
json!({"type":"function_call","id":id,"call_id":call_id,"name":name,"arguments":arguments,"status":"completed"})
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn json_projects_public_identity_text_and_actual_usage() {
|
||||
let fixture = Fixture::new(Session::new(vec![completed(json!([message("你好 🌍")]))])).await;
|
||||
let response = fixture.post(chat_request(false)).await;
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
assert_eq!(
|
||||
response.headers()["x-gateway-request-id"],
|
||||
"req_chat_fixture"
|
||||
);
|
||||
let body = json_body(response).await;
|
||||
assert_eq!(body["object"], "chat.completion");
|
||||
assert!(body["id"].as_str().unwrap().starts_with("chatcmpl-"));
|
||||
assert!(body["created"].as_u64().is_some());
|
||||
assert_eq!(body["model"], "model-a");
|
||||
assert_eq!(body["choices"][0]["message"]["content"], "你好 🌍");
|
||||
assert_eq!(body["choices"][0]["finish_reason"], "stop");
|
||||
assert_eq!(
|
||||
body["usage"],
|
||||
json!({"prompt_tokens":11,"completion_tokens":7,"total_tokens":18,
|
||||
"prompt_tokens_details":{"cached_tokens":3},"completion_tokens_details":{"reasoning_tokens":2}})
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn json_tool_arguments_and_refusal_do_not_become_assistant_text() {
|
||||
for output in [
|
||||
json!([tool("fc1", "call1", "weather", "{ \"city\" : \"北京\" }")]),
|
||||
json!([{"type":"reasoning","id":"rs1","summary":[{"type":"summary_text","text":"private"}]},
|
||||
{"type":"message","id":"refusal1","role":"assistant","status":"completed",
|
||||
"content":[{"type":"refusal","refusal":"cannot help"}]}]),
|
||||
] {
|
||||
let fixture = Fixture::new(Session::new(vec![completed(output.clone())])).await;
|
||||
let response = fixture.post(chat_request(false)).await;
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
let body = json_body(response).await;
|
||||
let choice = &body["choices"][0];
|
||||
assert_eq!(choice["message"]["content"], Value::Null);
|
||||
assert!(!body.to_string().contains("private"));
|
||||
if output[0]["type"] == "function_call" {
|
||||
assert_eq!(choice["finish_reason"], "tool_calls");
|
||||
assert_eq!(
|
||||
choice["message"]["tool_calls"][0]["function"]["arguments"],
|
||||
"{ \"city\" : \"北京\" }"
|
||||
);
|
||||
assert_eq!(choice["message"]["tool_calls"][0]["id"], "call1");
|
||||
} else {
|
||||
assert_eq!(choice["message"]["refusal"], "cannot help");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sse_deduplicates_text_snapshots_and_emits_usage_only_when_requested() {
|
||||
for include_usage in [false, true] {
|
||||
let fixture = Fixture::new(Session::new(vec![created(),
|
||||
wire("response.output_text.delta",json!({"item_id":"msg_chat_test","output_index":0,"content_index":0,"delta":"你好 "})),
|
||||
wire("response.output_text.done",json!({"item_id":"msg_chat_test","output_index":0,"content_index":0,"text":"你好 🌍"})),
|
||||
wire("response.content_part.done",json!({"item_id":"msg_chat_test","output_index":0,"content_index":0,"part":{"type":"output_text","text":"你好 🌍"}})),
|
||||
wire("response.output_item.done",json!({"output_index":0,"item":message("你好 🌍")})),
|
||||
completed(json!([message("你好 🌍")]))])).await;
|
||||
let mut body = chat_request(true);
|
||||
body["stream_options"] = json!({"include_usage":include_usage});
|
||||
let (_, chunks) = sse_body(fixture.post(body).await).await;
|
||||
assert_eq!(combined(&chunks, "content"), "你好 🌍");
|
||||
assert_eq!(
|
||||
chunks
|
||||
.iter()
|
||||
.filter(|chunk| chunk["choices"][0]["delta"]["role"] == "assistant")
|
||||
.count(),
|
||||
1
|
||||
);
|
||||
assert_eq!(
|
||||
chunks
|
||||
.iter()
|
||||
.filter(|chunk| chunk["choices"][0]["finish_reason"] == "stop")
|
||||
.count(),
|
||||
1
|
||||
);
|
||||
for chunk in &chunks {
|
||||
assert_eq!(chunk["object"], "chat.completion.chunk");
|
||||
assert_eq!(chunk["id"], chunks[0]["id"]);
|
||||
assert_eq!(chunk["created"], chunks[0]["created"]);
|
||||
assert_eq!(chunk["model"], "model-a");
|
||||
}
|
||||
let usage: Vec<_> = chunks
|
||||
.iter()
|
||||
.filter(|chunk| chunk["choices"] == json!([]))
|
||||
.collect();
|
||||
assert_eq!(usage.len(), usize::from(include_usage));
|
||||
if include_usage {
|
||||
assert_eq!(usage[0]["usage"]["total_tokens"], 18);
|
||||
}
|
||||
let captured = fixture.captured();
|
||||
assert!(captured.body.get("stream_options").is_none());
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sse_preserves_interleaved_tools_and_reordered_terminal_snapshots() {
|
||||
let first = tool(
|
||||
"fc_first",
|
||||
"call_first",
|
||||
"weather",
|
||||
"{ \"city\": \"北京\" }",
|
||||
);
|
||||
let second = tool("fc_second", "call_second", "search", "{\"query\":\"Rust\"}");
|
||||
let fixture = Fixture::new(Session::new(vec![
|
||||
created(),
|
||||
wire(
|
||||
"response.output_item.added",
|
||||
json!({"output_index":2,"item":tool("fc_first","call_first","weather","")}),
|
||||
),
|
||||
wire(
|
||||
"response.output_item.added",
|
||||
json!({"output_index":5,"item":tool("fc_second","call_second","search","")}),
|
||||
),
|
||||
wire(
|
||||
"response.function_call_arguments.delta",
|
||||
json!({"output_index":2,"item_id":"fc_first","delta":"{ \"city\": "}),
|
||||
),
|
||||
wire(
|
||||
"response.function_call_arguments.delta",
|
||||
json!({"output_index":5,"item_id":"fc_second","delta":"{\"query\":"}),
|
||||
),
|
||||
wire(
|
||||
"response.function_call_arguments.delta",
|
||||
json!({"output_index":2,"item_id":"fc_first","delta":"\"北京\" }"}),
|
||||
),
|
||||
wire(
|
||||
"response.function_call_arguments.done",
|
||||
json!({"output_index":5,"item_id":"fc_second","arguments":second["arguments"]}),
|
||||
),
|
||||
wire(
|
||||
"response.output_item.done",
|
||||
json!({"output_index":2,"item":first}),
|
||||
),
|
||||
completed(json!([second, first])),
|
||||
]))
|
||||
.await;
|
||||
let (_, chunks) = sse_body(fixture.post(chat_request(true)).await).await;
|
||||
let mut tools = BTreeMap::<u64, (String, String, String)>::new();
|
||||
for chunk in &chunks {
|
||||
if let Some(calls) = chunk["choices"][0]["delta"]["tool_calls"].as_array() {
|
||||
for call in calls {
|
||||
let entry = tools.entry(call["index"].as_u64().unwrap()).or_default();
|
||||
if let Some(id) = call["id"].as_str() {
|
||||
entry.0.push_str(id);
|
||||
}
|
||||
if let Some(name) = call["function"]["name"].as_str() {
|
||||
entry.1.push_str(name);
|
||||
}
|
||||
if let Some(arguments) = call["function"]["arguments"].as_str() {
|
||||
entry.2.push_str(arguments);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
assert_eq!(
|
||||
tools,
|
||||
BTreeMap::from([
|
||||
(
|
||||
0,
|
||||
(
|
||||
"call_first".into(),
|
||||
"weather".into(),
|
||||
"{ \"city\": \"北京\" }".into()
|
||||
)
|
||||
),
|
||||
(
|
||||
1,
|
||||
(
|
||||
"call_second".into(),
|
||||
"search".into(),
|
||||
"{\"query\":\"Rust\"}".into()
|
||||
)
|
||||
),
|
||||
])
|
||||
);
|
||||
assert_eq!(
|
||||
chunks.last().unwrap()["choices"][0]["finish_reason"],
|
||||
"tool_calls"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn extra_attributes_and_auxiliary_events_preserve_existing_chat_results() {
|
||||
let mut text = message("preserved");
|
||||
text["future_optional"] = json!({"opaque":true});
|
||||
text["content"][0]["future_attribute"] = json!([1, 2, 3]);
|
||||
let fixture = Fixture::new(Session::new(vec![
|
||||
wire("response.future_auxiliary", json!({"future":true})),
|
||||
wire(
|
||||
"response.reasoning_summary_text.delta",
|
||||
json!({"output_index":0,"summary_index":0,"delta":"private"}),
|
||||
),
|
||||
created(),
|
||||
completed(json!([text])),
|
||||
]))
|
||||
.await;
|
||||
let (_, chunks) = sse_body(fixture.post(chat_request(true)).await).await;
|
||||
assert_eq!(combined(&chunks, "content"), "preserved");
|
||||
assert!(
|
||||
!chunks
|
||||
.iter()
|
||||
.any(|chunk| chunk.to_string().contains("private"))
|
||||
);
|
||||
assert_eq!(
|
||||
fixture
|
||||
.trace
|
||||
.discarded
|
||||
.load(std::sync::atomic::Ordering::SeqCst),
|
||||
2
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn incomplete_projects_only_supported_finish_reasons() {
|
||||
for (reason, expected) in [
|
||||
("max_output_tokens", "length"),
|
||||
("content_filter", "content_filter"),
|
||||
] {
|
||||
for streaming in [false, true] {
|
||||
let event = wire(
|
||||
"response.incomplete",
|
||||
json!({"response":{
|
||||
"id":"resp_chat_test","status":"incomplete","output":[message("partial")],
|
||||
"incomplete_details":{"reason":reason}}}),
|
||||
);
|
||||
let fixture = Fixture::new(Session::new(vec![created(), event])).await;
|
||||
let response = fixture.post(chat_request(streaming)).await;
|
||||
if streaming {
|
||||
let (_, chunks) = sse_body(response).await;
|
||||
assert_eq!(
|
||||
chunks.last().unwrap()["choices"][0]["finish_reason"],
|
||||
expected
|
||||
);
|
||||
} else {
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
assert_eq!(
|
||||
json_body(response).await["choices"][0]["finish_reason"],
|
||||
expected
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn encrypted_reasoning_stays_private_while_public_text_and_usage_are_projected() {
|
||||
let reasoning = json!({
|
||||
"id":"rs_private","type":"reasoning",
|
||||
"summary":[{"type":"summary_text","text":"PRIVATE_SUMMARY_MARKER"}],
|
||||
"encrypted_content":"OPAQUE_ENCRYPTED_REASONING_MARKER"
|
||||
});
|
||||
for streaming in [false, true] {
|
||||
let fixture = Fixture::new(Session::new(vec![
|
||||
created(),
|
||||
wire(
|
||||
"response.output_item.added",
|
||||
json!({"output_index":0,"item":{"id":"rs_private","type":"reasoning","summary":[]}}),
|
||||
),
|
||||
wire(
|
||||
"response.reasoning_summary_text.delta",
|
||||
json!({"item_id":"rs_private","output_index":0,"summary_index":0,"delta":"PRIVATE_SUMMARY_MARKER"}),
|
||||
),
|
||||
wire(
|
||||
"response.output_item.done",
|
||||
json!({"output_index":0,"item":reasoning}),
|
||||
),
|
||||
wire(
|
||||
"response.output_item.done",
|
||||
json!({"output_index":1,"item":message("public answer")}),
|
||||
),
|
||||
completed(json!([reasoning, message("public answer")])),
|
||||
]))
|
||||
.await;
|
||||
let mut request = chat_request(streaming);
|
||||
if streaming {
|
||||
request["stream_options"] = json!({"include_usage":true});
|
||||
}
|
||||
let response = fixture.post(request).await;
|
||||
let (body, content, usage) = if streaming {
|
||||
let (body, chunks) = sse_body(response).await;
|
||||
let usage = chunks
|
||||
.iter()
|
||||
.find(|chunk| chunk["choices"] == json!([]))
|
||||
.expect("terminal usage chunk")["usage"]
|
||||
.clone();
|
||||
(body, combined(&chunks, "content"), usage)
|
||||
} else {
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
let body = json_body(response).await;
|
||||
(
|
||||
body.to_string(),
|
||||
body["choices"][0]["message"]["content"]
|
||||
.as_str()
|
||||
.unwrap()
|
||||
.to_owned(),
|
||||
body["usage"].clone(),
|
||||
)
|
||||
};
|
||||
assert_eq!(content, "public answer");
|
||||
assert!(!body.contains("PRIVATE_SUMMARY_MARKER"), "{body}");
|
||||
assert!(
|
||||
!body.contains("OPAQUE_ENCRYPTED_REASONING_MARKER"),
|
||||
"{body}"
|
||||
);
|
||||
assert_eq!(usage["completion_tokens_details"]["reasoning_tokens"], 2);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn unrepresentable_business_output_fails_without_successful_chat_completion() {
|
||||
for output in [
|
||||
json!({"id":"future_output","type":"future_business_output","payload":"unrepresentable"}),
|
||||
json!({"id":"ig_native","type":"image_generation_call","status":"completed","result":"OPAQUE_IMAGE_MARKER"}),
|
||||
] {
|
||||
for streaming in [false, true] {
|
||||
let fixture =
|
||||
Fixture::new(Session::new(vec![created(), completed(json!([output]))])).await;
|
||||
let mut request = chat_request(streaming);
|
||||
if streaming {
|
||||
request["stream_options"] = json!({"include_usage":true});
|
||||
}
|
||||
let response = fixture.post(request).await;
|
||||
if streaming {
|
||||
let (body, chunks) = sse_body(response).await;
|
||||
assert!(chunks.iter().any(|chunk| chunk.get("error").is_some()));
|
||||
assert!(
|
||||
!chunks
|
||||
.iter()
|
||||
.any(|chunk| chunk["choices"][0]["finish_reason"].is_string())
|
||||
);
|
||||
assert!(!chunks.iter().any(|chunk| chunk["choices"] == json!([])));
|
||||
assert!(!body.contains("OPAQUE_IMAGE_MARKER"));
|
||||
} else {
|
||||
assert!(response.status().is_server_error());
|
||||
let body = json_body(response).await;
|
||||
assert!(body.get("error").is_some());
|
||||
assert!(body.get("choices").is_none());
|
||||
assert!(!body.to_string().contains("OPAQUE_IMAGE_MARKER"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stream_without_terminal_does_not_emit_a_successful_finish_or_usage() {
|
||||
let fixture = Fixture::new(Session::new(vec![
|
||||
created(),
|
||||
wire(
|
||||
"response.output_text.delta",
|
||||
json!({"item_id":"msg_chat_test","output_index":0,"content_index":0,"delta":"partial"}),
|
||||
),
|
||||
]))
|
||||
.await;
|
||||
let mut body = chat_request(true);
|
||||
body["stream_options"] = json!({"include_usage":true});
|
||||
let (_, chunks) = sse_body(fixture.post(body).await).await;
|
||||
assert!(chunks.iter().any(|chunk| chunk.get("error").is_some()));
|
||||
assert!(
|
||||
!chunks
|
||||
.iter()
|
||||
.any(|chunk| chunk["choices"][0]["finish_reason"].is_string())
|
||||
);
|
||||
assert!(!chunks.iter().any(|chunk| chunk["choices"] == json!([])));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn first_batch_terminal_can_finish_without_creating_usage_facts() {
|
||||
let fixture = Fixture::new(Session::new(vec![wire(
|
||||
"response.completed",
|
||||
json!({"response":{
|
||||
"id":"resp_chat_test","status":"completed","output":[message("done only")]
|
||||
}}),
|
||||
)]))
|
||||
.await;
|
||||
let mut body = chat_request(true);
|
||||
body["stream_options"] = json!({"include_usage":true});
|
||||
let (_, chunks) = sse_body(fixture.post(body).await).await;
|
||||
assert_eq!(combined(&chunks, "content"), "done only");
|
||||
assert_eq!(
|
||||
chunks
|
||||
.iter()
|
||||
.filter(|chunk| chunk["choices"][0]["finish_reason"] == "stop")
|
||||
.count(),
|
||||
1
|
||||
);
|
||||
assert!(!chunks.iter().any(|chunk| chunk["usage"].is_object()));
|
||||
assert!(
|
||||
fixture
|
||||
.trace
|
||||
.finalized
|
||||
.load(std::sync::atomic::Ordering::SeqCst)
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn native_sse_byte_fragments_and_multiple_events_preserve_unicode() {
|
||||
let first = gateway_protocol::openai::sse::encode_sse_event("response.output_text.delta",&json!({
|
||||
"type":"response.output_text.delta","item_id":"msg_chat_test","output_index":0,"content_index":0,"delta":"你"
|
||||
}).to_string());
|
||||
let second = gateway_protocol::openai::sse::encode_sse_event("response.output_text.delta",&json!({
|
||||
"type":"response.output_text.delta","item_id":"msg_chat_test","output_index":0,"content_index":0,"delta":"好"
|
||||
}).to_string());
|
||||
let split = first.find('你').unwrap() + 1;
|
||||
let mut remainder = first.as_bytes()[split..].to_vec();
|
||||
remainder.extend_from_slice(second.as_bytes());
|
||||
let raw = |bytes| {
|
||||
gateway_core::event::ProviderEvent::wire(
|
||||
gateway_core::event::ProtocolWireEvent::raw_sse("openai", bytes).unwrap(),
|
||||
)
|
||||
};
|
||||
let fixture = Fixture::new(Session::new(vec![
|
||||
created(),
|
||||
raw(bytes::Bytes::copy_from_slice(&first.as_bytes()[..split])),
|
||||
raw(bytes::Bytes::from(remainder)),
|
||||
completed(json!([message("你好")])),
|
||||
]))
|
||||
.await;
|
||||
let (_, chunks) = sse_body(fixture.post(chat_request(true)).await).await;
|
||||
assert_eq!(combined(&chunks, "content"), "你好");
|
||||
assert_eq!(
|
||||
chunks.last().unwrap()["choices"][0]["finish_reason"],
|
||||
"stop"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn refusal_deltas_and_done_snapshots_produce_only_standard_refusal() {
|
||||
let output = json!({"id":"msg_refusal","type":"message","role":"assistant","status":"completed",
|
||||
"content":[{"type":"refusal","refusal":"cannot help"}]});
|
||||
let fixture = Fixture::new(Session::new(vec![created(),
|
||||
wire("response.refusal.delta",json!({"item_id":"msg_refusal","output_index":0,"content_index":0,"delta":"cannot "})),
|
||||
wire("response.refusal.done",json!({"item_id":"msg_refusal","output_index":0,"content_index":0,"refusal":"cannot help"})),
|
||||
completed(json!([output]))])).await;
|
||||
let (_, chunks) = sse_body(fixture.post(chat_request(true)).await).await;
|
||||
assert_eq!(combined(&chunks, "refusal"), "cannot help");
|
||||
assert_eq!(combined(&chunks, "content"), "");
|
||||
assert_eq!(
|
||||
chunks.last().unwrap()["choices"][0]["finish_reason"],
|
||||
"stop"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn auxiliary_events_after_completed_preserve_exactly_one_finish_and_usage() {
|
||||
for with_created in [false, true] {
|
||||
// 终态与辅助事件同属一批 Core 交付 不构造已终结会话继续产出事件的另一种异常
|
||||
let session = Session::new(if with_created {
|
||||
vec![created()]
|
||||
} else {
|
||||
Vec::new()
|
||||
})
|
||||
.with_batch(vec![
|
||||
completed(json!([message("completed text")])),
|
||||
wire(
|
||||
"response.future_metadata",
|
||||
json!({"response_id":"resp_chat_test","future":{"kept":true}}),
|
||||
),
|
||||
]);
|
||||
let fixture = Fixture::new(session).await;
|
||||
let mut body = chat_request(true);
|
||||
body["stream_options"] = json!({"include_usage":true});
|
||||
let (_, chunks) = sse_body(fixture.post(body).await).await;
|
||||
assert_eq!(combined(&chunks, "content"), "completed text");
|
||||
assert_eq!(
|
||||
chunks
|
||||
.iter()
|
||||
.filter(|chunk| chunk["choices"][0]["finish_reason"] == "stop")
|
||||
.count(),
|
||||
1
|
||||
);
|
||||
let usage = chunks
|
||||
.iter()
|
||||
.filter(|chunk| chunk["choices"] == json!([]))
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(usage.len(), 1);
|
||||
assert_eq!(usage[0]["usage"]["total_tokens"], 18);
|
||||
assert!(!chunks.iter().any(|chunk| chunk.get("error").is_some()));
|
||||
assert_eq!(
|
||||
fixture
|
||||
.trace
|
||||
.commits
|
||||
.load(std::sync::atomic::Ordering::SeqCst),
|
||||
1
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn wire_failures_preserve_existing_recovery_fields_without_success_chunks() {
|
||||
for shape in ["response.failed", "error", "bare_error"] {
|
||||
let mut expected = json!({
|
||||
"type":"rate_limit_error","code":"rate_limit_exceeded","param":null,
|
||||
"message":"retry later","headers":{"retry-after":"2"},
|
||||
"recovery":{"action":"retry","future":[1,2]},
|
||||
"future_error_property":{"enabled":true}
|
||||
});
|
||||
let failure = match shape {
|
||||
"response.failed" => wire(
|
||||
"response.failed",
|
||||
json!({"response":{
|
||||
"id":"resp_chat_test","object":"response","model":"upstream-model",
|
||||
"status":"failed","output":[],"error":expected.clone()
|
||||
}}),
|
||||
),
|
||||
"error" => wire("error", json!({"error":expected.clone()})),
|
||||
_ => {
|
||||
// 裸事件的 type 是 wire 名称,仅该包装身份归一化为 Chat 错误类型
|
||||
let failure = wire("error", expected.clone());
|
||||
expected["type"] = json!("server_error");
|
||||
failure
|
||||
}
|
||||
};
|
||||
let fixture = Fixture::new(Session::new(vec![created(), failure])).await;
|
||||
let mut body = chat_request(true);
|
||||
body["stream_options"] = json!({"include_usage":true});
|
||||
let (_, chunks) = sse_body(fixture.post(body).await).await;
|
||||
let errors = chunks
|
||||
.iter()
|
||||
.filter_map(|chunk| chunk.get("error"))
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(errors, vec![&expected], "{shape}");
|
||||
assert!(
|
||||
!chunks
|
||||
.iter()
|
||||
.any(|chunk| chunk["choices"][0]["finish_reason"].is_string()),
|
||||
"{shape}"
|
||||
);
|
||||
assert!(!chunks.iter().any(|chunk| chunk["choices"] == json!([])));
|
||||
assert!(!chunks.iter().any(|chunk| chunk["usage"].is_object()));
|
||||
assert_eq!(
|
||||
fixture
|
||||
.trace
|
||||
.commits
|
||||
.load(std::sync::atomic::Ordering::SeqCst),
|
||||
1
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn conflicting_text_snapshot_fails_instead_of_appending_replacement_content() {
|
||||
let fixture = Fixture::new(Session::new(vec![created(),
|
||||
wire("response.output_text.delta",json!({"item_id":"msg_chat_test","output_index":0,"content_index":0,"delta":"already sent"})),
|
||||
completed(json!([message("different result")]))])).await;
|
||||
let (_, chunks) = sse_body(fixture.post(chat_request(true)).await).await;
|
||||
assert_eq!(combined(&chunks, "content"), "already sent");
|
||||
assert!(chunks.iter().any(|chunk| chunk.get("error").is_some()));
|
||||
assert!(
|
||||
!chunks
|
||||
.iter()
|
||||
.any(|chunk| chunk["choices"][0]["finish_reason"].is_string())
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
//! OpenAI 协议 HTTP 与 WebSocket 接口的测试入口
|
||||
|
||||
mod auth;
|
||||
mod chat_completions;
|
||||
mod endpoint;
|
||||
mod error;
|
||||
mod image_policy;
|
||||
|
||||
@@ -78,9 +78,9 @@ impl ModelsExecution {
|
||||
})
|
||||
}
|
||||
|
||||
fn with_cli_min() -> Arc<Self> {
|
||||
pub(super) fn with_cli_min(minimum: &str) -> Arc<Self> {
|
||||
Arc::new(Self {
|
||||
client: authenticated_client_with_min_versions("sk_models_test", None, Some("0.40.0")),
|
||||
client: authenticated_client_with_min_versions("sk_models_test", None, Some(minimum)),
|
||||
presentation: None,
|
||||
native: None,
|
||||
requested_versions: Mutex::default(),
|
||||
@@ -440,7 +440,7 @@ async fn models_should_reject_recognized_cli_below_configured_min() {
|
||||
.header("user-agent", "codex_cli_rs/0.39.0 (Linux; x86_64)")
|
||||
.body(Body::empty())
|
||||
.expect("build models request");
|
||||
let response = api_router(ModelsExecution::with_cli_min())
|
||||
let response = api_router(ModelsExecution::with_cli_min("0.40.0"))
|
||||
.await
|
||||
.oneshot(request)
|
||||
.await
|
||||
@@ -464,7 +464,7 @@ async fn models_should_reject_recognized_cli_with_invalid_version() {
|
||||
.header("user-agent", "codex-cli/not-a-version")
|
||||
.body(Body::empty())
|
||||
.expect("build models request");
|
||||
let response = api_router(ModelsExecution::with_cli_min())
|
||||
let response = api_router(ModelsExecution::with_cli_min("0.40.0"))
|
||||
.await
|
||||
.oneshot(request)
|
||||
.await
|
||||
@@ -513,7 +513,7 @@ async fn models_should_allow_cli_at_its_configured_min() {
|
||||
.header("user-agent", "codex_cli_rs/0.40.0 (Linux; x86_64)")
|
||||
.body(Body::empty())
|
||||
.expect("build models request");
|
||||
let response = api_router(ModelsExecution::with_cli_min())
|
||||
let response = api_router(ModelsExecution::with_cli_min("0.40.0"))
|
||||
.await
|
||||
.oneshot(request)
|
||||
.await
|
||||
@@ -529,7 +529,7 @@ async fn models_should_leave_unknown_clients_unrestricted() {
|
||||
.header("user-agent", "curl/8.14.1")
|
||||
.body(Body::empty())
|
||||
.expect("build models request");
|
||||
let response = api_router(ModelsExecution::with_cli_min())
|
||||
let response = api_router(ModelsExecution::with_cli_min("0.40.0"))
|
||||
.await
|
||||
.oneshot(request)
|
||||
.await
|
||||
@@ -685,7 +685,7 @@ async fn model_detail_should_hide_unknown_models() {
|
||||
|
||||
#[tokio::test]
|
||||
async fn models_should_authenticate_before_applying_the_version_gate() {
|
||||
let response = api_router(ModelsExecution::with_cli_min())
|
||||
let response = api_router(ModelsExecution::with_cli_min("0.40.0"))
|
||||
.await
|
||||
.oneshot(
|
||||
Request::get("/v1/models")
|
||||
|
||||
@@ -2164,109 +2164,132 @@ async fn streaming_upstream_wire_failure_should_not_be_rewritten_as_a_gateway_er
|
||||
|
||||
#[tokio::test]
|
||||
async fn streaming_upstream_error_event_should_be_translated_to_response_failed_for_sse() {
|
||||
let trace = Arc::new(Trace::default());
|
||||
let error_data = json!({
|
||||
"type": "error",
|
||||
"error": {
|
||||
"type": "service_unavailable_error",
|
||||
"code": "server_is_overloaded",
|
||||
"message": "Our servers are currently overloaded. Please try again later.",
|
||||
"param": null,
|
||||
"future_error_field": {"keep": true}
|
||||
},
|
||||
"sequence_number": 2,
|
||||
"future_event_field": {"keep": true}
|
||||
});
|
||||
let projected_error_frame = Bytes::from(encode_sse_event("error", &error_data.to_string()));
|
||||
let error_wire = ProviderEvent::wire(
|
||||
ProtocolWireEvent::json_with_raw_sse_metadata(
|
||||
"openai",
|
||||
Some("error".to_owned()),
|
||||
error_data,
|
||||
projected_error_frame,
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.expect("valid upstream error wire"),
|
||||
);
|
||||
let started_wire = ProviderEvent::canonical_with_wire(
|
||||
vec![started()],
|
||||
ProtocolWireEvent::json(
|
||||
"openai",
|
||||
Some("response.created".to_owned()),
|
||||
json!({
|
||||
"type": "response.created",
|
||||
"response": {
|
||||
"id": "resp_test",
|
||||
"model": "public-model",
|
||||
"status": "in_progress",
|
||||
"future_response_field": {"keep": true}
|
||||
}
|
||||
}),
|
||||
)
|
||||
.expect("valid upstream started wire"),
|
||||
);
|
||||
let session = FakeSession::streaming(
|
||||
Arc::clone(&trace),
|
||||
vec![
|
||||
NextStep::Event(CoordinatedEvent::single(
|
||||
started_wire,
|
||||
CommitRequirement::CommitBeforeDelivery,
|
||||
)),
|
||||
NextStep::Event(CoordinatedEvent::single(
|
||||
error_wire,
|
||||
CommitRequirement::AlreadyCommitted,
|
||||
)),
|
||||
NextStep::Error(EngineError::Provider(ProviderError::new(
|
||||
ProviderErrorKind::UpstreamCapacityUnavailable,
|
||||
UpstreamSendState::Sent,
|
||||
))),
|
||||
],
|
||||
);
|
||||
|
||||
let response = stream_execution_response(Box::new(session), None).await;
|
||||
let body = to_bytes(response.into_body(), usize::MAX)
|
||||
.await
|
||||
.expect("read SSE body");
|
||||
let body = String::from_utf8(body.to_vec()).expect("SSE is UTF-8");
|
||||
let events = parse_sse_events(&body).expect("translated SSE should parse");
|
||||
let failed = events
|
||||
.iter()
|
||||
.find(|event| event.event.as_deref() == Some("response.failed"))
|
||||
.expect("translated response.failed event");
|
||||
let failed: Value = serde_json::from_str(&failed.data).expect("response.failed JSON");
|
||||
|
||||
assert_eq!(
|
||||
for (error_type, code, client_code, kind, client_status) in [
|
||||
(
|
||||
failed,
|
||||
body.matches("event: response.failed").count(),
|
||||
body.contains("event: error\n"),
|
||||
body.ends_with("data: [DONE]\n\n"),
|
||||
"service_unavailable_error",
|
||||
"server_is_overloaded",
|
||||
"server_error",
|
||||
ProviderErrorKind::UpstreamCapacityUnavailable,
|
||||
503,
|
||||
),
|
||||
(
|
||||
json!({
|
||||
"type": "response.failed",
|
||||
"response": {
|
||||
"id": "resp_test",
|
||||
"model": "public-model",
|
||||
"status": "failed",
|
||||
"error": {
|
||||
"type": "service_unavailable_error",
|
||||
"code": "server_error",
|
||||
"message": "Our servers are currently overloaded. Please try again later.",
|
||||
"param": null,
|
||||
"future_error_field": {"keep": true}
|
||||
"rate_limit_error",
|
||||
"turn_rate_limit_exceeded",
|
||||
"turn_rate_limit_exceeded",
|
||||
ProviderErrorKind::RateLimited,
|
||||
429,
|
||||
),
|
||||
] {
|
||||
let trace = Arc::new(Trace::default());
|
||||
let error_data = json!({
|
||||
"type": "error",
|
||||
"status": 429,
|
||||
"headers": {"Retry-After": "24"},
|
||||
"error": {
|
||||
"type": error_type,
|
||||
"code": code,
|
||||
"message": "Our servers are currently overloaded. Please try again later.",
|
||||
"param": null,
|
||||
"future_error_field": {"keep": true}
|
||||
},
|
||||
"sequence_number": 2,
|
||||
"future_event_field": {"keep": true}
|
||||
});
|
||||
let projected_error_frame = Bytes::from(encode_sse_event("error", &error_data.to_string()));
|
||||
let error_wire = ProviderEvent::wire(
|
||||
ProtocolWireEvent::json_with_raw_sse_metadata(
|
||||
"openai",
|
||||
Some("error".to_owned()),
|
||||
error_data,
|
||||
projected_error_frame,
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.expect("valid upstream error wire"),
|
||||
);
|
||||
let started_wire = ProviderEvent::canonical_with_wire(
|
||||
vec![started()],
|
||||
ProtocolWireEvent::json(
|
||||
"openai",
|
||||
Some("response.created".to_owned()),
|
||||
json!({
|
||||
"type": "response.created",
|
||||
"response": {
|
||||
"id": "resp_test",
|
||||
"model": "public-model",
|
||||
"status": "in_progress",
|
||||
"future_response_field": {"keep": true}
|
||||
}
|
||||
}),
|
||||
)
|
||||
.expect("valid upstream started wire"),
|
||||
);
|
||||
let session = FakeSession::streaming(
|
||||
Arc::clone(&trace),
|
||||
vec![
|
||||
NextStep::Event(CoordinatedEvent::single(
|
||||
started_wire,
|
||||
CommitRequirement::CommitBeforeDelivery,
|
||||
)),
|
||||
NextStep::Event(CoordinatedEvent::single(
|
||||
error_wire,
|
||||
CommitRequirement::AlreadyCommitted,
|
||||
)),
|
||||
NextStep::Error(EngineError::Provider(ProviderError::new(
|
||||
kind,
|
||||
UpstreamSendState::Sent,
|
||||
))),
|
||||
],
|
||||
);
|
||||
|
||||
let response = stream_execution_response(Box::new(session), None).await;
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
let body = to_bytes(response.into_body(), usize::MAX)
|
||||
.await
|
||||
.expect("read SSE body");
|
||||
let body = String::from_utf8(body.to_vec()).expect("SSE is UTF-8");
|
||||
let events = parse_sse_events(&body).expect("translated SSE should parse");
|
||||
let failed = events
|
||||
.iter()
|
||||
.find(|event| event.event.as_deref() == Some("response.failed"))
|
||||
.expect("translated response.failed event");
|
||||
let failed: Value = serde_json::from_str(&failed.data).expect("response.failed JSON");
|
||||
|
||||
assert_eq!(
|
||||
(
|
||||
failed,
|
||||
body.matches("event: response.failed").count(),
|
||||
body.contains("event: error\n"),
|
||||
body.ends_with("data: [DONE]\n\n"),
|
||||
),
|
||||
(
|
||||
json!({
|
||||
"type": "response.failed",
|
||||
"status": client_status,
|
||||
"headers": {"Retry-After": "24"},
|
||||
"response": {
|
||||
"id": "resp_test",
|
||||
"model": "public-model",
|
||||
"status": "failed",
|
||||
"error": {
|
||||
"type": error_type,
|
||||
"code": client_code,
|
||||
"message": "Our servers are currently overloaded. Please try again later.",
|
||||
"param": null,
|
||||
"future_error_field": {"keep": true},
|
||||
"headers": {"retry-after": "24"}
|
||||
},
|
||||
"future_response_field": {"keep": true}
|
||||
},
|
||||
"future_response_field": {"keep": true}
|
||||
},
|
||||
"sequence_number": 2,
|
||||
"future_event_field": {"keep": true}
|
||||
}),
|
||||
1,
|
||||
false,
|
||||
true,
|
||||
)
|
||||
);
|
||||
"sequence_number": 2,
|
||||
"future_event_field": {"keep": true}
|
||||
}),
|
||||
1,
|
||||
false,
|
||||
true,
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -2527,6 +2550,110 @@ async fn buffered_response_collects_completed_output_items_without_rewriting_str
|
||||
assert!(!trace.is_cancelled());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn native_responses_route_preserves_images_and_encrypted_reasoning_in_json_and_sse() {
|
||||
let admin = crate::admin::AdminTestFixture::new().await.services;
|
||||
let reasoning = json!({
|
||||
"id":"rs_native","type":"reasoning","encrypted_content":"opaque-reasoning-for-replay",
|
||||
"summary":[{"type":"summary_text","text":"native summary"}],
|
||||
"future_reasoning_field":{"keep":true}
|
||||
});
|
||||
let image = json!({
|
||||
"id":"ig_native","type":"image_generation_call","status":"completed",
|
||||
"result":"b3BhcXVlLWltYWdl","output_format":"png",
|
||||
"future_image_field":{"keep":true}
|
||||
});
|
||||
let terminal = json!({
|
||||
"id":"resp_test","object":"response","model":"public-model","status":"completed",
|
||||
"output":[reasoning, image],"future_terminal_field":{"keep":true}
|
||||
});
|
||||
for streaming in [false, true] {
|
||||
let trace = Arc::new(Trace::default());
|
||||
let mut expected_sse = Vec::new();
|
||||
let mut events = Vec::new();
|
||||
for (index, (kind, mut data, facts)) in [
|
||||
(
|
||||
"response.created",
|
||||
json!({"response":{"id":"resp_test","model":"public-model","status":"in_progress","output":[]}}),
|
||||
vec![started()],
|
||||
),
|
||||
(
|
||||
"response.output_item.done",
|
||||
json!({"output_index":0,"item":reasoning}),
|
||||
vec![],
|
||||
),
|
||||
(
|
||||
"response.image_generation_call.partial_image",
|
||||
json!({"item_id":"ig_native","output_index":1,"partial_image_index":0,"partial_image_b64":"b3BhcXVlLXBhcnRpYWw="}),
|
||||
vec![],
|
||||
),
|
||||
(
|
||||
"response.output_item.done",
|
||||
json!({"output_index":1,"item":image}),
|
||||
vec![],
|
||||
),
|
||||
(
|
||||
"response.completed",
|
||||
json!({"response":terminal}),
|
||||
vec![completed()],
|
||||
),
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
data["type"] = json!(kind);
|
||||
let id = format!("native-boundary-{index}");
|
||||
// 保留行结束符、空白和 SSE 元数据,不能仅比较 JSON 后掩盖重编码
|
||||
let raw = Bytes::from(format!(
|
||||
"id: {id}\r\nevent: {kind}\r\nretry: 1234\r\ndata: {data} \r\n\r\n"
|
||||
));
|
||||
expected_sse.extend_from_slice(&raw);
|
||||
events.push(ProviderEvent::canonical_with_wire(
|
||||
facts,
|
||||
ProtocolWireEvent::json_with_raw_sse_metadata(
|
||||
"openai",
|
||||
Some(kind.to_owned()),
|
||||
data,
|
||||
raw,
|
||||
Some(id),
|
||||
Some(1234),
|
||||
)
|
||||
.unwrap(),
|
||||
));
|
||||
}
|
||||
let session = if streaming {
|
||||
FakeSession::streaming(
|
||||
Arc::clone(&trace),
|
||||
vec![
|
||||
NextStep::Event(
|
||||
CoordinatedEvent::try_batch(
|
||||
events,
|
||||
CommitRequirement::CommitBeforeDelivery,
|
||||
)
|
||||
.unwrap(),
|
||||
),
|
||||
NextStep::FinalizeSuccess,
|
||||
],
|
||||
)
|
||||
} else {
|
||||
FakeSession::buffered_provider(Arc::clone(&trace), events)
|
||||
};
|
||||
// 使用真实 /v1/responses 入口,覆盖共享执行函数的可选适配器为空分支
|
||||
let response = response(&admin, "openai", session, streaming).await;
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
|
||||
if streaming {
|
||||
expected_sse.extend_from_slice(b"data: [DONE]\n\n");
|
||||
assert_eq!(body.as_ref(), expected_sse.as_slice());
|
||||
assert_eq!(trace.snapshot(), ["next_event", "commit", "next_end"]);
|
||||
} else {
|
||||
assert_eq!(serde_json::from_slice::<Value>(&body).unwrap(), terminal);
|
||||
assert_eq!(trace.snapshot(), ["collect", "commit"]);
|
||||
}
|
||||
assert!(!trace.is_cancelled());
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn buffered_response_keeps_authoritative_terminal_and_supports_omitted_output() {
|
||||
let item = json!({"id": "rs_test", "type": "reasoning", "encrypted_content": "opaque"});
|
||||
@@ -2821,6 +2948,69 @@ struct SessionExecution {
|
||||
middleware: Option<FrozenMiddlewarePlan>,
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn official_core_clients_should_be_version_checked_before_starting_responses() {
|
||||
let admin = crate::admin::AdminTestFixture::new().await.services;
|
||||
for product in [
|
||||
"codex-tui",
|
||||
"codex_exec",
|
||||
"codex_vscode",
|
||||
"codex_sdk_ts",
|
||||
"codex_python_sdk",
|
||||
] {
|
||||
for (version, allowed) in [("0.158.0", false), ("0.162.0", true)] {
|
||||
let trace = Arc::new(Trace::default());
|
||||
let execution = Arc::new(SessionExecution {
|
||||
client: authenticated_client_with_min_versions(
|
||||
"sk_version_test",
|
||||
None,
|
||||
Some("0.162.0"),
|
||||
),
|
||||
session: Mutex::new(Some(Box::new(FakeSession::streaming(
|
||||
Arc::clone(&trace),
|
||||
vec![
|
||||
NextStep::Event(delivery(
|
||||
started(),
|
||||
CommitRequirement::CommitBeforeDelivery,
|
||||
)),
|
||||
NextStep::Event(delivery(completed(), CommitRequirement::AlreadyCommitted)),
|
||||
NextStep::FinalizeSuccess,
|
||||
],
|
||||
)))),
|
||||
middleware: None,
|
||||
});
|
||||
let request = Request::post("/v1/responses")
|
||||
.header(AUTHORIZATION, "Bearer sk_version_test")
|
||||
.header("user-agent", format!(
|
||||
"{product}/{version} (Mac OS 26.6.2; arm64) Apple_Terminal ({product}; 0.165.0)"
|
||||
))
|
||||
.body(Body::from(json!({"model": "model-a", "input": "synthetic", "stream": true}).to_string()))
|
||||
.unwrap();
|
||||
let response = crate::openai::api_router_with_admin_and_execution(
|
||||
admin.clone(),
|
||||
execution.clone(),
|
||||
)
|
||||
.oneshot(request)
|
||||
.await
|
||||
.unwrap();
|
||||
let status = response.status();
|
||||
let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
|
||||
if allowed {
|
||||
assert_eq!(status, StatusCode::OK, "{product}/{version}");
|
||||
assert!(String::from_utf8_lossy(&body).contains("event: response.completed\n"));
|
||||
assert!(trace.snapshot().contains(&"commit"));
|
||||
} else {
|
||||
assert_eq!(status, StatusCode::UPGRADE_REQUIRED, "{product}/{version}");
|
||||
let value: Value = serde_json::from_slice(&body).unwrap();
|
||||
assert_eq!(value["error"]["code"], "client_version_too_old");
|
||||
assert_eq!(value["error"]["current_version"], version);
|
||||
assert_eq!(value["error"]["min_version"], "0.162.0");
|
||||
assert!(execution.session.lock().unwrap().is_some());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn chatgpt_remote_responses_should_only_skip_missing_desktop_versions() {
|
||||
let admin = crate::admin::AdminTestFixture::new().await.services;
|
||||
|
||||
@@ -948,8 +948,8 @@ fn transparent_encoder_should_translate_error_wire_to_response_failed_for_websoc
|
||||
json!({
|
||||
"type": "error",
|
||||
"status": 429,
|
||||
"headers": {"x-request-id": "req_raw"},
|
||||
"error": {"type": "custom_type", "code": "custom_code", "message": "raw marker"},
|
||||
"headers": {"x-request-id": "req_raw", "Retry-After": "24"},
|
||||
"error": {"type": "rate_limit_error", "code": "turn_rate_limit_exceeded", "message": "raw marker"},
|
||||
"future": {"keep": true}
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -557,7 +557,7 @@ async fn outbound_commands_are_written_in_acknowledged_order() {
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn stalled_write_times_out_at_three_hundred_seconds_and_aborts_the_pump() {
|
||||
async fn stalled_business_write_cannot_block_the_heartbeat_write_deadline() {
|
||||
let PumpHarness {
|
||||
mut connection,
|
||||
incoming: _incoming,
|
||||
@@ -566,6 +566,7 @@ async fn stalled_write_times_out_at_three_hundred_seconds_and_aborts_the_pump()
|
||||
..
|
||||
} = test_connection(true);
|
||||
let request_id = Arc::<str>::from("req_test");
|
||||
let started = tokio::time::Instant::now();
|
||||
|
||||
let error = connection
|
||||
.send_text(
|
||||
@@ -573,12 +574,14 @@ async fn stalled_write_times_out_at_three_hundred_seconds_and_aborts_the_pump()
|
||||
WriteContext::request(&request_id, FramePhase::First),
|
||||
)
|
||||
.await
|
||||
.expect_err("stalled write must time out");
|
||||
.expect_err("heartbeat deadline must interrupt the stalled business write");
|
||||
tokio::task::yield_now().await;
|
||||
|
||||
assert!(
|
||||
matches!(error, ConnectionWriteError::Timeout { timeout } if timeout == Duration::from_secs(300))
|
||||
&& dropped.load(Ordering::Acquire)
|
||||
assert!(matches!(error, ConnectionWriteError::Closed) && dropped.load(Ordering::Acquire));
|
||||
assert_eq!(started.elapsed(), Duration::from_secs(25 + 5));
|
||||
assert_eq!(
|
||||
connection.wait_for_exit().await,
|
||||
PumpExitReason::WriteTimeout
|
||||
);
|
||||
}
|
||||
|
||||
@@ -586,10 +589,19 @@ async fn stalled_write_times_out_at_three_hundred_seconds_and_aborts_the_pump()
|
||||
async fn pump_marks_the_connection_expired_at_sixty_minutes() {
|
||||
let PumpHarness {
|
||||
mut connection,
|
||||
incoming: _incoming,
|
||||
written: _written,
|
||||
incoming,
|
||||
mut written,
|
||||
..
|
||||
} = test_connection(false);
|
||||
let peer = tokio::spawn(async move {
|
||||
while let Some(message) = written.recv().await {
|
||||
if let Message::Ping(payload) = message {
|
||||
incoming
|
||||
.send(Ok(Message::Pong(payload)))
|
||||
.expect("reply to Ping");
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
let event = connection
|
||||
.next_event()
|
||||
@@ -597,6 +609,7 @@ async fn pump_marks_the_connection_expired_at_sixty_minutes() {
|
||||
.expect("deadline must emit an event");
|
||||
|
||||
assert!(matches!(event, ConnectionEvent::Expired) && connection.is_expired());
|
||||
peer.abort();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -606,6 +619,7 @@ async fn dropping_the_connection_aborts_and_drops_the_socket_owner() {
|
||||
incoming: _incoming,
|
||||
written: _written,
|
||||
dropped,
|
||||
cancellation,
|
||||
..
|
||||
} = test_connection(false);
|
||||
|
||||
@@ -613,6 +627,7 @@ async fn dropping_the_connection_aborts_and_drops_the_socket_owner() {
|
||||
tokio::task::yield_now().await;
|
||||
|
||||
assert!(dropped.load(Ordering::Acquire));
|
||||
assert!(cancellation.is_cancelled());
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
@@ -1122,7 +1137,7 @@ async fn client_close_should_cancel_active_execution_without_starting_queued_req
|
||||
async fn idle_pump_sends_heartbeat_without_bursting_after_a_delay() {
|
||||
let PumpHarness {
|
||||
connection,
|
||||
incoming: _incoming,
|
||||
incoming,
|
||||
mut written,
|
||||
..
|
||||
} = test_connection(false);
|
||||
@@ -1132,6 +1147,10 @@ async fn idle_pump_sends_heartbeat_without_bursting_after_a_delay() {
|
||||
tokio::time::advance(Duration::from_secs(25)).await;
|
||||
let first = written.recv().await.expect("first heartbeat");
|
||||
assert!(matches!(first, Message::Ping(_)));
|
||||
incoming
|
||||
.send(Ok(Message::Pong(vec![1].into())))
|
||||
.expect("reply before scheduler delay");
|
||||
tokio::task::yield_now().await;
|
||||
|
||||
tokio::time::advance(Duration::from_secs(120)).await;
|
||||
let second = written.recv().await.expect("heartbeat after delay");
|
||||
@@ -1143,7 +1162,35 @@ async fn idle_pump_sends_heartbeat_without_bursting_after_a_delay() {
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn missing_pongs_do_not_cancel_the_connection_or_block_business_frames() {
|
||||
async fn missing_responses_expire_from_the_first_ping_without_extending_on_repeated_pings() {
|
||||
let PumpHarness {
|
||||
mut connection,
|
||||
incoming,
|
||||
mut written,
|
||||
dropped,
|
||||
cancellation,
|
||||
..
|
||||
} = test_connection(false);
|
||||
let started = tokio::time::Instant::now();
|
||||
for _ in 0..32 {
|
||||
incoming
|
||||
.send(Ok(Message::Text("queued request".into())))
|
||||
.expect("fill the business queue before probing");
|
||||
}
|
||||
|
||||
assert_eq!(
|
||||
connection.wait_for_exit().await,
|
||||
PumpExitReason::PongTimeout
|
||||
);
|
||||
assert_eq!(started.elapsed(), Duration::from_secs(25 + 30));
|
||||
assert!(matches!(written.try_recv(), Ok(Message::Ping(_))));
|
||||
assert!(matches!(written.try_recv(), Ok(Message::Ping(_))));
|
||||
assert!(dropped.load(Ordering::Acquire));
|
||||
assert!(cancellation.is_cancelled());
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn business_frames_keep_the_connection_healthy_without_pongs() {
|
||||
let PumpHarness {
|
||||
mut connection,
|
||||
incoming,
|
||||
@@ -1153,15 +1200,14 @@ async fn missing_pongs_do_not_cancel_the_connection_or_block_business_frames() {
|
||||
for _ in 0..13 {
|
||||
tokio::time::advance(Duration::from_secs(25)).await;
|
||||
assert!(matches!(written.recv().await, Some(Message::Ping(_))));
|
||||
incoming
|
||||
.send(Ok(Message::Text("still connected".into())))
|
||||
.expect("send business frame instead of Pong");
|
||||
assert!(matches!(
|
||||
connection.next_event().await,
|
||||
Some(ConnectionEvent::Text(text)) if text == "still connected"
|
||||
));
|
||||
}
|
||||
|
||||
incoming
|
||||
.send(Ok(Message::Text("still connected".into())))
|
||||
.expect("send business frame after 325 seconds without Pong");
|
||||
assert!(matches!(
|
||||
connection.next_event().await,
|
||||
Some(ConnectionEvent::Text(text)) if text == "still connected"
|
||||
));
|
||||
incoming.send(Ok(Message::Close(None))).expect("close peer");
|
||||
assert_eq!(
|
||||
connection.wait_for_exit().await,
|
||||
@@ -1192,7 +1238,7 @@ async fn stalled_heartbeat_can_be_cancelled_without_waiting_for_write_timeout()
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn stalled_heartbeat_obeys_the_existing_write_timeout() {
|
||||
async fn stalled_heartbeat_uses_a_short_write_timeout() {
|
||||
let PumpHarness {
|
||||
mut connection,
|
||||
incoming: _incoming,
|
||||
@@ -1205,7 +1251,7 @@ async fn stalled_heartbeat_obeys_the_existing_write_timeout() {
|
||||
connection.wait_for_exit().await,
|
||||
PumpExitReason::WriteTimeout
|
||||
);
|
||||
assert_eq!(started.elapsed(), Duration::from_secs(25 + 300));
|
||||
assert_eq!(started.elapsed(), Duration::from_secs(25 + 5));
|
||||
assert!(dropped.load(Ordering::Acquire));
|
||||
}
|
||||
|
||||
|
||||
@@ -1208,6 +1208,50 @@ fn upgrade_request(authorization: &str) -> Request<Body> {
|
||||
.expect("build WebSocket upgrade request")
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn official_core_version_gate_should_run_before_websocket_upgrade() {
|
||||
let app = api_router(ModelsExecution::with_cli_min("0.162.0")).await;
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let address = listener.local_addr().unwrap();
|
||||
let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
|
||||
|
||||
for version in ["0.158.0", "0.162.0"] {
|
||||
let mut request = format!("ws://{address}/v1/responses")
|
||||
.into_client_request()
|
||||
.unwrap();
|
||||
request.headers_mut().insert(
|
||||
AUTHORIZATION,
|
||||
HeaderValue::from_static("Bearer sk_models_test"),
|
||||
);
|
||||
request.headers_mut().insert(
|
||||
"user-agent",
|
||||
HeaderValue::from_str(&format!(
|
||||
"codex-tui/{version} (Mac OS 26.6.2; arm64) Apple_Terminal (codex-tui; 0.165.0)"
|
||||
))
|
||||
.unwrap(),
|
||||
);
|
||||
let result = connect_async(request).await;
|
||||
if version == "0.162.0" {
|
||||
let (mut socket, response) = result.expect("current Core upgrades successfully");
|
||||
assert_eq!(response.status(), StatusCode::SWITCHING_PROTOCOLS);
|
||||
socket.close(None).await.unwrap();
|
||||
} else {
|
||||
let tokio_tungstenite::tungstenite::Error::Http(response) =
|
||||
result.expect_err("old Core must not upgrade")
|
||||
else {
|
||||
panic!("expected an HTTP version rejection");
|
||||
};
|
||||
assert_eq!(response.status(), StatusCode::UPGRADE_REQUIRED);
|
||||
let value: Value = serde_json::from_slice(response.body().as_deref().unwrap()).unwrap();
|
||||
assert_eq!(value["error"]["code"], "client_version_too_old");
|
||||
assert_eq!(value["error"]["current_version"], "0.158.0");
|
||||
assert_eq!(value["error"]["min_version"], "0.162.0");
|
||||
}
|
||||
}
|
||||
server.abort();
|
||||
let _ = server.await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn get_responses_should_route_to_the_websocket_upgrade_boundary() {
|
||||
let response = api_router(ModelsExecution::new())
|
||||
|
||||
@@ -0,0 +1,327 @@
|
||||
//! 账号错误保护的可编辑规则、匹配事实与有界恢复快照
|
||||
|
||||
use sha2::{Digest as _, Sha256};
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
/// 规则只观察已解析的上游事实,不扫描原始响应或改写协议分类
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct AccountErrorFacts<'a> {
|
||||
pub provider: &'a str,
|
||||
pub status: Option<u16>,
|
||||
pub code: Option<&'a str>,
|
||||
pub error_type: Option<&'a str>,
|
||||
pub message: Option<&'a str>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum AccountErrorField {
|
||||
Provider,
|
||||
Status,
|
||||
Code,
|
||||
Type,
|
||||
Message,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum AccountErrorOperator {
|
||||
Equals,
|
||||
Contains,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct AccountErrorCondition {
|
||||
pub field: AccountErrorField,
|
||||
pub operator: AccountErrorOperator,
|
||||
pub values: Vec<Option<String>>,
|
||||
#[serde(default)]
|
||||
pub ignore_case: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct AccountErrorRule {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub conditions: Vec<AccountErrorCondition>,
|
||||
}
|
||||
|
||||
/// 持久状态仅保存有界规则标识,不保存上游错误正文
|
||||
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct AccountProtectionMatch {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct AccountErrorProtection {
|
||||
pub enabled: bool,
|
||||
pub rules: Vec<AccountErrorRule>,
|
||||
pub threshold: u32,
|
||||
pub window_seconds: u64,
|
||||
pub duration_seconds: u64,
|
||||
pub probe_enabled: bool,
|
||||
pub probe_model: Option<String>,
|
||||
}
|
||||
|
||||
impl Default for AccountErrorProtection {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
enabled: false,
|
||||
rules: Vec::new(),
|
||||
threshold: 12,
|
||||
window_seconds: 600,
|
||||
duration_seconds: 7200,
|
||||
probe_enabled: true,
|
||||
probe_model: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl AccountErrorProtection {
|
||||
pub fn validate(&self) -> Result<(), &'static str> {
|
||||
if !(2..=1000).contains(&self.threshold)
|
||||
|| !(60..=3600).contains(&self.window_seconds)
|
||||
|| !(300..=604800).contains(&self.duration_seconds)
|
||||
|| self
|
||||
.probe_model
|
||||
.as_deref()
|
||||
.is_some_and(|v| !valid_label(v, 128))
|
||||
|| self.rules.len() > 32
|
||||
|| (self.enabled && self.rules.is_empty())
|
||||
{
|
||||
return Err("account_error_protection");
|
||||
}
|
||||
let mut text_bytes = self.probe_model.as_ref().map_or(0, String::len);
|
||||
let mut ids = BTreeSet::new();
|
||||
for rule in &self.rules {
|
||||
text_bytes += rule.id.len() + rule.name.len();
|
||||
if text_bytes > 65536 {
|
||||
return Err("account_error_protection");
|
||||
}
|
||||
if !valid_label(&rule.id, 128)
|
||||
|| !valid_label(&rule.name, 128)
|
||||
|| !ids.insert(&rule.id)
|
||||
|| rule.conditions.is_empty()
|
||||
|| rule.conditions.len() > 8
|
||||
|| !rule
|
||||
.conditions
|
||||
.iter()
|
||||
.any(|c| c.field != AccountErrorField::Provider)
|
||||
{
|
||||
return Err("account_error_protection");
|
||||
}
|
||||
for condition in &rule.conditions {
|
||||
let max = if condition.field == AccountErrorField::Message {
|
||||
1024
|
||||
} else {
|
||||
256
|
||||
};
|
||||
if condition.values.is_empty()
|
||||
|| condition.values.len() > 16
|
||||
|| (condition.operator == AccountErrorOperator::Contains
|
||||
&& condition.field != AccountErrorField::Message)
|
||||
{
|
||||
return Err("account_error_protection");
|
||||
}
|
||||
for value in &condition.values {
|
||||
text_bytes += value.as_ref().map_or(0, String::len);
|
||||
if text_bytes > 65536 {
|
||||
return Err("account_error_protection");
|
||||
}
|
||||
if value.as_deref().is_some_and(|v| v.chars().count() > max)
|
||||
|| (condition.operator == AccountErrorOperator::Contains
|
||||
&& value.as_deref().is_none_or(|v| v.trim().is_empty()))
|
||||
|| (condition.field == AccountErrorField::Status
|
||||
&& value.as_deref().is_some_and(|v| {
|
||||
v.len() != 3
|
||||
|| v.parse::<u16>()
|
||||
.map_or(true, |status| !(100..=599).contains(&status))
|
||||
}))
|
||||
{
|
||||
return Err("account_error_protection");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn compile(&self) -> CompiledAccountErrorProtection {
|
||||
let mut normalized = self.clone();
|
||||
let mut ignore_case = [false; 5];
|
||||
for rule in &mut normalized.rules {
|
||||
for condition in &mut rule.conditions {
|
||||
ignore_case[condition.field as usize] |=
|
||||
condition.ignore_case && condition.operator == AccountErrorOperator::Contains;
|
||||
for candidate in condition.values.iter_mut().flatten() {
|
||||
*candidate = if condition.ignore_case {
|
||||
candidate.trim().to_ascii_lowercase()
|
||||
} else {
|
||||
candidate.trim().to_owned()
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
CompiledAccountErrorProtection {
|
||||
policy: self.clone(),
|
||||
fingerprint: self.fingerprint(),
|
||||
normalized,
|
||||
ignore_case,
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn matching_rules(&self, facts: AccountErrorFacts<'_>) -> Vec<AccountProtectionMatch> {
|
||||
self.compile().matching_rules(facts)
|
||||
}
|
||||
|
||||
/// 长度前缀避免分隔符碰撞,内容指纹用于保留无关设置更新前的计数
|
||||
#[must_use]
|
||||
pub fn fingerprint(&self) -> String {
|
||||
let mut hash = Sha256::new();
|
||||
fn value(hash: &mut Sha256, value: &[u8]) {
|
||||
hash.update((value.len() as u64).to_le_bytes());
|
||||
hash.update(value);
|
||||
}
|
||||
value(
|
||||
&mut hash,
|
||||
&[u8::from(self.enabled), u8::from(self.probe_enabled)],
|
||||
);
|
||||
value(&mut hash, &self.threshold.to_le_bytes());
|
||||
value(&mut hash, &self.window_seconds.to_le_bytes());
|
||||
value(&mut hash, &self.duration_seconds.to_le_bytes());
|
||||
value(
|
||||
&mut hash,
|
||||
self.probe_model.as_deref().unwrap_or_default().as_bytes(),
|
||||
);
|
||||
for rule in &self.rules {
|
||||
value(&mut hash, rule.id.as_bytes());
|
||||
value(&mut hash, rule.name.as_bytes());
|
||||
value(&mut hash, &(rule.conditions.len() as u64).to_le_bytes());
|
||||
for c in &rule.conditions {
|
||||
value(
|
||||
&mut hash,
|
||||
&[c.field as u8, c.operator as u8, u8::from(c.ignore_case)],
|
||||
);
|
||||
value(&mut hash, &(c.values.len() as u64).to_le_bytes());
|
||||
for v in &c.values {
|
||||
value(&mut hash, &[u8::from(v.is_some())]);
|
||||
value(&mut hash, v.as_deref().unwrap_or_default().as_bytes());
|
||||
}
|
||||
}
|
||||
}
|
||||
hash.finalize()
|
||||
.iter()
|
||||
.map(|byte| format!("{byte:02x}"))
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
fn valid_label(value: &str, max: usize) -> bool {
|
||||
!value.is_empty()
|
||||
&& value == value.trim()
|
||||
&& value.chars().count() <= max
|
||||
&& !value.chars().any(char::is_control)
|
||||
}
|
||||
|
||||
/// 发布时归一化候选并缓存指纹,请求只归一化每个实际输入一次
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct CompiledAccountErrorProtection {
|
||||
policy: AccountErrorProtection,
|
||||
fingerprint: String,
|
||||
normalized: AccountErrorProtection,
|
||||
ignore_case: [bool; 5],
|
||||
}
|
||||
|
||||
impl CompiledAccountErrorProtection {
|
||||
#[must_use]
|
||||
pub fn policy(&self) -> &AccountErrorProtection {
|
||||
&self.policy
|
||||
}
|
||||
#[must_use]
|
||||
pub fn fingerprint(&self) -> &str {
|
||||
&self.fingerprint
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn matching_rules(&self, facts: AccountErrorFacts<'_>) -> Vec<AccountProtectionMatch> {
|
||||
if !self.policy.enabled {
|
||||
return Vec::new();
|
||||
}
|
||||
let status = facts.status.map(|value| value.to_string());
|
||||
let raw = [
|
||||
Some(facts.provider),
|
||||
status.as_deref(),
|
||||
facts.code,
|
||||
facts.error_type,
|
||||
facts.message,
|
||||
];
|
||||
// 保留实际存在性;超长输入不能冒充缺失,也不能用截断前缀做整串相等
|
||||
let full: [Option<&str>; 5] = raw.map(|value| value.map(str::trim));
|
||||
let limits = [1024, 3, 1024, 1024, 8192];
|
||||
let observed: [Option<&str>; 5] =
|
||||
std::array::from_fn(|index| raw[index].map(|text| prefix(text, limits[index]).trim()));
|
||||
let folded: [Option<String>; 5] = std::array::from_fn(|index| {
|
||||
if self.ignore_case[index] {
|
||||
observed[index].map(str::to_ascii_lowercase)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
});
|
||||
self.normalized
|
||||
.rules
|
||||
.iter()
|
||||
.filter(|rule| {
|
||||
!rule.conditions.is_empty()
|
||||
&& rule.conditions.iter().all(|condition| {
|
||||
let index = condition.field as usize;
|
||||
let actual = if condition.ignore_case
|
||||
&& condition.operator == AccountErrorOperator::Contains
|
||||
{
|
||||
folded[index].as_deref()
|
||||
} else {
|
||||
observed[index]
|
||||
};
|
||||
condition.values.iter().any(|candidate| {
|
||||
match (actual, candidate.as_deref()) {
|
||||
(None, None) => condition.operator == AccountErrorOperator::Equals,
|
||||
(Some(actual), Some(candidate)) => match condition.operator {
|
||||
AccountErrorOperator::Equals => {
|
||||
full[index].is_some_and(|value| {
|
||||
if condition.ignore_case {
|
||||
value.eq_ignore_ascii_case(candidate)
|
||||
} else {
|
||||
value == candidate
|
||||
}
|
||||
})
|
||||
}
|
||||
AccountErrorOperator::Contains => {
|
||||
!candidate.is_empty() && actual.contains(candidate)
|
||||
}
|
||||
},
|
||||
_ => false,
|
||||
}
|
||||
})
|
||||
})
|
||||
})
|
||||
.map(|rule| AccountProtectionMatch {
|
||||
id: rule.id.clone(),
|
||||
name: rule.name.clone(),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
fn prefix(value: &str, maximum: usize) -> &str {
|
||||
let mut end = value.len().min(maximum);
|
||||
while !value.is_char_boundary(end) {
|
||||
end -= 1;
|
||||
}
|
||||
&value[..end]
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
//! Provider 账号领域、持久化端口与同一 target 内的账号选择
|
||||
|
||||
mod error;
|
||||
mod error_protection;
|
||||
pub use error_protection::*;
|
||||
mod fast_mode;
|
||||
pub use fast_mode::FastMode;
|
||||
mod location;
|
||||
|
||||
@@ -623,6 +623,10 @@ pub enum AccountCooldownKind {
|
||||
CapacityFreeze,
|
||||
/// 到期后仍阻止调度,必须由恢复探测成功或管理员恢复解除
|
||||
CapacityFreezeProbe,
|
||||
/// 自定义错误规则触发的账号保护
|
||||
ErrorProtection,
|
||||
/// 账号保护到期后需要探测确认恢复
|
||||
ErrorProtectionProbe,
|
||||
}
|
||||
|
||||
impl AccountCooldownKind {
|
||||
@@ -632,17 +636,25 @@ impl AccountCooldownKind {
|
||||
Self::RateLimit => "rate_limit",
|
||||
Self::CapacityFreeze => "capacity_freeze",
|
||||
Self::CapacityFreezeProbe => "capacity_freeze_probe",
|
||||
Self::ErrorProtection => "error_protection",
|
||||
Self::ErrorProtectionProbe => "error_protection_probe",
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn is_capacity_freeze(self) -> bool {
|
||||
matches!(self, Self::CapacityFreeze | Self::CapacityFreezeProbe)
|
||||
pub const fn is_error_protection(self) -> bool {
|
||||
matches!(
|
||||
self,
|
||||
Self::CapacityFreeze
|
||||
| Self::CapacityFreezeProbe
|
||||
| Self::ErrorProtection
|
||||
| Self::ErrorProtectionProbe
|
||||
)
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn requires_probe(self) -> bool {
|
||||
matches!(self, Self::CapacityFreezeProbe)
|
||||
matches!(self, Self::CapacityFreezeProbe | Self::ErrorProtectionProbe)
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
@@ -651,6 +663,8 @@ impl AccountCooldownKind {
|
||||
"rate_limit" => Some(Self::RateLimit),
|
||||
"capacity_freeze" => Some(Self::CapacityFreeze),
|
||||
"capacity_freeze_probe" => Some(Self::CapacityFreezeProbe),
|
||||
"error_protection" => Some(Self::ErrorProtection),
|
||||
"error_protection_probe" => Some(Self::ErrorProtectionProbe),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
//! 单次上游尝试的通用保护反馈;副作用有界等待且不改变原始执行结果
|
||||
|
||||
use std::{sync::Arc, time::Duration};
|
||||
|
||||
use futures::{FutureExt, future::BoxFuture, pin_mut, select_biased};
|
||||
use futures_timer::Delay;
|
||||
|
||||
use super::provider::ProviderCallMetadata;
|
||||
use crate::{
|
||||
account::{AccountErrorFacts, CompiledAccountErrorProtection},
|
||||
error::ProviderError,
|
||||
event::ProviderEvent,
|
||||
provider_ports::{AccountProtectionGuard, ProviderCooldownPort},
|
||||
routing::ConfigRevision,
|
||||
};
|
||||
|
||||
const FEEDBACK_TIMEOUT: Duration = Duration::from_millis(100);
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(super) struct ProtectionContext {
|
||||
pub(super) store: Arc<dyn ProviderCooldownPort>,
|
||||
pub(super) policy: Arc<CompiledAccountErrorProtection>,
|
||||
pub(super) revision: u64,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for ProtectionContext {
|
||||
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
formatter
|
||||
.debug_struct("ProtectionContext")
|
||||
.field("revision", &self.revision)
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) struct AttemptProtection {
|
||||
store: Arc<dyn ProviderCooldownPort>,
|
||||
guard: AccountProtectionGuard,
|
||||
policy: Arc<CompiledAccountErrorProtection>,
|
||||
provider: crate::identity::ProviderKind,
|
||||
completed: bool,
|
||||
}
|
||||
|
||||
impl AttemptProtection {
|
||||
pub(super) async fn begin(
|
||||
store: Arc<dyn ProviderCooldownPort>,
|
||||
policy: Arc<CompiledAccountErrorProtection>,
|
||||
policy_revision: u64,
|
||||
metadata: &ProviderCallMetadata,
|
||||
) -> Option<Self> {
|
||||
if !policy.policy().enabled {
|
||||
return None;
|
||||
}
|
||||
let revision = metadata.credential_revision()?;
|
||||
let policy_revision = ConfigRevision::new(policy_revision).ok()?;
|
||||
let guard = match bounded(store.begin_protection(
|
||||
metadata.provider_account_id(),
|
||||
revision,
|
||||
policy.fingerprint(),
|
||||
policy_revision,
|
||||
))
|
||||
.await
|
||||
{
|
||||
Ok(Ok(guard)) => guard?,
|
||||
_ => {
|
||||
tracing::warn!("account protection feedback could not start");
|
||||
return None;
|
||||
}
|
||||
};
|
||||
Some(Self {
|
||||
store,
|
||||
guard,
|
||||
policy,
|
||||
provider: metadata.provider().clone(),
|
||||
completed: false,
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn observe(&mut self, event: &ProviderEvent) {
|
||||
self.completed |= event
|
||||
.canonical_facts()
|
||||
.iter()
|
||||
.any(|fact| matches!(fact, crate::event::GatewayEvent::Completed(_)));
|
||||
}
|
||||
|
||||
pub(super) const fn is_completed(&self) -> bool {
|
||||
self.completed
|
||||
}
|
||||
|
||||
pub(super) fn complete(
|
||||
self,
|
||||
result: Option<Result<ProviderEvent, ProviderError>>,
|
||||
) -> BoxFuture<'static, Option<Result<ProviderEvent, ProviderError>>> {
|
||||
Box::pin(async move {
|
||||
let feedback = match &result {
|
||||
Some(Err(error)) => {
|
||||
let Some(fields) = error.upstream_failure_fields() else {
|
||||
return result;
|
||||
};
|
||||
let matched = self.policy.matching_rules(AccountErrorFacts {
|
||||
provider: self.provider.as_str(),
|
||||
status: fields.status,
|
||||
code: fields.code.as_deref(),
|
||||
error_type: fields.error_type.as_deref(),
|
||||
message: fields.message.as_deref(),
|
||||
});
|
||||
if matched.is_empty() {
|
||||
return result;
|
||||
}
|
||||
bounded(self.store.record_protection_failure(
|
||||
&self.guard,
|
||||
self.policy.policy(),
|
||||
&matched,
|
||||
))
|
||||
.await
|
||||
}
|
||||
None | Some(Ok(_)) if self.completed => {
|
||||
bounded(self.store.record_protection_success(&self.guard)).await
|
||||
}
|
||||
_ => return result,
|
||||
};
|
||||
if !matches!(feedback, Ok(Ok(_))) {
|
||||
tracing::warn!("account protection feedback was not persisted");
|
||||
}
|
||||
result
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
async fn bounded<T>(future: impl std::future::Future<Output = T>) -> Result<T, ()> {
|
||||
let future = future.fuse();
|
||||
let timeout = Delay::new(FEEDBACK_TIMEOUT).fuse();
|
||||
pin_mut!(future, timeout);
|
||||
select_biased! {
|
||||
value = future => Ok(value),
|
||||
_ = timeout => Err(()),
|
||||
}
|
||||
}
|
||||
@@ -9,15 +9,38 @@ use std::{
|
||||
use futures::future::BoxFuture;
|
||||
|
||||
use crate::{
|
||||
error::GatewayError,
|
||||
policy::{ClientApiKeyId, PlaintextClientApiKey},
|
||||
routing::extensions::{ExtensionSetId, ExtensionSetReference},
|
||||
routing::{
|
||||
extensions::{ExtensionSetId, ExtensionSetReference},
|
||||
request_settings::RequestSettings,
|
||||
},
|
||||
};
|
||||
|
||||
use super::execution::AuthenticatedClient;
|
||||
|
||||
/// 身份解析与认证只返回冻结权限,不提供模型执行入口
|
||||
pub trait ClientIdentityPort: Send + Sync {
|
||||
/// 只解析身份与冻结权限,不建立模型执行图或记录使用事实
|
||||
fn resolve_client(
|
||||
&self,
|
||||
client_key_id: ClientApiKeyId,
|
||||
settings: Option<RequestSettings>,
|
||||
) -> BoxFuture<'_, Result<AuthenticatedClient, GatewayError>>;
|
||||
|
||||
/// 复用入口认证计划及 principal 映射,不进行模型准入
|
||||
fn verify_client(
|
||||
&self,
|
||||
request: ClientAuthenticationRequest,
|
||||
) -> BoxFuture<'_, Result<AuthenticatedClient, GatewayError>>;
|
||||
}
|
||||
|
||||
pub const MAXIMUM_AUTHORIZATION_BYTES: usize = 8 * 1024;
|
||||
|
||||
/// API 从数据面 Authorization 头构造的有界认证信封
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
#[derive(Clone)]
|
||||
pub struct ClientAuthenticationRequest {
|
||||
invocation: Option<Arc<super::extensions::InvocationOrigin>>,
|
||||
request_context: Option<Arc<super::extensions::RequestContext>>,
|
||||
settings: Option<crate::routing::request_settings::RequestSettings>,
|
||||
authorization: Arc<str>,
|
||||
@@ -25,6 +48,18 @@ pub struct ClientAuthenticationRequest {
|
||||
}
|
||||
|
||||
impl ClientAuthenticationRequest {
|
||||
/// 子认证继承受信调用的来源、取消和副作用归属,不据此跳过认证器
|
||||
#[must_use]
|
||||
pub fn with_invocation(mut self, origin: super::extensions::InvocationOrigin) -> Self {
|
||||
self.invocation = Some(Arc::new(origin));
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn invocation(&self) -> Option<&super::extensions::InvocationOrigin> {
|
||||
self.invocation.as_deref()
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn with_request_context(
|
||||
mut self,
|
||||
@@ -35,12 +70,18 @@ impl ClientAuthenticationRequest {
|
||||
}
|
||||
#[must_use]
|
||||
pub fn request_context(&self) -> Option<&super::extensions::RequestContext> {
|
||||
self.request_context.as_deref()
|
||||
self.invocation
|
||||
.as_ref()
|
||||
.and_then(|origin| origin.extensions.request())
|
||||
.or(self.request_context.as_deref())
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn shared_request_context(&self) -> Option<Arc<super::extensions::RequestContext>> {
|
||||
self.request_context.clone()
|
||||
self.invocation
|
||||
.as_ref()
|
||||
.and_then(|origin| origin.extensions.shared_request())
|
||||
.or_else(|| self.request_context.clone())
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
@@ -79,6 +120,7 @@ impl ClientAuthenticationRequest {
|
||||
.filter(|value| !value.is_empty())
|
||||
.and_then(|value| PlaintextClientApiKey::new(value.to_owned()).ok());
|
||||
Ok(Self {
|
||||
invocation: None,
|
||||
settings: None,
|
||||
request_context: None,
|
||||
authorization: authorization.into(),
|
||||
|
||||
@@ -1110,7 +1110,7 @@ where
|
||||
pinned_account.clone(),
|
||||
self.account_state_owner.clone(),
|
||||
)
|
||||
.with_account_scope(Arc::clone(self.plan.account_scope())),
|
||||
.with_account_scope(Arc::clone(candidate.account_scope())),
|
||||
}
|
||||
.with_credential_recovery_attempted(pinned_account.as_ref().is_some_and(|account| {
|
||||
self.credential_recovery_attempted_accounts
|
||||
@@ -1150,6 +1150,17 @@ where
|
||||
}
|
||||
let context = AttemptContext::new(
|
||||
RequestAttemptContext::new(self.request_id.clone(), self.client_api_key_ref.clone())
|
||||
.with_account_error_protection(
|
||||
(!self.account_selection.is_diagnostic()
|
||||
&& self.plan.account_error_protection().policy().enabled)
|
||||
.then(|| self.engine.account_error_protection.as_ref())
|
||||
.flatten()
|
||||
.map(|store| super::account_protection::ProtectionContext {
|
||||
store: Arc::clone(store),
|
||||
policy: self.plan.account_error_protection(),
|
||||
revision: self.plan.account_error_protection_revision(),
|
||||
}),
|
||||
)
|
||||
.with_lease_metadata(Arc::clone(&self.lease_metadata))
|
||||
.with_response_control(self.response_control.clone())
|
||||
.with_request_profile(self.request_profiles.get(candidate.provider()).cloned())
|
||||
|
||||
@@ -211,6 +211,15 @@ impl PreparedRootExecution {
|
||||
self.response_control.clone()
|
||||
}
|
||||
|
||||
/// 连接退出同时撤销跨轮次保留的上游资源,不改变单次执行的取消范围
|
||||
#[must_use]
|
||||
pub fn with_connection_cancellation(mut self, cancellation: CancellationToken) -> Self {
|
||||
self.response_control = self
|
||||
.response_control
|
||||
.with_connection_cancellation(cancellation);
|
||||
self
|
||||
}
|
||||
|
||||
pub(super) fn new(client: AuthenticatedClient) -> Result<Self, GatewayError> {
|
||||
let started_at = SystemTime::now();
|
||||
let deadline_at = Deadline::from_timeout(started_at, client.execution_timeout())
|
||||
|
||||
@@ -12,7 +12,6 @@ pub use contract::{
|
||||
StartedExecution,
|
||||
};
|
||||
mod scope;
|
||||
pub use scope::BoundModelExecutionContext;
|
||||
mod service;
|
||||
pub use failure::gateway_error_from_engine;
|
||||
pub use service::DefaultExecutionService;
|
||||
|
||||
@@ -15,13 +15,10 @@ use crate::{
|
||||
lifecycle::{CancellationToken, Deadline},
|
||||
operation::Operation,
|
||||
policy::ClientApiKeyId,
|
||||
routing::{
|
||||
FrozenAccountScope, PublicModelId, UpstreamModelId, request_settings::RequestSettings,
|
||||
},
|
||||
routing::{FrozenAccountScope, PublicModelId, UpstreamModelId},
|
||||
};
|
||||
use std::{
|
||||
collections::BTreeMap,
|
||||
fmt,
|
||||
sync::{
|
||||
Arc, Mutex, Weak,
|
||||
atomic::{AtomicUsize, Ordering},
|
||||
@@ -188,57 +185,6 @@ pub(super) struct ActiveRequestLease {
|
||||
pub(super) authority: Arc<ActiveRequestAuthority>,
|
||||
}
|
||||
|
||||
/// 管理页或 CLI 一次调用持有的显式模型执行身份
|
||||
///
|
||||
/// 结构不暴露 Key 明文;Runtime 只能把它原样交回 Core 发起模型请求
|
||||
#[derive(Clone)]
|
||||
pub struct BoundModelExecutionContext {
|
||||
pub(super) authority: Arc<BoundModelExecutionAuthority>,
|
||||
}
|
||||
|
||||
impl BoundModelExecutionContext {
|
||||
/// 与实际执行共用绑定时的快照,不能回退到后续发布的配置
|
||||
#[must_use]
|
||||
pub fn request_body_limit(&self) -> usize {
|
||||
self.authority
|
||||
.client
|
||||
.snapshot
|
||||
.responses_max_decompressed_body_bytes()
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn request_settings(&self) -> Option<&RequestSettings> {
|
||||
self.authority.client.request_settings()
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) struct BoundModelExecutionAuthority {
|
||||
pub(super) client: AuthenticatedClient,
|
||||
pub(super) account_scope: Arc<FrozenAccountScope>,
|
||||
pub(super) cancellation: CancellationToken,
|
||||
pub(super) extension_scope: ExtensionCallScope,
|
||||
pub(super) initiating_plugin_instance_id: String,
|
||||
}
|
||||
|
||||
impl fmt::Debug for BoundModelExecutionContext {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
formatter
|
||||
.debug_struct("BoundModelExecutionContext")
|
||||
.field("key_id", &self.authority.client.policy.key_id())
|
||||
.field(
|
||||
"initiating_plugin_instance_id",
|
||||
&self.authority.initiating_plugin_instance_id,
|
||||
)
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for BoundModelExecutionAuthority {
|
||||
fn drop(&mut self) {
|
||||
self.cancellation.cancel();
|
||||
}
|
||||
}
|
||||
|
||||
impl ActiveRequestLease {
|
||||
pub(super) fn release(self) {
|
||||
drop(self);
|
||||
|
||||
@@ -12,9 +12,8 @@ use super::contract::{
|
||||
use super::probe_store::{ProbeObservation, TransientExecutionStore};
|
||||
use super::scope::{
|
||||
ActiveRequestAuthority, ActiveRequestLease, ActiveRequestRegistry, AuthorizedExecution,
|
||||
BoundExecutionFacts, BoundModelExecutionAuthority, BoundModelExecutionContext,
|
||||
ExecutionStartGuard, ExecutionTarget, NestedExecutionFacts, NestedExecutionGraph,
|
||||
PendingStartExecution, PreparedExecutionStart,
|
||||
BoundExecutionFacts, ExecutionStartGuard, ExecutionTarget, NestedExecutionFacts,
|
||||
NestedExecutionGraph, PendingStartExecution, PreparedExecutionStart,
|
||||
};
|
||||
use super::{COORDINATION_TIMEOUT, DIAGNOSTIC_TIMEOUT};
|
||||
use super::{scope::ExecutionAdmission, session::DefaultExecutionSession};
|
||||
@@ -28,7 +27,7 @@ use crate::{
|
||||
ClientAdmissionRequest,
|
||||
},
|
||||
authentication::{
|
||||
ClientAuthenticationRequest, FrontendAuthenticationDecision,
|
||||
ClientAuthenticationRequest, ClientIdentityPort, FrontendAuthenticationDecision,
|
||||
FrontendAuthenticationExtensionIndex,
|
||||
},
|
||||
budget::{ClientBudgetCharge, ClientBudgetPort},
|
||||
@@ -41,8 +40,8 @@ use crate::{
|
||||
middleware::FrozenMiddlewarePlan,
|
||||
nested::{
|
||||
AffinityLookupPort, AffinityLookupRequest, AffinityLookupResult,
|
||||
BoundModelExecutionBinding, BoundModelExecutionRequest, ExecutionEffects,
|
||||
NestedModelExecutionPort, NestedModelExecutionRequest,
|
||||
BoundModelExecutionRequest, ExecutionEffects, NestedModelExecutionPort,
|
||||
NestedModelExecutionRequest,
|
||||
},
|
||||
observation::{
|
||||
FrozenRequestObservationContext, RequestObservationDispatch, RequestObservationScope,
|
||||
@@ -93,6 +92,7 @@ pub struct DefaultExecutionService {
|
||||
frontend_authentication: Option<FrontendAuthenticationExtensionIndex>,
|
||||
session_affinity: Option<Arc<dyn ProviderSessionAffinityPort>>,
|
||||
client_retry: Option<Arc<dyn crate::engine::client_retry::ClientRetryStore>>,
|
||||
account_error_protection: Option<Arc<dyn crate::provider_ports::ProviderCooldownPort>>,
|
||||
snapshot_refresh: Option<Arc<RuntimeSnapshotPublisher>>,
|
||||
active_requests: ActiveRequestRegistry,
|
||||
}
|
||||
@@ -124,6 +124,7 @@ impl DefaultExecutionService {
|
||||
frontend_authentication: None,
|
||||
session_affinity: None,
|
||||
client_retry: None,
|
||||
account_error_protection: None,
|
||||
snapshot_refresh: None,
|
||||
active_requests: Arc::default(),
|
||||
}
|
||||
@@ -135,6 +136,15 @@ impl DefaultExecutionService {
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn with_account_error_protection(
|
||||
mut self,
|
||||
store: Arc<dyn crate::provider_ports::ProviderCooldownPort>,
|
||||
) -> Self {
|
||||
self.account_error_protection = Some(store);
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn with_client_retry_store(
|
||||
mut self,
|
||||
@@ -851,6 +861,9 @@ impl DefaultExecutionService {
|
||||
deadline_at: authorization.deadline_at,
|
||||
};
|
||||
let mut engine = GatewayEngine::new(self.observations.clone(), providers);
|
||||
if let Some(store) = &self.account_error_protection {
|
||||
engine = engine.with_account_error_protection(Arc::clone(store));
|
||||
}
|
||||
// 插件内部调用不共享外部客户端的失败轮次,探测另走 transient engine
|
||||
if authorization.nested.is_none()
|
||||
&& authorization.bound.is_none()
|
||||
@@ -1081,72 +1094,54 @@ impl DefaultExecutionService {
|
||||
})
|
||||
}
|
||||
|
||||
async fn bind_bound_model_inner(
|
||||
&self,
|
||||
binding: BoundModelExecutionBinding,
|
||||
) -> Result<BoundModelExecutionContext, GatewayError> {
|
||||
let client = self
|
||||
.client_for_key_id(&binding.client_key_id, binding.settings)
|
||||
.await?;
|
||||
if binding.extension_scope.len() >= ExtensionCallScope::MAXIMUM_DEPTH {
|
||||
return Err(GatewayError::new(
|
||||
GatewayErrorKind::PolicyDenied,
|
||||
"plugin model execution depth exceeded",
|
||||
));
|
||||
}
|
||||
let extension_scope = binding
|
||||
.extension_scope
|
||||
.extending(binding.initiating_plugin_instance_id.clone())
|
||||
.ok_or_else(|| {
|
||||
GatewayError::new(
|
||||
GatewayErrorKind::Internal,
|
||||
"bound plugin execution scope is invalid",
|
||||
)
|
||||
})?;
|
||||
let account_scope = Arc::clone(client.policy.account_scope());
|
||||
Ok(BoundModelExecutionContext {
|
||||
authority: Arc::new(BoundModelExecutionAuthority {
|
||||
client,
|
||||
account_scope,
|
||||
cancellation: binding.cancellation,
|
||||
extension_scope,
|
||||
initiating_plugin_instance_id: binding.initiating_plugin_instance_id,
|
||||
}),
|
||||
})
|
||||
}
|
||||
|
||||
async fn start_bound_model_inner(
|
||||
&self,
|
||||
request: BoundModelExecutionRequest,
|
||||
) -> Result<StartedExecution, GatewayError> {
|
||||
let BoundModelExecutionRequest {
|
||||
context,
|
||||
client,
|
||||
initiating_plugin_instance_id,
|
||||
cancellation,
|
||||
extension_scope,
|
||||
public_model,
|
||||
operation,
|
||||
mut metadata,
|
||||
provider,
|
||||
account,
|
||||
} = request;
|
||||
let authority = &context.authority;
|
||||
if authority.cancellation.is_cancelled() {
|
||||
if cancellation.is_cancelled() {
|
||||
return Err(GatewayError::new(
|
||||
GatewayErrorKind::Cancelled,
|
||||
"bound plugin invocation was cancelled",
|
||||
));
|
||||
}
|
||||
let now = SystemTime::now();
|
||||
let deadline_at = Deadline::from_timeout(now, authority.client.execution_timeout())
|
||||
if extension_scope.len() >= ExtensionCallScope::MAXIMUM_DEPTH {
|
||||
return Err(GatewayError::new(
|
||||
GatewayErrorKind::PolicyDenied,
|
||||
"plugin model execution depth exceeded",
|
||||
));
|
||||
}
|
||||
let extension_scope = extension_scope
|
||||
.extending(initiating_plugin_instance_id.clone())
|
||||
.ok_or_else(|| {
|
||||
GatewayError::new(
|
||||
GatewayErrorKind::PolicyDenied,
|
||||
"plugin model execution scope is recursive",
|
||||
)
|
||||
})?;
|
||||
let now = SystemTime::now();
|
||||
let deadline_at =
|
||||
Deadline::from_timeout(now, client.execution_timeout()).ok_or_else(|| {
|
||||
GatewayError::new(GatewayErrorKind::Internal, "system clock is invalid")
|
||||
})?;
|
||||
let (account_scope, required_provider) = restrict_model_execution_scope(
|
||||
authority.account_scope.as_ref(),
|
||||
client.policy.account_scope().as_ref(),
|
||||
provider,
|
||||
account.as_ref(),
|
||||
None,
|
||||
)?;
|
||||
// 连接承载多个独立执行;递归预算和副作用只在本次执行的子调用图内共享
|
||||
// 父连接的取消仍通过 authority 传播,不能因新建执行丢失扩展调用链
|
||||
// 父调用的取消继续向子执行传播,不能因新建执行丢失扩展调用链
|
||||
let graph = Arc::new(NestedExecutionGraph::new(Arc::new(
|
||||
ExecutionEffects::default(),
|
||||
)));
|
||||
@@ -1154,12 +1149,12 @@ impl DefaultExecutionService {
|
||||
let execution_effects_baseline = graph.effects.epoch();
|
||||
metadata.endpoint = "host.model".to_owned();
|
||||
metadata.transport = ClientTransport::InternalPlugin;
|
||||
metadata.inherit_request_origin(&authority.extension_scope);
|
||||
metadata.inherit_request_origin(&extension_scope);
|
||||
self.client_api_key_usage
|
||||
.record_used(authority.client.policy.key_id());
|
||||
.record_used(client.policy.key_id());
|
||||
self.start_authorized(
|
||||
PendingStartExecution {
|
||||
client: authority.client.clone(),
|
||||
client,
|
||||
target: ExecutionTarget::Model(public_model),
|
||||
operation,
|
||||
metadata,
|
||||
@@ -1168,13 +1163,13 @@ impl DefaultExecutionService {
|
||||
account_scope,
|
||||
response_control: None,
|
||||
deadline_at,
|
||||
cancellation: authority.cancellation.child_token(),
|
||||
extension_scope: authority.extension_scope.clone(),
|
||||
cancellation: cancellation.child_token(),
|
||||
extension_scope,
|
||||
required_provider,
|
||||
required_account: account,
|
||||
nested: None,
|
||||
bound: Some(BoundExecutionFacts {
|
||||
initiating_plugin_instance_id: authority.initiating_plugin_instance_id.clone(),
|
||||
initiating_plugin_instance_id,
|
||||
}),
|
||||
graph: Some(graph),
|
||||
execution_effects_baseline,
|
||||
@@ -1570,14 +1565,7 @@ impl ExecutionService for DefaultExecutionService {
|
||||
.query_client_model_catalog(scope, protocol, client_version)
|
||||
.await?
|
||||
else {
|
||||
for profile in client.snapshot.public_model_profiles_for_provider(kind) {
|
||||
if !client.snapshot.catalog_model_allowed_for_scope(
|
||||
kind,
|
||||
profile.model(),
|
||||
scope,
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
for profile in client.snapshot.profiles_for_provider_scope(kind, scope) {
|
||||
if seen.insert(profile.model().clone()) {
|
||||
result.push(PublicModelDescriptor::Adapted(profile));
|
||||
}
|
||||
@@ -1629,6 +1617,12 @@ impl ExecutionService for DefaultExecutionService {
|
||||
result.push(source.content.for_public_model(model));
|
||||
}
|
||||
}
|
||||
// 原生完整对象优先;只补入当前授权账号实际提供的独立适配画像
|
||||
for profile in client.snapshot.contributed_profiles_for_scope(kind, scope) {
|
||||
if seen.insert(profile.model().clone()) {
|
||||
result.push(PublicModelDescriptor::Adapted(profile));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(result)
|
||||
})
|
||||
@@ -1724,23 +1718,57 @@ impl ExecutionService for DefaultExecutionService {
|
||||
}
|
||||
}
|
||||
|
||||
impl ClientIdentityPort for DefaultExecutionService {
|
||||
fn resolve_client(
|
||||
&self,
|
||||
client_key_id: ClientApiKeyId,
|
||||
settings: Option<RequestSettings>,
|
||||
) -> BoxFuture<'_, Result<AuthenticatedClient, GatewayError>> {
|
||||
Box::pin(async move { self.client_for_key_id(&client_key_id, settings).await })
|
||||
}
|
||||
|
||||
fn verify_client(
|
||||
&self,
|
||||
request: ClientAuthenticationRequest,
|
||||
) -> BoxFuture<'_, Result<AuthenticatedClient, GatewayError>> {
|
||||
Box::pin(async move {
|
||||
let cancellation = request
|
||||
.invocation()
|
||||
.map(|origin| origin.cancellation.clone());
|
||||
let verification = self.verify_request(request).fuse();
|
||||
pin_mut!(verification);
|
||||
match cancellation {
|
||||
Some(cancellation) => {
|
||||
let cancelled = cancellation.cancelled().fuse();
|
||||
pin_mut!(cancelled);
|
||||
select_biased! {
|
||||
() = cancelled => Err(GatewayError::new(GatewayErrorKind::Cancelled, "client verification was cancelled")),
|
||||
result = verification => result.map_err(authentication_gateway_error),
|
||||
}
|
||||
}
|
||||
None => verification.await.map_err(authentication_gateway_error),
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl NestedModelExecutionPort for DefaultExecutionService {
|
||||
fn models(
|
||||
&self,
|
||||
context: BoundModelExecutionContext,
|
||||
client: AuthenticatedClient,
|
||||
cancellation: CancellationToken,
|
||||
protocol: String,
|
||||
client_version: String,
|
||||
) -> BoxFuture<'_, Result<Vec<PublicModelId>, GatewayError>> {
|
||||
Box::pin(async move {
|
||||
let authority = &context.authority;
|
||||
let cancellation = authority.cancellation.cancelled().fuse();
|
||||
let cancelled = cancellation.cancelled().fuse();
|
||||
let timeout = Delay::new(DIAGNOSTIC_TIMEOUT).fuse();
|
||||
let catalog = self
|
||||
.client_model_catalog(&authority.client, &protocol, &client_version)
|
||||
.client_model_catalog(&client, &protocol, &client_version)
|
||||
.fuse();
|
||||
pin_mut!(cancellation, timeout, catalog);
|
||||
pin_mut!(cancelled, timeout, catalog);
|
||||
let models = select_biased! {
|
||||
() = cancellation => return Err(GatewayError::new(GatewayErrorKind::Cancelled, "model catalog call was cancelled")),
|
||||
() = cancelled => return Err(GatewayError::new(GatewayErrorKind::Cancelled, "model catalog call was cancelled")),
|
||||
() = timeout => return Err(GatewayError::new(GatewayErrorKind::Timeout, "model catalog deadline elapsed")),
|
||||
result = catalog => result.map_err(|_| GatewayError::new(GatewayErrorKind::Internal, "model catalog is unavailable"))?,
|
||||
};
|
||||
@@ -1754,13 +1782,6 @@ impl NestedModelExecutionPort for DefaultExecutionService {
|
||||
})
|
||||
}
|
||||
|
||||
fn bind(
|
||||
&self,
|
||||
binding: BoundModelExecutionBinding,
|
||||
) -> BoxFuture<'_, Result<BoundModelExecutionContext, GatewayError>> {
|
||||
Box::pin(async move { self.bind_bound_model_inner(binding).await })
|
||||
}
|
||||
|
||||
fn start(
|
||||
&self,
|
||||
request: NestedModelExecutionRequest,
|
||||
|
||||
@@ -62,6 +62,17 @@ impl ExtensionCallScope {
|
||||
}
|
||||
}
|
||||
|
||||
/// 宿主签发的父调用来源;身份裁决、执行链和实际资源仍由各自 owner 持有
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct InvocationOrigin {
|
||||
pub request_id: String,
|
||||
pub call_id: String,
|
||||
pub cancellation: crate::lifecycle::CancellationToken,
|
||||
pub extensions: ExtensionCallScope,
|
||||
pub plan: Option<super::middleware::FrozenMiddlewarePlan>,
|
||||
pub effects: Option<Arc<super::nested::ExecutionEffects>>,
|
||||
}
|
||||
|
||||
/// 同一代次的具体执行计划;不拥有发布状态,运行资源由对应发布集合保活
|
||||
#[derive(Debug, Default)]
|
||||
pub struct ExecutionExtensionPlans {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! 模型请求生命周期、单行持久化 port 与 commit/send/cancellation 边界
|
||||
|
||||
mod account_protection;
|
||||
pub mod admission;
|
||||
pub mod authentication;
|
||||
pub mod budget;
|
||||
@@ -167,7 +168,7 @@ impl AccountAttemptContext {
|
||||
}
|
||||
}
|
||||
|
||||
/// 附着普通请求认证时冻结的账号范围
|
||||
/// 附着本次尝试的冻结账号范围,包含路由候选的能力限制
|
||||
#[must_use]
|
||||
pub fn with_account_scope(
|
||||
mut self,
|
||||
@@ -286,6 +287,7 @@ impl ContinuationAttempt {
|
||||
/// Provider 每次执行可见的 request-local context
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct RequestAttemptContext {
|
||||
account_error_protection: Option<account_protection::ProtectionContext>,
|
||||
request_body_limit: Option<usize>,
|
||||
lease_metadata: Option<Arc<crate::provider_ports::ProviderLeaseMetadata>>,
|
||||
response_control: Option<response_control::ResponseControl>,
|
||||
@@ -312,6 +314,14 @@ pub struct RequestAttemptContext {
|
||||
}
|
||||
|
||||
impl RequestAttemptContext {
|
||||
fn with_account_error_protection(
|
||||
mut self,
|
||||
protection: Option<account_protection::ProtectionContext>,
|
||||
) -> Self {
|
||||
self.account_error_protection = protection;
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn with_request_body_limit(mut self, bytes: usize) -> Self {
|
||||
self.request_body_limit = Some(bytes);
|
||||
@@ -393,6 +403,7 @@ impl RequestAttemptContext {
|
||||
#[must_use]
|
||||
pub fn new(request_id: ModelRequestId, client_api_key_ref: ClientApiKeyId) -> Self {
|
||||
Self {
|
||||
account_error_protection: None,
|
||||
response_control: None,
|
||||
request_body_limit: None,
|
||||
lease_metadata: None,
|
||||
@@ -777,6 +788,24 @@ impl AttemptContext {
|
||||
} else {
|
||||
terminal
|
||||
};
|
||||
// 保护观察真正的 Provider terminal,先于 attempt 中间件的响应改写
|
||||
let terminal: provider::ProviderMiddlewareTerminal =
|
||||
if let Some(protection) = self.request.account_error_protection.clone() {
|
||||
Box::new(move |operation, headers| {
|
||||
Box::pin(async move {
|
||||
let stream = terminal(operation, headers).await?;
|
||||
Ok(stream
|
||||
.with_account_error_protection(
|
||||
protection.store,
|
||||
protection.policy,
|
||||
protection.revision,
|
||||
)
|
||||
.await)
|
||||
})
|
||||
})
|
||||
} else {
|
||||
terminal
|
||||
};
|
||||
let context = self.middleware_context(
|
||||
middleware::MiddlewareMount::Attempt,
|
||||
Some(operation.kind()),
|
||||
@@ -895,7 +924,7 @@ impl AttemptContext {
|
||||
self.account.is_diagnostic_required_account()
|
||||
}
|
||||
|
||||
/// 普通请求认证时冻结的账号范围;管理端诊断为 `None`
|
||||
/// 当前路由候选的冻结账号范围;管理端诊断为 `None`
|
||||
#[must_use]
|
||||
pub const fn account_scope(&self) -> Option<&Arc<crate::account::scope::FrozenAccountScope>> {
|
||||
self.account.account_scope()
|
||||
@@ -1245,6 +1274,7 @@ pub struct GatewayEngine<S: ?Sized> {
|
||||
store: Arc<S>,
|
||||
providers: provider::ProviderRegistry,
|
||||
client_retry: Option<Arc<dyn client_retry::ClientRetryStore>>,
|
||||
account_error_protection: Option<Arc<dyn crate::provider_ports::ProviderCooldownPort>>,
|
||||
}
|
||||
|
||||
impl<S: ?Sized> GatewayEngine<S> {
|
||||
@@ -1254,9 +1284,19 @@ impl<S: ?Sized> GatewayEngine<S> {
|
||||
store,
|
||||
providers,
|
||||
client_retry: None,
|
||||
account_error_protection: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn with_account_error_protection(
|
||||
mut self,
|
||||
store: Arc<dyn crate::provider_ports::ProviderCooldownPort>,
|
||||
) -> Self {
|
||||
self.account_error_protection = Some(store);
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn with_client_retry_store(
|
||||
mut self,
|
||||
|
||||
@@ -13,13 +13,13 @@ use futures::future::BoxFuture;
|
||||
|
||||
use crate::{
|
||||
account::ProviderAccountId, error::GatewayError, identity::ProviderKind,
|
||||
lifecycle::CancellationToken, operation::Operation, policy::ClientApiKeyId,
|
||||
provider_ports::ProviderSessionAffinityKey, routing::PublicModelId,
|
||||
lifecycle::CancellationToken, operation::Operation, provider_ports::ProviderSessionAffinityKey,
|
||||
routing::PublicModelId,
|
||||
};
|
||||
|
||||
use super::{
|
||||
ModelRequestId,
|
||||
execution::{BoundModelExecutionContext, ExecutionRequestMetadata, StartedExecution},
|
||||
execution::{AuthenticatedClient, ExecutionRequestMetadata, StartedExecution},
|
||||
};
|
||||
|
||||
/// 同一请求图内不可逆外部副作用的单调水位
|
||||
@@ -59,37 +59,14 @@ pub struct NestedModelExecutionRequest {
|
||||
pub parent_account: Option<ProviderAccountId>,
|
||||
}
|
||||
|
||||
/// 插件为当前调用或连接显式绑定的模型执行身份
|
||||
///
|
||||
/// Key ID 由插件选择,发起实例由宿主确定
|
||||
/// Core 在绑定时冻结当前
|
||||
/// Key 策略;每个实际模型请求仍独立经过准入、预算、账本与计费
|
||||
pub struct BoundModelExecutionBinding {
|
||||
pub settings: Option<crate::routing::request_settings::RequestSettings>,
|
||||
pub client_key_id: ClientApiKeyId,
|
||||
pub initiating_plugin_instance_id: String,
|
||||
/// 身份随父调用或连接回收;每个模型请求使用独立的执行期限
|
||||
pub cancellation: CancellationToken,
|
||||
/// 宿主保留的扩展调用链,异步观察不能通过新建模型请求清空防递归事实
|
||||
pub extension_scope: super::extensions::ExtensionCallScope,
|
||||
}
|
||||
|
||||
impl fmt::Debug for BoundModelExecutionBinding {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
formatter
|
||||
.debug_struct("BoundModelExecutionBinding")
|
||||
.field("client_key_id", &self.client_key_id)
|
||||
.field(
|
||||
"initiating_plugin_instance_id",
|
||||
&self.initiating_plugin_instance_id,
|
||||
)
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
/// 显式身份作用域内的一次模型请求
|
||||
///
|
||||
/// 身份与权限可先用于查询;执行链只在真正启动模型请求时建立
|
||||
pub struct BoundModelExecutionRequest {
|
||||
pub context: BoundModelExecutionContext,
|
||||
pub client: AuthenticatedClient,
|
||||
pub initiating_plugin_instance_id: String,
|
||||
pub cancellation: CancellationToken,
|
||||
pub extension_scope: super::extensions::ExtensionCallScope,
|
||||
pub public_model: PublicModelId,
|
||||
pub operation: Operation,
|
||||
pub metadata: ExecutionRequestMetadata,
|
||||
@@ -101,7 +78,11 @@ impl fmt::Debug for BoundModelExecutionRequest {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
formatter
|
||||
.debug_struct("BoundModelExecutionRequest")
|
||||
.field("context", &self.context)
|
||||
.field("client", &self.client)
|
||||
.field(
|
||||
"initiating_plugin_instance_id",
|
||||
&self.initiating_plugin_instance_id,
|
||||
)
|
||||
.field("public_model", &self.public_model)
|
||||
.field("operation", &self.operation.kind())
|
||||
.field("provider", &self.provider)
|
||||
@@ -132,17 +113,12 @@ impl fmt::Debug for NestedModelExecutionRequest {
|
||||
pub trait NestedModelExecutionPort: Send + Sync {
|
||||
fn models(
|
||||
&self,
|
||||
context: BoundModelExecutionContext,
|
||||
client: AuthenticatedClient,
|
||||
cancellation: CancellationToken,
|
||||
protocol: String,
|
||||
client_version: String,
|
||||
) -> BoxFuture<'_, Result<Vec<PublicModelId>, GatewayError>>;
|
||||
|
||||
/// 为插件调用冻结显式执行身份;取消父调用会取消其所有模型执行
|
||||
fn bind(
|
||||
&self,
|
||||
binding: BoundModelExecutionBinding,
|
||||
) -> BoxFuture<'_, Result<BoundModelExecutionContext, GatewayError>>;
|
||||
|
||||
fn start(
|
||||
&self,
|
||||
request: NestedModelExecutionRequest,
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user