Compare commits

..
31 Commits
Author SHA1 Message Date
ZyyandCodex b5e691c63d fix(dashboard): animate incremental data updates
Preserve chart state across updates and animate capacity, status distribution, and account reordering. Keep metric transition values synchronized when reduced motion is enabled.

Co-authored-by: Codex <noreply@openai.com>
2026-12-03 14:50:05 +08:00
Zyy 2d0a52096a fix(workers): prioritize shutdown during background tasks 2026-12-03 13:56:18 +08:00
github-actions[bot] 47620e217a chore(release): update release channels to 3.61.1-rc.2 2026-12-03 05:16:01 +00:00
ZyyandCodex 48aeccd0e0 chore: bump version to 3.61.1-rc.2
Co-authored-by: Codex <noreply@openai.com>
2026-12-03 12:54:43 +08:00
bdc618701b feat(system): add confirmed manual service restart (#832)
* feat(system): add confirmed manual service restart

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

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

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

* fix(system): require explicit restart support

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

* docs(deploy): drop legacy restart notes

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

---------

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

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

* ci: retrigger checks

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

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

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

* fix(routing): preserve explicit default Fast overrides

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

---------

Co-authored-by: Zyy <zyycn@users.noreply.github.com>
Co-authored-by: Codex <noreply@openai.com>
2026-12-03 11:39:33 +08:00
7e98130cac fix(openai): re-anchor bucket warmup after early quota reset (#830)
* fix(openai): re-anchor bucket warmup after upstream early quota reset

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

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

* fix(openai): preserve precise bucket reset boundaries

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

---------

Co-authored-by: Zyy <zyycn@users.noreply.github.com>
Co-authored-by: Codex <noreply@openai.com>
2026-12-03 11:36:44 +08:00
2821a5e3bd fix(protocol): handle empty Chat history and nullable fields (#831)
* fix(protocol): accept null-content system/developer chat messages

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

fixes #824

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

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

---------

Co-authored-by: Zyy <zyycn@users.noreply.github.com>
Co-authored-by: Codex <noreply@openai.com>
2026-12-03 11:36:44 +08:00
ZyyandCodex 6a6a167d41 perf(openai): trim SSE history after privacy processing
Match privacy-processed SSE requests against the existing WebSocket history prefix. Keep full input on a mismatch and resume trimming after a matching completed turn.

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

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

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

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

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

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

Update regression coverage and the public API contract.

Co-authored-by: Codex <noreply@openai.com>
2026-12-03 10:28:00 +08:00
github-actions[bot] 66f650f097 chore(release): update release channels to 3.61.1-rc.1 2026-12-02 13:47:28 +00:00
ZyyandCodex ca4d02068a chore: bump version to 3.61.1-rc.1
Co-authored-by: Codex <noreply@openai.com>
2026-12-02 21:33:34 +08:00
Zyy d185a639a9 perf(openai): send incremental SSE history over pooled WebSockets 2026-12-02 21:09:28 +08:00
github-actions[bot] 3078dd9993 chore(release): update release channels to 3.61.0 2026-12-01 13:39:52 +00:00
ZyyandCodex cad1a9245e chore: bump version to 3.61.0
Co-authored-by: Codex <noreply@openai.com>
2026-12-01 21:10:22 +08:00
ZyyandCodex d4d1114e73 fix(scheduling): score recent model load alongside concurrency
Include recent request pressure in Smart load scores before near-best
selection, keeping the concurrency penalty independent. Remove the
separate recent-count filter and share the score with diagnostics and
queue selection.

Co-authored-by: Codex <noreply@openai.com>
2026-12-01 19:20:04 +08:00
9e8a5a9b61 feat(scheduling): balance accounts using recent model load (#820)
Prefer accounts with fewer recent requests among near-best Smart candidates
while preserving affinity and existing eligibility constraints. Save recent
load snapshots asynchronously to Redis and restore live buckets on startup.

Co-authored-by: Zyy <zyycn@users.noreply.github.com>
Co-authored-by: Codex <noreply@openai.com>
2026-12-01 18:40:09 +08:00
ZyyandCodex 9a5bf55bdf fix(release): validate release branches and recover latest promotion
Co-authored-by: Codex <noreply@openai.com>
2026-12-01 17:17:35 +08:00
ZyyandCodex f57a375407 feat(frontend): show compact release channel badges in the sidebar
Co-authored-by: Codex <noreply@openai.com>
2026-12-01 17:17:35 +08:00
ZyyandCodex 82cb91e1af fix(updater): report the published version for the selected channel
Return an unknown version when discovery fails and preserve local update capability during rate limits. Keep release notes tied to the selected channel and require a higher version for installation.

Co-authored-by: Codex <noreply@openai.com>
2026-12-01 16:22:13 +08:00
ZyyandCodex 441c012613 fix(accounts): show token usage for the displayed quota window
Co-authored-by: Codex <noreply@openai.com>
2026-12-01 16:21:43 +08:00
ZyyandCodex 983eca5fe7 fix(frontend): stabilize select text and hide empty token values
Hide empty token values while preserving their labels and layout. Align the UI dependency, lockfile, and submodule with the select font-weight fix.

Co-authored-by: Codex <noreply@openai.com>
2026-12-01 16:05:44 +08:00
ZyyandCodex e0b0ab14da fix(openai): preserve quota observation timestamps
Keep header and stream quota facts tied to their collection time so delayed responses cannot replace a newer refresh. Filter stale observations again on merge conflicts and retain timestamps through failure and warmup paths.

Co-authored-by: Codex <noreply@openai.com>
2026-12-01 15:27:03 +08:00
b4bb97d1dc feat(accounts): add xAI and Antigravity API key upstreams (#816)
* feat(accounts): add xAI and Antigravity API key upstreams

Support native Responses and GenAI API key accounts with custom upstream URLs.
Reuse account management and isolate credentials, catalogs, and runtime connections by revision.

Refs #814

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

* refactor(antigravity): simplify API key account names

Use name consistently in API key account documents and verify the exported contract before reimport.

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

---------

Co-authored-by: Zyy <zyycn@users.noreply.github.com>
Co-authored-by: Codex <noreply@openai.com>
2026-12-01 15:07:11 +08:00
ZyyandCodex 9f979110d2 fix(gateway): forward upstream retry headers regardless of error kind
Co-authored-by: Codex <noreply@openai.com>
2026-12-01 13:33:10 +08:00
github-actions[bot] a5cddfe4a5 chore(release): update release channels to 3.60.5 2026-12-01 05:12:39 +00:00
254 changed files with 9076 additions and 1676 deletions
@@ -4,7 +4,9 @@
## 领域必读 ## 领域必读
确定页面方案或审查结论前,读取[前端职责](../../../../docs/architecture.md#34-前端模块职责)、[文案与信息层级](../../../../docs/theme.md#界面文案与信息层级)和[界面验证](../../../../CONTRIBUTING.md#界面验证)的完整章节,局部修改同样读取。明确本次用户操作、原页面、最接近的同类实现及可复用基础组件,沿用既有设计与请求层,按本轮验收分工留存所需截图 确定页面方案或审查结论前,读取[前端职责](../../../../docs/architecture.md#34-前端模块职责)、[文案与信息层级](../../../../docs/theme.md#界面文案与信息层级)和[界面验证](../../../../CONTRIBUTING.md#界面验证)的完整章节,局部修改同样读取。新增或移动文件时,页面与布局按同一套目录规则,根据调用范围和导出内容区分组件私有实现、共享常量和共享纯函数
明确本次用户操作、原页面、最接近的同类实现及可复用基础组件,沿用既有设计与请求层,按本轮验收分工留存所需截图
## 按改动补齐规范 ## 按改动补齐规范
@@ -28,6 +30,8 @@
验证前按[界面验证](../../../../CONTRIBUTING.md#界面验证)明确本次受影响的用户路径、状态和通过条件。局部修改围绕受影响区域及相关操作验收;主题、窗口尺寸和空/加载/错误状态仅在受影响时补充,共用主题或基础组件变更按主题规范扩大范围 验证前按[界面验证](../../../../CONTRIBUTING.md#界面验证)明确本次受影响的用户路径、状态和通过条件。局部修改围绕受影响区域及相关操作验收;主题、窗口尺寸和空/加载/错误状态仅在受影响时补充,共用主题或基础组件变更按主题规范扩大范围
沿实际操作验证待确认、执行中、完成、失败与取消等受影响阶段,同时检查当前弹层和背景区域,核对应该出现的反馈与不应出现的状态。必要时延迟模拟响应以观察过渡状态,不能仅凭请求成功或截图齐全判定交互通过
通过后按[验证停止条件](../../../../CONTRIBUTING.md#验证)收尾;只有新改动、失败或未解疑点时补验相关部分。补交截图或 PR 材料时复用仍有效的运行证据 通过后按[验证停止条件](../../../../CONTRIBUTING.md#验证)收尾;只有新改动、失败或未解疑点时补验相关部分。补交截图或 PR 材料时复用仍有效的运行证据
## 交付前 ## 交付前
@@ -40,7 +44,7 @@
- **样式与状态**:是否使用对应 Token 与 utility,局部样式是否符合适用边界,受影响的主题、窄屏及交互状态是否正确 - **样式与状态**:是否使用对应 Token 与 utility,局部样式是否符合适用边界,受影响的主题、窄屏及交互状态是否正确
- **模块归属**从调用方核对公开入口。页面或多文件组件通过 `index.vue` 提供界面,其他页面复用整页时引用所属模块的布局入口,独立复用的业务组件按领域放置 - **模块归属**从调用方核对公开入口。页面或多文件组件通过 `index.vue` 提供界面,其他页面复用整页时引用所属模块的布局入口,独立复用的业务组件按领域放置
- **Provider 边界**涉及账号操作、身份配置或定价时,沿接口响应、控件和提交载荷追踪同一条规则。服务端决定的能力使用接口字段,Provider 专属表单解释自己的字段,多个页面共用的编辑流程只维护一份。按[前端职责](../../../../docs/architecture.md#34-前端模块职责)核对归属 - **Provider 边界**涉及账号操作、身份配置或定价时,沿接口响应、控件和提交载荷追踪同一条规则。服务端决定的能力使用接口字段,Provider 专属表单解释自己的字段,多个页面共用的编辑流程只维护一份。按[前端职责](../../../../docs/architecture.md#34-前端模块职责)核对归属
- **查询与动作**:区分首次加载、刷新、分页、单行与批量操作,核对 loading、禁用状态的影响范围;沿用请求层错误处理,不在页面叠加同一错误的提示 - **查询与动作**:区分首次加载、刷新、分页、单行与批量操作,明确当前动作的反馈归属及其他控件的禁用范围,避免同一动作在前后景重复显示执行反馈。待确认不等于已提交,复用交互时重新核对 loading、进度与结果的显示条件是否适用于当前动作;沿用请求层错误处理,不在页面叠加同一错误的提示
- **运行证据**:按界面验证核对截图与实际交互,证据对应当前实现;页面 PR 的可访问图片和 Draft 条件按该节执行 - **运行证据**:按界面验证核对截图与实际交互,证据对应当前实现;页面 PR 的可访问图片和 Draft 条件按该节执行
交付简述所复用的页面或组件、实际验证范围及缺口;环境不足时如实说明,不能仅凭构建、源码或截图推断未验证的行为 交付简述所复用的页面或组件、实际验证范围及缺口;环境不足时如实说明,不能仅凭构建、源码或截图推断未验证的行为
@@ -46,7 +46,9 @@ release/publish "$release_version"
- 尚未推送:补齐缺失的步骤,按入口原子推送分支和 tag - 尚未推送:补齐缺失的步骤,按入口原子推送分支和 tag
- 已推送但未触发:使用入口提示的 dispatch 命令 - 已推送但未触发:使用入口提示的 dispatch 命令
- 已有 run:跟踪对应提交的任务,失败时重跑失败任务。构建产物保留 7 天,过期后从原 tag 重跑完整工作流 - Release 尚未公开时,跟踪原 run 并重跑失败任务。构建产物保留 7 天,过期后从原 tag 重跑工作流
- 正式版已公开,GitHub Latest 或镜像 `latest` 提升中断时,在已有恢复授权下执行 `gh workflow run release.yml --ref main -f tag="v$release_version" -f recover_latest=true`。任务核对公开附件、版本镜像与 tag 提交对应的镜像摘要,补齐稳定入口后同步通道表。若任一稳定入口已经指向更新版本,则保留现有入口
- 仅通道表写入失败时,确认工作流能写入 `main`,按已有授权执行 `gh workflow run release.yml --ref main -f tag="v$release_version" -f index_only=true`。各通道均可用此入口重新核对公开附件并合并通道表
### 修复源码后同版本重发 ### 修复源码后同版本重发
@@ -60,7 +62,7 @@ release/publish "$release_version"
- 发布完成后核对 GitHub Release 的版本、正式版/预发行状态和中文变更正文;对照平台清单与工作流确认归档、校验和及镜像产物。 - 发布完成后核对 GitHub Release 的版本、正式版/预发行状态和中文变更正文;对照平台清单与工作流确认归档、校验和及镜像产物。
工作流附加的安装说明和自动提交列表按其当前配置处理,不用它们替代手写的中文变更说明。 工作流附加的安装说明和自动提交列表按其当前配置处理,不用它们替代手写的中文变更说明。
- 回读 `main:release/version.yaml` 的 `published`。正式版参与同一大版本四个普通通道的比较;RC 参与 RC、Beta、Alpha,Beta 参与 Beta、Alpha,Alpha 只参与自身。实验版只推进 `exp["X.Y.Z"]`。有通道推进时应有 `chore(release): update release channels to <version>` 提交;重复执行或较旧版本未推进任何通道时无提交 - 回读 `main:release/version.yaml` 的 `published`。正式版参与同一大版本四个普通通道的比较;RC 参与 RC、Beta、Alpha,Beta 参与 Beta、Alpha,Alpha 只参与自身。实验版只推进 `exp["X.Y.Z"]`。有通道推进时应有 `chore(release): update release channels to <version>` 提交;重复执行或较旧版本未推进任何通道时无提交
- 通道表写入失败时,确认该版本已公开、工作流能写入 `main`,再按已有授权执行 `gh workflow run release.yml --ref main -f tag="v$release_version" -f index_only=true`。恢复任务重新校验公开附件、读取并合并当前清单,不重新打包或改 tag - 正式版提升或恢复后,回读 GitHub Latest 的 tag 与镜像 `latest` 的摘要,核对两者均指向预期正式版
- 保留 v3.42.0 在线升级使用的 `update-index` 页面和 v3.42.1 的 `version.yaml` 附件 - 保留 v3.42.0 在线升级使用的 `update-index` 页面和 v3.42.1 的 `version.yaml` 附件
- 返回版本、tag 对应提交、Release/工作流链接及实际结果。失败、仍在构建或缺失产物时明确说明,不能称为发布成功; - 返回版本、tag 对应提交、Release/工作流链接及实际结果。失败、仍在构建或缺失产物时明确说明,不能称为发布成功;
Release 和镜像已生成也不表示用户的运行实例已经升级。 Release 和镜像已生成也不表示用户的运行实例已经升级。
+40 -15
View File
@@ -1,4 +1,4 @@
require_relative 'release-metadata' require_relative 'published-channels'
# 构建和验证可以并行;调用方必须在仓库级发布锁内执行本脚本 # 构建和验证可以并行;调用方必须在仓库级发布锁内执行本脚本
module ReleasePublication module ReleasePublication
@@ -39,44 +39,69 @@ module ReleasePublication
end end
end end
def self.image_digest(ref)
digest = run('docker', 'buildx', 'imagetools', 'inspect', ref, '--format', '{{.Manifest.Digest}}')
raise "Invalid image digest for #{ref}" unless digest.match?(/\Asha256:[a-f0-9]{64}\z/)
digest
end
def self.tag(image, digest, name) def self.tag(image, digest, name)
ref = "#{image}:#{name}" ref = "#{image}:#{name}"
run('docker', 'buildx', 'imagetools', 'create', '-t', ref, "#{image}@#{digest}") run('docker', 'buildx', 'imagetools', 'create', '-t', ref, "#{image}@#{digest}")
actual = run('docker', 'buildx', 'imagetools', 'inspect', ref, '--format', '{{.Manifest.Digest}}') raise "Promoted image digest changed: #{ref}" unless image_digest(ref) == digest
raise "Promoted image digest changed: #{ref}" unless actual == digest
end end
def self.publish(version:, image:, digest:, repository:, release_id:) def self.publish(version:, image:, digest:, repository:, release_id:)
version = ReleaseMetadata.version(version) version = ReleaseMetadata.release_version(version)
raise 'Invalid image digest' unless digest.match?(/\Asha256:[a-f0-9]{64}\z/) raise 'Invalid image digest' unless digest.match?(/\Asha256:[a-f0-9]{64}\z/)
raise 'Invalid GitHub release ID' unless release_id.match?(/\A\d+\z/) raise 'Invalid GitHub release ID' unless release_id.match?(/\A\d+\z/)
endpoint = "repos/#{repository}/releases/#{release_id}" endpoint = "repos/#{repository}/releases/#{release_id}"
# 附件上传及镜像证明、签名已完成,再公开版本入口;失败可从本 job 重跑 # 附件、签名和证明就绪后才公开版本入口
tag(image, digest, version.tr('+', '-')) tag(image, digest, version)
run('gh', 'api', '--method', 'PATCH', endpoint, '-F', 'draft=false', '-f', 'make_latest=false') run('gh', 'api', '--method', 'PATCH', endpoint, '-F', 'draft=false', '-f', 'make_latest=false')
return if ReleaseMetadata.prerelease?(version) promote_latest(version, image, digest, repository, endpoint) unless ReleaseMetadata.prerelease?(version)
end
current_versions = [latest_release(repository), latest_image(image)] def self.recover_latest(tag:, image:, repository:, ref:)
version = ReleaseMetadata.release_version(tag)
raise 'Latest recovery requires a stable release' if ReleaseMetadata.prerelease?(version)
commit = ReleaseMetadata.tag_commit(tag, ref)
release = PublishedChannels::Publisher.new(repository).verify_assets(version)
digest = image_digest("#{image}:#{version}")
raise "Version image differs from the image built for #{commit}" unless image_digest("#{image}:sha-#{commit}") == digest
promote_latest(version, image, digest, repository, "repos/#{repository}/releases/#{release.fetch('id')}")
end
def self.promote_latest(version, image, digest, repository, endpoint)
github_latest = latest_release(repository)
docker_latest = latest_image(image)
current_versions = [github_latest, docker_latest]
unless can_promote?(version, current_versions) unless can_promote?(version, current_versions)
puts "Published #{version}; latest remains at #{current_versions.compact.join(', ')}" puts "Published #{version}; latest remains at #{current_versions.compact.join(', ')}"
return return
end end
# 两个服务不能原子更新;同时检查两侧版本,让失败重试可以补齐而旧版不能回退 # 两个服务不能原子更新;同时检查两侧版本,让失败重试可以补齐而旧版不能回退
tag(image, digest, 'latest') tag(image, digest, 'latest') unless docker_latest == version && image_digest("#{image}:latest") == digest
run('gh', 'api', '--method', 'PATCH', endpoint, '-f', 'make_latest=true') run('gh', 'api', '--method', 'PATCH', endpoint, '-f', 'make_latest=true') unless github_latest == "v#{version}"
puts "Published #{version} and promoted latest" puts "Published #{version} and promoted latest"
end end
end end
if $PROGRAM_NAME == __FILE__ if $PROGRAM_NAME == __FILE__
begin begin
ReleasePublication.publish( image = "#{ENV.fetch('REGISTRY')}/#{ENV.fetch('IMAGE_NAME')}"
version: ENV.fetch('VERSION'), image: "#{ENV.fetch('REGISTRY')}/#{ENV.fetch('IMAGE_NAME')}", repository = ENV.fetch('GITHUB_REPOSITORY')
digest: ENV.fetch('DIGEST'), repository: ENV.fetch('GITHUB_REPOSITORY'), case ARGV
release_id: ENV.fetch('RELEASE_ID') when []
) ReleasePublication.publish(version: ENV.fetch('VERSION'), image: image, digest: ENV.fetch('DIGEST'),
repository: repository, release_id: ENV.fetch('RELEASE_ID'))
when ['recover-latest']
ReleasePublication.recover_latest(tag: ENV.fetch('TAG'), image: image, repository: repository, ref: ENV.fetch('GITHUB_REF'))
else
raise 'usage: publish-release.rb [recover-latest]'
end
rescue StandardError => error rescue StandardError => error
warn "error: #{error.message}" warn "error: #{error.message}"
exit 1 exit 1
+2 -1
View File
@@ -67,11 +67,12 @@ module PublishedChannels
end end
missing = expected - uploaded missing = expected - uploaded
raise "Incomplete release #{tag}: #{missing.join(', ')}" unless missing.empty? raise "Incomplete release #{tag}: #{missing.join(', ')}" unless missing.empty?
release
end end
def check_unpublished(version) def check_unpublished(version)
existing = find_release(version) existing = find_release(version)
raise "Release v#{version} already public; use index-only recovery" if existing && !existing.fetch('draft') raise "Release v#{version} already public; use recover_latest or index_only" if existing && !existing.fetch('draft')
end end
def publish(version) def publish(version)
+32 -5
View File
@@ -20,6 +20,31 @@ module ReleaseMetadata
version(value).split('+', 2).first.include?('-') version(value).split('+', 2).first.include?('-')
end end
def self.release_version(raw)
value = version(raw)
raise "Release versions cannot contain build metadata: #{raw}" if value.include?('+')
value
end
def self.validate_branch(raw, ref)
value = release_version(raw)
if value.include?('-exp.')
raise "Experimental releases require an experimental/<purpose> branch" unless ref.match?(%r{\Arefs/heads/experimental/.+\z})
elsif ref != 'refs/heads/main'
raise "Release #{value} requires the main branch"
end
value
end
# 从触发工作流的提交核对 tag,允许分支前进后重试同一发行
def self.tag_commit(tag, ref)
value = validate_branch(tag, ref)
raise "Expected release tag v#{value}" unless tag == "v#{value}"
commit = git('rev-parse', '--verify', "refs/tags/#{tag}^{commit}")
raise "#{tag} is outside #{ref}" unless git('merge-base', commit, 'HEAD') == commit
commit
end
def self.sort_key(value) def self.sort_key(value)
Gem::Version.new(version(value).split('+', 2).first) Gem::Version.new(version(value).split('+', 2).first)
end end
@@ -67,7 +92,7 @@ module ReleaseMetadata
end end
def self.outputs(tag) def self.outputs(tag)
value = version(YAML.load_file('release/version.yaml').fetch('version')) value = release_version(YAML.load_file('release/version.yaml').fetch('version'))
raise "Release tag #{tag} does not match v#{value}" unless tag == "v#{value}" raise "Release tag #{tag} does not match v#{value}" unless tag == "v#{value}"
validate_notes(value) validate_notes(value)
entries = platforms entries = platforms
@@ -80,7 +105,6 @@ module ReleaseMetadata
{ {
'tag' => tag, 'tag' => tag,
'version' => value, 'version' => value,
'docker_version' => value.tr('+', '-'),
'build_time' => Time.now.utc.iso8601, 'build_time' => Time.now.utc.iso8601,
'git_sha' => git('rev-parse', 'HEAD'), 'git_sha' => git('rev-parse', 'HEAD'),
'platform_matrix' => JSON.generate('include' => entries), 'platform_matrix' => JSON.generate('include' => entries),
@@ -113,13 +137,16 @@ end
if $PROGRAM_NAME == __FILE__ if $PROGRAM_NAME == __FILE__
begin begin
command, value = ARGV command, value, ref = ARGV
raise 'usage: release-metadata.rb validate VERSION | outputs TAG' unless ARGV.length == 2 arity = command == 'outputs' ? 2 : 3
raise 'usage: release-metadata.rb validate VERSION REF | tag-commit TAG REF | outputs TAG' unless ARGV.length == arity
case command case command
when 'validate' when 'validate'
value = ReleaseMetadata.version(value) value = ReleaseMetadata.validate_branch(value, ref)
ReleaseMetadata.validate_notes(value) ReleaseMetadata.validate_notes(value)
puts value puts value
when 'tag-commit'
puts ReleaseMetadata.tag_commit(value, ref)
when 'outputs' when 'outputs'
metadata = ReleaseMetadata.outputs(value) metadata = ReleaseMetadata.outputs(value)
ReleaseMetadata.seal_manifest(metadata) ReleaseMetadata.seal_manifest(metadata)
+50 -14
View File
@@ -11,6 +11,10 @@ on:
description: 'Recover the index for an already public release without rebuilding' description: 'Recover the index for an already public release without rebuilding'
type: boolean type: boolean
default: false default: false
recover_latest:
description: 'Recover latest and the channel index for an already public stable release'
type: boolean
default: false
permissions: permissions:
contents: read contents: read
@@ -25,7 +29,7 @@ env:
jobs: jobs:
release-info: release-info:
if: ${{ !inputs.index_only }} if: ${{ !inputs.index_only && !inputs.recover_latest }}
runs-on: ubuntu-26.04 runs-on: ubuntu-26.04
timeout-minutes: 10 timeout-minutes: 10
permissions: permissions:
@@ -34,7 +38,6 @@ jobs:
outputs: outputs:
tag: ${{ steps.version.outputs.tag }} tag: ${{ steps.version.outputs.tag }}
version: ${{ steps.version.outputs.version }} version: ${{ steps.version.outputs.version }}
docker_version: ${{ steps.version.outputs.docker_version }}
build_time: ${{ steps.version.outputs.build_time }} build_time: ${{ steps.version.outputs.build_time }}
git_sha: ${{ steps.version.outputs.git_sha }} git_sha: ${{ steps.version.outputs.git_sha }}
platform_matrix: ${{ steps.version.outputs.platform_matrix }} platform_matrix: ${{ steps.version.outputs.platform_matrix }}
@@ -53,9 +56,15 @@ jobs:
- name: Checkout - name: Checkout
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with: with:
ref: ${{ inputs.tag }}
fetch-depth: 0 fetch-depth: 0
- name: Verify release branch and check out the tagged commit
env:
RELEASE_TAG: ${{ inputs.tag }}
run: |
commit="$(ruby .github/scripts/release-metadata.rb tag-commit "$RELEASE_TAG" "$GITHUB_REF")"
git checkout --detach "$commit"
- name: Read release metadata and seal plugin manifest - name: Read release metadata and seal plugin manifest
id: version id: version
env: env:
@@ -273,7 +282,7 @@ jobs:
shell: bash shell: bash
env: env:
VERSION: ${{ needs.release-info.outputs.version }} VERSION: ${{ needs.release-info.outputs.version }}
DOCKER_VERSION: ${{ needs.release-info.outputs.docker_version }} DOCKER_VERSION: ${{ needs.release-info.outputs.version }}
PLATFORM_MATRIX: ${{ needs.release-info.outputs.platform_matrix }} PLATFORM_MATRIX: ${{ needs.release-info.outputs.platform_matrix }}
run: ruby .github/scripts/package-release.rb archives run: ruby .github/scripts/package-release.rb archives
@@ -443,6 +452,12 @@ jobs:
username: ${{ github.actor }} username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }} password: ${{ secrets.GITHUB_TOKEN }}
- name: Check that the release is unpublished
env:
GH_TOKEN: ${{ github.token }}
VERSION: ${{ needs.release-info.outputs.version }}
run: ruby .github/scripts/published-channels.rb check "$VERSION"
- name: Assemble candidate image manifest - name: Assemble candidate image manifest
id: manifest id: manifest
shell: bash shell: bash
@@ -507,6 +522,7 @@ jobs:
- name: Prepare release notes - name: Prepare release notes
shell: bash shell: bash
env: env:
BUILD_TYPE: ${{ needs.release-info.outputs.build_type }}
INSTALLATION_NOTES: | INSTALLATION_NOTES: |
## Linux 一键安装(Docker Compose) ## Linux 一键安装(Docker Compose)
@@ -521,17 +537,11 @@ jobs:
run: | run: |
ruby <<'RUBY' ruby <<'RUBY'
notes = File.readlines('release/notes.md').drop(1).join.strip notes = File.readlines('release/notes.md').drop(1).join.strip
installation = ENV.fetch('INSTALLATION_NOTES').strip notes += "\n\n#{ENV.fetch('INSTALLATION_NOTES').strip}" unless ENV.fetch('BUILD_TYPE') == 'experimental'
output = File.join(ENV.fetch('RUNNER_TEMP'), 'release-notes.md') output = File.join(ENV.fetch('RUNNER_TEMP'), 'release-notes.md')
File.write(output, "#{notes}\n\n#{installation}\n") File.write(output, "#{notes}\n")
RUBY RUBY
- name: Check that the release is unpublished
env:
GH_TOKEN: ${{ github.token }}
VERSION: ${{ needs.release-info.outputs.version }}
run: ruby .github/scripts/published-channels.rb check "$VERSION"
- name: Generate release asset provenance - name: Generate release asset provenance
uses: actions/attest@1e69f48acb82d1966a394da916b4c1698aa569d6 # v4.2.2 uses: actions/attest@1e69f48acb82d1966a394da916b4c1698aa569d6 # v4.2.2
with: with:
@@ -542,7 +552,7 @@ jobs:
uses: softprops/action-gh-release@8a0cd651e5b2365bd640854a3fa5dfc70e4875f3 # v3.0.4 uses: softprops/action-gh-release@8a0cd651e5b2365bd640854a3fa5dfc70e4875f3 # v3.0.4
with: with:
tag_name: ${{ needs.release-info.outputs.tag }} tag_name: ${{ needs.release-info.outputs.tag }}
generate_release_notes: true generate_release_notes: ${{ needs.release-info.outputs.build_type != 'experimental' }}
previous_tag: ${{ needs.release-info.outputs.previous_tag }} previous_tag: ${{ needs.release-info.outputs.previous_tag }}
prerelease: ${{ needs.release-info.outputs.prerelease == 'true' }} prerelease: ${{ needs.release-info.outputs.prerelease == 'true' }}
# action 保留已公开 Release 的状态,新 Release 上传完成后仍保持草稿 # action 保留已公开 Release 的状态,新 Release 上传完成后仍保持草稿
@@ -567,8 +577,34 @@ jobs:
VERSION: ${{ needs.release-info.outputs.version }} VERSION: ${{ needs.release-info.outputs.version }}
run: ruby .github/scripts/published-channels.rb publish "$VERSION" run: ruby .github/scripts/published-channels.rb publish "$VERSION"
recover-latest:
if: inputs.recover_latest
runs-on: ubuntu-26.04
concurrency:
group: release-publication
queue: max
permissions:
contents: write
packages: write
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
fetch-depth: 0
- uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1
- uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ github.token }}
- name: Restore latest from the verified version image
env:
GH_TOKEN: ${{ github.token }}
TAG: ${{ inputs.tag }}
run: ruby .github/scripts/publish-release.rb recover-latest
recover-index: recover-index:
if: inputs.index_only needs: recover-latest
if: ${{ !cancelled() && (needs.recover-latest.result == 'success' || (inputs.index_only && !inputs.recover_latest)) }}
runs-on: ubuntu-26.04 runs-on: ubuntu-26.04
concurrency: concurrency:
group: release-publication group: release-publication
+1
View File
@@ -1887,6 +1887,7 @@ dependencies = [
"tracing", "tracing",
"tracing-appender", "tracing-appender",
"tracing-subscriber", "tracing-subscriber",
"uuid",
"wiremock", "wiremock",
"yaml-rust2 0.13.2", "yaml-rust2 0.13.2",
] ]
@@ -263,10 +263,11 @@ impl ScheduledTask for FreezeRecoveryTask {
context: WorkerCycleContext, context: WorkerCycleContext,
) -> futures::future::BoxFuture<'_, Result<(), WorkerTaskError>> { ) -> futures::future::BoxFuture<'_, Result<(), WorkerTaskError>> {
Box::pin(async move { Box::pin(async move {
if context.cancellation().is_cancelled() { // 中止在途探测,避免把停机当成探测失败而延长冻结
return Ok(()); context
} .cancellation()
self.run_cycle_inner().await; .run_until_cancelled(self.run_cycle_inner())
.await;
Ok(()) Ok(())
}) })
} }
@@ -50,11 +50,13 @@ pub struct SystemUpdatePolicy {
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub struct SystemVersion { pub struct SystemVersion {
pub version: String, pub version: String,
pub instance_id: String,
pub restart_supported: bool,
pub git_sha: String, pub git_sha: String,
pub build_time: String, pub build_time: String,
pub deployment_mode: String, pub deployment_mode: String,
pub update_channel: String, pub update_channel: String,
pub latest_version: String, pub latest_version: Option<String>,
pub has_update: bool, pub has_update: bool,
pub update_cached: bool, pub update_cached: bool,
pub update_warning: Option<String>, pub update_warning: Option<String>,
@@ -67,7 +69,7 @@ pub struct SystemVersion {
pub struct SystemUpdateDetail { pub struct SystemUpdateDetail {
pub policy: SystemUpdatePolicy, pub policy: SystemUpdatePolicy,
pub current_version: String, pub current_version: String,
pub latest_version: String, pub latest_version: Option<String>,
pub has_update: bool, pub has_update: bool,
pub deployment_mode: String, pub deployment_mode: String,
pub build_type: String, pub build_type: String,
@@ -55,37 +55,44 @@ impl ScheduledTask for ResetCreditAutomationTask {
context: WorkerCycleContext, context: WorkerCycleContext,
) -> futures::future::BoxFuture<'_, Result<(), WorkerTaskError>> { ) -> futures::future::BoxFuture<'_, Result<(), WorkerTaskError>> {
Box::pin(async move { Box::pin(async move {
let settings = self context
.settings .cancellation()
.load_runtime_settings() .run_until_cancelled(self.run_due())
.await .await
.map_err(|_| WorkerTaskError::safe("重置卡设置读取失败"))?; .unwrap_or(Ok(()))
// 单轮有界,积压沿到期顺序继续;并发复用已有账号刷新配置
let due = self
.store
.due_reset_credit_automations(Utc::now(), 100)
.await
.map_err(|_| WorkerTaskError::safe("重置卡计划读取失败"))?;
let work = futures::stream::iter(due)
.map(|account_id| async move {
let id = ProviderAccountId::new(account_id.clone())
.map_err(|_| WorkerTaskError::safe("重置卡账号 ID 不合法"))?;
if let Err(error) = self.accounts.reconcile_reset_credit_automation(id).await {
tracing::warn!(
account_id,
error_kind = error.kind().as_str(),
"自动重置卡任务失败"
);
}
Ok::<_, WorkerTaskError>(())
})
.buffer_unordered(settings.values.refresh_concurrency.max(1) as usize)
.collect::<Vec<_>>();
tokio::select! {
() = context.cancellation().cancelled() => {},
_ = tokio::time::timeout(Duration::from_secs(30), work) => {},
}
Ok(())
}) })
} }
} }
impl ResetCreditAutomationTask {
async fn run_due(&self) -> Result<(), WorkerTaskError> {
let settings = self
.settings
.load_runtime_settings()
.await
.map_err(|_| WorkerTaskError::safe("重置卡设置读取失败"))?;
// 单轮有界,积压沿到期顺序继续;并发复用已有账号刷新配置
let due = self
.store
.due_reset_credit_automations(Utc::now(), 100)
.await
.map_err(|_| WorkerTaskError::safe("重置卡计划读取失败"))?;
let work = futures::stream::iter(due)
.map(|account_id| async move {
let id = ProviderAccountId::new(account_id.clone())
.map_err(|_| WorkerTaskError::safe("重置卡账号 ID 不合法"))?;
if let Err(error) = self.accounts.reconcile_reset_credit_automation(id).await {
tracing::warn!(
account_id,
error_kind = error.kind().as_str(),
"自动重置卡任务失败"
);
}
Ok::<_, WorkerTaskError>(())
})
.buffer_unordered(settings.values.refresh_concurrency.max(1) as usize)
.collect::<Vec<_>>();
let _ = tokio::time::timeout(Duration::from_secs(30), work).await;
Ok(())
}
}
@@ -4,7 +4,7 @@ mod flow;
use std::sync::Arc; use std::sync::Arc;
use gateway_core::{routing::ProviderKind, runtime::SnapshotControl}; use gateway_core::{account::ProviderAccountId, routing::ProviderKind, runtime::SnapshotControl};
use crate::{ use crate::{
model::AdminError, model::AdminError,
@@ -40,6 +40,20 @@ impl CredentialsService {
} }
} }
/// 已有账号的凭据操作按已保存的归属选择 Provider
pub async fn for_account(
&self,
account_id: &ProviderAccountId,
) -> Result<ProviderCredentials, AdminError> {
let account = self
.accounts
.load_account_record(account_id)
.await
.map_err(|error| super::map_store_error(error, "provider credentials"))?
.ok_or_else(|| AdminError::not_found("账号不存在"))?;
self.for_provider(&account.provider_kind)
}
pub fn for_provider(&self, kind: &ProviderKind) -> Result<ProviderCredentials, AdminError> { pub fn for_provider(&self, kind: &ProviderKind) -> Result<ProviderCredentials, AdminError> {
let provider = self let provider = self
.providers .providers
@@ -1,5 +1,108 @@
//! 按 Provider 组织凭据导入、授权与提交边界测试 //! 验证账号归属分派,并组织凭据导入、授权与提交边界测试
mod openai; mod openai;
mod peer; mod peer;
mod xai; mod xai;
use gateway_admin::model::{
AdminErrorKind,
provider_credentials::{CredentialMutation, RotateCredential},
};
use gateway_core::account::ProviderAccountId;
use super::{
AdminHarness,
accounts::{
FakeAccountStore, FakeProviderAdmin, account_record, context, document, events, recorded,
revision,
},
};
#[tokio::test]
async fn account_rotation_should_dispatch_by_saved_provider_for_each_authentication_kind() {
for kind in ["openai", "xai", "antigravity"] {
for authentication in ["oauth", "api_key"] {
let store_events = events();
let mut account = account_record(kind);
account.authentication_kind = authentication.to_owned();
if authentication == "api_key" {
account.upstream_user_id = None;
account.has_refresh_token = false;
account.access_token_expires_at = None;
account.next_refresh_at = None;
}
let account_id = ProviderAccountId::new(account.id.clone()).unwrap();
let store = FakeAccountStore::with_account(account, store_events.clone());
let mut harness = AdminHarness::new().accounts(store.clone());
let mut provider_events = Vec::new();
for registered_kind in ["openai", "xai", "antigravity"] {
let calls = events();
harness = harness.provider(FakeProviderAdmin::new(registered_kind, calls.clone()));
provider_events.push((registered_kind, calls));
}
let services = harness.build().await;
let result = services
.credentials()
.for_account(&account_id)
.await
.expect("select saved provider")
.rotate(RotateCredential {
mutation: CredentialMutation {
context: context("rotate-account-connection"),
account_id: account_id.clone(),
},
settings: None,
provider_material: document(),
})
.await
.expect("rotate selected account");
assert_eq!(result.account_id, account_id);
assert_eq!(result.credential_revision, Some(revision(2)));
assert_eq!(store.audit_requests(), ["rotate-account-connection"]);
assert_eq!(
recorded(&store_events),
[
"store.load_account_record",
"store.credential_details",
"store.commit_rotation",
]
);
for (registered_kind, calls) in provider_events {
let expected: &[&str] = if registered_kind == kind {
&[
"provider.prepare_rotation",
"guard.finish",
"provider.account_facts_changed",
]
} else {
&[]
};
assert_eq!(recorded(&calls), expected, "{kind}/{authentication}");
}
}
}
}
#[tokio::test]
async fn missing_account_should_stop_credential_dispatch_before_provider_or_store_mutation() {
let store_events = events();
let provider_events = events();
let store = FakeAccountStore::new("openai", store_events.clone());
let mut harness = AdminHarness::new().accounts(store.clone());
for kind in ["openai", "xai", "antigravity"] {
harness = harness.provider(FakeProviderAdmin::new(kind, provider_events.clone()));
}
let services = harness.build().await;
let error = services
.credentials()
.for_account(&ProviderAccountId::new("acct_missing").unwrap())
.await
.err()
.expect("missing account must fail before selecting a provider");
assert_eq!(error.kind(), AdminErrorKind::NotFound);
assert_eq!(recorded(&store_events), ["store.load_account_record"]);
assert!(recorded(&provider_events).is_empty());
assert!(store.audit_requests().is_empty());
}
@@ -27,12 +27,14 @@ impl SystemOperations for RecordingSystemOperations {
} }
Ok(SystemVersion { Ok(SystemVersion {
version: "1.0.0".to_owned(), version: "1.0.0".to_owned(),
instance_id: "test-instance".to_owned(),
restart_supported: false,
git_sha: "unknown".to_owned(), git_sha: "unknown".to_owned(),
build_time: "unknown".to_owned(), build_time: "unknown".to_owned(),
deployment_mode: "source".to_owned(), deployment_mode: "source".to_owned(),
update_channel: "stable".to_owned(), update_channel: "stable".to_owned(),
latest_version: "1.0.0".to_owned(), latest_version: None,
has_update: false, has_update: false,
update_cached: false, update_cached: false,
update_warning: None, update_warning: None,
@@ -50,7 +52,7 @@ impl SystemOperations for RecordingSystemOperations {
available_channels: vec![gateway_admin::model::system::SystemUpdateChannel::Stable], available_channels: vec![gateway_admin::model::system::SystemUpdateChannel::Stable],
}, },
current_version: "1.0.0".to_owned(), current_version: "1.0.0".to_owned(),
latest_version: "1.0.0".to_owned(), latest_version: None,
has_update: false, has_update: false,
deployment_mode: "source".to_owned(), deployment_mode: "source".to_owned(),
build_type: "source".to_owned(), build_type: "source".to_owned(),
@@ -288,13 +288,13 @@ impl UpdateAccountRequest {
} }
} }
/// 编辑 OpenAI 账号的连接设置;OAuth 仅接受传输方式 /// 连接字段由 Provider 按账号类型校验,未提供的选项不注入凭据文档
#[derive(Clone, Deserialize)] #[derive(Clone, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)] #[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct AccountConnectionUpdateRequest { pub struct AccountConnectionUpdateRequest {
pub protocol: Option<String>, pub protocol: Option<String>,
pub base_url: Option<String>, pub base_url: Option<String>,
pub transport: String, pub transport: Option<String>,
pub api_key: Option<String>, pub api_key: Option<String>,
} }
@@ -310,7 +310,11 @@ impl AccountConnectionUpdateRequest {
if let Some(base_url) = &self.base_url { if let Some(base_url) = &self.base_url {
require_text(base_url, 2048, "connection.baseUrl")?; require_text(base_url, 2048, "connection.baseUrl")?;
} }
if !matches!(self.transport.as_str(), "http" | "prefer_websocket") { if self
.transport
.as_deref()
.is_some_and(|transport| !matches!(transport, "http" | "prefer_websocket"))
{
return Err(WireValidationError::new("connection.transport")); return Err(WireValidationError::new("connection.transport"));
} }
if self.api_key.as_ref().is_some_and(|key| { if self.api_key.as_ref().is_some_and(|key| {
@@ -324,8 +328,10 @@ impl AccountConnectionUpdateRequest {
} }
fn into_document(self) -> ProviderDocument { fn into_document(self) -> ProviderDocument {
let mut material = let mut material = Map::new();
Map::from_iter([("transport".to_owned(), Value::String(self.transport))]); if let Some(transport) = self.transport {
material.insert("transport".to_owned(), Value::String(transport));
}
if let Some(protocol) = self.protocol { if let Some(protocol) = self.protocol {
material.insert("protocol".to_owned(), Value::String(protocol)); material.insert("protocol".to_owned(), Value::String(protocol));
} }
@@ -281,13 +281,13 @@ where
let (command, connection) = request.into_command().map_err(map_wire_error)?; let (command, connection) = request.into_command().map_err(map_wire_error)?;
let context = auth.context().mutation_context(); let context = auth.context().mutation_context();
let result = if let Some(provider_material) = connection { let result = if let Some(provider_material) = connection {
let provider = ProviderKind::new("openai").map_err(|_| AdminError::internal())?;
let account_id = ProviderAccountId::new(command.account_id.clone()) let account_id = ProviderAccountId::new(command.account_id.clone())
.map_err(|_| AdminError::internal())?; .map_err(|_| AdminError::internal())?;
let result = state let result = state
.admin_services() .admin_services()
.credentials() .credentials()
.for_provider(&provider) .for_account(&account_id)
.await
.map_err(map_service_error)? .map_err(map_service_error)?
.rotate(RotateCredential { .rotate(RotateCredential {
mutation: CredentialMutation { mutation: CredentialMutation {
@@ -81,12 +81,14 @@ impl UpdateRequest {
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
struct SystemVersionView { struct SystemVersionView {
version: String, version: String,
instance_id: String,
restart_supported: bool,
git_sha: String, git_sha: String,
build_time: String, build_time: String,
deployment_mode: String, deployment_mode: String,
deployment_mode_label: String, deployment_mode_label: String,
update_channel: String, update_channel: String,
latest_version: String, latest_version: Option<String>,
has_update: bool, has_update: bool,
update_cached: bool, update_cached: bool,
update_warning: Option<String>, update_warning: Option<String>,
@@ -97,6 +99,8 @@ impl From<SystemVersion> for SystemVersionView {
Self { Self {
deployment_mode_label: deployment_mode_label(&version.deployment_mode).to_owned(), deployment_mode_label: deployment_mode_label(&version.deployment_mode).to_owned(),
version: version.version, version: version.version,
instance_id: version.instance_id,
restart_supported: version.restart_supported,
git_sha: version.git_sha, git_sha: version.git_sha,
build_time: version.build_time, build_time: version.build_time,
deployment_mode: version.deployment_mode, deployment_mode: version.deployment_mode,
@@ -114,7 +118,7 @@ impl From<SystemVersion> for SystemVersionView {
struct SystemUpdateDetailView { struct SystemUpdateDetailView {
policy: SystemUpdatePolicy, policy: SystemUpdatePolicy,
current_version: String, current_version: String,
latest_version: String, latest_version: Option<String>,
has_update: bool, has_update: bool,
deployment_mode: String, deployment_mode: String,
deployment_mode_label: String, deployment_mode_label: String,
@@ -11,6 +11,7 @@ use gateway_core::{
error::ProviderErrorKind, error::ProviderErrorKind,
policy::{ClientVersionRejection, CodexClientKind}, policy::{ClientVersionRejection, CodexClientKind},
}; };
use gateway_protocol::http::preferred_response_request_id;
use serde_json::{Value, json}; use serde_json::{Value, json};
pub use gateway_core::engine::execution::gateway_error_from_engine; pub use gateway_core::engine::execution::gateway_error_from_engine;
@@ -109,27 +110,22 @@ pub fn model_not_found_response() -> (StatusCode, Json<Value>) {
) )
} }
/// 已提交的 Responses 流通过终止事件交付容量错误的等待头 /// 将上游实际给出的等待头交给客户端错误事件
pub(crate) fn capacity_retry_headers(error: &EngineError) -> serde_json::Map<String, Value> { pub(crate) fn upstream_retry_headers(error: &EngineError) -> serde_json::Map<String, Value> {
let mut headers = serde_json::Map::new(); let mut headers = Vec::new();
if let EngineError::Provider(provider) = error if let EngineError::Provider(provider) = error {
&& provider.kind() == ProviderErrorKind::UpstreamCapacityUnavailable provider.extend_client_retry_headers(&mut headers, &[]);
&& let Some(response) = provider.client_visible_upstream_response()
{
for header in response.headers() {
if (header.name().eq_ignore_ascii_case("retry-after")
|| header.name().eq_ignore_ascii_case("retry-after-ms"))
&& let Ok(value) = HeaderValue::from_bytes(header.value())
&& let Ok(value) = value.to_str()
{
headers.insert(
header.name().to_ascii_lowercase(),
Value::String(value.to_owned()),
);
}
}
} }
headers headers
.into_iter()
.filter_map(|header| {
let value = HeaderValue::from_bytes(header.value()).ok()?;
Some((
header.name().to_ascii_lowercase(),
Value::String(value.to_str().ok()?.to_owned()),
))
})
.collect()
} }
/// 在下游尚未提交时交付 Provider 的 HTTP 失败响应,并应用客户端容量恢复合同 /// 在下游尚未提交时交付 Provider 的 HTTP 失败响应,并应用客户端容量恢复合同
@@ -175,8 +171,8 @@ pub fn engine_error_response(error: &EngineError) -> Response {
}; };
response.headers_mut().append(name, value); response.headers_mut().append(name, value);
} }
if !response.headers().contains_key("x-request-id") if preferred_response_request_id(|name| response.headers().get(name)?.to_str().ok())
&& !response.headers().contains_key("x-oai-request-id") .is_none()
&& let Some(request_id) = error.upstream_request_id() && let Some(request_id) = error.upstream_request_id()
&& let Ok(value) = HeaderValue::from_str(request_id.as_str()) && let Ok(value) = HeaderValue::from_str(request_id.as_str())
{ {
@@ -665,7 +665,7 @@ fn engine_error_response_with_headers(
response_headers: &[ProviderResponseHeader], response_headers: &[ProviderResponseHeader],
) -> Response { ) -> Response {
let response = engine_error_response(error); let response = engine_error_response(error);
let failure_request_ids = ["x-request-id", "x-oai-request-id"] let failure_request_ids = gateway_protocol::http::RESPONSE_REQUEST_ID_HEADERS
.into_iter() .into_iter()
.flat_map(|name| { .flat_map(|name| {
response response
@@ -678,8 +678,9 @@ fn engine_error_response_with_headers(
.collect::<Vec<_>>(); .collect::<Vec<_>>();
// 失败后仍须交付已采集的 turn state;只隔离 opening 身份,不丢弃会话状态 // 失败后仍须交付已采集的 turn state;只隔离 opening 身份,不丢弃会话状态
let mut response = apply_provider_response_headers(response, response_headers); let mut response = apply_provider_response_headers(response, response_headers);
response.headers_mut().remove("x-request-id"); for name in gateway_protocol::http::RESPONSE_REQUEST_ID_HEADERS {
response.headers_mut().remove("x-oai-request-id"); response.headers_mut().remove(name);
}
for (name, value) in failure_request_ids { for (name, value) in failure_request_ids {
response.headers_mut().append(name, value); response.headers_mut().append(name, value);
} }
@@ -832,7 +833,7 @@ impl StreamingExecutionBody {
Err(error) if self.committed => { Err(error) if self.committed => {
self.push_stream_error( self.push_stream_error(
gateway_error_from_engine(&error), gateway_error_from_engine(&error),
crate::data_plane::error::capacity_retry_headers(&error), crate::data_plane::error::upstream_retry_headers(&error),
); );
continue; continue;
} }
@@ -113,15 +113,9 @@ async fn stream_failure(
error_encoder: Option<fn(&Value) -> Bytes>, error_encoder: Option<fn(&Value) -> Bytes>,
append_done: bool, append_done: bool,
) -> Body { ) -> Body {
let status = response.status(); let (parts, body) = response.into_parts();
let retry_after = response let status = parts.status;
.headers() let bytes = to_bytes(body, usize::MAX).await.unwrap_or_default();
.get(header::RETRY_AFTER)
.and_then(|value| value.to_str().ok())
.map(ToOwned::to_owned);
let bytes = to_bytes(response.into_body(), usize::MAX)
.await
.unwrap_or_default();
let json = serde_json::from_slice::<Value>(&bytes).ok(); let json = serde_json::from_slice::<Value>(&bytes).ok();
let raw_message = std::str::from_utf8(&bytes) let raw_message = std::str::from_utf8(&bytes)
.ok() .ok()
@@ -144,16 +138,20 @@ async fn stream_failure(
) )
}); });
// HTTP 头已提交,按官方 SSE 错误合同保留允许下发的重试建议 // HTTP 头已提交,按官方 SSE 错误合同保留允许下发的重试建议
if let Some(retry_after) = retry_after for name in gateway_protocol::http::RETRY_AFTER_HEADERS {
&& let Some(error) = data["response"]["error"].as_object_mut() if let Some(value) = parts
&& let Some(headers) = error .headers
.entry("headers") .get(name)
.or_insert_with(|| serde_json::json!({})) .and_then(|value| value.to_str().ok())
.as_object_mut() && let Some(error) = data["response"]["error"].as_object_mut()
{ && let Some(headers) = error
headers .entry("headers")
.entry("retry-after") .or_insert_with(|| serde_json::json!({}))
.or_insert(Value::String(retry_after)); .as_object_mut()
&& !headers.keys().any(|key| key.eq_ignore_ascii_case(name))
{
headers.insert(name.to_owned(), Value::String(value.to_owned()));
}
} }
let mut event = match error_encoder { let mut event = match error_encoder {
Some(encode) => encode(&data).to_vec(), Some(encode) => encode(&data).to_vec(),
@@ -37,11 +37,11 @@ pub(crate) fn with_model_request_id(
let usable = |value: &HeaderValue| value.to_str().is_ok_and(|id| !id.trim().is_empty()); let usable = |value: &HeaderValue| value.to_str().is_ok_and(|id| !id.trim().is_empty());
if !headers.get("x-request-id").is_some_and(usable) { if !headers.get("x-request-id").is_some_and(usable) {
// 只有别名时沿用同一个上游值,避免外层 middleware 再填入入口 ID // 只有别名时沿用同一个上游值,避免外层 middleware 再填入入口 ID
let client_id = headers let client_id = gateway_protocol::http::preferred_response_request_id(|name| {
.get("x-oai-request-id") headers.get(name)?.to_str().ok()
.filter(|value| usable(value)) })
.unwrap_or(&gateway_id) .and_then(|value| HeaderValue::from_str(value).ok())
.clone(); .unwrap_or_else(|| gateway_id.clone());
headers.insert("x-request-id", client_id); headers.insert("x-request-id", client_id);
} }
headers.insert("x-gateway-request-id", gateway_id); headers.insert("x-gateway-request-id", gateway_id);
@@ -7,6 +7,7 @@ use crate::{
auth::{ClientKeyHeaders, authenticate_client, client_access_error_response}, auth::{ClientKeyHeaders, authenticate_client, client_access_error_response},
error::gateway_error_response, error::gateway_error_response,
generation::{GenerationEndpoint, GenerationHttpRequest, execute_prepared_generation}, generation::{GenerationEndpoint, GenerationHttpRequest, execute_prepared_generation},
router::IngressStarted,
}, },
}; };
use axum::{ use axum::{
@@ -15,18 +16,43 @@ use axum::{
http::{HeaderMap, StatusCode}, http::{HeaderMap, StatusCode},
response::Response, response::Response,
}; };
use std::net::SocketAddr; use std::{net::SocketAddr, time::Instant};
/// `POST /v1/responses` /// `POST /v1/responses`
pub(crate) async fn responses( pub(crate) async fn responses(
State(state): State<ApiState>, State(state): State<ApiState>,
connect_info: Option<Extension<ConnectInfo<SocketAddr>>>, connect_info: Option<Extension<ConnectInfo<SocketAddr>>>,
ingress_id: Option<Extension<tower_http::request_id::RequestId>>, ingress_id: Option<Extension<tower_http::request_id::RequestId>>,
ingress_started: Option<Extension<IngressStarted>>,
headers: HeaderMap, headers: HeaderMap,
body: Bytes, body: Bytes,
) -> Response { ) -> Response {
// Bytes extractor 已读完传输正文;此时尚未认证、解压或解析 JSON
let mut encodings = headers.get_all(axum::http::header::CONTENT_ENCODING).iter();
let encoding = match (encodings.next(), encodings.next()) {
(None, _) => "identity",
(Some(value), None) => value
.to_str()
.ok()
.and_then(|value| {
["identity", "gzip", "deflate", "zstd"]
.into_iter()
.find(|known| known.eq_ignore_ascii_case(value.trim()))
})
.unwrap_or("other"),
_ => "other",
};
tracing::info!(target: "request_trace", stage = "http.body.received",
receive_ms = ingress_started.map(|Extension(start)| start.0.elapsed().as_millis()),
encoded_bytes = body.len(), content_encoding = encoding,
"HTTP request body received");
let service = state.data_plane().clone(); let service = state.data_plane().clone();
let client = match authenticate_client(&service, &headers, ClientKeyHeaders::Bearer).await { let started = Instant::now();
let authentication = authenticate_client(&service, &headers, ClientKeyHeaders::Bearer).await;
tracing::info!(target: "request_trace", stage = "http.auth.finished",
auth_ms = started.elapsed().as_millis(), accepted = authentication.is_ok(),
"HTTP request authentication finished");
let client = match authentication {
Ok(client) => client, Ok(client) => client,
Err(error) => return client_access_error_response(error), Err(error) => return client_access_error_response(error),
}; };
@@ -42,7 +68,12 @@ pub(crate) async fn responses(
} }
}; };
let execution = service.execution(); let execution = service.execution();
let prepared = match execution.prepare_execution(client).await { let started = Instant::now();
let preparation = execution.prepare_execution(client).await;
tracing::info!(target: "request_trace", stage = "http.execution.prepared",
prepare_ms = started.elapsed().as_millis(), accepted = preparation.is_ok(),
"HTTP execution preparation finished");
let prepared = match preparation {
Ok(prepared) => prepared, Ok(prepared) => prepared,
Err(error) => return gateway_error_response(&error), Err(error) => return gateway_error_response(&error),
}; };
@@ -143,9 +143,20 @@ pub(crate) fn decode_request_with_body(
headers: &HeaderMap, headers: &HeaderMap,
max_decompressed_bytes: usize, max_decompressed_bytes: usize,
) -> Result<(DecodedGenerationRequest, Bytes), RequestDecodeError> { ) -> Result<(DecodedGenerationRequest, Bytes), RequestDecodeError> {
let body = decompress_request_body(body, headers, max_decompressed_bytes)?; let started = std::time::Instant::now();
let decoded = decode_request_inner(&body, &OpenAiRequestHeaders::from_headers(headers))?; let decompressed = decompress_request_body(body, headers, max_decompressed_bytes);
Ok((decoded, Bytes::copy_from_slice(&body))) tracing::info!(target: "request_trace", stage = "http.body.decompressed",
decompress_ms = started.elapsed().as_millis(),
decoded_bytes = decompressed.as_ref().ok().map(|body| body.len()),
accepted = decompressed.is_ok(), "HTTP request body decompressed");
let body = decompressed?;
let started = std::time::Instant::now();
let decoded = decode_request_inner(&body, &OpenAiRequestHeaders::from_headers(headers))
.map(|decoded| (decoded, Bytes::copy_from_slice(&body)));
tracing::info!(target: "request_trace", stage = "http.body.decoded",
decode_ms = started.elapsed().as_millis(), accepted = decoded.is_ok(),
"HTTP request body decoded");
decoded
} }
pub(super) fn decode_request_inner( pub(super) fn decode_request_inner(
@@ -577,7 +577,7 @@ impl WebSocketExecutionBody {
Err(error) if self.committed => { Err(error) if self.committed => {
self.push_gateway_error( self.push_gateway_error(
gateway_error_from_engine(&error), gateway_error_from_engine(&error),
crate::data_plane::error::capacity_retry_headers(&error), crate::data_plane::error::upstream_retry_headers(&error),
); );
continue; continue;
} }
@@ -8,6 +8,7 @@ use axum::http::{HeaderName, HeaderValue, StatusCode};
use gateway_core::engine::EngineError; use gateway_core::engine::EngineError;
use gateway_core::error::ProviderErrorKind; use gateway_core::error::ProviderErrorKind;
use gateway_core::event::ProviderResponseHeader; use gateway_core::event::ProviderResponseHeader;
use gateway_protocol::http::{RESPONSE_REQUEST_ID_HEADERS, preferred_response_request_id};
use serde_json::{Map, Value, json}; use serde_json::{Map, Value, json};
use thiserror::Error; use thiserror::Error;
@@ -119,9 +120,12 @@ pub(super) fn response_metadata_event(
response_headers: &[ProviderResponseHeader], response_headers: &[ProviderResponseHeader],
) -> String { ) -> String {
let mut headers = response_event_headers(response_headers); let mut headers = response_event_headers(response_headers);
let client_request_id = preferred_response_request_id(|name| headers.get(name)?.as_str())
.unwrap_or(request_id)
.to_owned();
headers headers
.entry("x-request-id".to_owned()) .entry("x-request-id".to_owned())
.or_insert_with(|| Value::String(request_id.to_owned())); .or_insert(Value::String(client_request_id));
json!({ json!({
"type": "response.metadata", "type": "response.metadata",
"headers": headers, "headers": headers,
@@ -149,7 +153,7 @@ fn response_event_headers(response_headers: &[ProviderResponseHeader]) -> Map<St
let Ok(value) = std::str::from_utf8(header.value()) else { let Ok(value) = std::str::from_utf8(header.value()) else {
continue; continue;
}; };
if matches!(name.as_str(), "x-request-id" | "x-oai-request-id") if RESPONSE_REQUEST_ID_HEADERS.contains(&name.as_str())
&& (value.trim().is_empty() || http_value.to_str().is_err()) && (value.trim().is_empty() || http_value.to_str().is_err())
{ {
continue; continue;
@@ -173,12 +177,18 @@ pub(super) fn initial_engine_error_event(
}; };
let upstream = provider.and_then(|error| error.client_visible_upstream_response()); let upstream = provider.and_then(|error| error.client_visible_upstream_response());
// 最终失败响应优先于会话快照,避免混入先前 attempt 或 opening 的关联头 // 最终失败响应优先于会话快照,避免混入先前 attempt 或 opening 的关联头
let mut headers = let mut headers = if let Some((provider, response)) = provider.zip(upstream) {
response_event_headers(upstream.map_or(response_headers, |response| response.headers())); let mut headers = response.headers().to_vec();
provider.extend_client_retry_headers(&mut headers, &[]);
response_event_headers(&headers)
} else {
response_event_headers(response_headers)
};
if upstream.is_none() { if upstream.is_none() {
// 会话 opening 身份不证明当前失败属于该请求;仅保留其他允许的会话头 // 会话 opening 身份不证明当前失败属于该请求;仅保留其他允许的会话头
headers.remove("x-request-id"); for name in RESPONSE_REQUEST_ID_HEADERS {
headers.remove("x-oai-request-id"); headers.remove(name);
}
} }
let status = if provider let status = if provider
.is_some_and(|error| error.kind() == ProviderErrorKind::UpstreamCapacityUnavailable) .is_some_and(|error| error.kind() == ProviderErrorKind::UpstreamCapacityUnavailable)
@@ -216,7 +226,7 @@ pub(super) fn initial_engine_error_event(
} }
fn has_request_id(headers: &Map<String, Value>) -> bool { fn has_request_id(headers: &Map<String, Value>) -> bool {
headers.contains_key("x-request-id") || headers.contains_key("x-oai-request-id") preferred_response_request_id(|name| headers.get(name)?.as_str()).is_some()
} }
pub(super) fn error_event( pub(super) fn error_event(
@@ -46,6 +46,10 @@ pub(crate) fn router() -> Router<ApiState> {
.merge(super::provider_endpoints::router()) .merge(super::provider_endpoints::router())
} }
/// 在读取正文前保存入口时刻,交给端点区分接收与执行耗时
#[derive(Clone, Copy)]
pub(crate) struct IngressStarted(pub(crate) std::time::Instant);
#[derive(Clone, Copy)] #[derive(Clone, Copy)]
pub(crate) enum DataPlaneNamespace { pub(crate) enum DataPlaneNamespace {
V1, V1,
@@ -19,7 +19,7 @@ use serde_json::json;
use tower_http::request_id::RequestId; use tower_http::request_id::RequestId;
use crate::client_error::{AccessRejection, ProtocolErrorBody}; use crate::client_error::{AccessRejection, ProtocolErrorBody};
use crate::data_plane::router::DataPlaneNamespace; use crate::data_plane::router::{DataPlaneNamespace, IngressStarted};
pub(crate) async fn record_ingress( pub(crate) async fn record_ingress(
State(diagnostics): State<Arc<dyn OperationalDiagnostics>>, State(diagnostics): State<Arc<dyn OperationalDiagnostics>>,
@@ -29,6 +29,9 @@ pub(crate) async fn record_ingress(
let Some(namespace) = DataPlaneNamespace::for_path(request.uri().path()) else { let Some(namespace) = DataPlaneNamespace::for_path(request.uri().path()) else {
return next.run(request).await; return next.run(request).await;
}; };
request
.extensions_mut()
.insert(IngressStarted(std::time::Instant::now()));
let correlation_id = request let correlation_id = request
.extensions() .extensions()
.get::<RequestId>() .get::<RequestId>()
@@ -639,14 +639,22 @@ async fn connection_update_requires_admin_and_validates_before_calling_the_servi
"connection":{"baseUrl":"https://api.example.invalid/v1", "transport":"http"} "connection":{"baseUrl":"https://api.example.invalid/v1", "transport":"http"}
}); });
for (authenticated, transport, oauth, expected) in [ for (authenticated, transport, oauth, expected) in [
(false, "http", false, StatusCode::UNAUTHORIZED), (false, Some("http"), false, StatusCode::UNAUTHORIZED),
(true, "invalid", false, StatusCode::BAD_REQUEST), (true, Some("invalid"), false, StatusCode::BAD_REQUEST),
// 夹具没有凭据 Store,合法输入必须进入服务,不能按普通设置静默保存 // 夹具没有凭据 Store,合法输入必须进入服务,不能按普通设置静默保存
(true, "http", false, StatusCode::SERVICE_UNAVAILABLE), (true, Some("http"), false, StatusCode::SERVICE_UNAVAILABLE),
(true, "http", true, StatusCode::SERVICE_UNAVAILABLE), (true, Some("http"), true, StatusCode::SERVICE_UNAVAILABLE),
(true, None, false, StatusCode::SERVICE_UNAVAILABLE),
] { ] {
let mut input = input.clone(); let mut input = input.clone();
input["connection"]["transport"] = serde_json::json!(transport); if let Some(transport) = transport {
input["connection"]["transport"] = serde_json::json!(transport);
} else {
input["connection"]
.as_object_mut()
.unwrap()
.remove("transport");
}
if oauth { if oauth {
input["connection"] input["connection"]
.as_object_mut() .as_object_mut()
@@ -724,6 +724,20 @@ mod actions {
); );
} }
#[test]
fn native_api_key_connection_accepts_address_and_key_without_transport() {
let request: UpdateAccountRequest = serde_json::from_value(json!({
"accountId":"acct_api", "enabled":true, "concurrencyLimit":null,
"weight":1, "groupIds":[],
"connection":{"baseUrl":"https://relay.example/antigravity/v1beta","apiKey":"fixture-key"}
})).unwrap();
request.validate().unwrap();
let connection = request.connection.unwrap();
assert!(connection.protocol.is_none());
assert!(connection.transport.is_none());
assert_eq!(connection.api_key.as_deref(), Some("fixture-key"));
}
#[test] #[test]
fn account_connection_update_rejects_invalid_fields_and_generic_credentials() { fn account_connection_update_rejects_invalid_fields_and_generic_credentials() {
let request = json!({ let request = json!({
@@ -24,6 +24,27 @@ use tower::ServiceExt as _;
use super::{AdminTestFixture, AdminTestState, unavailable_system}; use super::{AdminTestFixture, AdminTestState, unavailable_system};
#[tokio::test]
async fn version_should_expose_runtime_identity_and_restart_capability() {
let fixture = crate::support::key_fixture().await;
fixture.auth.insert_session("valid-session");
let response = app(fixture.state())
.oneshot(
Request::builder()
.uri("/api/admin/system/version")
.header(header::COOKIE, "cpr_session=valid-session")
.header("x-request-id", "req_system_version")
.body(Body::empty())
.expect("version request"),
)
.await
.expect("version response");
assert_eq!(response.status(), StatusCode::OK);
let body = crate::support::response_json(response).await;
assert_eq!(body["data"]["instanceId"], "test-instance");
assert_eq!(body["data"]["restartSupported"], true);
}
#[test] #[test]
fn update_detail_query_should_default_to_no_refresh_and_reject_unknown_fields() { fn update_detail_query_should_default_to_no_refresh_and_reject_unknown_fields() {
let query: UpdateDetailQuery = serde_json::from_str("{}").expect("empty query object"); let query: UpdateDetailQuery = serde_json::from_str("{}").expect("empty query object");
@@ -216,7 +237,7 @@ impl SystemOperations for ProgressSystem {
available_channels: vec![SystemUpdateChannel::Stable, SystemUpdateChannel::Beta], available_channels: vec![SystemUpdateChannel::Stable, SystemUpdateChannel::Beta],
}, },
current_version: "0.1.0".into(), current_version: "0.1.0".into(),
latest_version: "0.2.0".into(), latest_version: Some("0.2.0".into()),
has_update: true, has_update: true,
deployment_mode: "docker".into(), deployment_mode: "docker".into(),
build_type: "release".into(), build_type: "release".into(),
@@ -256,12 +256,20 @@ async fn request_middleware_sees_original_chat_and_preserves_the_endpoint() {
let mut execution = Execution::new(Session::new(vec![created(), completed("ok")])); let mut execution = Execution::new(Session::new(vec![created(), completed("ok")]));
execution.middleware = Some(middleware.frozen()); execution.middleware = Some(middleware.frozen());
let fixture = Fixture::with_execution(execution).await; let fixture = Fixture::with_execution(execution).await;
let response = fixture.post(chat_request(false)).await; let mut request = chat_request(false);
request["stream_options"] = json!({"include_usage":true});
request["messages"] = json!([
{"role":"developer","content":"brief"},
{"role":"system","content":null},
{"role":"assistant","tool_calls":[]},
{"role":"user","content":[{"type":"text","text":null},{"type":"text","text":"hello"}]}
]);
let response = fixture.post(request.clone()).await;
assert_eq!(response.status(), StatusCode::OK); assert_eq!(response.status(), StatusCode::OK);
let downstream = json_body(response).await; let downstream = json_body(response).await;
assert_eq!(downstream["object"], "chat.completion"); assert_eq!(downstream["object"], "chat.completion");
let observed = middleware.requests.lock().unwrap(); let observed = middleware.requests.lock().unwrap();
assert_eq!(observed.as_slice(), [chat_request(false)]); assert_eq!(observed.as_slice(), [request]);
assert_eq!( assert_eq!(
middleware.inner.endpoints.lock().unwrap().as_slice(), middleware.inner.endpoints.lock().unwrap().as_slice(),
[PATH] [PATH]
@@ -396,16 +396,16 @@ fn local_provider_capacity_exhaustion_should_map_to_service_unavailable() {
); );
assert_eq!( assert_eq!(
projected.safe_message(), projected.safe_message(),
"The gateway account pool is busy." "No eligible account currently has capacity for this request."
); );
} }
#[test] #[tokio::test]
fn no_eligible_provider_account_should_preserve_safe_provider_detail() { async fn no_eligible_provider_account_should_preserve_safe_provider_detail() {
let detail = ClientVisibleUpstreamError::new( let detail = ClientVisibleUpstreamError::new(
"no account is eligible for the requested model", "This request requires an upstream WebSocket.",
Some("no_eligible_account".to_owned()), Some("websocket_account_unavailable".to_owned()),
Some("account_unavailable_error".to_owned()), None,
); );
let error = EngineError::Provider( let error = EngineError::Provider(
ProviderError::new( ProviderError::new(
@@ -419,17 +419,24 @@ fn no_eligible_provider_account_should_preserve_safe_provider_detail() {
assert_eq!(gateway.kind(), GatewayErrorKind::NoAvailableProvider); assert_eq!(gateway.kind(), GatewayErrorKind::NoAvailableProvider);
assert_eq!( assert_eq!(
gateway.client_message(), gateway.client_message(),
"no account is eligible for the requested model" "This request requires an upstream WebSocket."
); );
assert_eq!(gateway.client_error_code(), Some("no_eligible_account"));
assert_eq!( assert_eq!(
gateway.client_error_type(), gateway.client_error_code(),
Some("account_unavailable_error") Some("websocket_account_unavailable")
); );
assert_eq!(gateway.client_error_type(), None);
assert_eq!( assert_eq!(
gateway.safe_message(), gateway.safe_message(),
"The gateway found no eligible account for this request." "The gateway found no eligible account for this request."
); );
let response = engine_error_response(&error);
assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
let body: serde_json::Value =
serde_json::from_slice(&to_bytes(response.into_body(), usize::MAX).await.unwrap()).unwrap();
assert_eq!(body["error"]["type"], "server_error");
assert_eq!(body["error"]["code"], "websocket_account_unavailable");
assert_eq!(body["error"]["message"], gateway.client_message());
} }
#[test] #[test]
@@ -508,6 +515,7 @@ fn engine_provider_unsupported_capability_should_remain_unsupported() {
#[test] #[test]
fn engine_provider_credential_failures_should_not_impersonate_client_auth_failures() { fn engine_provider_credential_failures_should_not_impersonate_client_auth_failures() {
let mut messages = std::collections::HashSet::new();
for kind in [ for kind in [
ProviderErrorKind::Unauthorized, ProviderErrorKind::Unauthorized,
ProviderErrorKind::PermissionDenied, ProviderErrorKind::PermissionDenied,
@@ -516,11 +524,19 @@ fn engine_provider_credential_failures_should_not_impersonate_client_auth_failur
let mapped = gateway_error_from_engine(&error); let mapped = gateway_error_from_engine(&error);
assert_eq!(mapped.kind(), GatewayErrorKind::UpstreamUnavailable); assert_eq!(mapped.kind(), GatewayErrorKind::UpstreamUnavailable);
assert_eq!( assert!(
mapped.safe_message(), mapped
"The upstream account cannot access the service." .safe_message()
.to_lowercase()
.contains("upstream account")
); );
messages.insert(mapped.safe_message().to_owned());
} }
assert_eq!(
messages.len(),
2,
"authentication and permission failures must be distinguishable"
);
} }
#[test] #[test]
@@ -577,19 +593,29 @@ fn engine_provider_timeout_and_cancellation_should_remain_distinct() {
} }
#[test] #[test]
fn engine_provider_runtime_failures_should_collapse_to_safe_unavailability() { fn engine_provider_runtime_failures_preserve_the_cause_without_exposing_internal_details() {
let mut messages = std::collections::HashSet::new();
for kind in [ for kind in [
ProviderErrorKind::Transport, ProviderErrorKind::Transport,
ProviderErrorKind::Protocol, ProviderErrorKind::Protocol,
ProviderErrorKind::Unavailable, ProviderErrorKind::Unavailable,
ProviderErrorKind::ProcessTerminated, ProviderErrorKind::ProcessTerminated,
] { ] {
let error = EngineError::Provider(ProviderError::new(kind, UpstreamSendState::Ambiguous)); let error = EngineError::Provider(
ProviderError::new(kind, UpstreamSendState::Ambiguous)
.with_source(std::io::Error::other("PRIVATE_ENDPOINT_AND_CREDENTIAL")),
);
let projected = gateway_error_from_engine(&error); let projected = gateway_error_from_engine(&error);
assert_eq!(projected.kind(), GatewayErrorKind::UpstreamUnavailable); assert_eq!(projected.kind(), GatewayErrorKind::UpstreamUnavailable);
assert_eq!(projected.safe_message(), "Upstream service is unavailable."); assert!(!projected.client_message().contains("PRIVATE_"));
messages.insert(projected.client_message().to_owned());
} }
assert_eq!(
messages.len(),
4,
"different failure causes must remain distinguishable"
);
} }
#[test] #[test]
@@ -334,7 +334,7 @@ async fn request_settings_reach_query_terminal_without_mutating_authenticated_ba
runtime["account_queue_timeout_seconds"] = serde_json::json!(30); runtime["account_queue_timeout_seconds"] = serde_json::json!(30);
runtime["switch_account_on_queue_failure"] = serde_json::json!(false); runtime["switch_account_on_queue_failure"] = serde_json::json!(false);
settings.runtime = serde_json::from_value(runtime).unwrap(); settings.runtime = serde_json::from_value(runtime).unwrap();
settings.fast_mode = FastMode::Disabled; settings.fast_mode = Some(FastMode::Disabled);
}), }),
..Default::default() ..Default::default()
})); }));
@@ -355,8 +355,12 @@ async fn request_settings_reach_query_terminal_without_mutating_authenticated_ba
"model-a" "model-a"
); );
assert_ne!( assert_ne!(
execution.client.policy().account_scope().fast_mode(), execution
FastMode::Disabled .client
.policy()
.account_scope()
.fast_mode_override(),
Some(FastMode::Disabled)
); );
} }
} }
@@ -1416,7 +1416,7 @@ async fn streaming_bad_request_preserves_extended_error_fields_before_and_after_
Some(b"application/json".to_vec()), Some(b"application/json".to_vec()),
Bytes::from(json!({"error": error}).to_string()), Bytes::from(json!({"error": error}).to_string()),
) )
.with_headers(headers(&[("retry-after", "7")])), .with_headers(headers(&[("retry-after", "7"), ("retry-after-ms", "7012")])),
) )
}; };
let immediate = FakeSession::streaming( let immediate = FakeSession::streaming(
@@ -1447,7 +1447,7 @@ async fn streaming_bad_request_preserves_extended_error_fields_before_and_after_
.find(|event| event.event.as_deref() == Some("response.failed")) .find(|event| event.event.as_deref() == Some("response.failed"))
.unwrap(); .unwrap();
let payload: Value = serde_json::from_str(&failed.data).unwrap(); let payload: Value = serde_json::from_str(&failed.data).unwrap();
error["headers"] = json!({"retry-after": "7"}); error["headers"] = json!({"retry-after": "7", "retry-after-ms":"7012"});
assert_eq!(payload["response"]["error"], error); assert_eq!(payload["response"]["error"], error);
assert!(bytes.ends_with(b"data: [DONE]\n\n")); assert!(bytes.ends_with(b"data: [DONE]\n\n"));
} }
@@ -2340,29 +2340,38 @@ async fn streaming_upstream_error_event_should_be_translated_to_response_failed_
} }
#[tokio::test] #[tokio::test]
async fn streaming_capacity_error_after_commit_offers_client_retry() { async fn streaming_errors_after_commit_preserve_upstream_retry_headers() {
for (code, expected) in [ for (kind, code, expected) in [
("server_is_overloaded", "server_error"), (
("slow_down", "server_error"), ProviderErrorKind::UpstreamCapacityUnavailable,
("previous_response_not_found", "previous_response_not_found"), "server_is_overloaded",
"server_error",
),
(
ProviderErrorKind::UpstreamCapacityUnavailable,
"slow_down",
"server_error",
),
(
ProviderErrorKind::QuotaExhausted,
"previous_response_not_found",
"previous_response_not_found",
),
] { ] {
let trace = Arc::new(Trace::default()); let trace = Arc::new(Trace::default());
let error = ProviderError::new( let error = ProviderError::new(kind, UpstreamSendState::Sent)
ProviderErrorKind::UpstreamCapacityUnavailable, .with_client_visible_upstream_response(
UpstreamSendState::Sent, ClientVisibleUpstreamResponse::new(400, None, Bytes::new()).with_headers(vec![
) ProviderResponseHeader::new("Retry-After", Bytes::from_static(b"309")),
.with_client_visible_upstream_response( ProviderResponseHeader::new("retry-after-ms", Bytes::from_static(b"309001")),
ClientVisibleUpstreamResponse::new(400, None, Bytes::new()).with_headers(vec![ ProviderResponseHeader::new("x-unrelated", Bytes::from_static(b"omit")),
ProviderResponseHeader::new("Retry-After", Bytes::from_static(b"309")), ]),
ProviderResponseHeader::new("retry-after-ms", Bytes::from_static(b"309001")), )
ProviderResponseHeader::new("x-unrelated", Bytes::from_static(b"omit")), .with_client_visible_upstream_error(ClientVisibleUpstreamError::new(
]), "busy",
) Some(code.to_owned()),
.with_client_visible_upstream_error(ClientVisibleUpstreamError::new( Some("service_unavailable_error".to_owned()),
"busy", ));
Some(code.to_owned()),
Some("service_unavailable_error".to_owned()),
));
let session = FakeSession::streaming( let session = FakeSession::streaming(
Arc::clone(&trace), Arc::clone(&trace),
vec![ vec![
@@ -3291,6 +3300,12 @@ async fn response_ids_are_provider_and_client_independent() {
(&[], MODEL_REQUEST_ID), (&[], MODEL_REQUEST_ID),
(&[("x-request-id", "upstream-primary")], "upstream-primary"), (&[("x-request-id", "upstream-primary")], "upstream-primary"),
(&[("x-oai-request-id", "upstream-alias")], "upstream-alias"), (&[("x-oai-request-id", "upstream-alias")], "upstream-alias"),
(
&[("x-openai-request-id", "upstream-openai")],
"upstream-openai",
),
(&[("x-ms-request-id", "upstream-ms")], "upstream-ms"),
(&[("cf-ray", "trace-only")], MODEL_REQUEST_ID),
( (
&[ &[
("x-request-id", "upstream-primary"), ("x-request-id", "upstream-primary"),
@@ -3306,6 +3321,22 @@ async fn response_ids_are_provider_and_client_independent() {
"upstream-alias", "upstream-alias",
), ),
(&[("x-request-id", "")], MODEL_REQUEST_ID), (&[("x-request-id", "")], MODEL_REQUEST_ID),
(
&[
("x-request-id", "é"),
("x-oai-request-id", " "),
("x-openai-request-id", ""),
("x-ms-request-id", "upstream-ms"),
],
"upstream-ms",
),
(
&[
("x-openai-request-id", "upstream-openai"),
("x-ms-request-id", "upstream-ms"),
],
"upstream-openai",
),
]; ];
for provider in ["openai", "xai"] { for provider in ["openai", "xai"] {
for streaming in [false, true] { for streaming in [false, true] {
@@ -3334,6 +3365,11 @@ async fn response_ids_are_provider_and_client_independent() {
assert_eq!(response.status(), StatusCode::OK); assert_eq!(response.status(), StatusCode::OK);
assert_eq!(response.headers()["x-request-id"], *expected); assert_eq!(response.headers()["x-request-id"], *expected);
assert_eq!(response.headers()["x-gateway-request-id"], MODEL_REQUEST_ID); assert_eq!(response.headers()["x-gateway-request-id"], MODEL_REQUEST_ID);
for (name, value) in *upstream_headers {
if *name != "x-request-id" {
assert_eq!(response.headers()[*name].as_bytes(), value.as_bytes());
}
}
assert!( assert!(
!to_bytes(response.into_body(), 64 * 1024) !to_bytes(response.into_body(), 64 * 1024)
.await .await
@@ -3350,7 +3386,12 @@ async fn failure_ids_prefer_the_actual_error_over_session_headers() {
let admin = crate::admin::AdminTestFixture::new().await.services; let admin = crate::admin::AdminTestFixture::new().await.services;
for provider in ["openai", "xai"] { for provider in ["openai", "xai"] {
for streaming in [false, true] { for streaming in [false, true] {
for upstream_headers in [vec![], headers(&[("x-oai-request-id", "actual-error")])] { for upstream_headers in [
vec![],
headers(&[("x-oai-request-id", "actual-error")]),
headers(&[("x-openai-request-id", "actual-error")]),
headers(&[("x-ms-request-id", "actual-error")]),
] {
let expected = if upstream_headers.is_empty() { let expected = if upstream_headers.is_empty() {
MODEL_REQUEST_ID MODEL_REQUEST_ID
} else { } else {
@@ -3358,7 +3399,7 @@ async fn failure_ids_prefer_the_actual_error_over_session_headers() {
}; };
let raw = let raw =
Bytes::from_static(br#"{"error":{"message":"synthetic upstream detail"}}"#); Bytes::from_static(br#"{"error":{"message":"synthetic upstream detail"}}"#);
let error = let mut error =
ProviderError::new(ProviderErrorKind::InvalidRequest, UpstreamSendState::Sent) ProviderError::new(ProviderErrorKind::InvalidRequest, UpstreamSendState::Sent)
.with_client_visible_upstream_response( .with_client_visible_upstream_response(
ClientVisibleUpstreamResponse::new( ClientVisibleUpstreamResponse::new(
@@ -3368,12 +3409,25 @@ async fn failure_ids_prefer_the_actual_error_over_session_headers() {
) )
.with_headers(upstream_headers), .with_headers(upstream_headers),
); );
if expected == "actual-error" {
// 最终响应头优先于错误对象中残留的旧观测 ID
error = error.with_upstream_request_id(OpaqueUpstreamValue::new("stale-fact"));
}
let session = failed_session(streaming, EngineError::Provider(error)) let session = failed_session(streaming, EngineError::Provider(error))
.with_response_headers(headers(&[("x-request-id", "earlier-session")])); .with_response_headers(headers(&[
("x-request-id", "earlier-session"),
("x-openai-request-id", "earlier-openai"),
("x-ms-request-id", "earlier-ms"),
]));
let response = response(&admin, provider, session, streaming).await; let response = response(&admin, provider, session, streaming).await;
assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY); assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
assert_eq!(response.headers()["x-request-id"], expected); assert_eq!(response.headers()["x-request-id"], expected);
assert_eq!(response.headers()["x-gateway-request-id"], MODEL_REQUEST_ID); assert_eq!(response.headers()["x-gateway-request-id"], MODEL_REQUEST_ID);
for name in ["x-openai-request-id", "x-ms-request-id"] {
if let Some(value) = response.headers().get(name) {
assert_eq!(value, "actual-error");
}
}
assert_eq!(to_bytes(response.into_body(), 4096).await.unwrap(), raw); assert_eq!(to_bytes(response.into_body(), 4096).await.unwrap(), raw);
} }
@@ -3385,12 +3439,16 @@ async fn failure_ids_prefer_the_actual_error_over_session_headers() {
.with_response_headers(headers(&[ .with_response_headers(headers(&[
("x-request-id", "earlier-session"), ("x-request-id", "earlier-session"),
("x-oai-request-id", "earlier-alias"), ("x-oai-request-id", "earlier-alias"),
("x-openai-request-id", "earlier-openai"),
("x-ms-request-id", "earlier-ms"),
])); ]));
let response = response(&admin, provider, session, streaming).await; let response = response(&admin, provider, session, streaming).await;
assert_eq!(response.status(), StatusCode::BAD_GATEWAY); assert_eq!(response.status(), StatusCode::BAD_GATEWAY);
assert_eq!(response.headers()["x-request-id"], "body-read-error"); assert_eq!(response.headers()["x-request-id"], "body-read-error");
assert_eq!(response.headers().get_all("x-request-id").iter().count(), 1); assert_eq!(response.headers().get_all("x-request-id").iter().count(), 1);
assert!(response.headers().get("x-oai-request-id").is_none()); assert!(response.headers().get("x-oai-request-id").is_none());
assert!(response.headers().get("x-openai-request-id").is_none());
assert!(response.headers().get("x-ms-request-id").is_none());
assert_eq!(response.headers()["x-gateway-request-id"], MODEL_REQUEST_ID); assert_eq!(response.headers()["x-gateway-request-id"], MODEL_REQUEST_ID);
} }
} }
@@ -3405,12 +3463,16 @@ async fn local_execution_failure_uses_the_existing_model_id() {
failed_session(streaming, EngineError::Deadline).with_response_headers(headers(&[ failed_session(streaming, EngineError::Deadline).with_response_headers(headers(&[
("x-request-id", "opening-primary"), ("x-request-id", "opening-primary"),
("x-oai-request-id", "opening-alias"), ("x-oai-request-id", "opening-alias"),
("x-openai-request-id", "opening-openai"),
("x-ms-request-id", "opening-ms"),
("x-codex-turn-state", "retained-turn-state"), ("x-codex-turn-state", "retained-turn-state"),
])); ]));
let response = response(&admin, provider, session, streaming).await; let response = response(&admin, provider, session, streaming).await;
assert_eq!(response.headers()["x-request-id"], MODEL_REQUEST_ID); assert_eq!(response.headers()["x-request-id"], MODEL_REQUEST_ID);
assert_eq!(response.headers()["x-gateway-request-id"], MODEL_REQUEST_ID); assert_eq!(response.headers()["x-gateway-request-id"], MODEL_REQUEST_ID);
assert!(response.headers().get("x-oai-request-id").is_none()); assert!(response.headers().get("x-oai-request-id").is_none());
assert!(response.headers().get("x-openai-request-id").is_none());
assert!(response.headers().get("x-ms-request-id").is_none());
assert_eq!( assert_eq!(
response.headers()["x-codex-turn-state"], response.headers()["x-codex-turn-state"],
"retained-turn-state" "retained-turn-state"
@@ -369,23 +369,25 @@ async fn classified_capacity_error_without_special_code_returns_retryable_websoc
#[tokio::test] #[tokio::test]
async fn final_failure_headers_take_precedence_over_observed_opening_headers() { async fn final_failure_headers_take_precedence_over_observed_opening_headers() {
let provider = upstream_failure(403, b"", vec![header("x-oai-request-id", b"req_final")]) for name in ["x-oai-request-id", "x-openai-request-id", "x-ms-request-id"] {
.with_status(502) let provider = upstream_failure(403, b"", vec![header(name, b"req_final")])
.with_upstream_request_id(OpaqueUpstreamValue::new("req_stale_fact")); .with_status(502)
let error = initial_error( .with_upstream_request_id(OpaqueUpstreamValue::new("req_stale_fact"));
EngineError::Provider(provider), let error = initial_error(
vec![ EngineError::Provider(provider),
header("x-request-id", b"req_old_opening"), vec![
header("x-codex-turn-state", b"old-turn-state"), header("x-request-id", b"req_old_opening"),
], header("x-codex-turn-state", b"old-turn-state"),
) ],
.await; )
assert_eq!(error["status"], 403); .await;
assert_eq!(error["headers"]["x-oai-request-id"], "req_final"); assert_eq!(error["status"], 403);
assert!(error["headers"].get("x-request-id").is_none()); assert_eq!(error["headers"][name], "req_final");
assert!(!error.to_string().contains("req_old_opening")); assert!(error["headers"].get("x-request-id").is_none());
assert!(!error.to_string().contains("req_stale_fact")); assert!(!error.to_string().contains("req_old_opening"));
assert!(!error.to_string().contains("old-turn-state")); assert!(!error.to_string().contains("req_stale_fact"));
assert!(!error.to_string().contains("old-turn-state"));
}
} }
#[tokio::test] #[tokio::test]
@@ -398,6 +400,8 @@ async fn provider_failure_facts_survive_without_a_complete_http_response() {
vec![ vec![
header("x-request-id", b"req_old"), header("x-request-id", b"req_old"),
header("x-oai-request-id", b"req_old_alias"), header("x-oai-request-id", b"req_old_alias"),
header("x-openai-request-id", b"req_old_openai"),
header("x-ms-request-id", b"req_old_ms"),
header("x-codex-turn-state", b"observed-turn-state"), header("x-codex-turn-state", b"observed-turn-state"),
], ],
) )
@@ -409,9 +413,11 @@ async fn provider_failure_facts_survive_without_a_complete_http_response() {
"observed-turn-state" "observed-turn-state"
); );
assert!(error["headers"].get("x-oai-request-id").is_none()); assert!(error["headers"].get("x-oai-request-id").is_none());
assert!(error["headers"].get("x-openai-request-id").is_none());
assert!(error["headers"].get("x-ms-request-id").is_none());
assert_eq!( assert_eq!(
error["error"]["message"], error["error"]["message"],
"Upstream service is unavailable." "Communication with the upstream service failed."
); );
} }
@@ -511,6 +517,8 @@ async fn opening_ids_stay_in_metadata_but_do_not_identify_initial_failures() {
vec![ vec![
header("x-request-id", b"req_old_opening"), header("x-request-id", b"req_old_opening"),
header("x-oai-request-id", b"req_observed"), header("x-oai-request-id", b"req_observed"),
header("x-openai-request-id", b"req_observed_openai"),
header("x-ms-request-id", b"req_observed_ms"),
header("x-codex-turn-state", b"observed-turn-state"), header("x-codex-turn-state", b"observed-turn-state"),
header("x-future-header", b"future-value"), header("x-future-header", b"future-value"),
], ],
@@ -525,6 +533,8 @@ async fn opening_ids_stay_in_metadata_but_do_not_identify_initial_failures() {
"headers": { "headers": {
"x-request-id": "req_old_opening", "x-request-id": "req_old_opening",
"x-oai-request-id": "req_observed", "x-oai-request-id": "req_observed",
"x-openai-request-id": "req_observed_openai",
"x-ms-request-id": "req_observed_ms",
"x-codex-turn-state": "observed-turn-state", "x-codex-turn-state": "observed-turn-state",
"x-future-header": "future-value", "x-future-header": "future-value",
}, },
@@ -548,6 +558,46 @@ async fn opening_ids_stay_in_metadata_but_do_not_identify_initial_failures() {
} }
} }
#[tokio::test]
async fn metadata_prefers_readable_upstream_aliases_before_the_model_id() {
let cases: &[(&str, &[u8], Option<&str>)] = &[
("x-oai-request-id", b"req_oai", Some("req_oai")),
("X-OpenAI-Request-ID", b"req_openai", Some("req_openai")),
("x-ms-request-id", b"req_ms", Some("req_ms")),
("x-ms-request-id", b" \t ", None),
("x-ms-request-id", b"\xc3\xa9", None),
];
for (name, value, expected) in cases {
let trace = Arc::new(AtomicFailureTrace {
initial_errors: Mutex::new(VecDeque::from([EngineError::Deadline])),
..AtomicFailureTrace::default()
});
let (mut socket, _server) = connect(
Arc::clone(&trace),
vec![header("x-request-id", b"\xff"), header(name, value)],
)
.await;
send_request(&mut socket).await;
let metadata = next_event(&mut socket).await;
assert_eq!(metadata["type"], "response.metadata");
let model_id = trace.prepared_request_id.lock().unwrap().clone().unwrap();
assert_eq!(
metadata["headers"]["x-request-id"],
expected.unwrap_or(&model_id)
);
assert_eq!(
metadata["headers"][name.to_ascii_lowercase()].as_str(),
*expected
);
let error = next_event(&mut socket).await;
assert_eq!(error["type"], "error");
assert_eq!(error["headers"]["x-request-id"], "req_ws_atomic");
assert_eq!(error["headers"]["x-gateway-request-id"], "req_ws_atomic");
assert!(error["headers"].get(name.to_ascii_lowercase()).is_none());
socket.close(None).await.unwrap();
}
}
#[tokio::test] #[tokio::test]
async fn header_only_request_middleware_updates_websocket_turn_context() { async fn header_only_request_middleware_updates_websocket_turn_context() {
let middleware = Arc::new(crate::data_plane::middleware::RequestMiddleware { let middleware = Arc::new(crate::data_plane::middleware::RequestMiddleware {
@@ -720,7 +770,9 @@ async fn initial_quota_recovery_delivers_client_projection_instead_of_upstream_s
ClientVisibleUpstreamResponse::new( ClientVisibleUpstreamResponse::new(
400, 400,
Some(b"application/json".to_vec()), Some(b"application/json".to_vec()),
Bytes::from(json!({"error":detail}).to_string()), Bytes::from(
json!({"error":detail, "headers":{"Retry-After-Ms":"777"}}).to_string(),
),
) )
.with_headers(vec![header("x-request-id", b"req-quota-rejected")]), .with_headers(vec![header("x-request-id", b"req-quota-rejected")]),
); );
@@ -729,6 +781,7 @@ async fn initial_quota_recovery_delivers_client_projection_instead_of_upstream_s
assert_eq!(error["error"], detail); assert_eq!(error["error"], detail);
assert_eq!(error["headers"]["x-request-id"], "req-quota-rejected"); assert_eq!(error["headers"]["x-request-id"], "req-quota-rejected");
assert!(error["headers"].get("retry-after").is_none()); assert!(error["headers"].get("retry-after").is_none());
assert_eq!(error["headers"]["retry-after-ms"], "777");
} }
#[tokio::test] #[tokio::test]
@@ -743,13 +796,38 @@ async fn initial_continuation_recovery_delivers_the_official_client_replay_signa
} }
#[tokio::test] #[tokio::test]
async fn locally_exhausted_account_pool_sends_one_official_usage_limit_error() { async fn account_selection_errors_distinguish_quota_from_websocket_requirements() {
let provider = ProviderError::new( let exhausted = ProviderError::new(
ProviderErrorKind::AccountPoolQuotaExhausted, ProviderErrorKind::AccountPoolQuotaExhausted,
UpstreamSendState::NotSent, UpstreamSendState::NotSent,
); );
let error = initial_error(EngineError::Provider(provider), Vec::new()).await; let incompatible = ProviderError::new(
assert_eq!(error["status"], 429); ProviderErrorKind::NoEligibleAccount,
assert_eq!(error["error"]["type"], "usage_limit_reached"); UpstreamSendState::NotSent,
assert_eq!(error["error"]["code"], "usage_limit_reached"); )
.with_client_visible_upstream_error(ClientVisibleUpstreamError::new(
"This request requires an upstream WebSocket.",
Some("websocket_account_unavailable".to_owned()),
None,
));
for (provider, status, kind, code) in [
(exhausted, 429, "usage_limit_reached", "usage_limit_reached"),
(
incompatible,
503,
"server_error",
"websocket_account_unavailable",
),
] {
let error = initial_error(EngineError::Provider(provider), Vec::new()).await;
assert_eq!(error["status"], status);
assert_eq!(error["error"]["type"], kind);
assert_eq!(error["error"]["code"], code);
if status == 503 {
assert_eq!(
error["error"]["message"],
"This request requires an upstream WebSocket."
);
}
}
} }
@@ -313,6 +313,7 @@ fn response_create_should_reject_non_boolean_stream_without_disclosing_body_valu
#[derive(Default)] #[derive(Default)]
struct AtomicFailureTrace { struct AtomicFailureTrace {
prepared_request_id: Mutex<Option<String>>,
starts: AtomicUsize, starts: AtomicUsize,
next_calls: AtomicUsize, next_calls: AtomicUsize,
committed: AtomicBool, committed: AtomicBool,
@@ -414,8 +415,9 @@ struct AtomicFailureExecution {
impl ExecutionService for AtomicFailureExecution { impl ExecutionService for AtomicFailureExecution {
fn middleware_plan( fn middleware_plan(
&self, &self,
_: &gateway_core::engine::execution::PreparedRootExecution, prepared: &gateway_core::engine::execution::PreparedRootExecution,
) -> Option<gateway_core::engine::middleware::FrozenMiddlewarePlan> { ) -> Option<gateway_core::engine::middleware::FrozenMiddlewarePlan> {
*self.trace.prepared_request_id.lock().unwrap() = Some(prepared.request_id().to_string());
self.trace.middleware.clone() self.trace.middleware.clone()
} }
@@ -255,3 +255,71 @@ async fn original_rejected_request_is_dumped_only_when_explicitly_enabled() {
} }
} }
} }
#[tokio::test]
async fn responses_ingress_separates_body_receipt_from_decompression_and_decoding() {
use std::io::Write as _;
use tracing::instrument::WithSubscriber as _;
let recorder = Recorder {
dump_enabled: false,
events: Arc::default(),
};
let events = recorder.events.clone();
let decoded = json!({"model":42,"input":"SENSITIVE_CONTENT".repeat(1024)}).to_string();
let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast());
encoder.write_all(decoded.as_bytes()).unwrap();
let encoded = encoder.finish().unwrap();
let encoded_len = encoded.len();
assert!(encoded_len < decoded.len());
async {
let (router, _) = fixture().await;
let body = Body::from_stream(futures::stream::once(async move {
tokio::time::sleep(std::time::Duration::from_millis(40)).await;
Ok::<_, std::io::Error>(encoded)
}));
let response = router
.oneshot(
Request::post("/v1/responses")
.header("authorization", "Bearer unused-client-route-key")
.header("content-encoding", "gzip")
.body(body)
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
}
.with_subscriber(recorder)
.await;
let events = events.lock().unwrap();
let phases = events
.iter()
.filter(|event| {
event.get("stage").is_some_and(|stage| {
stage.starts_with("http.body.") || stage == "http.auth.finished"
})
})
.collect::<Vec<_>>();
assert_eq!(
phases
.iter()
.map(|event| event["stage"].as_str())
.collect::<Vec<_>>(),
[
"http.body.received",
"http.auth.finished",
"http.body.decompressed",
"http.body.decoded",
]
);
assert!(phases[0]["receive_ms"].parse::<u64>().unwrap() >= 30);
assert_eq!(phases[0]["encoded_bytes"], encoded_len.to_string());
assert_eq!(phases[0]["content_encoding"], "gzip");
assert_eq!(phases[2]["decoded_bytes"], decoded.len().to_string());
assert_eq!(phases[2]["accepted"], "true");
assert_eq!(phases[3]["accepted"], "false");
assert!(events.iter().flat_map(|event| event.values()).all(|value| {
!value.contains("SENSITIVE_CONTENT") && !value.contains("unused-client-route-key")
}));
}
@@ -91,12 +91,14 @@ impl SystemOperations for VersionSystem {
async fn version(&self) -> Result<SystemVersion, SystemOperationError> { async fn version(&self) -> Result<SystemVersion, SystemOperationError> {
Ok(SystemVersion { Ok(SystemVersion {
version: "3.7.0".to_owned(), version: "3.7.0".to_owned(),
instance_id: "test-instance".to_owned(),
restart_supported: true,
git_sha: "internal-revision".to_owned(), git_sha: "internal-revision".to_owned(),
build_time: "internal-build-time".to_owned(), build_time: "internal-build-time".to_owned(),
deployment_mode: "binary".to_owned(), deployment_mode: "binary".to_owned(),
update_channel: "release".to_owned(), update_channel: "release".to_owned(),
latest_version: "3.8.0".to_owned(), latest_version: Some("3.8.0".to_owned()),
has_update: true, has_update: true,
update_cached: true, update_cached: true,
update_warning: Some("internal-update-warning".to_owned()), update_warning: Some("internal-update-warning".to_owned()),
@@ -21,6 +21,8 @@ pub use quota_settings::{
}; };
mod proxy; mod proxy;
pub use proxy::{InvalidOutboundProxy, OutboundProxy}; pub use proxy::{InvalidOutboundProxy, OutboundProxy};
mod recent_requests;
pub use recent_requests::{InvalidRecentRequestSnapshot, RecentRequestSnapshot};
mod scheduling; mod scheduling;
pub mod scope; pub mod scope;
mod selection; mod selection;
@@ -36,6 +38,6 @@ pub(crate) use selection::smart_score;
pub use selection::*; pub use selection::*;
pub use store::{ pub use store::{
AccountCatalogObservation, AccountCatalogOmissions, ProviderAccountStore, QuotaWarmupState, AccountCatalogObservation, AccountCatalogOmissions, ProviderAccountStore, QuotaWarmupState,
QuotaWarmupStateUpdate, StoredAccountCatalog, QuotaWarmupStateUpdate, RecentRequestStore, StoredAccountCatalog,
}; };
pub use upstream::*; pub use upstream::*;
@@ -0,0 +1,230 @@
//! 账号与模型的近期请求计数,按秒滚动并在进程内回收过期记录
use std::collections::HashMap;
use std::time::{Duration, Instant, SystemTime};
use crate::identity::ProviderKind;
use super::ProviderAccountId;
const WINDOW_SECONDS: u64 = 60;
/// 快照内容不满足账号标识、秒桶或计数约束
#[derive(Debug, Clone, Copy, thiserror::Error)]
#[error("recent request snapshot is invalid")]
pub struct InvalidRecentRequestSnapshot;
/// 可丢失的近期请求快照,保留观测时间与每个秒桶的年龄
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct RecentRequestSnapshot {
captured_at: SystemTime,
windows: Vec<PersistedWindow>,
}
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
struct PersistedWindow {
provider: ProviderKind,
account: String,
model: String,
buckets: Vec<(Duration, u64)>,
}
#[derive(Debug)]
pub(super) struct RecentRequests {
epoch: Instant,
last_cleanup: u64,
windows: HashMap<(ProviderKind, ProviderAccountId, String), RequestWindow>,
}
#[derive(Debug)]
struct RequestWindow {
buckets: [u64; WINDOW_SECONDS as usize],
second: u64,
total: u64,
}
impl RequestWindow {
fn advance(&mut self, second: u64) {
let elapsed = second.saturating_sub(self.second);
if elapsed >= WINDOW_SECONDS {
self.buckets.fill(0);
self.total = 0;
} else {
for offset in 1..=elapsed {
let index = ((self.second + offset) % WINDOW_SECONDS) as usize;
self.total -= self.buckets[index];
self.buckets[index] = 0;
}
}
self.second = self.second.max(second);
}
}
impl Default for RecentRequests {
fn default() -> Self {
Self {
epoch: Instant::now(),
last_cleanup: 0,
windows: HashMap::new(),
}
}
}
impl RecentRequests {
pub(super) fn snapshot(&mut self, now: Instant, wall_now: SystemTime) -> RecentRequestSnapshot {
let second = self.second(now);
let mut windows = Vec::with_capacity(self.windows.len());
for ((provider, account, model), window) in &mut self.windows {
window.advance(second);
if window.total == 0 {
continue;
}
let buckets = (0..WINDOW_SECONDS.min(second + 1))
.filter_map(|age| {
let index = ((second - age) % WINDOW_SECONDS) as usize;
let count = window.buckets[index];
(count > 0).then(|| {
let started = self.epoch + Duration::from_secs(second - age);
(now.saturating_duration_since(started), count)
})
})
.collect();
windows.push(PersistedWindow {
provider: provider.clone(),
account: account.as_str().to_owned(),
model: model.clone(),
buckets,
});
}
RecentRequestSnapshot {
captured_at: wall_now,
windows,
}
}
pub(super) fn restore(
snapshot: RecentRequestSnapshot,
now: Instant,
wall_now: SystemTime,
) -> Result<Self, InvalidRecentRequestSnapshot> {
let mut restored = Self {
epoch: now,
last_cleanup: 0,
windows: HashMap::new(),
};
// 墙钟只用于跨进程计算停机时长,回拨或过期快照从空窗口重新积累
let Ok(downtime) = wall_now.duration_since(snapshot.captured_at) else {
return Ok(restored);
};
if downtime.as_secs() >= WINDOW_SECONDS {
return Ok(restored);
}
// 单调时钟无法容纳完整窗口时重新积累,避免延长历史计数寿命
let Some(epoch) = now.checked_sub(Duration::from_secs(WINDOW_SECONDS)) else {
return Ok(restored);
};
restored.epoch = epoch;
let second = restored.second(now);
for entry in snapshot.windows {
let account =
ProviderAccountId::new(entry.account).map_err(|_| InvalidRecentRequestSnapshot)?;
if entry.buckets.len() > WINDOW_SECONDS as usize {
return Err(InvalidRecentRequestSnapshot);
}
let mut window = RequestWindow {
buckets: [0; WINDOW_SECONDS as usize],
second,
total: 0,
};
for (age, count) in entry.buckets {
let age = age.saturating_add(downtime);
if age.as_secs() >= WINDOW_SECONDS || count == 0 {
continue;
}
let Some(started) = now.checked_sub(age) else {
continue;
};
let offset = started.saturating_duration_since(restored.epoch).as_secs();
let index = (offset % WINDOW_SECONDS) as usize;
window.buckets[index] = window.buckets[index]
.checked_add(count)
.ok_or(InvalidRecentRequestSnapshot)?;
window.total = window
.total
.checked_add(count)
.ok_or(InvalidRecentRequestSnapshot)?;
}
if window.total > 0 {
restored
.windows
.insert((entry.provider, account, entry.model), window);
}
}
Ok(restored)
}
fn second(&mut self, now: Instant) -> u64 {
let second = now
.checked_duration_since(self.epoch)
.unwrap_or_default()
.as_secs();
if second.saturating_sub(self.last_cleanup) >= WINDOW_SECONDS {
self.windows.retain(|_, window| {
window.advance(second);
window.total > 0
});
self.last_cleanup = second;
}
second
}
pub(super) fn record(
&mut self,
provider: &ProviderKind,
account: &ProviderAccountId,
model: &str,
started_at: Instant,
now: Instant,
) {
// 首个响应确认请求已发送,使用 attempt 开始时间,避免慢响应挤到完成时刻
if now.saturating_duration_since(started_at).as_secs() >= WINDOW_SECONDS {
return;
}
let second = self.second(now);
let started = started_at
.checked_duration_since(self.epoch)
.unwrap_or_default()
.as_secs();
let window = self
.windows
.entry((provider.clone(), account.clone(), model.to_owned()))
.or_insert(RequestWindow {
buckets: [0; WINDOW_SECONDS as usize],
second,
total: 0,
});
window.advance(second);
if window.second.saturating_sub(started) < WINDOW_SECONDS {
window.buckets[(started % WINDOW_SECONDS) as usize] += 1;
window.total += 1;
}
}
pub(super) fn count(
&mut self,
provider: &ProviderKind,
account: &ProviderAccountId,
model: &str,
now: Instant,
) -> u64 {
let second = self.second(now);
let Some(window) =
self.windows
.get_mut(&(provider.clone(), account.clone(), model.to_owned()))
else {
return 0;
};
window.advance(second);
window.total
}
}
@@ -108,6 +108,7 @@ pub struct RuntimeAccountDirectory {
providers_with_accounts: BTreeSet<ProviderKind>, providers_with_accounts: BTreeSet<ProviderKind>,
providers_by_group: BTreeMap<AccountGroupId, BTreeSet<ProviderKind>>, providers_by_group: BTreeMap<AccountGroupId, BTreeSet<ProviderKind>>,
group_model_access: BTreeMap<AccountGroupId, AccountModelAccess>, group_model_access: BTreeMap<AccountGroupId, AccountModelAccess>,
group_fast_modes: BTreeMap<AccountGroupId, FastMode>,
} }
impl RuntimeAccountDirectory { impl RuntimeAccountDirectory {
@@ -129,6 +130,7 @@ impl RuntimeAccountDirectory {
providers_with_accounts, providers_with_accounts,
providers_by_group, providers_by_group,
group_model_access: BTreeMap::new(), group_model_access: BTreeMap::new(),
group_fast_modes: BTreeMap::new(),
} }
} }
@@ -141,6 +143,12 @@ impl RuntimeAccountDirectory {
self self
} }
#[must_use]
pub fn with_group_fast_modes(mut self, policies: BTreeMap<AccountGroupId, FastMode>) -> Self {
self.group_fast_modes = policies;
self
}
pub(crate) fn accounts_in_group( pub(crate) fn accounts_in_group(
&self, &self,
group: &AccountGroupId, group: &AccountGroupId,
@@ -288,7 +296,7 @@ impl ClientRoutingScope {
pub struct FrozenAccountScope { pub struct FrozenAccountScope {
allow_image_generation: bool, allow_image_generation: bool,
allow_subagents: bool, allow_subagents: bool,
fast_mode: FastMode, fast_mode_override: Option<FastMode>,
request_profiles: BTreeMap<ProviderKind, super::OpaqueProviderData>, request_profiles: BTreeMap<ProviderKind, super::OpaqueProviderData>,
directory: Arc<RuntimeAccountDirectory>, directory: Arc<RuntimeAccountDirectory>,
client_scope: ClientRoutingScope, client_scope: ClientRoutingScope,
@@ -355,16 +363,34 @@ impl FrozenAccountScope {
self self
} }
/// Key 绑定分组的冻结 Fast 策略,与账号成员资格无关 /// 显式请求覆盖独立于分组策略;None 表示按选中账号的有效分组计算
#[must_use] #[must_use]
pub const fn with_fast_mode(mut self, fast_mode: FastMode) -> Self { pub const fn with_fast_mode_override(mut self, fast_mode: Option<FastMode>) -> Self {
self.fast_mode = fast_mode; self.fast_mode_override = fast_mode;
self self
} }
#[must_use] #[must_use]
pub const fn fast_mode(&self) -> FastMode { pub const fn fast_mode_override(&self) -> Option<FastMode> {
self.fast_mode self.fast_mode_override
}
/// 只合并当前 Key 授权该账号与模型的启用分组,换号仍使用同一冻结目录
#[must_use]
pub fn fast_mode_for_account(
&self,
account_id: &ProviderAccountId,
upstream_model: &str,
) -> FastMode {
if let Some(mode) = self.fast_mode_override {
return mode;
}
let Some(account) = self.directory.account(account_id) else {
return FastMode::Default;
};
self.matching_groups(account, |access| access.allows(upstream_model))
.filter_map(|id| self.directory.group_fast_modes.get(id))
.fold(FastMode::Default, |mode, other| mode.merge(*other))
} }
#[must_use] #[must_use]
@@ -376,7 +402,7 @@ impl FrozenAccountScope {
Self { Self {
allow_image_generation: true, allow_image_generation: true,
allow_subagents: true, allow_subagents: true,
fast_mode: FastMode::Default, fast_mode_override: None,
request_profiles: BTreeMap::new(), request_profiles: BTreeMap::new(),
directory, directory,
client_scope, client_scope,
@@ -460,18 +486,31 @@ impl FrozenAccountScope {
} }
match &self.client_scope { match &self.client_scope {
ClientRoutingScope::AllAccounts => true, ClientRoutingScope::AllAccounts => true,
ClientRoutingScope::Restricted { .. } => {
self.matching_groups(account, accepts).next().is_some()
}
}
}
fn matching_groups<'a>(
&'a self,
account: &'a RuntimeAccount,
accepts: impl Fn(&AccountModelAccess) -> bool + 'a,
) -> impl Iterator<Item = &'a AccountGroupId> {
let enabled = match &self.client_scope {
ClientRoutingScope::AllAccounts => None,
ClientRoutingScope::Restricted { ClientRoutingScope::Restricted {
enabled_group_ids, .. enabled_group_ids, ..
} => account } => Some(enabled_group_ids),
.group_ids() };
.intersection(enabled_group_ids) account.group_ids().iter().filter(move |id| {
.any(|id| { enabled.is_some_and(|groups| groups.contains(*id))
self.directory && self
.group_model_access .directory
.get(id) .group_model_access
.is_none_or(&accepts) .get(*id)
}), .is_none_or(&accepts)
} })
} }
#[must_use] #[must_use]
@@ -257,6 +257,8 @@ impl AccountSelectionPolicy {
pub struct AccountRuntimeSignals { pub struct AccountRuntimeSignals {
/// 本次调度容量池的在途数,不合并其他独立池 /// 本次调度容量池的在途数,不合并其他独立池
pub in_flight: u32, pub in_flight: u32,
/// 同模型最近一分钟已确认发送的请求数,按秒滚动
pub recent_requests: u64,
pub last_started_at: Option<SystemTime>, pub last_started_at: Option<SystemTime>,
pub quota_reset_at: Option<SystemTime>, pub quota_reset_at: Option<SystemTime>,
pub quota_reset_windows: Option<Arc<[AccountQuotaResetWindow]>>, pub quota_reset_windows: Option<Arc<[AccountQuotaResetWindow]>>,
@@ -368,9 +370,82 @@ impl AccountFeedback {
#[derive(Debug, Default)] #[derive(Debug, Default)]
pub struct AccountFeedbackStats { pub struct AccountFeedbackStats {
accounts: RwLock<HashMap<AccountFeedbackKey, AccountFeedback>>, accounts: RwLock<HashMap<AccountFeedbackKey, AccountFeedback>>,
requests: Mutex<super::recent_requests::RecentRequests>,
} }
impl AccountFeedbackStats { impl AccountFeedbackStats {
/// 后台导出当前窗口,序列化与存储在释放锁后执行
#[must_use]
pub fn snapshot_recent_requests_at(
&self,
now: Instant,
wall_now: SystemTime,
) -> super::RecentRequestSnapshot {
self.requests
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.snapshot(now, wall_now)
}
/// 仅在数据面启动前恢复窗口,按实际停机时长淘汰过期请求
pub fn restore_recent_requests_at(
&self,
snapshot: super::RecentRequestSnapshot,
now: Instant,
wall_now: SystemTime,
) -> Result<(), super::InvalidRecentRequestSnapshot> {
let restored = super::recent_requests::RecentRequests::restore(snapshot, now, wall_now)?;
*self
.requests
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner) = restored;
Ok(())
}
/// 记录已确认发送的请求;同一 attempt 由 stream 边界保证只记录一次
pub fn record_request_at(
&self,
provider: &ProviderKind,
account: &ProviderAccountId,
model: &str,
started_at: Instant,
now: Instant,
) {
self.requests
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.record(provider, account, model, started_at, now);
}
/// 读取指定模型的近期负载,未知模型不参与比较
#[must_use]
pub fn recent_requests(
&self,
provider: &ProviderKind,
account: &ProviderAccountId,
model: Option<&str>,
) -> u64 {
self.recent_requests_at(provider, account, model, Instant::now())
}
/// 在指定单调时刻读取秒级滚动窗口
#[doc(hidden)]
#[must_use]
pub fn recent_requests_at(
&self,
provider: &ProviderKind,
account: &ProviderAccountId,
model: Option<&str>,
now: Instant,
) -> u64 {
model.map_or(0, |model| {
self.requests
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.count(provider, account, model, now)
})
}
/// 读取账号当前的错误率与首个有效输出延迟 EWMA /// 读取账号当前的错误率与首个有效输出延迟 EWMA
#[must_use] #[must_use]
pub fn scheduling_signals( pub fn scheduling_signals(
@@ -978,6 +1053,8 @@ impl AccountSelector {
// 首输出 10 秒时延迟得分减半;固定尺度不随其他候选账号变化 // 首输出 10 秒时延迟得分减半;固定尺度不随其他候选账号变化
const SMART_LATENCY_HALF_SCORE_MS: f64 = 10_000.0; const SMART_LATENCY_HALF_SCORE_MS: f64 = 10_000.0;
// 最近一分钟 10 次请求对应 0.5 的近期负载压力,固定尺度不代表上游 RPM 限额
const SMART_RECENT_REQUEST_HALF_LOAD: f64 = 10.0;
fn capacity_utilization(candidate: &AccountCandidate, context: &AccountSelectionContext) -> f64 { fn capacity_utilization(candidate: &AccountCandidate, context: &AccountSelectionContext) -> f64 {
context context
@@ -1012,7 +1089,10 @@ fn select_smart_candidate<'a>(
pub(crate) fn smart_score(candidate: &AccountCandidate, context: &AccountSelectionContext) -> f64 { pub(crate) fn smart_score(candidate: &AccountCandidate, context: &AccountSelectionContext) -> f64 {
let config = context.policy.smart_scheduling(); let config = context.policy.smart_scheduling();
let now = context.now; let now = context.now;
let load = 1.0 - capacity_utilization(candidate, context).clamp(0.0, 1.0); // 两类压力独立扣分,近期热度不能稀释当前并发占用的代价
let recent_requests = candidate.signals.recent_requests as f64;
let recent_load = recent_requests / (SMART_RECENT_REQUEST_HALF_LOAD + recent_requests);
let load = 1.0 - capacity_utilization(candidate, context).clamp(0.0, 1.0) - recent_load;
let quota = candidate let quota = candidate
.signals .signals
.quota_remaining_rank .quota_remaining_rank
@@ -1,6 +1,7 @@
//! Provider 账号持久化端口 //! Provider 账号持久化端口
use async_trait::async_trait; use async_trait::async_trait;
use futures::future::BoxFuture;
use crate::error::StoreError; use crate::error::StoreError;
use crate::identity::ProviderKind; use crate::identity::ProviderKind;
@@ -9,9 +10,19 @@ use super::{
AccountStateChange, CredentialCasOutcome, CredentialCasUpdate, CredentialRevision, AccountStateChange, CredentialCasOutcome, CredentialCasUpdate, CredentialRevision,
LoadedCredential, NewProviderAccount, ProviderAccount, ProviderAccountId, LoadedCredential, NewProviderAccount, ProviderAccount, ProviderAccountId,
ProviderAccountUpdate, ProviderRefreshQuery, QuotaAccessChange, QuotaObservation, ProviderAccountUpdate, ProviderRefreshQuery, QuotaAccessChange, QuotaObservation,
QuotaObservationTouch, QuotaObservationVersion, QuotaWriteOutcome, QuotaObservationTouch, QuotaObservationVersion, QuotaWriteOutcome, RecentRequestSnapshot,
}; };
/// 快照存储只供启动与后台任务使用,数据面不依赖此端口
pub trait RecentRequestStore: Send + Sync {
fn load(&self) -> BoxFuture<'_, Result<Option<RecentRequestSnapshot>, StoreError>>;
fn save<'a>(
&'a self,
snapshot: &'a RecentRequestSnapshot,
ttl: std::time::Duration,
) -> BoxFuture<'a, Result<(), StoreError>>;
}
/// 一个账号最后成功的目录观测;正文由 Provider 解释,归属不能按相同正文合并 /// 一个账号最后成功的目录观测;正文由 Provider 解释,归属不能按相同正文合并
#[derive(Clone)] #[derive(Clone)]
pub struct AccountCatalogObservation { pub struct AccountCatalogObservation {
@@ -41,6 +41,7 @@ impl TraceContext {
"blocker": AccountSelector.scheduling_blocker(candidate, context) "blocker": AccountSelector.scheduling_blocker(candidate, context)
.map(|blocker| format!("{blocker:?}")), .map(|blocker| format!("{blocker:?}")),
"inFlight": signals.in_flight, "inFlight": signals.in_flight,
"recentRequests": signals.recent_requests,
"concurrencyLimit": context.concurrency_limit(candidate).get(), "concurrencyLimit": context.concurrency_limit(candidate).get(),
"quotaRemainingBasisPoints": signals.quota_remaining_rank, "quotaRemainingBasisPoints": signals.quota_remaining_rank,
"quotaResetAtUnixMs": signals.quota_reset_at.and_then(|reset| "quotaResetAtUnixMs": signals.quota_reset_at.and_then(|reset|
@@ -1200,7 +1200,6 @@ where
.with_lease_metadata(Arc::clone(&self.lease_metadata)) .with_lease_metadata(Arc::clone(&self.lease_metadata))
.with_response_control(self.response_control.clone()) .with_response_control(self.response_control.clone())
.with_request_profile(self.request_profiles.get(candidate.provider()).cloned()) .with_request_profile(self.request_profiles.get(candidate.provider()).cloned())
.with_fast_mode(self.plan.fast_mode())
.with_prompt_rewrite_rules(self.plan.prompt_rewrite_rules(candidate.provider())) .with_prompt_rewrite_rules(self.plan.prompt_rewrite_rules(candidate.provider()))
.with_pricing(self.plan.pricing()) .with_pricing(self.plan.pricing())
.with_request_location(self.plan.request_location().cloned()) .with_request_location(self.plan.request_location().cloned())
@@ -48,11 +48,17 @@ pub(super) fn map_routing_error(error: crate::validation::RoutingError) -> Gatew
"Mapped model unavailable for this API key. Check the model mapping." "Mapped model unavailable for this API key. Check the model mapping."
}, },
), ),
crate::validation::RoutingError::NoCapableProvider { .. } crate::validation::RoutingError::NoCapableProvider { .. } => GatewayError::new(
| crate::validation::RoutingError::NoCapableProviderEndpoint { .. }
| crate::validation::RoutingError::EmptyAccountScope => GatewayError::new(
GatewayErrorKind::NoAvailableProvider, GatewayErrorKind::NoAvailableProvider,
"The gateway has no eligible provider for this request.", "The gateway cannot select a provider for this model and the requested capabilities.",
),
crate::validation::RoutingError::NoCapableProviderEndpoint { .. } => GatewayError::new(
GatewayErrorKind::NoAvailableProvider,
"No eligible provider is available for the requested API endpoint.",
),
crate::validation::RoutingError::EmptyAccountScope => GatewayError::new(
GatewayErrorKind::NoAvailableProvider,
"This API key has no accounts in its scope. Add accounts or check its enabled account groups.",
), ),
crate::validation::RoutingError::UnsupportedProviderEndpoint { .. } => GatewayError::new( crate::validation::RoutingError::UnsupportedProviderEndpoint { .. } => GatewayError::new(
GatewayErrorKind::Unsupported, GatewayErrorKind::Unsupported,
+10 -10
View File
@@ -18,12 +18,14 @@ pub mod policy;
pub mod probe; pub mod probe;
mod prompt_rewrite; mod prompt_rewrite;
pub mod provider; pub mod provider;
mod recent_request_persistence;
pub mod response_control; pub mod response_control;
pub mod upstream_adapter; pub mod upstream_adapter;
use crate::lifecycle::{Deadline, LeaseGuard}; use crate::lifecycle::{Deadline, LeaseGuard};
pub use coordinator::{AttemptCoordinator, ResponseExecutionSession}; pub use coordinator::{AttemptCoordinator, ResponseExecutionSession};
pub use recent_request_persistence::RecentRequestPersistence;
use std::collections::BTreeSet; use std::collections::BTreeSet;
use std::fmt; use std::fmt;
@@ -328,7 +330,6 @@ pub struct RequestAttemptContext {
prompt_rewrite_rules: Option<Arc<crate::settings::prompt_rewrite::ProviderPromptRules>>, prompt_rewrite_rules: Option<Arc<crate::settings::prompt_rewrite::ProviderPromptRules>>,
pricing: Arc<crate::metering::PricingOverrides>, pricing: Arc<crate::metering::PricingOverrides>,
request_profile: Option<crate::account::OpaqueProviderData>, request_profile: Option<crate::account::OpaqueProviderData>,
fast_mode: FastMode,
openai_websocket_pool: crate::settings::OpenAiWebSocketPoolSettings, openai_websocket_pool: crate::settings::OpenAiWebSocketPoolSettings,
openai_request_settings: crate::settings::OpenAiRequestSettings, openai_request_settings: crate::settings::OpenAiRequestSettings,
request_location: Option<crate::account::RequestLocation>, request_location: Option<crate::account::RequestLocation>,
@@ -422,12 +423,6 @@ impl RequestAttemptContext {
self self
} }
#[must_use]
pub const fn with_fast_mode(mut self, fast_mode: FastMode) -> Self {
self.fast_mode = fast_mode;
self
}
#[must_use] #[must_use]
pub fn with_privacy( pub fn with_privacy(
mut self, mut self,
@@ -476,7 +471,6 @@ impl RequestAttemptContext {
request_profile: None, request_profile: None,
prompt_rewrite_rules: None, prompt_rewrite_rules: None,
pricing: Arc::default(), pricing: Arc::default(),
fast_mode: FastMode::Default,
openai_websocket_pool: Default::default(), openai_websocket_pool: Default::default(),
openai_request_settings: Default::default(), openai_request_settings: Default::default(),
request_location: None, request_location: None,
@@ -741,8 +735,14 @@ impl AttemptContext {
} }
#[must_use] #[must_use]
pub const fn fast_mode(&self) -> FastMode { pub fn fast_mode_for_account(
self.request.fast_mode &self,
account: &ProviderAccountId,
upstream_model: &str,
) -> FastMode {
self.account_scope().map_or(FastMode::Default, |scope| {
scope.fast_mode_for_account(account, upstream_model)
})
} }
#[must_use] #[must_use]
@@ -283,6 +283,8 @@ struct ProviderStreamAccountFeedback {
provider_kind: ProviderKind, provider_kind: ProviderKind,
account_id: ProviderAccountId, account_id: ProviderAccountId,
failure_filter: fn(&ProviderError) -> bool, failure_filter: fn(&ProviderError) -> bool,
upstream_model: Option<UpstreamModelId>,
request_recorded: bool,
started_at: Option<Instant>, started_at: Option<Instant>,
first_output_ms: Option<u64>, first_output_ms: Option<u64>,
reported: bool, reported: bool,
@@ -297,7 +299,27 @@ impl ProviderStreamAccountFeedback {
self.started_at.get_or_insert_with(Instant::now); self.started_at.get_or_insert_with(Instant::now);
} }
fn record_request(&mut self) {
if self.request_recorded {
return;
}
if let (Some(model), Some(started_at)) = (&self.upstream_model, self.started_at) {
self.stats.record_request_at(
&self.provider_kind,
&self.account_id,
model.as_str(),
started_at,
Instant::now(),
);
}
self.request_recorded = true;
}
fn observe(&mut self, event: &ProviderEvent) { fn observe(&mut self, event: &ProviderEvent) {
// 纯连接观测可能出现在未发送失败之前,不能单独证明请求已送达
if event.has_client_event() {
self.record_request();
}
if self.first_output_ms.is_some() if self.first_output_ms.is_some()
|| !event.canonical_facts().iter().any(|event| { || !event.canonical_facts().iter().any(|event| {
matches!( matches!(
@@ -332,6 +354,9 @@ impl ProviderStreamAccountFeedback {
} }
fn report_failure(&mut self, error: &ProviderError) { fn report_failure(&mut self, error: &ProviderError) {
if error.send_state() == UpstreamSendState::Sent {
self.record_request();
}
if self.reported if self.reported
// `Ambiguous` 仍须关闭重放边界,但不能证明失败由账号造成;将它计入 // `Ambiguous` 仍须关闭重放边界,但不能证明失败由账号造成;将它计入
// 账号评分会把传输不确定性错误归因给账号 // 账号评分会把传输不确定性错误归因给账号
@@ -523,6 +548,8 @@ impl ProviderStream {
provider_kind: self.metadata.provider().clone(), provider_kind: self.metadata.provider().clone(),
account_id: self.metadata.provider_account_id().clone(), account_id: self.metadata.provider_account_id().clone(),
failure_filter, failure_filter,
upstream_model: self.metadata.upstream_model().cloned(),
request_recorded: false,
started_at: None, started_at: None,
first_output_ms: None, first_output_ms: None,
reported: false, reported: false,
@@ -0,0 +1,77 @@
//! 近期请求统计的启动恢复、周期快照与有界关闭刷写
use std::sync::Arc;
use std::time::{Duration, Instant, SystemTime};
use futures::{FutureExt, future::BoxFuture};
use futures_timer::Delay;
use crate::account::{AccountFeedbackStats, RecentRequestStore};
use crate::error::{StoreError, StoreErrorKind};
use crate::task::{DaemonTask, WorkerDaemonContext, WorkerTaskError};
const FLUSH_INTERVAL: Duration = Duration::from_secs(1);
const IO_TIMEOUT: Duration = Duration::from_secs(2);
const SNAPSHOT_TTL: Duration = Duration::from_secs(120);
/// 由 Host 监督的单进程快照任务,不重放单次请求或恢复旧健康分
pub struct RecentRequestPersistence {
stats: Arc<AccountFeedbackStats>,
store: Arc<dyn RecentRequestStore>,
}
impl RecentRequestPersistence {
#[must_use]
pub fn new(stats: Arc<AccountFeedbackStats>, store: Arc<dyn RecentRequestStore>) -> Self {
Self { stats, store }
}
/// 在 Provider 接收请求前恢复一次,后台任务重启不再次覆盖内存
pub async fn restore(&self) -> Result<(), StoreError> {
if let Some(snapshot) = bounded(self.store.load()).await? {
self.stats
.restore_recent_requests_at(snapshot, Instant::now(), SystemTime::now())
.map_err(|error| StoreError::caused_by(StoreErrorKind::InvalidData, error))?;
}
Ok(())
}
async fn flush(&self) -> Result<(), StoreError> {
let snapshot = self
.stats
.snapshot_recent_requests_at(Instant::now(), SystemTime::now());
// 快照离开内存锁后才序列化和等待存储,慢 Redis 不占用选号锁
bounded(self.store.save(&snapshot, SNAPSHOT_TTL)).await
}
}
impl DaemonTask for RecentRequestPersistence {
fn run(&self, context: WorkerDaemonContext) -> BoxFuture<'_, Result<(), WorkerTaskError>> {
Box::pin(async move {
loop {
let stopping = futures::select_biased! {
() = context.cancellation().cancelled().fuse() => true,
() = Delay::new(FLUSH_INTERVAL).fuse() => false,
};
self.flush().await.map_err(|error| {
WorkerTaskError::safe("近期请求统计保存失败").with_source(error)
})?;
if stopping {
return Ok(());
}
context.succeeded();
}
})
}
}
async fn bounded<T>(
operation: impl std::future::Future<Output = Result<T, StoreError>>,
) -> Result<T, StoreError> {
let operation = operation.fuse();
futures::pin_mut!(operation);
futures::select_biased! {
result = operation => result,
() = Delay::new(IO_TIMEOUT).fuse() => Err(StoreError::new(StoreErrorKind::Unavailable)),
}
}
+78 -45
View File
@@ -1093,43 +1093,59 @@ impl ProviderError {
self.client_visible_upstream_response.as_deref() self.client_visible_upstream_response.as_deref()
} }
/// 将原失败携带的等待头补入客户端响应,保留响应中已有的值
pub fn extend_client_retry_headers(
&self,
headers: &mut Vec<ProviderResponseHeader>,
events: &[ProviderEvent],
) {
let original = self.client_visible_upstream_response();
let body = std::cell::LazyCell::new(|| {
original.and_then(|response| serde_json::from_slice(response.body()).ok())
});
let event = events
.iter()
.rev()
.find_map(ProviderEvent::wire_event)
.map(|wire| wire.data());
for name in gateway_protocol::http::RETRY_AFTER_HEADERS {
if headers
.iter()
.any(|header| header.name().eq_ignore_ascii_case(name))
{
continue;
}
if let Some(header) = original.and_then(|response| {
response
.headers()
.iter()
.rev()
.find(|header| header.name().eq_ignore_ascii_case(name))
}) {
headers.push(header.clone());
continue;
}
let read = |value| gateway_protocol::openai::events::error_event_header(value, name);
if let Some(value) = event
.and_then(read)
.or_else(|| body.as_ref().and_then(read))
{
headers.push(ProviderResponseHeader::new(
name,
Bytes::copy_from_slice(value.as_bytes()),
));
}
}
}
/// 绑定迁移完成后仅替换客户端恢复投影,保留原始失败的诊断与计费事实 /// 绑定迁移完成后仅替换客户端恢复投影,保留原始失败的诊断与计费事实
pub(crate) fn with_client_recovery_from( pub(crate) fn with_client_recovery_from(
mut self, mut self,
mut recovery: Self, mut recovery: Self,
events: &[ProviderEvent], events: &[ProviderEvent],
) -> Self { ) -> Self {
if self.kind() == ProviderErrorKind::UpstreamCapacityUnavailable if let Some(response) = recovery.client_visible_upstream_response.as_deref_mut() {
&& let Some(response) = recovery.client_visible_upstream_response.as_deref_mut() self.extend_client_retry_headers(&mut response.headers, events);
{
// 迁移响应继承原失败的等待头;其余旧账号头和错误正文不属于新响应
let original = self.client_visible_upstream_response();
let body = original.and_then(|original| serde_json::from_slice(original.body()).ok());
let event = events
.iter()
.rev()
.find_map(ProviderEvent::wire_event)
.map(|wire| wire.data());
for name in ["retry-after", "retry-after-ms"] {
if let Some(header) = original.and_then(|original| {
original
.headers()
.iter()
.rev()
.find(|h| h.name().eq_ignore_ascii_case(name))
}) {
response.headers.push(header.clone());
} else if let Some(value) =
event.into_iter().chain(body.as_ref()).find_map(|value| {
gateway_protocol::openai::events::error_event_header(value, name)
})
{
response.headers.push(ProviderResponseHeader::new(
name,
Bytes::copy_from_slice(value.as_bytes()),
));
}
}
} }
if let Some(reason) = recovery.continuation_unavailable_reason() { if let Some(reason) = recovery.continuation_unavailable_reason() {
self = self.with_continuation_unavailable_reason(reason); self = self.with_continuation_unavailable_reason(reason);
@@ -1420,14 +1436,14 @@ impl GatewayError {
pub(crate) const fn concurrency_queue_full() -> Self { pub(crate) const fn concurrency_queue_full() -> Self {
Self::new( Self::new(
GatewayErrorKind::ConcurrencyQueueFull, GatewayErrorKind::ConcurrencyQueueFull,
"The gateway request queue is full.", "The gateway concurrency queue is full.",
) )
} }
pub(crate) const fn concurrency_queue_timeout() -> Self { pub(crate) const fn concurrency_queue_timeout() -> Self {
Self::new( Self::new(
GatewayErrorKind::ConcurrencyQueueTimeout, GatewayErrorKind::ConcurrencyQueueTimeout,
"The request timed out in the gateway queue.", "Timed out waiting for available concurrency in the gateway.",
) )
} }
@@ -1500,20 +1516,25 @@ impl GatewayError {
GatewayErrorKind::Unsupported, GatewayErrorKind::Unsupported,
"Requested capability is unsupported.", "Requested capability is unsupported.",
), ),
ProviderErrorKind::Unauthorized | ProviderErrorKind::PermissionDenied => Self::new( ProviderErrorKind::Unauthorized => Self::new(
GatewayErrorKind::UpstreamUnavailable, GatewayErrorKind::UpstreamUnavailable,
"The upstream account cannot access the service.", "Upstream account authentication failed.",
),
ProviderErrorKind::PermissionDenied => Self::new(
GatewayErrorKind::UpstreamUnavailable,
"The upstream account does not have permission for this request.",
), ),
ProviderErrorKind::RequestPolicyDenied => error.denied_group_feature.map_or_else( ProviderErrorKind::RequestPolicyDenied => error.denied_group_feature.map_or_else(
|| Self::new(GatewayErrorKind::PolicyDenied, "Request blocked by policy."), || Self::new(GatewayErrorKind::PolicyDenied, "Request blocked by policy."),
Self::from, Self::from,
), ),
ProviderErrorKind::RateLimited => { ProviderErrorKind::RateLimited => Self::new(
Self::new(GatewayErrorKind::RateLimited, "Request rate limit reached.") GatewayErrorKind::RateLimited,
} "Upstream request rate limit reached.",
),
ProviderErrorKind::QuotaExhausted => Self::new( ProviderErrorKind::QuotaExhausted => Self::new(
GatewayErrorKind::QuotaExhausted, GatewayErrorKind::QuotaExhausted,
"Account quota is exhausted.", "Upstream account quota is exhausted.",
), ),
ProviderErrorKind::AccountPoolQuotaExhausted => Self::new( ProviderErrorKind::AccountPoolQuotaExhausted => Self::new(
GatewayErrorKind::AccountPoolQuotaExhausted, GatewayErrorKind::AccountPoolQuotaExhausted,
@@ -1523,7 +1544,7 @@ impl GatewayError {
ProviderErrorKind::ConcurrencyQueueTimeout => Self::concurrency_queue_timeout(), ProviderErrorKind::ConcurrencyQueueTimeout => Self::concurrency_queue_timeout(),
ProviderErrorKind::AccountCapacityUnavailable => Self::new( ProviderErrorKind::AccountCapacityUnavailable => Self::new(
GatewayErrorKind::AccountCapacityUnavailable, GatewayErrorKind::AccountCapacityUnavailable,
"The gateway account pool is busy.", "No eligible account currently has capacity for this request.",
), ),
ProviderErrorKind::NoEligibleAccount => Self::new( ProviderErrorKind::NoEligibleAccount => Self::new(
GatewayErrorKind::NoAvailableProvider, GatewayErrorKind::NoAvailableProvider,
@@ -1543,11 +1564,23 @@ impl GatewayError {
ProviderErrorKind::Cancelled => { ProviderErrorKind::Cancelled => {
Self::new(GatewayErrorKind::Cancelled, "Request was cancelled.") Self::new(GatewayErrorKind::Cancelled, "Request was cancelled.")
} }
ProviderErrorKind::Transport ProviderErrorKind::Transport => Self::new(
| ProviderErrorKind::Protocol GatewayErrorKind::UpstreamUnavailable,
| ProviderErrorKind::Unavailable "Communication with the upstream service failed.",
| ProviderErrorKind::UpstreamCapacityUnavailable ),
| ProviderErrorKind::ProcessTerminated => Self::new( ProviderErrorKind::Protocol => Self::new(
GatewayErrorKind::UpstreamUnavailable,
"Upstream protocol handling failed.",
),
ProviderErrorKind::ProcessTerminated => Self::new(
GatewayErrorKind::UpstreamUnavailable,
"The gateway stopped before the request completed.",
),
ProviderErrorKind::UpstreamCapacityUnavailable => Self::new(
GatewayErrorKind::UpstreamUnavailable,
"The upstream service has no capacity for this request.",
),
ProviderErrorKind::Unavailable => Self::new(
GatewayErrorKind::UpstreamUnavailable, GatewayErrorKind::UpstreamUnavailable,
"Upstream service is unavailable.", "Upstream service is unavailable.",
), ),
@@ -5,6 +5,7 @@ use std::sync::{Arc, OnceLock};
use std::time::{Duration, SystemTime}; use std::time::{Duration, SystemTime};
use event_listener::Event; use event_listener::Event;
use futures::FutureExt as _;
use futures::future::{BoxFuture, pending}; use futures::future::{BoxFuture, pending};
use futures_timer::Delay; use futures_timer::Delay;
@@ -142,6 +143,14 @@ impl CancellationToken {
self.reason().is_some() self.reason().is_some()
} }
/// 取消优先于同时就绪的工作,只用于可安全丢弃的 future
pub async fn run_until_cancelled<T>(&self, work: impl Future<Output = T>) -> Option<T> {
futures::select_biased! {
() = self.cancelled().fuse() => None,
result = work.fuse() => Some(result),
}
}
pub async fn cancelled(&self) { pub async fn cancelled(&self) {
if self.is_cancelled() { if self.is_cancelled() {
return; return;
@@ -158,7 +158,7 @@ impl RateLimits {
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub struct ClientSettings { pub struct ClientSettings {
pub request_profiles: BTreeMap<ProviderKind, OpaqueProviderData>, pub request_profiles: BTreeMap<ProviderKind, OpaqueProviderData>,
pub fast_mode: FastMode, pub fast_mode_override: Option<FastMode>,
pub limits: RateLimits, pub limits: RateLimits,
} }
@@ -185,18 +185,18 @@ impl ClientPolicy {
pub(crate) fn with_settings( pub(crate) fn with_settings(
mut self, mut self,
profiles: &BTreeMap<ProviderKind, OpaqueProviderData>, profiles: &BTreeMap<ProviderKind, OpaqueProviderData>,
fast_mode: FastMode, fast_mode_override: Option<FastMode>,
limits: RateLimits, limits: RateLimits,
) -> Self { ) -> Self {
if self.account_scope.request_profiles() != profiles if self.account_scope.request_profiles() != profiles
|| self.account_scope.fast_mode() != fast_mode || self.account_scope.fast_mode_override() != fast_mode_override
{ {
self.account_scope = Arc::new( self.account_scope = Arc::new(
self.account_scope self.account_scope
.as_ref() .as_ref()
.clone() .clone()
.with_request_profiles(profiles.clone()) .with_request_profiles(profiles.clone())
.with_fast_mode(fast_mode), .with_fast_mode_override(fast_mode_override),
); );
} }
self.limits = limits; self.limits = limits;
@@ -217,7 +217,7 @@ impl ClientPolicy {
name_snapshot: None, name_snapshot: None,
defaults: Arc::new(ClientSettings { defaults: Arc::new(ClientSettings {
request_profiles: account_scope.request_profiles().clone(), request_profiles: account_scope.request_profiles().clone(),
fast_mode: account_scope.fast_mode(), fast_mode_override: account_scope.fast_mode_override(),
limits, limits,
}), }),
key_id, key_id,
@@ -23,7 +23,7 @@ use std::fmt;
use std::num::{NonZeroU32, NonZeroU64}; use std::num::{NonZeroU32, NonZeroU64};
use std::sync::Arc; use std::sync::Arc;
use crate::account::{AccountSelectionPolicy, FastMode}; use crate::account::AccountSelectionPolicy;
use crate::operation::{CapabilityRequirements, Feature, OperationKind}; use crate::operation::{CapabilityRequirements, Feature, OperationKind};
use crate::validation::{IdentifierError, RoutingError, validate_text}; use crate::validation::{IdentifierError, RoutingError, validate_text};
@@ -767,11 +767,6 @@ impl RoutingPlan {
Arc::clone(&self.pricing) Arc::clone(&self.pricing)
} }
#[must_use]
pub fn fast_mode(&self) -> FastMode {
self.account_scope.fast_mode()
}
/// 本次请求冻结的已编译规则,重试不读取新的全局策略 /// 本次请求冻结的已编译规则,重试不读取新的全局策略
#[must_use] #[must_use]
pub fn privacy(&self) -> Option<Arc<dyn crate::settings::privacy::CompiledPrivacyPolicy>> { pub fn privacy(&self) -> Option<Arc<dyn crate::settings::privacy::CompiledPrivacyPolicy>> {
@@ -19,7 +19,8 @@ use crate::settings::{InvalidSettings, SettingsValues};
#[serde(deny_unknown_fields)] #[serde(deny_unknown_fields)]
pub struct ExecutionSettings { pub struct ExecutionSettings {
pub runtime: SettingsValues, pub runtime: SettingsValues,
pub fast_mode: FastMode, /// None 按选中账号的有效分组解析;Some(Default) 显式跟随客户端
pub fast_mode: Option<FastMode>,
pub client_limits: RateLimits, pub client_limits: RateLimits,
/// null 表示不限制总时长;显式时限从请求开始计时,改写不重置计时原点 /// null 表示不限制总时长;显式时限从请求开始计时,改写不重置计时原点
pub timeout_ms: Option<u64>, pub timeout_ms: Option<u64>,
@@ -38,7 +39,7 @@ struct ExecutionOverrides {
defaults: Arc<ClientSettings>, defaults: Arc<ClientSettings>,
client_key_id: String, client_key_id: String,
input: Arc<ExecutionSettings>, input: Arc<ExecutionSettings>,
fast_mode: Option<SettingOverride<FastMode>>, fast_mode: Option<SettingOverride<Option<FastMode>>>,
client_limits: Option<SettingOverride<RateLimits>>, client_limits: Option<SettingOverride<RateLimits>>,
timeout_ms: Option<SettingOverride<Option<u64>>>, timeout_ms: Option<SettingOverride<Option<u64>>>,
} }
@@ -186,9 +187,10 @@ impl RequestSettings {
#[must_use] #[must_use]
pub fn apply_policy(&self, policy: ClientPolicy) -> ClientPolicy { pub fn apply_policy(&self, policy: ClientPolicy) -> ClientPolicy {
let values = self.resolve_execution(policy.key_id().as_str(), policy.defaults(), None); let values = self.resolve_execution(policy.key_id().as_str(), policy.defaults(), None);
let fast_mode = self.fast_mode_override(policy.key_id().as_str(), policy.defaults());
policy.with_settings( policy.with_settings(
values.runtime.request_profiles(), values.runtime.request_profiles(),
values.fast_mode, fast_mode,
values.client_limits, values.client_limits,
) )
} }
@@ -247,9 +249,7 @@ impl RequestSettings {
} }
ExecutionSettings { ExecutionSettings {
runtime, runtime,
fast_mode: overrides fast_mode: self.fast_mode_override(key, defaults),
.and_then(|scope| scope.fast_mode.as_ref())
.map_or(defaults.fast_mode, |change| change.value),
client_limits: overrides client_limits: overrides
.and_then(|scope| scope.client_limits.as_ref()) .and_then(|scope| scope.client_limits.as_ref())
.map_or(defaults.limits, |change| change.value), .map_or(defaults.limits, |change| change.value),
@@ -259,6 +259,15 @@ impl RequestSettings {
} }
} }
fn fast_mode_override(&self, key: &str, defaults: &ClientSettings) -> Option<FastMode> {
self.execution
.as_ref()
.filter(|scope| scope.client_key_id == key)
.and_then(|scope| scope.fast_mode.as_ref())
.map(|change| change.value)
.unwrap_or(defaults.fast_mode_override)
}
pub(crate) fn execution_deadline( pub(crate) fn execution_deadline(
&self, &self,
key: &ClientApiKeyId, key: &ClientApiKeyId,
@@ -583,12 +583,19 @@ async fn compile_runtime_snapshot(
.map(|group| (group.id.clone(), std::mem::take(&mut group.model_access))) .map(|group| (group.id.clone(), std::mem::take(&mut group.model_access)))
.collect(); .collect();
let account_directory = Arc::new( let account_directory = Arc::new(
RuntimeAccountDirectory::new(accounts).with_group_model_access(group_model_access), RuntimeAccountDirectory::new(accounts)
.with_group_model_access(group_model_access)
.with_group_fast_modes(
groups
.values()
.filter(|group| group.enabled && group.fast_mode != FastMode::Default)
.map(|group| (group.id.clone(), group.fast_mode))
.collect(),
),
); );
let mut client_policies = Vec::with_capacity(facts.client_policies.len()); let mut client_policies = Vec::with_capacity(facts.client_policies.len());
for policy in facts.client_policies { for policy in facts.client_policies {
let mut fast_mode = FastMode::Default;
let mut allow_image_generation = true; let mut allow_image_generation = true;
let mut allow_subagents = true; let mut allow_subagents = true;
let account_scope = if policy.group_ids.is_empty() { let account_scope = if policy.group_ids.is_empty() {
@@ -607,8 +614,7 @@ async fn compile_runtime_snapshot(
let group = groups let group = groups
.get(&group_id) .get(&group_id)
.ok_or(RuntimeSnapshotCompileError::InvalidData)?; .ok_or(RuntimeSnapshotCompileError::InvalidData)?;
// 停用只影响选号,仍绑定的分组继续贡献请求策略 // 功能权限仍按 Key 合并,停用分组不解除生图和子代理限制
fast_mode = fast_mode.merge(group.fast_mode);
allow_image_generation &= group.allow_image_generation; allow_image_generation &= group.allow_image_generation;
allow_subagents &= group.allow_subagents; allow_subagents &= group.allow_subagents;
bound_groups.push(RoutingGroupSnapshot::new( bound_groups.push(RoutingGroupSnapshot::new(
@@ -635,7 +641,6 @@ async fn compile_runtime_snapshot(
account_scope account_scope
.with_image_generation(allow_image_generation) .with_image_generation(allow_image_generation)
.with_subagents(allow_subagents) .with_subagents(allow_subagents)
.with_fast_mode(fast_mode)
.with_request_profiles(policy.request_profiles), .with_request_profiles(policy.request_profiles),
), ),
true, true,
@@ -399,14 +399,13 @@ struct RuntimeSnapshotReconciliationTask {
} }
impl ScheduledTask for RuntimeSnapshotReconciliationTask { impl ScheduledTask for RuntimeSnapshotReconciliationTask {
fn run_cycle( fn run_cycle(&self, context: WorkerCycleContext) -> BoxFuture<'_, Result<(), WorkerTaskError>> {
&self,
_context: WorkerCycleContext,
) -> BoxFuture<'_, Result<(), WorkerTaskError>> {
Box::pin(async move { Box::pin(async move {
self.publisher context
.refresh_with_mode(RefreshMode::Reconcile) .cancellation()
.run_until_cancelled(self.publisher.refresh_with_mode(RefreshMode::Reconcile))
.await .await
.transpose()
.map(|_| ()) .map(|_| ())
.map_err(|source| { .map_err(|source| {
WorkerTaskError::safe("runtime snapshot reconciliation failed") WorkerTaskError::safe("runtime snapshot reconciliation failed")
@@ -430,10 +429,12 @@ impl DaemonTask for RuntimeSnapshotSubscriptionTask {
let cancellation = context.cancellation(); let cancellation = context.cancellation();
let mut retry_delay = INITIAL_BACKOFF; let mut retry_delay = INITIAL_BACKOFF;
loop { loop {
if cancellation.is_cancelled() { let Some(subscription) = cancellation
.run_until_cancelled(self.subscriptions.subscribe_snapshot_revisions())
.await
else {
return Ok(()); return Ok(());
} };
let subscription = self.subscriptions.subscribe_snapshot_revisions().await;
let mut subscription = match subscription { let mut subscription = match subscription {
Ok(subscription) => { Ok(subscription) => {
retry_delay = INITIAL_BACKOFF; retry_delay = INITIAL_BACKOFF;
@@ -456,7 +457,13 @@ impl DaemonTask for RuntimeSnapshotSubscriptionTask {
}; };
match notified { match notified {
Some(Ok(_)) => { Some(Ok(_)) => {
let _ = self.publisher.refresh().await; if cancellation
.run_until_cancelled(self.publisher.refresh())
.await
.is_none()
{
return Ok(());
}
} }
Some(Err(_)) | None => break, Some(Err(_)) | None => break,
} }
@@ -5,6 +5,7 @@ mod model_access;
mod proxy; mod proxy;
mod quota_reset_priority; mod quota_reset_priority;
mod quota_settings; mod quota_settings;
mod recent_requests;
mod scope; mod scope;
mod selection; mod selection;
mod selection_diagnostics; mod selection_diagnostics;
@@ -56,6 +57,7 @@ fn candidate(id: &str, in_flight: u32, remaining: Option<u64>) -> AccountCandida
account: account(id), account: account(id),
signals: AccountRuntimeSignals { signals: AccountRuntimeSignals {
in_flight, in_flight,
recent_requests: 0,
last_started_at: None, last_started_at: None,
quota_reset_at: None, quota_reset_at: None,
quota_reset_windows: None, quota_reset_windows: None,
@@ -229,6 +231,7 @@ fn diagnostic_selection_bypasses_all_local_account_eligibility() {
), ),
signals: AccountRuntimeSignals { signals: AccountRuntimeSignals {
in_flight: 0, in_flight: 0,
recent_requests: 0,
last_started_at: None, last_started_at: None,
quota_reset_at: None, quota_reset_at: None,
quota_reset_windows: None, quota_reset_windows: None,
@@ -249,6 +252,7 @@ fn diagnostic_selection_bypasses_all_local_account_eligibility() {
), ),
signals: AccountRuntimeSignals { signals: AccountRuntimeSignals {
in_flight: 0, in_flight: 0,
recent_requests: 0,
last_started_at: None, last_started_at: None,
quota_reset_at: None, quota_reset_at: None,
quota_reset_windows: None, quota_reset_windows: None,
@@ -644,6 +648,7 @@ fn provider_quota_overlay_should_preserve_store_concurrency_facts() {
let last_started_at = SystemTime::now(); let last_started_at = SystemTime::now();
let signals = AccountRuntimeSignals { let signals = AccountRuntimeSignals {
in_flight: 2, in_flight: 2,
recent_requests: 0,
last_started_at: Some(last_started_at), last_started_at: Some(last_started_at),
quota_reset_at: None, quota_reset_at: None,
quota_reset_windows: None, quota_reset_windows: None,
@@ -0,0 +1,182 @@
//! 验证近期负载的模型隔离、滑动过期、延迟确认与并发计数
use std::time::{Duration, Instant};
use gateway_core::account::{AccountFeedbackStats, ProviderAccountId};
use gateway_core::identity::ProviderKind;
#[test]
fn recent_requests_expire_by_start_time_and_isolate_accounts_models_and_providers() {
let stats = AccountFeedbackStats::default();
let provider = ProviderKind::new("openai").unwrap();
let other_provider = ProviderKind::new("xai").unwrap();
let account = ProviderAccountId::new("acct_recent").unwrap();
let other_account = ProviderAccountId::new("acct_other").unwrap();
let start = Instant::now();
for offset in [0, 30, 59] {
let now = start + Duration::from_secs(offset);
stats.record_request_at(&provider, &account, "model-a", now, now);
}
let now = start + Duration::from_secs(59);
assert_eq!(
stats.recent_requests_at(&provider, &account, Some("model-a"), now),
3
);
for (provider, account, model) in [
(&provider, &other_account, Some("model-a")),
(&other_provider, &account, Some("model-a")),
(&provider, &account, Some("model-b")),
(&provider, &account, None),
] {
assert_eq!(stats.recent_requests_at(provider, account, model, now), 0);
}
let now = start + Duration::from_secs(60);
assert_eq!(
stats.recent_requests_at(&provider, &account, Some("model-a"), now),
2
);
// 响应晚到时仍落在开始时的桶,已经过期的请求不重新进入窗口
stats.record_request_at(&provider, &account, "model-a", start, now);
stats.record_request_at(
&provider,
&account,
"model-a",
start + Duration::from_secs(30),
now,
);
assert_eq!(
stats.recent_requests_at(&provider, &account, Some("model-a"), now),
3
);
let now = start + Duration::from_secs(90);
assert_eq!(
stats.recent_requests_at(&provider, &account, Some("model-a"), now),
1
);
let now = start + Duration::from_secs(120);
assert_eq!(
stats.recent_requests_at(&provider, &account, Some("model-a"), now),
0
);
stats.record_request_at(&provider, &account, "model-a", now, now);
assert_eq!(
stats.recent_requests_at(&provider, &account, Some("model-a"), now),
1
);
assert_eq!(
AccountFeedbackStats::default().recent_requests(&provider, &account, Some("model-a")),
0
);
}
#[test]
fn concurrent_requests_are_counted_once_per_record() {
let stats = AccountFeedbackStats::default();
let provider = ProviderKind::new("openai").unwrap();
let account = ProviderAccountId::new("acct_recent").unwrap();
std::thread::scope(|scope| {
for _ in 0..8 {
scope.spawn(|| {
for _ in 0..1000 {
let now = Instant::now();
stats.record_request_at(&provider, &account, "model", now, now);
}
});
}
});
assert_eq!(
stats.recent_requests(&provider, &account, Some("model")),
8000
);
}
#[test]
fn snapshot_restores_only_live_buckets_and_preserves_expiration_after_downtime() {
let stats = AccountFeedbackStats::default();
let provider = ProviderKind::new("openai").unwrap();
let account = ProviderAccountId::new("acct_restart").unwrap();
let start = Instant::now();
let wall_start = std::time::SystemTime::now();
for offset in [0, 30, 59] {
let now = start + Duration::from_secs(offset);
stats.record_request_at(&provider, &account, "model", now, now);
}
let snapshot = stats.snapshot_recent_requests_at(
start + Duration::from_secs(59),
wall_start + Duration::from_secs(59),
);
let bytes = serde_json::to_vec(&snapshot).unwrap();
let snapshot = serde_json::from_slice(&bytes).unwrap();
let restored = AccountFeedbackStats::default();
restored
.restore_recent_requests_at(
snapshot,
start + Duration::from_secs(79),
wall_start + Duration::from_secs(79),
)
.unwrap();
for (offset, expected) in [(79, 2), (91, 1), (120, 0)] {
assert_eq!(
restored.recent_requests_at(
&provider,
&account,
Some("model"),
start + Duration::from_secs(offset)
),
expected,
);
}
}
#[test]
fn stale_snapshots_and_backward_wall_clock_start_with_an_empty_window() {
let stats = AccountFeedbackStats::default();
let provider = ProviderKind::new("openai").unwrap();
let account = ProviderAccountId::new("acct_restart").unwrap();
let now = Instant::now();
let wall_now = std::time::SystemTime::now();
stats.record_request_at(&provider, &account, "model", now, now);
let snapshot = stats.snapshot_recent_requests_at(now, wall_now);
for wall_restart in [
wall_now + Duration::from_secs(60),
wall_now - Duration::from_secs(1),
] {
let restored = AccountFeedbackStats::default();
restored
.restore_recent_requests_at(snapshot.clone(), now, wall_restart)
.unwrap();
assert_eq!(
restored.recent_requests_at(&provider, &account, Some("model"), now),
0
);
}
}
#[test]
fn invalid_snapshot_does_not_partially_replace_live_counts() {
let source = AccountFeedbackStats::default();
let live = AccountFeedbackStats::default();
let provider = ProviderKind::new("openai").unwrap();
let account = ProviderAccountId::new("acct_restart").unwrap();
let now = Instant::now();
let wall_now = std::time::SystemTime::now();
for _ in 0..2 {
source.record_request_at(&provider, &account, "model", now, now);
}
live.record_request_at(&provider, &account, "model", now, now);
let mut value =
serde_json::to_value(source.snapshot_recent_requests_at(now, wall_now)).unwrap();
let windows = value["windows"].as_array_mut().unwrap();
let mut invalid = windows[0].clone();
invalid["account"] = serde_json::json!("");
windows.push(invalid);
let snapshot = serde_json::from_value(value).unwrap();
assert!(
live.restore_recent_requests_at(snapshot, now, wall_now)
.is_err()
);
assert_eq!(
live.recent_requests_at(&provider, &account, Some("model"), now),
1,
);
}
@@ -36,6 +36,7 @@ fn reserved_pool_scoring_and_trace_use_its_capacity_instead_of_the_normal_limit(
let selected = &snapshot["events"][0]["data"]["candidates"][0]; let selected = &snapshot["events"][0]["data"]["candidates"][0];
assert_eq!(selected["concurrencyLimit"], 5); assert_eq!(selected["concurrencyLimit"], 5);
assert_eq!(selected["inFlight"], 1); assert_eq!(selected["inFlight"], 1);
assert_eq!(selected["recentRequests"], 0);
assert_eq!(selected["smartScore"], 0.8); assert_eq!(selected["smartScore"], 0.8);
} }
@@ -429,3 +430,189 @@ fn missing_expired_and_duplicate_periods_do_not_inflate_reset_score() {
); );
} }
} }
#[test]
fn smart_prefers_recently_idle_accounts_and_disables_recent_load_with_zero_weight() {
let candidates = (0..130)
.map(|index| {
let mut candidate = candidate_with_concurrency(&format!("acct_{index:03}"), 0, 8);
candidate.signals.recent_requests = index / 2;
candidate
})
.collect::<Vec<_>>();
let mut context = context(RotationStrategy::Smart);
for cursor in 0..260 {
context.round_robin_cursor = cursor;
let selected = AccountSelector.select(&candidates, &context).unwrap();
assert_eq!(
selected.candidate().account.id(),
candidates[(cursor % 2) as usize].account.id()
);
}
// 系数归零时由其余维度和轮换决定,近期负载退出比较
context.policy = context
.policy
.with_smart_scheduling(SmartSchedulingConfig::new([0.0, 0.8, 1.0, 0.5, 0.0, 0.0]).unwrap());
for cursor in 0..130 {
context.round_robin_cursor = cursor;
let selected = AccountSelector.select(&candidates, &context).unwrap();
assert_eq!(
selected.candidate().account.id(),
candidates[cursor as usize].account.id()
);
}
}
#[test]
fn recent_load_respects_affinity_weight_capacity_and_configured_quota_weight() {
let mut candidates = [
candidate_with_concurrency("acct_busy", 0, 8),
candidate_with_concurrency("acct_idle", 0, 8),
];
candidates[0].signals.recent_requests = 20;
let mut context = context(RotationStrategy::Smart);
context.preferred_account = Some(candidates[0].account.id().clone());
assert_eq!(
AccountSelector
.select(&candidates, &context)
.unwrap()
.candidate()
.account
.id()
.as_str(),
"acct_busy"
);
context.preferred_account = None;
candidates[1].signals.in_flight = 8;
assert_eq!(
AccountSelector
.select(&candidates, &context)
.unwrap()
.candidate()
.account
.id()
.as_str(),
"acct_busy"
);
candidates[1].signals.in_flight = 0;
candidates[1].signals.quota_remaining_rank = Some(0);
candidates[0].signals.quota_remaining_rank = Some(10_000);
assert_eq!(
AccountSelector
.select(&candidates, &context)
.unwrap()
.candidate()
.account
.id()
.as_str(),
"acct_busy"
);
candidates[1].signals.quota_remaining_rank = Some(10_000);
candidates[0].account = candidates[0]
.account
.clone()
.with_scheduling(None, gateway_core::account::AccountWeight::new(2).unwrap());
candidates[1].account = candidates[1]
.account
.clone()
.with_scheduling(None, gateway_core::account::AccountWeight::new(1).unwrap());
assert_eq!(
AccountSelector
.select(&candidates, &context)
.unwrap()
.candidate()
.account
.id()
.as_str(),
"acct_busy"
);
}
#[test]
fn recent_model_load_competes_with_quota_and_cross_model_concurrency_before_score_filtering() {
for weights in [
[1.0, 0.1, 1.0, 0.0, 0.0, 0.0],
[1.0, 0.8, 1.0, 0.5, 0.0, 0.0],
] {
for limit in [6, 8] {
for (hot_requests, cool_requests, cool_in_flight, cool_quota) in [
(18, 0, 0, 9_000),
(18, 0, 0, 7_000),
(18, 0, 1, 10_000),
(16, 4, 1, 9_000),
(27, 3, 1, 7_000),
] {
let mut candidates = [
candidate_with_concurrency("acct_hot", 0, limit),
candidate_with_concurrency("acct_cool", cool_in_flight, limit),
];
candidates[0].signals.quota_remaining_rank = Some(10_000);
candidates[0].signals.recent_requests = hot_requests;
candidates[1].signals.quota_remaining_rank = Some(cool_quota);
candidates[1].signals.recent_requests = cool_requests;
let mut context = context(RotationStrategy::Smart);
context.policy = context
.policy
.with_smart_scheduling(SmartSchedulingConfig::new(weights).unwrap());
let selected = AccountSelector.select(&candidates, &context).unwrap();
assert_eq!(selected.candidate().account.id().as_str(), "acct_cool");
let trace = gateway_core::diagnostics::TraceContext::new("req_recent_score");
trace.account_selection(&candidates, &context, Some(&selected));
let snapshot = trace.snapshot().unwrap();
let scores = &snapshot["events"][0]["data"]["candidates"];
assert!(
scores[0]["smartScore"].as_f64().unwrap()
> scores[1]["smartScore"].as_f64().unwrap()
);
}
}
}
}
#[test]
fn recent_heat_does_not_dilute_concurrency_pressure_or_require_nonnegative_load_scores() {
let mut candidates = [
candidate_with_concurrency("acct_busy", 5, 6),
candidate_with_concurrency("acct_idle", 4, 6),
];
candidates[0].signals.quota_remaining_rank = Some(10_000);
candidates[1].signals.quota_remaining_rank = Some(9_000);
for candidate in &mut candidates {
candidate.signals.recent_requests = 30;
}
let mut context = context(RotationStrategy::Smart);
for quota_weight in [0.0, 0.8] {
context.policy = context.policy.with_smart_scheduling(
SmartSchedulingConfig::new([1.0, quota_weight, 0.0, 0.0, 0.0, 0.0]).unwrap(),
);
let selected = AccountSelector.select(&candidates, &context).unwrap();
assert_eq!(selected.candidate().account.id().as_str(), "acct_idle");
if quota_weight == 0.0 {
let trace = gateway_core::diagnostics::TraceContext::new("req_negative_load");
trace.account_selection(&candidates, &context, Some(&selected));
assert!(
trace.snapshot().unwrap()["events"][0]["data"]["candidates"][0]["smartScore"]
.as_f64()
.unwrap()
< 0.0
);
}
}
}
#[test]
fn recent_load_remains_effective_without_a_concurrency_limit() {
let mut candidates = [
super::candidate("acct_hot", 0, None),
super::candidate("acct_cool", 1, None),
];
candidates[0].signals.recent_requests = u64::MAX;
let mut context = context(RotationStrategy::Smart);
context.policy = gateway_core::account::AccountSelectionPolicy::new(
RotationStrategy::Smart,
gateway_core::account::AccountConcurrency::new(0),
);
let selected = AccountSelector.select(&candidates, &context).unwrap();
assert_eq!(selected.candidate().account.id().as_str(), "acct_cool");
}
@@ -1138,26 +1138,12 @@ fn plan_with_location(
operation: &Operation, operation: &Operation,
account_selection_policy: AccountSelectionPolicy, account_selection_policy: AccountSelectionPolicy,
request_location: gateway_core::account::RequestLocation, request_location: gateway_core::account::RequestLocation,
) -> RoutingPlan {
plan_with_location_and_fast_policy(
operation,
account_selection_policy,
request_location,
FastMode::Default,
)
}
fn plan_with_location_and_fast_policy(
operation: &Operation,
account_selection_policy: AccountSelectionPolicy,
request_location: gateway_core::account::RequestLocation,
fast_mode: FastMode,
) -> RoutingPlan { ) -> RoutingPlan {
plan_with_profiles( plan_with_profiles(
operation, operation,
account_selection_policy, account_selection_policy,
request_location, request_location,
fast_mode, FastMode::Default,
Default::default(), Default::default(),
) )
} }
@@ -1255,7 +1241,7 @@ fn plan_with_protection(
operation, operation,
Arc::new( Arc::new(
FrozenAccountScope::new(directory, ClientRoutingScope::all_accounts()) FrozenAccountScope::new(directory, ClientRoutingScope::all_accounts())
.with_fast_mode(fast_mode) .with_fast_mode_override(Some(fast_mode))
.with_request_profiles(profiles), .with_request_profiles(profiles),
), ),
&RoutingContext { &RoutingContext {
@@ -6414,6 +6400,8 @@ fn deadline_before_first_event_is_persisted_as_failed_attempt() {
#[test] #[test]
fn global_location_and_group_fast_policy_reach_every_account_retry() { fn global_location_and_group_fast_policy_reach_every_account_retry() {
use gateway_core::routing::{AccountGroupId, RoutingGroupSnapshot};
for mode in [ for mode in [
FastMode::Default, FastMode::Default,
FastMode::Enabled, FastMode::Enabled,
@@ -6425,12 +6413,67 @@ fn global_location_and_group_fast_policy_reach_every_account_retry() {
timezone: "Asia/Tokyo".parse().unwrap(), timezone: "Asia/Tokyo".parse().unwrap(),
..Default::default() ..Default::default()
}; };
let route_plan = plan_with_location_and_fast_policy( let kind = ProviderKind::new("openai").unwrap();
&operation, let first_group = AccountGroupId::new(format!("grp_{:032x}", 1)).unwrap();
plan(&operation).account_selection_policy(), let second_group = AccountGroupId::new(format!("grp_{:032x}", 2)).unwrap();
location.clone(), let second_mode = if mode == FastMode::Disabled {
mode, FastMode::Default
} else {
FastMode::Disabled
};
let directory = Arc::new(
RuntimeAccountDirectory::new(
[
("acct_first", first_group.clone()),
("acct_second", second_group.clone()),
]
.into_iter()
.map(|(account, group)| {
(
ProviderAccountId::new(account).unwrap(),
RuntimeAccount::new(kind.clone(), BTreeSet::from([group])),
)
})
.collect(),
)
.with_group_fast_modes(BTreeMap::from([
(first_group.clone(), mode),
(second_group.clone(), second_mode),
])),
); );
let scope = Arc::new(FrozenAccountScope::new(
Arc::clone(&directory),
ClientRoutingScope::restricted(
vec![
RoutingGroupSnapshot::new(first_group.clone(), "A".into()),
RoutingGroupSnapshot::new(second_group.clone(), "B".into()),
],
BTreeSet::from([first_group, second_group]),
BTreeSet::from([kind.clone()]),
)
.unwrap(),
));
let route_plan = RuntimeSnapshot::new(
ConfigRevision::new(1).unwrap(),
gateway_core::settings::SettingsValues::new(2, "smart", Default::default(), None, None)
.with_request_location(location.clone(), true),
vec![kind.clone()],
vec![ProviderModel::new(
kind,
UpstreamModelId::new("gpt-5").unwrap(),
ModelCapabilities::new(BTreeSet::from([operation.kind()]), Some(32_000)),
)],
Vec::new(),
)
.unwrap()
.with_account_directory(directory)
.plan(
&PublicModelId::new("gpt-5").unwrap(),
&operation,
Arc::clone(&scope),
&RoutingContext::default(),
)
.unwrap();
let (coordinator, _, provider) = coordinator(vec![ let (coordinator, _, provider) = coordinator(vec![
Script::Stream { Script::Stream {
account_id: "acct_first", account_id: "acct_first",
@@ -6459,12 +6502,17 @@ fn global_location_and_group_fast_policy_reach_every_account_retry() {
block_on(session.commit_downstream(Some(200))).unwrap(); block_on(session.commit_downstream(Some(200))).unwrap();
let contexts = provider.contexts.lock().unwrap(); let contexts = provider.contexts.lock().unwrap();
assert_eq!(contexts.len(), 2); assert_eq!(contexts.len(), 2);
assert!( for (context, account, expected) in [
contexts (&contexts[0], "acct_first", mode),
.iter() (&contexts[1], "acct_second", second_mode),
.all(|context| context.request_location() == Some(&location) ] {
&& context.fast_mode() == mode) assert_eq!(context.request_location(), Some(&location));
); assert!(Arc::ptr_eq(context.account_scope().unwrap(), &scope));
assert_eq!(
context.fast_mode_for_account(&ProviderAccountId::new(account).unwrap(), "gpt-5"),
expected,
);
}
} }
} }
@@ -2470,6 +2470,7 @@ impl Provider for PolicySelectingProvider {
account, account,
signals: AccountRuntimeSignals { signals: AccountRuntimeSignals {
in_flight: 0, in_flight: 0,
recent_requests: 0,
last_started_at: None, last_started_at: None,
quota_reset_at: None, quota_reset_at: None,
quota_reset_windows: None, quota_reset_windows: None,
@@ -3067,8 +3068,14 @@ impl Provider for ChargedProvider {
request: ProviderRequest, request: ProviderRequest,
context: AttemptContext, context: AttemptContext,
) -> Result<ProviderStream, ProviderError> { ) -> Result<ProviderStream, ProviderError> {
self.policies.lock().unwrap().push(context.fast_mode());
let candidate = request.candidate(); let candidate = request.candidate();
self.policies
.lock()
.unwrap()
.push(context.fast_mode_for_account(
&ProviderAccountId::new("acct_start").unwrap(),
candidate.upstream_model().unwrap().as_str(),
));
let metadata = ProviderCallMetadata::new( let metadata = ProviderCallMetadata::new(
candidate.provider().clone(), candidate.provider().clone(),
candidate.upstream_model().unwrap().clone(), candidate.upstream_model().unwrap().clone(),
@@ -4791,7 +4798,7 @@ fn start_snapshot_with_image_policy(
account_scope(&provider, "acct_start") account_scope(&provider, "acct_start")
.as_ref() .as_ref()
.clone() .clone()
.with_fast_mode(fast_mode) .with_fast_mode_override(Some(fast_mode))
.with_image_generation(allow_image_generation), .with_image_generation(allow_image_generation),
), ),
enabled, enabled,
@@ -5525,7 +5532,7 @@ fn entry_settings_freeze_authentication_and_rebase_only_explicit_overrides() {
.execution_values() .execution_values()
.unwrap() .unwrap()
.fast_mode, .fast_mode,
FastMode::Disabled Some(FastMode::Disabled)
); );
assert_eq!( assert_eq!(
prepared prepared
@@ -5648,7 +5655,7 @@ fn child_settings_recompute_key_scope_without_inheriting_parent_defaults() {
account_scope(&provider, "acct_start") account_scope(&provider, "acct_start")
.as_ref() .as_ref()
.clone() .clone()
.with_fast_mode(FastMode::Disabled) .with_fast_mode_override(Some(FastMode::Disabled))
.with_request_profiles(profiles(name)), .with_request_profiles(profiles(name)),
), ),
true, true,
@@ -5687,7 +5694,7 @@ fn child_settings_recompute_key_scope_without_inheriting_parent_defaults() {
let configuration = RequestSettings::new(snapshots.acquire().unwrap()) let configuration = RequestSettings::new(snapshots.acquire().unwrap())
.with_execution(parent.client().policy(), previous.timeout_ms); .with_execution(parent.client().policy(), previous.timeout_ms);
let mut values = previous.clone(); let mut values = previous.clone();
values.fast_mode = FastMode::Default; values.fast_mode = Some(FastMode::Default);
values.client_limits = RateLimits::unlimited(); values.client_limits = RateLimits::unlimited();
values.timeout_ms = Some(90_000); values.timeout_ms = Some(90_000);
let mut runtime = serde_json::to_value(&values.runtime).unwrap(); let mut runtime = serde_json::to_value(&values.runtime).unwrap();
@@ -5721,7 +5728,7 @@ fn child_settings_recompute_key_scope_without_inheriting_parent_defaults() {
Some(actual.clone()) Some(actual.clone())
); );
assert_eq!(actual.client_limits.max_concurrency, expected_limit); assert_eq!(actual.client_limits.max_concurrency, expected_limit);
assert_eq!(actual.fast_mode, expected_fast); assert_eq!(actual.fast_mode, Some(expected_fast));
assert_eq!(actual.timeout_ms, expected_timeout); assert_eq!(actual.timeout_ms, expected_timeout);
let facts = serde_json::to_value(actual.runtime).unwrap(); let facts = serde_json::to_value(actual.runtime).unwrap();
assert_eq!(facts["request_profiles"]["openai"]["identity"], profile); assert_eq!(facts["request_profiles"]["openai"]["identity"], profile);
@@ -10,6 +10,7 @@ mod extensions;
mod middleware; mod middleware;
mod policy; mod policy;
mod provider; mod provider;
mod recent_request_persistence;
mod response_control; mod response_control;
use gateway_core::engine::AttemptTrigger; use gateway_core::engine::AttemptTrigger;
@@ -75,6 +75,7 @@ fn candidate(id: &str) -> AccountCandidate {
.with_scheduling(None, AccountWeight::new(100).unwrap()), .with_scheduling(None, AccountWeight::new(100).unwrap()),
signals: AccountRuntimeSignals { signals: AccountRuntimeSignals {
in_flight: 0, in_flight: 0,
recent_requests: 0,
last_started_at: None, last_started_at: None,
quota_reset_at: None, quota_reset_at: None,
quota_reset_windows: None, quota_reset_windows: None,
@@ -242,6 +242,10 @@ fn provider_stream_should_report_common_account_success_and_first_output() {
let (failure_rate, first_output_ms) = feedback.scheduling_signals(&provider, &account); let (failure_rate, first_output_ms) = feedback.scheduling_signals(&provider, &account);
assert_eq!(failure_rate, Some(0)); assert_eq!(failure_rate, Some(0));
assert!(first_output_ms.is_some_and(|value| value >= 2)); assert!(first_output_ms.is_some_and(|value| value >= 2));
assert_eq!(
feedback.recent_requests(&provider, &account, Some("gpt-5")),
1
);
} }
#[test] #[test]
@@ -367,16 +371,25 @@ fn provider_stream_should_report_confirmed_sent_failure_but_ignore_unconfirmed_f
let metadata = ProviderCallMetadata::new( let metadata = ProviderCallMetadata::new(
provider.clone(), provider.clone(),
UpstreamModelId::new("grok-4.5").expect("valid model"), UpstreamModelId::new("grok-4.5").expect("valid model"),
account, account.clone(),
UpstreamTransport::new("http_sse").expect("valid transport"), UpstreamTransport::new("http_sse").expect("valid transport"),
); );
let events: EventStream = Box::pin(stream::iter([Err(ProviderError::new( let events: EventStream = Box::pin(stream::iter([
ProviderErrorKind::Transport, Ok(gateway_core::event::ProviderEvent::observation(
send_state, gateway_core::event::ProviderResponseObservation::new(
))])); UpstreamTransport::new("http_sse").unwrap(),
),
)),
Err(ProviderError::new(ProviderErrorKind::Transport, send_state)),
]));
let mut provider_stream = let mut provider_stream =
ProviderStream::new(metadata, events, ()).with_account_feedback(Arc::clone(&feedback)); ProviderStream::new(metadata, events, ()).with_account_feedback(Arc::clone(&feedback));
futures::executor::block_on(async { futures::executor::block_on(async {
provider_stream.next().await.unwrap().unwrap();
assert_eq!(
feedback.recent_requests(&provider, &account, Some("grok-4.5")),
0
);
assert!( assert!(
provider_stream provider_stream
.next() .next()
@@ -386,6 +399,17 @@ fn provider_stream_should_report_confirmed_sent_failure_but_ignore_unconfirmed_f
}); });
} }
for (account, count) in [
(&sent_account, 1),
(&ambiguous_account, 0),
(&not_sent_account, 0),
] {
assert_eq!(
feedback.recent_requests(&provider, account, Some("grok-4.5")),
count
);
}
assert_eq!( assert_eq!(
feedback.scheduling_signals(&provider, &sent_account).0, feedback.scheduling_signals(&provider, &sent_account).0,
Some(2_000) Some(2_000)
@@ -434,6 +458,10 @@ fn provider_stream_should_ignore_repeated_failures_rejected_by_the_filter() {
feedback.scheduling_signals(&provider, &account), feedback.scheduling_signals(&provider, &account),
(None, None) (None, None)
); );
assert_eq!(
feedback.recent_requests(&provider, &account, Some("gpt-5")),
100
);
} }
#[test] #[test]
@@ -0,0 +1,162 @@
//! 验证近期请求快照异步合并、慢存储隔离、关闭刷写及失败预算
use std::sync::{
Arc, Mutex,
atomic::{AtomicUsize, Ordering},
};
use std::time::{Duration, Instant};
use futures::{channel::oneshot, future::BoxFuture};
use gateway_core::{
account::{AccountFeedbackStats, ProviderAccountId, RecentRequestSnapshot, RecentRequestStore},
engine::RecentRequestPersistence,
error::{StoreError, StoreErrorKind},
identity::ProviderKind,
lifecycle::CancellationToken,
task::{DaemonTask, WorkerDaemonContext},
};
#[derive(Default)]
struct MemoryStore {
snapshot: Mutex<Option<RecentRequestSnapshot>>,
saves: AtomicUsize,
loads: AtomicUsize,
started: Mutex<Option<oneshot::Sender<()>>>,
gate: Mutex<Option<oneshot::Receiver<()>>>,
fail: bool,
stalled: bool,
}
impl RecentRequestStore for MemoryStore {
fn load(&self) -> BoxFuture<'_, Result<Option<RecentRequestSnapshot>, StoreError>> {
Box::pin(async move {
self.loads.fetch_add(1, Ordering::SeqCst);
if self.stalled {
return std::future::pending().await;
}
Ok(self.snapshot.lock().unwrap().clone())
})
}
fn save<'a>(
&'a self,
snapshot: &'a RecentRequestSnapshot,
ttl: Duration,
) -> BoxFuture<'a, Result<(), StoreError>> {
Box::pin(async move {
assert_eq!(ttl, Duration::from_secs(120));
self.saves.fetch_add(1, Ordering::SeqCst);
if let Some(started) = self.started.lock().unwrap().take() {
started.send(()).unwrap();
}
let gate = self.gate.lock().unwrap().take();
if let Some(gate) = gate {
gate.await.unwrap();
}
if self.stalled {
return std::future::pending().await;
}
if self.fail {
return Err(StoreError::new(StoreErrorKind::Unavailable));
}
*self.snapshot.lock().unwrap() = Some(snapshot.clone());
Ok(())
})
}
}
#[test]
fn periodic_snapshot_keeps_traffic_live_during_slow_save_and_flushes_latest_on_shutdown() {
futures::executor::block_on(async {
let stats = Arc::new(AccountFeedbackStats::default());
let provider = ProviderKind::new("openai").unwrap();
let account = ProviderAccountId::new("acct_async").unwrap();
let (entered, entering) = oneshot::channel();
let (release, released) = oneshot::channel();
let store = Arc::new(MemoryStore {
started: Mutex::new(Some(entered)),
gate: Mutex::new(Some(released)),
..Default::default()
});
let persistence = RecentRequestPersistence::new(stats.clone(), store.clone());
for _ in 0..100 {
let now = Instant::now();
stats.record_request_at(&provider, &account, "model", now, now);
}
assert_eq!(store.saves.load(Ordering::SeqCst), 0);
let cancellation = CancellationToken::new();
let context = WorkerDaemonContext::new(cancellation.clone());
let driver = async {
entering.await.unwrap();
let now = Instant::now();
stats.record_request_at(&provider, &account, "model", now, now);
assert_eq!(
stats.recent_requests(&provider, &account, Some("model")),
101
);
assert_eq!(store.loads.load(Ordering::SeqCst), 0);
cancellation.cancel();
release.send(()).unwrap();
};
let (result, ()) = futures::join!(persistence.run(context), driver);
result.unwrap();
assert_eq!(store.saves.load(Ordering::SeqCst), 2);
let restarted = Arc::new(AccountFeedbackStats::default());
RecentRequestPersistence::new(restarted.clone(), store)
.restore()
.await
.unwrap();
assert_eq!(
restarted.recent_requests(&provider, &account, Some("model")),
101
);
});
}
#[test]
fn failed_save_preserves_memory_and_reports_failure_to_supervision() {
futures::executor::block_on(async {
let stats = Arc::new(AccountFeedbackStats::default());
let provider = ProviderKind::new("openai").unwrap();
let account = ProviderAccountId::new("acct_failed").unwrap();
let now = Instant::now();
stats.record_request_at(&provider, &account, "model", now, now);
let store = Arc::new(MemoryStore {
fail: true,
..Default::default()
});
let persistence = RecentRequestPersistence::new(stats.clone(), store.clone());
let stopping = CancellationToken::new();
stopping.cancel();
assert!(
persistence
.run(WorkerDaemonContext::new(stopping))
.await
.is_err()
);
assert_eq!(store.saves.load(Ordering::SeqCst), 1);
assert_eq!(stats.recent_requests(&provider, &account, Some("model")), 1);
});
}
#[test]
fn stalled_restore_and_shutdown_have_bounded_waits() {
futures::executor::block_on(async {
let stats = Arc::new(AccountFeedbackStats::default());
let store = Arc::new(MemoryStore {
stalled: true,
..Default::default()
});
let persistence = RecentRequestPersistence::new(stats, store);
let stopping = CancellationToken::new();
stopping.cancel();
let began = Instant::now();
let (restore, save) = futures::join!(
persistence.restore(),
persistence.run(WorkerDaemonContext::new(stopping)),
);
assert!(restore.is_err());
assert!(save.is_err());
assert!(began.elapsed() < Duration::from_secs(4));
});
}
@@ -186,7 +186,10 @@ fn gateway_error_should_keep_client_visible_upstream_fields_out_of_safe_diagnost
)); ));
let gateway = GatewayError::from_provider(&error); let gateway = GatewayError::from_provider(&error);
assert_eq!(gateway.safe_message(), "Account quota is exhausted."); assert_eq!(
gateway.safe_message(),
"Upstream account quota is exhausted."
);
assert_eq!(gateway.client_message(), message); assert_eq!(gateway.client_message(), message);
assert_eq!(gateway.client_error_code(), Some("quota_exhausted")); assert_eq!(gateway.client_error_code(), Some("quota_exhausted"));
assert_eq!(gateway.client_error_type(), Some("rate_limit_error")); assert_eq!(gateway.client_error_type(), Some("rate_limit_error"));
@@ -9,6 +9,7 @@ fn scheduling_state_preserves_provider_neutral_signals() {
account.clone(), account.clone(),
AccountRuntimeSignals { AccountRuntimeSignals {
in_flight: 2, in_flight: 2,
recent_requests: 0,
last_started_at: None, last_started_at: None,
quota_reset_at: None, quota_reset_at: None,
quota_reset_windows: None, quota_reset_windows: None,
@@ -37,6 +37,7 @@ fn candidate(id: &str, busy: bool) -> AccountCandidate {
inherited_concurrency: None, inherited_concurrency: None,
signals: AccountRuntimeSignals { signals: AccountRuntimeSignals {
in_flight: u32::from(busy), in_flight: u32::from(busy),
recent_requests: 0,
last_started_at: None, last_started_at: None,
quota_reset_at: None, quota_reset_at: None,
quota_reset_windows: None, quota_reset_windows: None,
@@ -53,7 +53,7 @@ fn policy_with_profiles(
Arc::new( Arc::new(
FrozenAccountScope::new(Arc::default(), ClientRoutingScope::all_accounts()) FrozenAccountScope::new(Arc::default(), ClientRoutingScope::all_accounts())
.with_request_profiles(overrides) .with_request_profiles(overrides)
.with_fast_mode(FastMode::Disabled), .with_fast_mode_override(Some(FastMode::Disabled)),
), ),
true, true,
RateLimits { RateLimits {
@@ -153,7 +153,7 @@ fn scope_changes_recompute_defaults_and_inherit_only_explicit_overrides() {
values.runtime = values values.runtime = values
.runtime .runtime
.with_model_mappings(BTreeMap::from([("alias".into(), "model".into())])); .with_model_mappings(BTreeMap::from([("alias".into(), "model".into())]));
values.fast_mode = FastMode::Default; values.fast_mode = Some(FastMode::Default);
values.client_limits = RateLimits::unlimited(); values.client_limits = RateLimits::unlimited();
values.timeout_ms = Some(90_000); values.timeout_ms = Some(90_000);
let changed = original.replace_execution(&values, "plugin").unwrap(); let changed = original.replace_execution(&values, "plugin").unwrap();
@@ -168,14 +168,14 @@ fn scope_changes_recompute_defaults_and_inherit_only_explicit_overrides() {
parent_values.runtime.request_profiles(), parent_values.runtime.request_profiles(),
&profiles(&[("openai", "parent"), ("xai", "second")]) &profiles(&[("openai", "parent"), ("xai", "second")])
); );
assert_eq!(parent_values.fast_mode, FastMode::Default); assert_eq!(parent_values.fast_mode, Some(FastMode::Default));
let child_settings = rebased.with_execution(&child, Some(60_000)); let child_settings = rebased.with_execution(&child, Some(60_000));
let child_values = child_settings.execution_values().unwrap(); let child_values = child_settings.execution_values().unwrap();
assert_eq!( assert_eq!(
child_values.runtime.request_profiles(), child_values.runtime.request_profiles(),
&profiles(&[("openai", "child"), ("xai", "second")]) &profiles(&[("openai", "child"), ("xai", "second")])
); );
assert_eq!(child_values.fast_mode, FastMode::Disabled); assert_eq!(child_values.fast_mode, Some(FastMode::Disabled));
assert_eq!(child_values.client_limits, child.limits()); assert_eq!(child_values.client_limits, child.limits());
assert_eq!(child_values.timeout_ms, Some(60_000)); assert_eq!(child_values.timeout_ms, Some(60_000));
assert_eq!(child_settings.snapshot().mapped_model("alias"), "model"); assert_eq!(child_settings.snapshot().mapped_model("alias"), "model");
@@ -186,6 +186,81 @@ fn scope_changes_recompute_defaults_and_inherit_only_explicit_overrides() {
); );
} }
#[test]
fn group_fast_policy_survives_settings_resolution_until_explicitly_overridden() {
use gateway_core::{
account::ProviderAccountId,
routing::{AccountGroupId, RoutingGroupSnapshot, RuntimeAccount, RuntimeAccountDirectory},
};
let group = AccountGroupId::new(format!("grp_{:032x}", 1)).unwrap();
let account = ProviderAccountId::new("acct_group_fast").unwrap();
let provider = ProviderKind::new("openai").unwrap();
let scope = Arc::new(FrozenAccountScope::new(
Arc::new(
RuntimeAccountDirectory::new(BTreeMap::from([(
account.clone(),
RuntimeAccount::new(provider.clone(), [group.clone()].into()),
)]))
.with_group_fast_modes([(group.clone(), FastMode::Disabled)].into()),
),
ClientRoutingScope::restricted(
vec![RoutingGroupSnapshot::new(group.clone(), "Standard".into())],
[group].into(),
[provider].into(),
)
.unwrap(),
));
let key = |name: &str| {
ClientPolicy::new(
ClientApiKeyId::new(name).unwrap(),
PlaintextClientApiKey::new(format!("fixture-{name}")).unwrap(),
scope.clone(),
true,
RateLimits::unlimited(),
)
};
let parent = key("parent");
let settings = RequestSettings::new(snapshot(1, "host")).with_execution(&parent, None);
assert_eq!(settings.execution_values().unwrap().fast_mode, None);
let resolved = |settings: &RequestSettings, key| {
settings
.apply_policy(key)
.account_scope()
.fast_mode_for_account(&account, "model")
};
assert_eq!(resolved(&settings, parent.clone()), FastMode::Disabled);
let unchanged = settings
.replace_execution(&settings.execution_values().unwrap(), "pass-through")
.unwrap();
assert_eq!(resolved(&unchanged, parent.clone()), FastMode::Disabled);
let mut values = settings.execution_values().unwrap();
values.fast_mode = Some(FastMode::Default);
let direct_default = settings
.replace_execution(&values, "follow-client")
.unwrap();
assert_eq!(resolved(&direct_default, parent.clone()), FastMode::Default);
values.fast_mode = Some(FastMode::Enabled);
let enabled = settings.replace_execution(&values, "force-fast").unwrap();
assert_eq!(resolved(&enabled, parent.clone()), FastMode::Enabled);
values.fast_mode = Some(FastMode::Default);
let default = enabled.replace_execution(&values, "follow-client").unwrap();
assert_eq!(resolved(&default, parent.clone()), FastMode::Default);
values.fast_mode = None;
let cleared = default.replace_execution(&values, "group-policy").unwrap();
assert_eq!(resolved(&cleared, parent.clone()), FastMode::Disabled);
assert_eq!(
cleared.inspect()["execution"]["fast_mode"]["value"],
serde_json::Value::Null
);
let child = key("child");
assert_eq!(
resolved(&default.with_execution(&child, None), child),
FastMode::Disabled
);
assert_eq!(resolved(&settings, parent), FastMode::Disabled);
}
#[test] #[test]
fn explicitly_selecting_the_host_profiles_overrides_keys_after_rebase() { fn explicitly_selecting_the_host_profiles_overrides_keys_after_rebase() {
let host = snapshot(1, "first"); let host = snapshot(1, "first");
@@ -2727,7 +2727,7 @@ fn decompression_setting_should_validate_and_remain_frozen_across_publication()
} }
#[test] #[test]
fn fast_mode_merges_only_bound_groups_without_changing_account_scope() { fn fast_mode_merges_only_enabled_bound_groups_of_the_selected_account() {
use gateway_core::account::ProviderAccountId; use gateway_core::account::ProviderAccountId;
use gateway_core::routing::AccountGroupId; use gateway_core::routing::AccountGroupId;
for (mode, other_mode, expected) in [ for (mode, other_mode, expected) in [
@@ -2758,6 +2758,8 @@ fn fast_mode_merges_only_bound_groups_without_changing_account_scope() {
let open_group_id = let open_group_id =
AccountGroupId::new("grp_00000000000000000000000000000002").unwrap(); AccountGroupId::new("grp_00000000000000000000000000000002").unwrap();
let account_id = ProviderAccountId::new("acct_fast_policy").unwrap(); let account_id = ProviderAccountId::new("acct_fast_policy").unwrap();
let first_account = ProviderAccountId::new("acct_first_group").unwrap();
let second_account = ProviderAccountId::new("acct_second_group").unwrap();
let facts = SnapshotFacts::new( let facts = SnapshotFacts::new(
revision(1), revision(1),
revision(1), revision(1),
@@ -2786,11 +2788,19 @@ fn fast_mode_merges_only_bound_groups_without_changing_account_scope() {
) )
.with_fast_mode(other_mode), .with_fast_mode(other_mode),
], ],
vec![SnapshotProviderAccountFacts::new( [&account_id, &first_account, &second_account]
account_id.clone(), .into_iter()
"alpha", .map(|id| SnapshotProviderAccountFacts::new(id.clone(), "alpha"))
)], .collect(),
vec![ vec![
SnapshotAccountGroupMemberFacts::new(
group_id.clone(),
first_account.clone(),
),
SnapshotAccountGroupMemberFacts::new(
open_group_id.clone(),
second_account.clone(),
),
SnapshotAccountGroupMemberFacts::new(group_id, account_id.clone()), SnapshotAccountGroupMemberFacts::new(group_id, account_id.clone()),
SnapshotAccountGroupMemberFacts::new(open_group_id, account_id.clone()), SnapshotAccountGroupMemberFacts::new(open_group_id, account_id.clone()),
], ],
@@ -2818,16 +2828,99 @@ fn fast_mode_merges_only_bound_groups_without_changing_account_scope() {
&Default::default(), &Default::default(),
) )
.unwrap(); .unwrap();
for (account, effective) in [
(
&account_id,
if group_enabled { expected } else { other_mode },
),
(
&first_account,
if group_enabled {
mode
} else {
FastMode::Default
},
),
(&second_account, other_mode),
] {
assert_eq!(
plan.account_scope()
.fast_mode_for_account(account, "public-model"),
if bound { effective } else { FastMode::Default },
"account={account}, mode={mode:?}, other={other_mode:?}, enabled={group_enabled}, bound={bound}"
);
}
assert_eq!( assert_eq!(
plan.fast_mode(), plan.account_scope().allows(&first_account),
if bound { expected } else { FastMode::Default }, !bound || group_enabled
"mode={mode:?}, other={other_mode:?}, enabled={group_enabled}, bound={bound}"
); );
} }
} }
} }
} }
#[test]
fn fast_mode_ignores_unbound_groups_and_groups_that_deny_the_model() {
use gateway_core::account::{AccountModelAccess, AccountModelAccessMode, ProviderAccountId};
use gateway_core::routing::AccountGroupId;
let group = |id| AccountGroupId::new(format!("grp_{id:032x}")).unwrap();
let account = ProviderAccountId::new("acct_model_fast").unwrap();
let facts = SnapshotFacts::new(
revision(1),
revision(1),
SettingsValues::new(3, "smart", BTreeMap::new(), None, None),
vec![SnapshotClientPolicyFacts::new(
ClientApiKeyId::new("key_model_fast").unwrap(),
PlaintextClientApiKey::new("fixture-model-fast").unwrap(),
vec![group(1), group(2)],
RateLimits::unlimited(),
)],
vec![
SnapshotAccountGroupFacts::new(group(1), "Fast".into(), true)
.with_fast_mode(FastMode::Enabled)
.with_model_access(
AccountModelAccess::new(
AccountModelAccessMode::Allowlist,
vec!["fast-model".into()],
)
.unwrap(),
),
SnapshotAccountGroupFacts::new(group(2), "Standard".into(), true)
.with_fast_mode(FastMode::Disabled)
.with_model_access(
AccountModelAccess::new(
AccountModelAccessMode::Denylist,
vec!["fast-model".into()],
)
.unwrap(),
),
SnapshotAccountGroupFacts::new(group(3), "Unbound".into(), true)
.with_fast_mode(FastMode::Disabled),
],
vec![SnapshotProviderAccountFacts::new(account.clone(), "alpha")],
(1..=3)
.map(|id| SnapshotAccountGroupMemberFacts::new(group(id), account.clone()))
.collect(),
);
let snapshot = block_on(
RuntimeSnapshotCompiler::new(
Arc::new(TestSnapshotStore::new(Ok(facts))),
Arc::new(TestCatalog::Unavailable),
)
.compile(),
)
.unwrap();
let scope = snapshot.client_policies().next().unwrap().account_scope();
for (model, expected) in [
("fast-model", FastMode::Enabled),
("standard-model", FastMode::Disabled),
] {
assert!(scope.allows_model(&account, model));
assert_eq!(scope.fast_mode_for_account(&account, model), expected);
}
}
#[test] #[test]
fn group_feature_permissions_merge_independently_with_deny_precedence() { fn group_feature_permissions_merge_independently_with_deny_precedence() {
use gateway_core::account::ProviderAccountId; use gateway_core::account::ProviderAccountId;
+1
View File
@@ -48,6 +48,7 @@ tracing = "0.1.44"
tracing-appender = "0.2.5" tracing-appender = "0.2.5"
tracing-subscriber = { version = "0.3.23", features = ["env-filter", "json"] } tracing-subscriber = { version = "0.3.23", features = ["env-filter", "json"] }
yaml-rust2 = "0.13.0" yaml-rust2 = "0.13.0"
uuid = { version = "1.23.3", features = ["v4"] }
[dev-dependencies] [dev-dependencies]
hyper = { version = "=1.11.1", default-features = false, features = ["server"] } hyper = { version = "=1.11.1", default-features = false, features = ["server"] }
@@ -13,9 +13,7 @@ use yaml_rust2::Yaml;
use super::diagnostics::Diagnostics; use super::diagnostics::Diagnostics;
use super::metadata::{Metadata, published_version}; use super::metadata::{Metadata, published_version};
use super::release::{ use super::release::{GitHubRelease, base_update_detail, update_target_allowed};
GitHubRelease, base_update_detail, detail_from_release, update_target_allowed,
};
use super::{OperationError, SystemUpdateConfig, conflict, upstream}; use super::{OperationError, SystemUpdateConfig, conflict, upstream};
const NORMAL: Duration = Duration::from_secs(1200); const NORMAL: Duration = Duration::from_secs(1200);
@@ -155,11 +153,14 @@ impl ReleaseCache {
let (mut detail, target) = candidate(config, channel, &index)?; let (mut detail, target) = candidate(config, channel, &index)?;
detail.cached = cached; detail.cached = cached;
if check != Check::Summary || detail.has_update { if check != Check::Summary || detail.has_update {
let (release, reused) = self.exact(config, &target, age, diagnostics).await?; let (release, reused) = self
.exact(config, &target, detail.has_update, age, diagnostics)
.await?;
if let Some(release) = release if let Some(release) = release
&& check != Check::Summary && check != Check::Summary
{ {
detail = detail_from_release(config, &release, channel); detail.release_url.clone_from(&release.html_url);
detail.notes = release.body.clone().or_else(|| release.name.clone());
} }
detail.cached = cached && reused; detail.cached = cached && reused;
} }
@@ -173,6 +174,7 @@ impl ReleaseCache {
&self, &self,
config: &SystemUpdateConfig, config: &SystemUpdateConfig,
target: &Version, target: &Version,
has_update: bool,
age: Duration, age: Duration,
diagnostics: &Diagnostics, diagnostics: &Diagnostics,
) -> Result<(Option<Arc<GitHubRelease>>, bool), OperationError> { ) -> Result<(Option<Arc<GitHubRelease>>, bool), OperationError> {
@@ -191,8 +193,12 @@ impl ReleaseCache {
entries.push_back((target.clone(), Arc::clone(&slot))); entries.push_back((target.clone(), Arc::clone(&slot)));
slot slot
}; };
slot.get(age, self.metadata.release(config, target), diagnostics) slot.get(
.await age,
self.metadata.release(config, target, has_update),
diagnostics,
)
.await
} }
pub(super) async fn install( pub(super) async fn install(
@@ -209,10 +215,10 @@ impl ReleaseCache {
.get(Duration::ZERO, self.metadata.index(config), diagnostics) .get(Duration::ZERO, self.metadata.index(config), diagnostics)
.await?; .await?;
let (detail, target) = candidate(config, channel, &index)?; let (detail, target) = candidate(config, channel, &index)?;
if !detail.has_update || detail.latest_version != confirmed { if !detail.has_update || detail.latest_version.as_deref() != Some(confirmed) {
return Err(conflict("远端最新版本已变化,请重新检查并确认")); return Err(conflict("远端最新版本已变化,请重新检查并确认"));
} }
self.exact(config, &target, Duration::ZERO, diagnostics) self.exact(config, &target, true, Duration::ZERO, diagnostics)
.await? .await?
.0 .0
.ok_or_else(|| upstream("发布索引指向的 Release 不存在")) .ok_or_else(|| upstream("发布索引指向的 Release 不存在"))
@@ -231,11 +237,7 @@ fn candidate(
.map_err(|_| conflict("当前版本号无效"))?; .map_err(|_| conflict("当前版本号无效"))?;
let target = published_version(index, &current, channel)?; let target = published_version(index, &current, channel)?;
let mut detail = base_update_detail(config, channel, None, None); let mut detail = base_update_detail(config, channel, None, None);
if update_target_allowed(&current, &target, channel) { detail.latest_version = Some(target.to_string());
detail.latest_version = target.to_string(); detail.has_update = update_target_allowed(&current, &target, channel);
detail.has_update = true; Ok((detail, target))
Ok((detail, target))
} else {
Ok((detail, current))
}
} }
@@ -83,6 +83,7 @@ impl Metadata {
&self, &self,
config: &SystemUpdateConfig, config: &SystemUpdateConfig,
version: &Version, version: &Version,
has_update: bool,
) -> Result<Option<Arc<GitHubRelease>>, OperationError> { ) -> Result<Option<Arc<GitHubRelease>>, OperationError> {
let mut url = let mut url =
Url::parse(&config.github_api_base).map_err(|_| invalid("发行查询地址无效"))?; Url::parse(&config.github_api_base).map_err(|_| invalid("发行查询地址无效"))?;
@@ -109,7 +110,7 @@ impl Metadata {
if release.tag_name != tag || release.draft || release.prerelease != prerelease { if release.tag_name != tag || release.draft || release.prerelease != prerelease {
return Err(upstream("GitHub 发行身份与发布索引不符")); return Err(upstream("GitHub 发行身份与发布索引不符"));
} }
if config.version.trim_start_matches('v') != version { if has_update {
release.install_assets(&version, &config.github_api_base)?; release.install_assets(&version, &config.github_api_base)?;
} }
Ok(Some(Arc::new(release))) Ok(Some(Arc::new(release)))
@@ -37,6 +37,7 @@ const MAX_OFFICIAL_PLUGIN_MANIFEST_SIZE: u64 = 256 * 1024;
/// gateway-admin 消费的真实进程/文件系统操作实现 /// gateway-admin 消费的真实进程/文件系统操作实现
#[derive(Clone)] #[derive(Clone)]
pub struct ProcessSystemOperations { pub struct ProcessSystemOperations {
instance_id: String,
cancellation: CancellationToken, cancellation: CancellationToken,
events: Arc<UpdateEvents>, events: Arc<UpdateEvents>,
config: Arc<SystemUpdateConfig>, config: Arc<SystemUpdateConfig>,
@@ -62,6 +63,7 @@ impl ProcessSystemOperations {
ReleaseFiles::installed(&config) ReleaseFiles::installed(&config)
})); }));
Self { Self {
instance_id: uuid::Uuid::new_v4().to_string(),
cancellation, cancellation,
events: Arc::new(UpdateEvents::default()), events: Arc::new(UpdateEvents::default()),
config: Arc::new(config), config: Arc::new(config),
@@ -350,6 +352,8 @@ impl SystemOperations for ProcessSystemOperations {
.await; .await;
Ok(SystemVersion { Ok(SystemVersion {
version: self.config.version.clone(), version: self.config.version.clone(),
instance_id: self.instance_id.clone(),
restart_supported: self.config.self_restart_enabled,
git_sha: self.config.git_sha.clone(), git_sha: self.config.git_sha.clone(),
build_time: self.config.build_time.clone(), build_time: self.config.build_time.clone(),
deployment_mode: self.config.deployment_mode.clone(), deployment_mode: self.config.deployment_mode.clone(),
@@ -72,36 +72,6 @@ impl GitHubRelease {
} }
} }
pub(crate) fn detail_from_release(
config: &SystemUpdateConfig,
release: &GitHubRelease,
channel: UpdateChannel,
) -> SystemUpdateDetail {
let unsupported_reason = config.update_support_error();
let latest_version = normalize_version(&release.tag_name);
let has_update = validate_update_target(&config.version, &latest_version, channel).is_ok();
if unsupported_reason.is_some()
|| (!has_update && latest_version != normalize_version(&config.version))
{
return base_update_detail(config, channel, unsupported_reason, None);
}
SystemUpdateDetail {
policy: update_policy(config, channel),
current_version: config.version.clone(),
latest_version,
has_update,
deployment_mode: config.deployment_mode.clone(),
build_type: config.build_type.clone(),
release_url: release.html_url.clone(),
notes: release.body.clone().or_else(|| release.name.clone()),
cached: false,
update_supported: true,
unsupported_reason: None,
warning: None,
retry_at: None,
}
}
pub(crate) fn confirmed_target(target: Option<String>) -> Result<String, OperationError> { pub(crate) fn confirmed_target(target: Option<String>) -> Result<String, OperationError> {
let target = target.ok_or_else(|| conflict("请先确认目标版本"))?; let target = target.ok_or_else(|| conflict("请先确认目标版本"))?;
let target = normalize_version(&target); let target = normalize_version(&target);
@@ -364,14 +334,14 @@ pub(super) fn base_update_detail(
SystemUpdateDetail { SystemUpdateDetail {
policy: update_policy(config, channel), policy: update_policy(config, channel),
current_version: config.version.clone(), current_version: config.version.clone(),
latest_version: config.version.clone(), latest_version: None,
has_update: false, has_update: false,
deployment_mode: config.deployment_mode.clone(), deployment_mode: config.deployment_mode.clone(),
build_type: config.build_type.clone(), build_type: config.build_type.clone(),
release_url: None, release_url: None,
notes: None, notes: None,
cached: false, cached: false,
update_supported: unsupported_reason.is_none() && warning.is_none(), update_supported: unsupported_reason.is_none(),
unsupported_reason, unsupported_reason,
warning: warning.map(|error| error.message().to_owned()), warning: warning.map(|error| error.message().to_owned()),
retry_at: warning.and_then(OperationError::retry_at), retry_at: warning.and_then(OperationError::retry_at),
+12 -5
View File
@@ -122,11 +122,12 @@ impl WorkerSupervisor {
health: &self.health, health: &self.health,
}; };
let deadline = tokio::time::Instant::now() + timeout; let deadline = tokio::time::Instant::now() + timeout;
for (_, handle) in &mut shutdown.handles { for (worker, handle) in &mut shutdown.handles {
if tokio::time::timeout_at(deadline, &mut *handle) if tokio::time::timeout_at(deadline, &mut *handle)
.await .await
.is_err() .is_err()
{ {
tracing::warn!(target: "gateway_shutdown", %worker, "后台任务收尾超时,强制终止");
handle.abort(); handle.abort();
let _ = handle.await; let _ = handle.await;
} }
@@ -459,6 +460,7 @@ async fn acquire_and_run(
let acquisition = AssertUnwindSafe(leader_lease.try_acquire(request)).catch_unwind(); let acquisition = AssertUnwindSafe(leader_lease.try_acquire(request)).catch_unwind();
tokio::pin!(acquisition); tokio::pin!(acquisition);
let acquisition = tokio::select! { let acquisition = tokio::select! {
biased;
() = cancellation.cancelled() => return ScheduledOutcome::ShuttingDown, () = cancellation.cancelled() => return ScheduledOutcome::ShuttingDown,
acquisition = &mut acquisition => acquisition, acquisition = &mut acquisition => acquisition,
}; };
@@ -490,12 +492,13 @@ async fn run_local_cycle(
.catch_unwind(); .catch_unwind();
tokio::pin!(cycle); tokio::pin!(cycle);
tokio::select! { tokio::select! {
outcome = &mut cycle => task_result(outcome), biased;
() = cancellation.cancelled() => { () = cancellation.cancelled() => {
cycle_cancel.cancel(); cycle_cancel.cancel();
let _ = cycle.await; let _ = cycle.await;
ScheduledOutcome::ShuttingDown ScheduledOutcome::ShuttingDown
} }
outcome = &mut cycle => task_result(outcome),
} }
} }
@@ -527,17 +530,21 @@ async fn run_leased_cycle(
let outcome = loop { let outcome = loop {
tokio::select! { tokio::select! {
result = &mut cycle => break task_result(result), biased;
() = cancellation.cancelled() => { () = cancellation.cancelled() => {
cycle_cancel.cancel(); cycle_cancel.cancel();
let _ = cycle.await; let _ = cycle.await;
break ScheduledOutcome::ShuttingDown; break ScheduledOutcome::ShuttingDown;
} }
result = &mut cycle => break task_result(result),
() = &mut renewal => { () = &mut renewal => {
let renewed = renew_guard( let Some(renewed) = cancellation.run_until_cancelled(renew_guard(
guard.as_mut(), guard.as_mut(),
schedule.leader_lease_renewal_interval(), schedule.leader_lease_renewal_interval(),
).await; )).await else {
// 返回循环首个取消分支,统一等待正在执行的周期收尾
continue;
};
if let Err(error) = renewed { if let Err(error) = renewed {
cycle_cancel.cancel(); cycle_cancel.cancel();
let _ = cycle.await; let _ = cycle.await;
@@ -30,7 +30,7 @@ async fn temporary_channel_should_filter_future_releases_without_changing_runnin
.update_detail(SystemUpdateCheck::Detail, Some(channel)) .update_detail(SystemUpdateCheck::Detail, Some(channel))
.await .await
.expect("detail"); .expect("detail");
assert_eq!(detail.latest_version, target); assert_eq!(detail.latest_version.as_deref(), Some(target));
assert_eq!(detail.policy.channel, channel); assert_eq!(detail.policy.channel, channel);
assert_eq!( assert_eq!(
detail.policy.available_channels, detail.policy.available_channels,
@@ -42,11 +42,11 @@ async fn temporary_channel_should_filter_future_releases_without_changing_runnin
.await .await
.expect("cached"); .expect("cached");
assert!(cached.cached); assert!(cached.cached);
assert_eq!(cached.latest_version, target); assert_eq!(cached.latest_version.as_deref(), Some(target));
} }
let version = service.version().await.expect("default check"); let version = service.version().await.expect("default check");
assert_eq!(version.update_channel, "stable"); assert_eq!(version.update_channel, "stable");
assert_eq!(version.latest_version, "1.1.0"); assert_eq!(version.latest_version.as_deref(), Some("1.1.0"));
assert!(!fixture.state().exists(), "检查通道不能写入实例偏好"); assert!(!fixture.state().exists(), "检查通道不能写入实例偏好");
let requests = server.received_requests().await.expect("requests"); let requests = server.received_requests().await.expect("requests");
assert_eq!(requests.len(), 5); assert_eq!(requests.len(), 5);
@@ -56,17 +56,27 @@ async fn temporary_channel_should_filter_future_releases_without_changing_runnin
async fn reopening_should_infer_running_channel_and_switching_to_stable_should_not_downgrade() { async fn reopening_should_infer_running_channel_and_switching_to_stable_should_not_downgrade() {
let server = MockServer::start().await; let server = MockServer::start().await;
let fixture = Fixture::new(); let fixture = Fixture::new();
fixture.mount_release_once(&server, "1.0.0").await; mount_index(&server, fixture_index("1.0.0")).await;
Mock::given(path("/repos/owner/repository/releases/tags/v1.0.0"))
.respond_with(release_response("1.0.0", Vec::new()))
.mount(&server)
.await;
let mut config = fixture.config(&format!("{}/repos", server.uri())); let mut config = fixture.config(&format!("{}/repos", server.uri()));
config.version = "1.1.0-beta.1".into(); config.version = "1.1.0-beta.1".into();
let service = ProcessSystemOperations::new(CancellationToken::new(), config.clone()); let service = ProcessSystemOperations::new(CancellationToken::new(), config.clone());
let temporary = service for check in [SystemUpdateCheck::Summary, SystemUpdateCheck::Refresh] {
.update_detail(SystemUpdateCheck::Refresh, Some(Stable)) let temporary = service
.await .update_detail(check, Some(Stable))
.expect("view stable"); .await
assert_eq!(temporary.policy.channel, Stable); .expect("view stable");
assert!(!temporary.has_update); assert_eq!(temporary.policy.channel, Stable);
assert_eq!(temporary.latest_version, "1.1.0-beta.1"); assert!(!temporary.has_update);
assert_eq!(temporary.latest_version.as_deref(), Some("1.0.0"));
assert_eq!(
temporary.notes.is_some(),
check != SystemUpdateCheck::Summary
);
}
assert_eq!( assert_eq!(
service service
.update_detail(SystemUpdateCheck::Detail, None) .update_detail(SystemUpdateCheck::Detail, None)
@@ -231,7 +241,7 @@ async fn inferred_prerelease_policy_should_follow_future_minor_and_patch_release
.await .await
.expect("check"); .expect("check");
assert!(detail.has_update); assert!(detail.has_update);
assert_eq!(detail.latest_version, target); assert_eq!(detail.latest_version.as_deref(), Some(target));
assert_eq!( assert_eq!(
complete_update(&service, target).await.operation.status, complete_update(&service, target).await.operation.status,
SystemOperationStatus::Succeeded SystemOperationStatus::Succeeded
@@ -78,7 +78,7 @@ async fn discovery_request_budget_is_constant_under_load() {
.update_detail(SystemUpdateCheck::Summary, None) .update_detail(SystemUpdateCheck::Summary, None)
.await .await
.unwrap(); .unwrap();
assert_eq!(summary.latest_version, target); assert_eq!(summary.latest_version.as_deref(), Some(target.as_str()));
assert!(summary.notes.is_none()); assert!(summary.notes.is_none());
assert_eq!(server.received_requests().await.unwrap().len(), 2); assert_eq!(server.received_requests().await.unwrap().len(), 2);
@@ -96,7 +96,7 @@ async fn discovery_request_budget_is_constant_under_load() {
} }
while let Some(detail) = callers.join_next().await { while let Some(detail) = callers.join_next().await {
let detail = detail.unwrap(); let detail = detail.unwrap();
assert_eq!(detail.latest_version, target); assert_eq!(detail.latest_version.as_deref(), Some(target.as_str()));
assert_eq!(detail.notes.as_deref(), Some("notes")); assert_eq!(detail.notes.as_deref(), Some("notes"));
} }
for _ in 0..64 { for _ in 0..64 {
@@ -199,6 +199,10 @@ async fn api_cooldown_is_shared_and_summary_does_not_advertise_an_unverified_rel
.await .await
.unwrap(); .unwrap();
assert!(first.warning.is_some()); assert!(first.warning.is_some());
assert!(first.update_supported);
assert!(first.unsupported_reason.is_none());
assert!(!first.has_update);
assert!(first.latest_version.is_none());
let retry_at = first.retry_at.expect("限流应提供重试时间"); let retry_at = first.retry_at.expect("限流应提供重试时间");
assert!((298..=300).contains(&(retry_at - chrono::Utc::now()).num_seconds())); assert!((298..=300).contains(&(retry_at - chrono::Utc::now()).num_seconds()));
for _ in 0..32 { for _ in 0..32 {
@@ -306,7 +310,11 @@ async fn install_rechecks_even_a_warm_candidate_and_never_downloads_a_changed_ta
.await .await
.unwrap(); .unwrap();
assert!(detail.has_update); assert!(detail.has_update);
let status = complete_update(&service, &detail.latest_version).await; let status = complete_update(
&service,
detail.latest_version.as_deref().expect("confirmed target"),
)
.await;
assert_eq!(status.operation.status, SystemOperationStatus::Failed); assert_eq!(status.operation.status, SystemOperationStatus::Failed);
assert!(status.operation.error.unwrap().contains("重新检查并确认")); assert!(status.operation.error.unwrap().contains("重新检查并确认"));
assert_eq!(server.received_requests().await.unwrap().len(), 3); assert_eq!(server.received_requests().await.unwrap().len(), 3);
@@ -142,6 +142,8 @@ async fn restart_should_request_process_restart_inside_docker() {
config.deployment_mode = "docker".to_owned(); config.deployment_mode = "docker".to_owned();
let shutdown = CancellationToken::new(); let shutdown = CancellationToken::new();
let service = ProcessSystemOperations::new(shutdown.clone(), config); let service = ProcessSystemOperations::new(shutdown.clone(), config);
assert!(!service.update_status().await.expect("status").need_restart);
assert!(service.version().await.expect("version").restart_supported);
service service
.restart(Arc::new(AllowingUpdatePreflight)) .restart(Arc::new(AllowingUpdatePreflight))
.await .await
@@ -152,6 +154,48 @@ async fn restart_should_request_process_restart_inside_docker() {
.expect("shutdown requested"); .expect("shutdown requested");
} }
#[tokio::test]
async fn version_should_distinguish_same_version_service_instances() {
let fixture = Fixture::new();
let config = fixture.config("http://127.0.0.1:1/repos");
let service = ProcessSystemOperations::new(CancellationToken::new(), config.clone());
let version = service.version().await.expect("version");
assert!(!version.instance_id.is_empty());
assert_eq!(
service
.clone()
.version()
.await
.expect("same instance")
.instance_id,
version.instance_id
);
let replacement = ProcessSystemOperations::new(CancellationToken::new(), config);
let restarted = replacement.version().await.expect("new instance");
assert_eq!(restarted.version, version.version);
assert_ne!(restarted.instance_id, version.instance_id);
}
#[tokio::test]
async fn version_should_report_restart_disabled_when_host_rejects_it() {
let fixture = Fixture::new();
let mut config = fixture.config("http://127.0.0.1:1/repos");
config.self_restart_enabled = false;
let shutdown = CancellationToken::new();
let service = ProcessSystemOperations::new(shutdown.clone(), config);
assert!(!service.version().await.expect("version").restart_supported);
assert_eq!(
service
.restart(Arc::new(AllowingUpdatePreflight))
.await
.expect_err("restart disabled")
.kind(),
SystemOperationErrorKind::Conflict
);
assert!(!shutdown.is_cancelled());
}
#[tokio::test(start_paused = true)] #[tokio::test(start_paused = true)]
async fn accepted_restart_excludes_system_operations_until_service_release() { async fn accepted_restart_excludes_system_operations_until_service_release() {
let fixture = Fixture::new(); let fixture = Fixture::new();
@@ -59,7 +59,7 @@ async fn update_detail_should_withhold_updates_for_source_builds() {
.update_detail(SystemUpdateCheck::Refresh, None) .update_detail(SystemUpdateCheck::Refresh, None)
.await .await
.expect("detail"); .expect("detail");
assert_eq!(detail.latest_version, "1.0.0"); assert!(detail.latest_version.is_none());
assert!(!detail.update_supported); assert!(!detail.update_supported);
assert!(detail.unsupported_reason.is_some()); assert!(detail.unsupported_reason.is_some());
assert!(!detail.has_update); assert!(!detail.has_update);
@@ -107,10 +107,7 @@ async fn update_checks_should_follow_stage_promotion_and_experimental_isolation(
.await .await
.expect("detail"); .expect("detail");
assert_eq!(detail.has_update, allowed, "{current} -> {target}"); assert_eq!(detail.has_update, allowed, "{current} -> {target}");
assert_eq!( assert_eq!(detail.latest_version.as_deref(), allowed.then_some(target));
detail.latest_version,
if allowed { target } else { current }
);
assert_eq!(detail.notes.is_some(), allowed); assert_eq!(detail.notes.is_some(), allowed);
assert_eq!(detail.release_url.is_some(), allowed); assert_eq!(detail.release_url.is_some(), allowed);
assert_eq!(detail.warning.is_none(), allowed); assert_eq!(detail.warning.is_none(), allowed);
@@ -161,7 +158,7 @@ async fn update_detail_should_keep_current_release_notes_without_allowing_reinst
.update_detail(SystemUpdateCheck::Refresh, None) .update_detail(SystemUpdateCheck::Refresh, None)
.await .await
.expect("current release"); .expect("current release");
assert_eq!(detail.latest_version, current); assert_eq!(detail.latest_version.as_deref(), Some(current));
assert!(!detail.has_update); assert!(!detail.has_update);
assert!(detail.update_supported); assert!(detail.update_supported);
assert_eq!( assert_eq!(
@@ -193,15 +190,15 @@ async fn update_detail_should_keep_current_release_notes_without_allowing_reinst
#[tokio::test] #[tokio::test]
async fn update_checks_should_ignore_downgrades_unknown_stages_and_build_metadata() { async fn update_checks_should_ignore_downgrades_unknown_stages_and_build_metadata() {
for (current, target) in [ for (current, target, published) in [
("3.12.0-beta.2", "3.12.0-beta.1"), ("3.12.0-beta.2", "3.12.0-beta.1", true),
("3.12.0", "3.12.0+new-build"), ("3.12.0", "3.12.0+new-build", true),
("3.12.0-beta.1+aaa", "3.12.0-beta.1+zzz"), ("3.12.0-beta.1+aaa", "3.12.0-beta.1+zzz", true),
("3.12.0", "3.11.0"), ("3.12.0", "3.11.0", true),
("3.12.0-alpha.1", "3.12.0-preview.2"), ("3.12.0-alpha.1", "3.12.0-preview.2", false),
("3.12.0-alpha.1", "3.12.0-beta"), ("3.12.0-alpha.1", "3.12.0-beta", false),
("3.12.0-alpha.1", "3.12.0-beta.0"), ("3.12.0-alpha.1", "3.12.0-beta.0", false),
("3.12.0-alpha.1", "3.12.0-beta.2.extra"), ("3.12.0-alpha.1", "3.12.0-beta.2.extra", false),
] { ] {
let server = MockServer::start().await; let server = MockServer::start().await;
let fixture = Fixture::new(); let fixture = Fixture::new();
@@ -214,9 +211,12 @@ async fn update_checks_should_ignore_downgrades_unknown_stages_and_build_metadat
.await .await
.expect("detail"); .expect("detail");
assert!(!detail.has_update, "{current} -> {target}"); assert!(!detail.has_update, "{current} -> {target}");
assert_eq!(detail.latest_version, current); assert_eq!(
assert!(detail.notes.is_none()); detail.latest_version.as_deref(),
assert!(detail.release_url.is_none()); published.then_some(target)
);
assert_eq!(detail.notes.is_some(), published);
assert_eq!(detail.release_url.is_some(), published);
} }
} }
+30 -3
View File
@@ -219,6 +219,7 @@ enum LeaseStep {
enum RenewStep { enum RenewStep {
Success, Success,
Error, Error,
Pending,
} }
#[derive(Default)] #[derive(Default)]
@@ -268,11 +269,12 @@ impl WorkerLeaderLeaseGuard for FakeLeaseGuard {
fn renew(&mut self) -> BoxFuture<'_, Result<(), WorkerLeaseError>> { fn renew(&mut self) -> BoxFuture<'_, Result<(), WorkerLeaseError>> {
Box::pin(async move { Box::pin(async move {
lock_unpoisoned(&self.renewals).push(self.worker.clone()); lock_unpoisoned(&self.renewals).push(self.worker.clone());
match lock_unpoisoned(&self.renew_scripts) let step = lock_unpoisoned(&self.renew_scripts)
.get_mut(&self.worker) .get_mut(&self.worker)
.and_then(VecDeque::pop_front) .and_then(VecDeque::pop_front)
.unwrap_or(RenewStep::Success) .unwrap_or(RenewStep::Success);
{ match step {
RenewStep::Pending => pending().await,
RenewStep::Success => Ok(()), RenewStep::Success => Ok(()),
RenewStep::Error => Err(WorkerLeaseError::safe("expected renewal failure")), RenewStep::Error => Err(WorkerLeaseError::safe("expected renewal failure")),
} }
@@ -510,6 +512,31 @@ async fn long_cycle_renews_leader_lease_before_ttl() {
supervisor.shutdown(Duration::from_secs(1)).await; supervisor.shutdown(Duration::from_secs(1)).await;
} }
#[tokio::test(start_paused = true)]
async fn shutdown_signals_the_cycle_while_lease_renewal_is_pending() {
let leases = Arc::new(FakeLeasePort::default());
leases.renew_script(target_worker(), [RenewStep::Pending]);
let task = CancellationTask {
entered: Arc::new(AtomicUsize::new(0)),
observed: Arc::new(AtomicUsize::new(0)),
};
let supervisor = supervisor();
supervisor
.start(
target_plan(task.clone(), renewal_schedule()),
leases.clone(),
Arc::new(RecordingDiagnostics::default()),
)
.unwrap();
yield_until(|| task.entered.load(Ordering::SeqCst) != 0).await;
tokio::time::advance(Duration::from_millis(10)).await;
yield_until(|| leases.renewal_count(&target_worker()) == 1).await;
// 关闭预算短于续租超时,协作取消仍应完成
supervisor.shutdown(Duration::from_millis(1)).await;
assert_eq!(task.observed.load(Ordering::SeqCst), 1);
assert!(lock_unpoisoned(&leases.active_guards).is_empty());
}
#[tokio::test(start_paused = true)] #[tokio::test(start_paused = true)]
async fn renewal_failure_cancels_old_cycle_before_another_leader_cycle_starts() { async fn renewal_failure_cancels_old_cycle_before_another_leader_cycle_starts() {
let task = ConcurrentCycleTask { let task = ConcurrentCycleTask {
@@ -248,21 +248,21 @@ impl Execution {
request_body_limit, request_body_limit,
) )
.map_err(|error| fault_error(error, UpstreamSendState::NotSent))?; .map_err(|error| fault_error(error, UpstreamSendState::NotSent))?;
let upstream_model = invocation.metadata.upstream_model().ok_or_else(invalid)?;
let request = UpstreamAdapterRequest { let request = UpstreamAdapterRequest {
adapter_id: declaration.id.clone(), adapter_id: declaration.id.clone(),
provider: declaration.provider, provider: declaration.provider,
upstream_model: invocation upstream_model: upstream_model.as_str().to_owned(),
.metadata
.upstream_model()
.ok_or_else(invalid)?
.as_str()
.to_owned(),
client_key_id: invocation.context.client_api_key_ref().as_str().to_owned(), client_key_id: invocation.context.client_api_key_ref().as_str().to_owned(),
account_id: invocation.account.account_id().as_str().to_owned(), account_id: invocation.account.account_id().as_str().to_owned(),
credential_revision: invocation.account.credential_revision().get(), credential_revision: invocation.account.credential_revision().get(),
protocol: invocation.operation.protocol().to_owned(), protocol: invocation.operation.protocol().to_owned(),
client_transport: invocation.context.client_transport().as_str().to_owned(), client_transport: invocation.context.client_transport().as_str().to_owned(),
fast_mode: invocation.context.fast_mode().as_str().to_owned(), fast_mode: invocation
.context
.fast_mode_for_account(invocation.account.account_id(), upstream_model.as_str())
.as_str()
.to_owned(),
request_elapsed_ms: u64::try_from( request_elapsed_ms: u64::try_from(
invocation.context.timing_started_at().elapsed().as_millis(), invocation.context.timing_started_at().elapsed().as_millis(),
) )
@@ -7,13 +7,16 @@ use serde_json::{Value, json};
#[tokio::test] #[tokio::test]
async fn middleware_preserves_fast_modes_and_sources() { async fn middleware_preserves_fast_modes_and_sources() {
for (mode, expected) in [ for (mode, expected) in [
(FastMode::Default, FastMode::Default), (None, None),
(FastMode::Enabled, FastMode::Enabled), (None, Some(FastMode::Default)),
(FastMode::Disabled, FastMode::Disabled), (Some(FastMode::Default), Some(FastMode::Default)),
(FastMode::Enabled, FastMode::Disabled), (Some(FastMode::Enabled), Some(FastMode::Enabled)),
(FastMode::Ultrafast, FastMode::Ultrafast), (Some(FastMode::Disabled), Some(FastMode::Disabled)),
(FastMode::Enabled, FastMode::Ultrafast), (Some(FastMode::Enabled), Some(FastMode::Disabled)),
(FastMode::Disabled, FastMode::Default), (Some(FastMode::Ultrafast), Some(FastMode::Ultrafast)),
(Some(FastMode::Enabled), Some(FastMode::Ultrafast)),
(Some(FastMode::Disabled), Some(FastMode::Default)),
(Some(FastMode::Enabled), None),
] { ] {
let snapshot = gateway_core::routing::RuntimeSnapshot::new( let snapshot = gateway_core::routing::RuntimeSnapshot::new(
ConfigRevision::new(1).unwrap(), ConfigRevision::new(1).unwrap(),
@@ -43,8 +46,7 @@ async fn middleware_preserves_fast_modes_and_sources() {
let settings = settings.replace_execution(&seed, "seed").unwrap(); let settings = settings.replace_execution(&seed, "seed").unwrap();
let wire = serde_json::to_value(&seed).unwrap(); let wire = serde_json::to_value(&seed).unwrap();
let mut updated = wire.clone(); let mut updated = wire.clone();
updated["fast_mode"] = json!(expected.as_str()); updated["fast_mode"] = json!(expected);
updated["timeout_ms"] = json!(90_000);
let contribution = crate::support::contribution( let contribution = crate::support::contribution(
Capability::Middleware, Capability::Middleware,
vec![Stage::Request], vec![Stage::Request],
@@ -61,8 +63,8 @@ async fn middleware_preserves_fast_modes_and_sources() {
id: "fast-settings", id: "fast-settings",
configuration: json!({ configuration: json!({
"mode":"settings", "expected_settings":wire, "settings":updated, "mode":"settings", "expected_settings":wire, "settings":updated,
"expected_fast_source": if mode == FastMode::Default { Value::Null } else { "expected_fast_source": if mode.is_none() { Value::Null } else {
json!({"instance_id":"seed", "order":1, "value":mode.as_str()}) json!({"instance_id":"seed", "order":1, "value":mode})
}, },
}), }),
bindings: vec![binding( bindings: vec![binding(
@@ -102,11 +104,11 @@ async fn middleware_preserves_fast_modes_and_sources() {
assert_eq!(settings.execution_values().unwrap().fast_mode, expected); assert_eq!(settings.execution_values().unwrap().fast_mode, expected);
assert_eq!( assert_eq!(
settings.execution_values().unwrap().timeout_ms, settings.execution_values().unwrap().timeout_ms,
Some(90_000) Some(60_000)
); );
let sources = settings.inspect(); let sources = settings.inspect();
let fast_source = &sources["execution"]["fast_mode"]; let fast_source = &sources["execution"]["fast_mode"];
if mode == FastMode::Default && expected == FastMode::Default { if mode.is_none() && expected.is_none() {
assert!(fast_source.is_null()); assert!(fast_source.is_null());
} else { } else {
assert_eq!( assert_eq!(
@@ -117,12 +119,9 @@ async fn middleware_preserves_fast_modes_and_sources() {
"fast-settings" "fast-settings"
} }
); );
assert_eq!(fast_source["value"], expected.as_str()); assert_eq!(fast_source["value"], json!(expected));
} }
assert_eq!( assert!(sources["execution"]["timeout_ms"].is_null());
sources["execution"]["timeout_ms"]["instance_id"],
"fast-settings"
);
next.run(request).await next.run(request).await
}) })
}), }),
@@ -628,6 +628,7 @@ fn candidate(id: &str, weight: u16) -> AccountCandidate {
.with_scheduling(None, AccountWeight::new(weight).unwrap()), .with_scheduling(None, AccountWeight::new(weight).unwrap()),
signals: AccountRuntimeSignals { signals: AccountRuntimeSignals {
in_flight: 0, in_flight: 0,
recent_requests: 0,
last_started_at: None, last_started_at: None,
quota_reset_at: None, quota_reset_at: None,
quota_reset_windows: None, quota_reset_windows: None,
@@ -1276,7 +1277,7 @@ async fn real_request_plugins_rewrite_settings_in_onion_order() {
let baseline = ExecutionSettings { let baseline = ExecutionSettings {
runtime: SettingsValues::new(3, "smart", BTreeMap::new(), None, None) runtime: SettingsValues::new(3, "smart", BTreeMap::new(), None, None)
.with_request_profiles(profiles("key-default")), .with_request_profiles(profiles("key-default")),
fast_mode: FastMode::Disabled, fast_mode: Some(FastMode::Disabled),
client_limits: RateLimits { client_limits: RateLimits {
max_concurrency: 2, max_concurrency: 2,
requests_per_minute: 10, requests_per_minute: 10,
@@ -1313,7 +1314,7 @@ async fn real_request_plugins_rewrite_settings_in_onion_order() {
gateway_core::routing::ClientRoutingScope::all_accounts(), gateway_core::routing::ClientRoutingScope::all_accounts(),
) )
.with_request_profiles(profiles("key-default")) .with_request_profiles(profiles("key-default"))
.with_fast_mode(baseline.fast_mode), .with_fast_mode_override(baseline.fast_mode),
), ),
true, true,
baseline.client_limits, baseline.client_limits,
@@ -179,7 +179,6 @@ fn context_with_body_limit(
ClientApiKeyId::new(key).unwrap(), ClientApiKeyId::new(key).unwrap(),
) )
.with_upstream_adapters(runtime.execution_registry().upstream_adapters(generation)) .with_upstream_adapters(runtime.execution_registry().upstream_adapters(generation))
.with_fast_mode(mode)
.with_request_body_limit(bytes), .with_request_body_limit(bytes),
NonZeroU32::new(1).unwrap(), NonZeroU32::new(1).unwrap(),
SystemTime::now() + Duration::from_secs(5), SystemTime::now() + Duration::from_secs(5),
@@ -187,7 +186,13 @@ fn context_with_body_limit(
gateway_core::account::RotationStrategy::RoundRobin, gateway_core::account::RotationStrategy::RoundRobin,
std::num::NonZeroU32::new(1).unwrap(), std::num::NonZeroU32::new(1).unwrap(),
), ),
AccountAttemptContext::new(Default::default(), None, None), AccountAttemptContext::new(Default::default(), None, None).with_account_scope(Arc::new(
gateway_core::routing::FrozenAccountScope::new(
Arc::default(),
gateway_core::routing::ClientRoutingScope::all_accounts(),
)
.with_fast_mode_override(Some(mode)),
)),
None, None,
CancellationToken::new(), CancellationToken::new(),
) )
@@ -588,7 +588,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
); );
if let Some(expected) = configuration.get("expected_fast_source") { if let Some(expected) = configuration.get("expected_fast_source") {
let sources = &call.request.head.settings_sources["execution"]; let sources = &call.request.head.settings_sources["execution"];
assert_eq!(sources["input"]["fast_mode"], "default"); assert!(sources["input"]["fast_mode"].is_null());
assert_eq!(&sources["fast_mode"], expected); assert_eq!(&sources["fast_mode"], expected);
} }
if let Some(settings) = configuration.get("settings") { if let Some(settings) = configuration.get("settings") {
@@ -489,7 +489,7 @@ let plugin = PluginBuilder::from_json(manifest_json)?
#### 模型请求与 attempt #### 模型请求与 attempt
`RequestCall.request.head` 包含完整 Client Key 与分组归属。request 中间件改写正文后,OpenAI 在进入 attempt 前应用宿主 Fast 策略; `RequestCall.request.head` 包含完整 Client Key 与分组归属。request 中间件改写正文后,OpenAI 按选中账号和上游模型解析宿主 Fast 策略,在进入 attempt 前应用;
attempt 中间件在此基线上继续改写,终端不再应用 Fast 策略。 attempt 中间件在此基线上继续改写,终端不再应用 Fast 策略。
request 与 attempt 阶段通过 `append_header` 添加的请求头会进入上游请求,不适合存放插件内部标记或仅供下游读取的信息。 request 与 attempt 阶段通过 `append_header` 添加的请求头会进入上游请求,不适合存放插件内部标记或仅供下游读取的信息。
OpenAI 与 xAI 的上游 headers 先由账号和画像生成,插件同名字段覆盖基线,同名多值按插件顺序保留;不存在按认证、Cookie 或会话名称划分的保护列表。 OpenAI 与 xAI 的上游 headers 先由账号和画像生成,插件同名字段覆盖基线,同名多值按插件顺序保留;不存在按认证、Cookie 或会话名称划分的保护列表。
@@ -498,7 +498,8 @@ CPR 中间件添加的 HTTP 扩展头在发往 Antigravity 时经过该 Provider
实际账号租约、凭据版本与计费归属仍记录真实选中事实,不随插件修改 header 名称而伪造 实际账号租约、凭据版本与计费归属仍记录真实选中事实,不随插件修改 header 名称而伪造
request 阶段 `request.head.settings` 是本次调用的有效设置对象,包含 `runtime`、`fast_mode`、`client_limits` 和 `timeout_ms`。 request 阶段 `request.head.settings` 是本次调用的有效设置对象,包含 `runtime`、`fast_mode`、`client_limits` 和 `timeout_ms`。
`fast_mode` 使用 `default`、`enabled`、`ultrafast`、`disabled` 四个值,具体档位语义见[账号分组](../../../../../docs/api.md#6-账号分组)。 `fast_mode` 为 `null` 时按选中账号的有效分组解析;显式 `default` 表示跟随客户端,`enabled`、`ultrafast`、`disabled` 覆盖分组策略,具体档位语义见[账号分组](../../../../../docs/api.md#6-账号分组)。
保留该字段不建立新覆盖,改写为 `null` 恢复按分组解析;其他改写形成当前 Key 的显式覆盖,优先于分组策略。attempt 中间件仍可直接改写正文档位
`runtime` 使用宿主快照的设置字段,画像已合并 Client Key 设置;可以修改映射、画像、调度、位置及计价等执行参数。 `runtime` 使用宿主快照的设置字段,画像已合并 Client Key 设置;可以修改映射、画像、调度、位置及计价等执行参数。
SDK 仅在对象改变时提交完整替换,`false`、`0`、空映射和合同允许的 `null` 不表示跳过;不做隐式深合并。 SDK 仅在对象改变时提交完整替换,`false`、`0`、空映射和合同允许的 `null` 不表示跳过;不做隐式深合并。
线协议省略 `next.settings` 才表示保留;显式 `null` 仍按完整替换校验,因不符合设置对象合同而拒绝。 线协议省略 `next.settings` 才表示保留;显式 `null` 仍按完整替换校验,因不符合设置对象合同而拒绝。
@@ -41,7 +41,7 @@ Provider、业务协议和传输名称不能写入宿主兼容清单的 capabili
`TypedCall<UpstreamAdapterRequest>` 包含只读的 Key、账号、凭据版本、模型、协议、Header 和宿主续接投影; `TypedCall<UpstreamAdapterRequest>` 包含只读的 Key、账号、凭据版本、模型、协议、Header 和宿主续接投影;
原始请求正文位于 `call.payload`,原始账号凭据不进入插件输入。宿主首次消费冷流才调用插件 原始请求正文位于 `call.payload`,原始账号凭据不进入插件输入。宿主首次消费冷流才调用插件
`fast_mode` 是本次模型执行的有效设置,取值为 `default`、`enabled`、`ultrafast` 或 `disabled`。OpenAI 在 attempt 中间件之前将 Fast 设置应用到正文基线, `fast_mode` 是按选中账号及上游模型解析后的有效策略,取值为 `default`、`enabled`、`ultrafast` 或 `disabled`,请求设置的显式覆盖优先于分组策略。OpenAI 在 attempt 中间件之前将 Fast 设置应用到正文基线,
适配器收到经过 attempt 中间件处理的正文;attempt 中间件显式改写档位后,宿主不会在发送前再次应用 Fast 策略。 适配器收到经过 attempt 中间件处理的正文;attempt 中间件显式改写档位后,宿主不会在发送前再次应用 Fast 策略。
其他请求设置与 Key 作用域的覆盖规则见[模型请求与 attempt](capabilities.md#模型请求与-attempt) 其他请求设置与 Key 作用域的覆盖规则见[模型请求与 attempt](capabilities.md#模型请求与-attempt)
@@ -3,7 +3,10 @@
use crate::chat_completions::{ use crate::chat_completions::{
ChatError, custom_tool_schema, ChatError, custom_tool_schema,
error::{invalid, unsupported}, error::{invalid, unsupported},
request::string, request::{
block_text, empty_history_content, empty_history_part, function_parameters,
reasoning_effort, response_format, stop_sequences, string,
},
validate_request, validate_request,
}; };
use serde_json::{Map, Value, json}; use serde_json::{Map, Value, json};
@@ -13,7 +16,7 @@ pub fn convert_request(chat: &Map<String, Value>) -> Result<Map<String, Value>,
validate_request(chat)?; validate_request(chat)?;
let mut system = Vec::new(); let mut system = Vec::new();
if let Some(instructions) = chat.get("instructions").filter(|v| !v.is_null()) { if let Some(instructions) = chat.get("instructions").filter(|v| !v.is_null()) {
system.extend(parts(instructions, "instructions", true)?); system.extend(parts(instructions, "instructions", "system")?);
} }
let mut contents = Vec::new(); let mut contents = Vec::new();
let mut calls = BTreeMap::new(); let mut calls = BTreeMap::new();
@@ -30,7 +33,7 @@ pub fn convert_request(chat: &Map<String, Value>) -> Result<Map<String, Value>,
system.extend(parts( system.extend(parts(
&message["content"], &message["content"],
&format!("{path}.content"), &format!("{path}.content"),
true, role,
)?); )?);
continue; continue;
} }
@@ -48,7 +51,7 @@ pub fn convert_request(chat: &Map<String, Value>) -> Result<Map<String, Value>,
} }
let mut text = Vec::new(); let mut text = Vec::new();
let mut media = Vec::new(); let mut media = Vec::new();
for part in parts(&message["content"], &format!("{path}.content"), false)? { for part in parts(&message["content"], &format!("{path}.content"), role)? {
if let Some(value) = part.get("text").and_then(Value::as_str) { if let Some(value) = part.get("text").and_then(Value::as_str) {
text.push(value.to_owned()); text.push(value.to_owned());
} else { } else {
@@ -61,12 +64,12 @@ pub fn convert_request(chat: &Map<String, Value>) -> Result<Map<String, Value>,
} }
vec![response] vec![response]
} else { } else {
let mut content = if message["content"].is_null() { let mut content = parts(&message["content"], &format!("{path}.content"), role)?;
Vec::new() if let Some(refusal) = message
} else { .get("refusal")
parts(&message["content"], &format!("{path}.content"), false)? .and_then(Value::as_str)
}; .filter(|v| !v.is_empty())
if let Some(refusal) = message.get("refusal").and_then(Value::as_str) { {
content.push(json!({"text":refusal})); content.push(json!({"text":refusal}));
} }
for (call_index, call) in message for (call_index, call) in message
@@ -105,6 +108,9 @@ pub fn convert_request(chat: &Map<String, Value>) -> Result<Map<String, Value>,
} }
content content
}; };
if role == "assistant" && content.is_empty() {
continue;
}
append( append(
&mut contents, &mut contents,
if role == "assistant" { "model" } else { "user" }, if role == "assistant" { "model" } else { "user" },
@@ -134,11 +140,10 @@ pub fn convert_request(chat: &Map<String, Value>) -> Result<Map<String, Value>,
generation.insert(to.into(), value.clone()); generation.insert(to.into(), value.clone());
} }
} }
if let Some(effort) = chat if let Some(stops) = stop_sequences(chat)? {
.get("reasoning_effort") generation.insert("stopSequences".into(), stops);
.or_else(|| chat.get("reasoning").and_then(|v| v.get("effort"))) }
.filter(|v| !v.is_null()) if let Some(effort) = reasoning_effort(chat) {
{
let budget: i64 = match effort.as_str() { let budget: i64 = match effort.as_str() {
Some("none") => 0, Some("none") => 0,
Some("minimal" | "low") => 1024, Some("minimal" | "low") => 1024,
@@ -158,11 +163,7 @@ pub fn convert_request(chat: &Map<String, Value>) -> Result<Map<String, Value>,
}, },
); );
} }
if let Some(format) = chat if let Some(format) = response_format(chat) {
.get("response_format")
.or_else(|| chat.get("text").and_then(|v| v.get("format")))
.filter(|v| !v.is_null())
{
match format["type"].as_str() { match format["type"].as_str() {
Some("json_schema") => { Some("json_schema") => {
generation.insert("responseMimeType".into(), json!("application/json")); generation.insert("responseMimeType".into(), json!("application/json"));
@@ -205,7 +206,11 @@ fn append(contents: &mut Vec<Value>, role: &str, parts: Vec<Value>) {
} }
} }
fn parts(value: &Value, path: &str, system: bool) -> Result<Vec<Value>, ChatError> { fn parts(value: &Value, path: &str, role: &str) -> Result<Vec<Value>, ChatError> {
if empty_history_content(role, value) {
return Ok(Vec::new());
}
let system = matches!(role, "system" | "developer");
if let Some(text) = value.as_str() { if let Some(text) = value.as_str() {
return Ok(vec![json!({"text":text})]); return Ok(vec![json!({"text":text})]);
} }
@@ -214,12 +219,13 @@ fn parts(value: &Value, path: &str, system: bool) -> Result<Vec<Value>, ChatErro
.ok_or_else(|| invalid(path))? .ok_or_else(|| invalid(path))?
.iter() .iter()
.enumerate() .enumerate()
.filter(|(_, part)| !empty_history_part(role, part))
.map(|(index, part)| { .map(|(index, part)| {
let path = format!("{path}[{index}]"); let path = format!("{path}[{index}]");
let kind = string(part.get("type"), &format!("{path}.type"), false)?; let kind = string(part.get("type"), &format!("{path}.type"), false)?;
match kind { match kind {
"text" | "input_text" | "output_text" => { "text" | "input_text" | "output_text" => {
Ok(json!({"text":string(part.get("text"), &format!("{path}.text"), true)?})) Ok(json!({"text":block_text(part.get("text"), &path)?}))
} }
"refusal" if !system => Ok( "refusal" if !system => Ok(
json!({"text":string(part.get("refusal"), &format!("{path}.refusal"), true)?}), json!({"text":string(part.get("refusal"), &format!("{path}.refusal"), true)?}),
@@ -314,16 +320,10 @@ fn tools(chat: &Map<String, Value>, result: &mut Map<String, Value>) -> Result<(
let parameters = if kind == "custom" { let parameters = if kind == "custom" {
custom_tool_schema(definition.get("format"), &format!("{path}.custom.format"))? custom_tool_schema(definition.get("format"), &format!("{path}.custom.format"))?
} else { } else {
definition function_parameters(definition, &path)?
.get("parameters")
.cloned()
.unwrap_or_else(|| json!({"type":"object","properties":{}}))
}; };
if !parameters.is_object() {
return Err(invalid(&format!("{path}.function.parameters")));
}
let mut declaration = json!({"name":name,"parametersJsonSchema":parameters}); let mut declaration = json!({"name":name,"parametersJsonSchema":parameters});
if let Some(value) = definition.get("description") { if let Some(value) = definition.get("description").filter(|v| !v.is_null()) {
declaration["description"] = value.clone(); declaration["description"] = value.clone();
} }
declarations.push(declaration); declarations.push(declaration);
@@ -4,7 +4,10 @@ use crate::anthropic::MessagesModelCapabilities;
use crate::chat_completions::{ use crate::chat_completions::{
ChatError, custom_tool_schema, ChatError, custom_tool_schema,
error::{invalid, unsupported}, error::{invalid, unsupported},
request::string, request::{
block_text, empty_history_content, empty_history_part, function_parameters,
reasoning_effort, response_format, stop_sequences, string,
},
validate_request, validate_request,
}; };
use serde_json::{Map, Value, json}; use serde_json::{Map, Value, json};
@@ -37,6 +40,9 @@ pub fn convert_request(
result.insert(field.into(), value.clone()); result.insert(field.into(), value.clone());
} }
} }
if let Some(stops) = stop_sequences(chat)? {
result.insert("stop_sequences".into(), stops);
}
if let Some(tier) = chat.get("service_tier").and_then(Value::as_str) { if let Some(tier) = chat.get("service_tier").and_then(Value::as_str) {
match tier { match tier {
"priority" => { "priority" => {
@@ -53,7 +59,7 @@ pub fn convert_request(
} }
let mut system = Vec::new(); let mut system = Vec::new();
if let Some(instructions) = chat.get("instructions").filter(|v| !v.is_null()) { if let Some(instructions) = chat.get("instructions").filter(|v| !v.is_null()) {
system.extend(content(instructions, "instructions", true)?); system.extend(content(instructions, "instructions", "system")?);
} }
let mut messages = Vec::new(); let mut messages = Vec::new();
let mut calls = BTreeMap::new(); let mut calls = BTreeMap::new();
@@ -70,7 +76,7 @@ pub fn convert_request(
system.extend(content( system.extend(content(
&message["content"], &message["content"],
&format!("{path}.content"), &format!("{path}.content"),
true, role,
)?); )?);
continue; continue;
} }
@@ -84,15 +90,15 @@ pub fn convert_request(
return Err(invalid(&format!("{path}.tool_call_id"))); return Err(invalid(&format!("{path}.tool_call_id")));
} }
vec![ vec![
json!({"type":"tool_result","tool_use_id":id,"content":content(&message["content"], &format!("{path}.content"), false)?}), json!({"type":"tool_result","tool_use_id":id,"content":content(&message["content"], &format!("{path}.content"), role)?}),
] ]
} else { } else {
let mut blocks = if message["content"].is_null() { let mut blocks = content(&message["content"], &format!("{path}.content"), role)?;
Vec::new() if let Some(refusal) = message
} else { .get("refusal")
content(&message["content"], &format!("{path}.content"), false)? .and_then(Value::as_str)
}; .filter(|v| !v.is_empty())
if let Some(refusal) = message.get("refusal").and_then(Value::as_str) { {
blocks.push(json!({"type":"text","text":refusal})); blocks.push(json!({"type":"text","text":refusal}));
} }
for (call_index, call) in message for (call_index, call) in message
@@ -130,6 +136,9 @@ pub fn convert_request(
} }
blocks blocks
}; };
if role == "assistant" && blocks.is_empty() {
continue;
}
append_message( append_message(
&mut messages, &mut messages,
if role == "assistant" { if role == "assistant" {
@@ -148,10 +157,7 @@ pub fn convert_request(
} }
result.insert("messages".into(), messages.into()); result.insert("messages".into(), messages.into());
tools(chat, &mut result, capabilities)?; tools(chat, &mut result, capabilities)?;
let format = chat if let Some(format) = response_format(chat) {
.get("response_format")
.or_else(|| chat.get("text").and_then(|v| v.get("format")));
if let Some(format) = format.filter(|v| !v.is_null()) {
match format["type"].as_str() { match format["type"].as_str() {
Some("json_schema") => { Some("json_schema") => {
let schema = format let schema = format
@@ -190,7 +196,11 @@ fn append_message(messages: &mut Vec<Value>, role: &str, blocks: Vec<Value>) {
} }
} }
fn content(value: &Value, path: &str, system: bool) -> Result<Vec<Value>, ChatError> { fn content(value: &Value, path: &str, role: &str) -> Result<Vec<Value>, ChatError> {
if empty_history_content(role, value) {
return Ok(Vec::new());
}
let system = matches!(role, "system" | "developer");
if let Some(text) = value.as_str() { if let Some(text) = value.as_str() {
return Ok(vec![json!({"type":"text","text":text})]); return Ok(vec![json!({"type":"text","text":text})]);
} }
@@ -200,12 +210,13 @@ fn content(value: &Value, path: &str, system: bool) -> Result<Vec<Value>, ChatEr
.ok_or_else(|| invalid(path))? .ok_or_else(|| invalid(path))?
.iter() .iter()
.enumerate() .enumerate()
.filter(|(_, part)| !empty_history_part(role, part))
{ {
let path = format!("{path}[{index}]"); let path = format!("{path}[{index}]");
let kind = string(part.get("type"), &format!("{path}.type"), false)?; let kind = string(part.get("type"), &format!("{path}.type"), false)?;
let block = match kind { let block = match kind {
"text" | "input_text" | "output_text" => { "text" | "input_text" | "output_text" => {
json!({"type":"text","text":string(part.get("text"), &format!("{path}.text"), true)?}) json!({"type":"text","text":block_text(part.get("text"), &path)?})
} }
"refusal" if !system => { "refusal" if !system => {
json!({"type":"text","text":string(part.get("refusal"), &format!("{path}.refusal"), true)?}) json!({"type":"text","text":string(part.get("refusal"), &format!("{path}.refusal"), true)?})
@@ -295,17 +306,11 @@ fn tools(
let schema = if kind == "custom" { let schema = if kind == "custom" {
custom_tool_schema(declaration.get("format"), &format!("{path}.custom.format"))? custom_tool_schema(declaration.get("format"), &format!("{path}.custom.format"))?
} else { } else {
declaration function_parameters(declaration, &path)?
.get("parameters")
.cloned()
.unwrap_or_else(|| json!({"type":"object","properties":{}}))
}; };
if !schema.is_object() {
return Err(invalid(&format!("{path}.function.parameters")));
}
let mut target = json!({"name":name,"input_schema":schema}); let mut target = json!({"name":name,"input_schema":schema});
for field in ["description", "strict", "cache_control"] { for field in ["description", "strict", "cache_control"] {
if let Some(value) = declaration.get(field) { if let Some(value) = declaration.get(field).filter(|v| !v.is_null()) {
target[field] = value.clone(); target[field] = value.clone();
} }
} }
@@ -393,11 +398,7 @@ fn reasoning(
capabilities: &MessagesModelCapabilities, capabilities: &MessagesModelCapabilities,
max_tokens: u64, max_tokens: u64,
) -> Result<(), ChatError> { ) -> Result<(), ChatError> {
let Some(effort) = chat let Some(effort) = reasoning_effort(chat) else {
.get("reasoning_effort")
.or_else(|| chat.get("reasoning").and_then(|v| v.get("effort")))
.filter(|v| !v.is_null())
else {
return Ok(()); return Ok(());
}; };
let effort = effort.as_str().ok_or_else(|| invalid("reasoning_effort"))?; let effort = effort.as_str().ok_or_else(|| invalid("reasoning_effort"))?;
@@ -30,11 +30,7 @@ pub fn validate_request(body: &Map<String, Value>) -> Result<(), ChatError> {
field: "messages".into(), field: "messages".into(),
expected: "an array", expected: "an array",
})?; })?;
if messages.is_empty() { let mut has_message = false;
return Err(ChatError::EmptyField {
field: "messages".into(),
});
}
for (index, message) in messages.iter().enumerate() { for (index, message) in messages.iter().enumerate() {
let path = format!("messages[{index}]"); let path = format!("messages[{index}]");
let message = message.as_object().ok_or_else(|| invalid(&path))?; let message = message.as_object().ok_or_else(|| invalid(&path))?;
@@ -42,43 +38,51 @@ pub fn validate_request(body: &Map<String, Value>) -> Result<(), ChatError> {
if !matches!(role, "system" | "developer" | "user" | "assistant" | "tool") { if !matches!(role, "system" | "developer" | "user" | "assistant" | "tool") {
return Err(unsupported(&format!("{path}.role"))); return Err(unsupported(&format!("{path}.role")));
} }
for (field, allowed) in [ let calls = match message.get("tool_calls") {
("tool_calls", "assistant"), None | Some(Value::Null) => &[][..],
("refusal", "assistant"), Some(Value::Array(calls)) => calls.as_slice(),
("tool_call_id", "tool"), _ => return Err(invalid(&format!("{path}.tool_calls"))),
] { };
if role != allowed && message.get(field).is_some_and(|v| !v.is_null()) { if role != "assistant" && !calls.is_empty() {
return Err(invalid(&format!("{path}.{field}"))); return Err(invalid(&format!("{path}.tool_calls")));
}
let refusal = message.get("refusal").filter(|v| !v.is_null() && *v != "");
if let Some(value) = refusal {
if role != "assistant" {
return Err(invalid(&format!("{path}.refusal")));
} }
string(Some(value), &format!("{path}.refusal"), true)?;
} }
for field in ["function_call", "audio"] { for field in ["function_call", "audio"] {
if message.get(field).is_some_and(|v| !v.is_null()) { if message.get(field).is_some_and(|v| !v.is_null()) {
return Err(unsupported(&format!("{path}.{field}"))); return Err(unsupported(&format!("{path}.{field}")));
} }
} }
for field in ["name", "refusal"] {
if let Some(value) = message.get(field).filter(|v| !v.is_null()) {
string(Some(value), &format!("{path}.{field}"), true)?;
}
}
if role == "tool" { if role == "tool" {
string( string(
message.get("tool_call_id"), message.get("tool_call_id"),
&format!("{path}.tool_call_id"), &format!("{path}.tool_call_id"),
false, false,
)?; )?;
} else if message
.get("tool_call_id")
.is_some_and(|v| !v.is_null() && v != "")
{
return Err(invalid(&format!("{path}.tool_call_id")));
} }
if let Some(content) = message.get("content").filter(|v| !v.is_null()) { let content = message.get("content").unwrap_or(&Value::Null);
if !empty_history_content(role, content) {
if !content.is_string() && !content.is_array() { if !content.is_string() && !content.is_array() {
return Err(invalid(&format!("{path}.content"))); return Err(invalid(&format!("{path}.content")));
} }
has_message = true;
if let Some(parts) = content.as_array() { if let Some(parts) = content.as_array() {
for (part_index, part) in parts.iter().enumerate() { for (part_index, part) in parts.iter().enumerate() {
let part_path = format!("{path}.content[{part_index}]"); let part_path = format!("{path}.content[{part_index}]");
let kind = string(part.get("type"), &format!("{part_path}.type"), false)?; let kind = string(part.get("type"), &format!("{part_path}.type"), false)?;
match kind { match kind {
"text" | "input_text" | "output_text" => { "text" | "input_text" | "output_text" => {
string(part.get("text"), &format!("{part_path}.text"), true)?; block_text(part.get("text"), &part_path)?;
} }
"image_url" | "file" | "input_audio" | "input_image" | "input_file" "image_url" | "file" | "input_audio" | "input_image" | "input_file"
if matches!(role, "user" | "tool") => {} if matches!(role, "user" | "tool") => {}
@@ -89,45 +93,37 @@ pub fn validate_request(body: &Map<String, Value>) -> Result<(), ChatError> {
} }
} }
} }
} else if role != "assistant"
|| (!message
.get("tool_calls")
.is_some_and(|v| v.as_array().is_some_and(|v| !v.is_empty()))
&& !message.get("refusal").is_some_and(Value::is_string))
{
return Err(invalid(&format!("{path}.content")));
} }
if let Some(calls) = message.get("tool_calls").filter(|v| !v.is_null()) { has_message |= refusal.is_some() || !calls.is_empty();
for (call_index, call) in calls for (call_index, call) in calls.iter().enumerate() {
.as_array() let call_path = format!("{path}.tool_calls[{call_index}]");
.ok_or_else(|| invalid(&format!("{path}.tool_calls")))? string(call.get("id"), &format!("{call_path}.id"), false)?;
.iter() let kind = string(call.get("type"), &format!("{call_path}.type"), false)?;
.enumerate() if !matches!(kind, "function" | "custom") {
{ return Err(unsupported(&format!("{call_path}.type")));
let call_path = format!("{path}.tool_calls[{call_index}]");
string(call.get("id"), &format!("{call_path}.id"), false)?;
let kind = string(call.get("type"), &format!("{call_path}.type"), false)?;
if !matches!(kind, "function" | "custom") {
return Err(unsupported(&format!("{call_path}.type")));
}
string(
call.get(kind).and_then(|v| v.get("name")),
&format!("{call_path}.{kind}.name"),
false,
)?;
let data_field = if kind == "function" {
"arguments"
} else {
"input"
};
string(
call.get(kind).and_then(|v| v.get(data_field)),
&format!("{call_path}.{kind}.{data_field}"),
true,
)?;
} }
string(
call.get(kind).and_then(|v| v.get("name")),
&format!("{call_path}.{kind}.name"),
false,
)?;
let data_field = if kind == "function" {
"arguments"
} else {
"input"
};
string(
call.get(kind).and_then(|v| v.get(data_field)),
&format!("{call_path}.{kind}.{data_field}"),
true,
)?;
} }
} }
if !has_message {
return Err(ChatError::EmptyField {
field: "messages".into(),
});
}
for (field, value) in body.iter().filter(|(_, v)| !v.is_null()) { for (field, value) in body.iter().filter(|(_, v)| !v.is_null()) {
let valid = match field.as_str() { let valid = match field.as_str() {
"n" => value.as_u64() == Some(1), "n" => value.as_u64() == Some(1),
@@ -150,7 +146,7 @@ pub fn validate_request(body: &Map<String, Value>) -> Result<(), ChatError> {
} }
} }
if let Some(options) = body.get("stream_options").filter(|v| !v.is_null()) { if let Some(options) = body.get("stream_options").filter(|v| !v.is_null()) {
if body.get("stream") != Some(&Value::Bool(true)) || !options.is_object() { if !options.is_object() {
return Err(invalid("stream_options")); return Err(invalid("stream_options"));
} }
for field in ["include_usage", "include_obfuscation"] { for field in ["include_usage", "include_obfuscation"] {
@@ -161,13 +157,99 @@ pub fn validate_request(body: &Map<String, Value>) -> Result<(), ChatError> {
return Err(invalid(&format!("stream_options.{field}"))); return Err(invalid(&format!("stream_options.{field}")));
} }
} }
if options.get("include_obfuscation") == Some(&Value::Bool(true)) { if body.get("stream") == Some(&Value::Bool(true))
&& options.get("include_obfuscation") == Some(&Value::Bool(true))
{
return Err(unsupported("stream_options.include_obfuscation")); return Err(unsupported("stream_options.include_obfuscation"));
} }
} }
Ok(()) Ok(())
} }
// 用户输入和工具结果保留原值,空指令或 assistant 正文不生成上游内容块
pub(super) fn empty_history_content(role: &str, content: &Value) -> bool {
can_omit_empty_text(role)
&& (content.is_null()
|| content == ""
|| content
.as_array()
.is_some_and(|parts| parts.iter().all(plain_empty_text)))
}
fn can_omit_empty_text(role: &str) -> bool {
matches!(role, "system" | "developer" | "assistant")
}
fn plain_empty_text(part: &Value) -> bool {
// 只移除纯文本占位,带缓存断点等附加字段的块交给目标转换器
part.get("text")
.is_some_and(|text| text.is_null() || text == "")
&& matches!(
part.get("type").and_then(Value::as_str),
Some("text" | "input_text" | "output_text")
)
&& part.as_object().is_some_and(|fields| {
fields
.iter()
.all(|(key, value)| matches!(key.as_str(), "type" | "text") || value.is_null())
})
}
pub(super) fn empty_history_part(role: &str, part: &Value) -> bool {
can_omit_empty_text(role) && plain_empty_text(part)
}
// 部分 Chat 客户端用显式 null 表示空文本,缺少 text 或其他类型仍按原字段报错
pub(super) fn block_text<'a>(
value: Option<&'a Value>,
part_path: &str,
) -> Result<&'a str, ChatError> {
match value {
Some(Value::Null) => Ok(""),
value => string(value, &format!("{part_path}.text"), true),
}
}
pub(super) fn response_format(body: &Map<String, Value>) -> Option<&Value> {
body.get("response_format")
.filter(|v| !v.is_null())
.or_else(|| body.get("text")?.get("format").filter(|v| !v.is_null()))
}
pub(super) fn reasoning_effort(body: &Map<String, Value>) -> Option<&Value> {
body.get("reasoning_effort")
.filter(|v| !v.is_null())
.or_else(|| {
body.get("reasoning")?
.get("effort")
.filter(|v| !v.is_null())
})
}
pub(super) fn stop_sequences(body: &Map<String, Value>) -> Result<Option<Value>, ChatError> {
match body.get("stop") {
None | Some(Value::Null) => Ok(None),
Some(Value::String(text)) => Ok(Some(json!([text]))),
Some(Value::Array(values)) => {
for (index, value) in values.iter().enumerate() {
if !value.is_string() {
return Err(invalid(&format!("stop[{index}]")));
}
}
Ok((!values.is_empty()).then(|| Value::Array(values.clone())))
}
_ => Err(invalid("stop")),
}
}
pub(super) fn function_parameters(function: &Value, path: &str) -> Result<Value, ChatError> {
match function.get("parameters") {
None | Some(Value::Null) => Ok(json!({"type":"object","properties":{}})),
Some(schema) if schema.is_object() => Ok(schema.clone()),
_ => Err(invalid(&format!("{path}.function.parameters"))),
}
}
pub(super) fn string<'a>( pub(super) fn string<'a>(
value: Option<&'a Value>, value: Option<&'a Value>,
path: &str, path: &str,
@@ -222,28 +304,16 @@ pub(crate) fn request_facts(body: &Map<String, Value>) -> RequestFacts {
.any(|tool| tool.get("type").and_then(Value::as_str) == Some("image_generation")), .any(|tool| tool.get("type").and_then(Value::as_str) == Some("image_generation")),
reasoning: body.get("reasoning_effort").is_some_and(|v| !v.is_null()) reasoning: body.get("reasoning_effort").is_some_and(|v| !v.is_null())
|| body.get("reasoning").is_some_and(Value::is_object), || body.get("reasoning").is_some_and(Value::is_object),
json_schema: body json_schema: response_format(body)
.get("response_format")
.and_then(|v| v.get("type")) .and_then(|v| v.get("type"))
.and_then(Value::as_str) .and_then(Value::as_str)
== Some("json_schema") == Some("json_schema"),
|| body
.get("text")
.and_then(|v| v.pointer("/format/type"))
.and_then(Value::as_str)
== Some("json_schema"),
..RequestFacts::default() ..RequestFacts::default()
} }
} }
pub(crate) fn request_effort(body: &Map<String, Value>) -> Option<&str> { pub(crate) fn request_effort(body: &Map<String, Value>) -> Option<&str> {
body.get("reasoning_effort") reasoning_effort(body).and_then(Value::as_str)
.and_then(Value::as_str)
.or_else(|| {
body.get("reasoning")
.and_then(|value| value.get("effort"))
.and_then(Value::as_str)
})
} }
/// 将无格式约束的 custom 工具表达为字符串参数,受约束格式必须由目标原生支持 /// 将无格式约束的 custom 工具表达为字符串参数,受约束格式必须由目标原生支持
@@ -4,7 +4,11 @@ use std::collections::HashSet;
use serde_json::{Map, Value, json}; use serde_json::{Map, Value, json};
use crate::chat_completions::{ChatError as RequestDecodeError, validate_request}; use crate::chat_completions::{
ChatError as RequestDecodeError,
request::{block_text, empty_history_content, empty_history_part},
validate_request,
};
/// 将已验证的 Chat 正文直接转换为 Responses 请求 /// 将已验证的 Chat 正文直接转换为 Responses 请求
pub fn convert_request( pub fn convert_request(
@@ -161,7 +165,6 @@ fn messages(value: Value) -> Result<Vec<Value>, RequestDecodeError> {
let path = format!("messages[{index}]"); let path = format!("messages[{index}]");
let mut message = object(value, &path)?; let mut message = object(value, &path)?;
let role = required_string(&mut message, "role", &format!("{path}.role"), false)?; let role = required_string(&mut message, "role", &format!("{path}.role"), false)?;
let name = optional(&mut message, "name").filter(|name| name != "");
if role == "tool" { if role == "tool" {
let call_id = required_string( let call_id = required_string(
&mut message, &mut message,
@@ -182,7 +185,8 @@ fn messages(value: Value) -> Result<Vec<Value>, RequestDecodeError> {
"function_call_output" "function_call_output"
}; };
let mut item = json!({"type": kind, "call_id": call_id, "output": output}); let mut item = json!({"type": kind, "call_id": call_id, "output": output});
if let Some(name) = name { if let Some(name) = optional(&mut message, "name").filter(|name| name != "") {
string(&name, &format!("{path}.name"), true)?;
item["name"] = name; item["name"] = name;
} }
input.push(item); input.push(item);
@@ -193,8 +197,9 @@ fn messages(value: Value) -> Result<Vec<Value>, RequestDecodeError> {
.map(|value| tool_calls(value, &format!("{path}.tool_calls"))) .map(|value| tool_calls(value, &format!("{path}.tool_calls")))
.transpose()? .transpose()?
.unwrap_or_default(); .unwrap_or_default();
let refusal = optional(&mut message, "refusal"); let refusal = optional(&mut message, "refusal").filter(|v| v != "");
let content = optional(&mut message, "content"); let content =
optional(&mut message, "content").filter(|v| !empty_history_content(&role, v));
let is_assistant = role == "assistant"; let is_assistant = role == "assistant";
let mut parts = content let mut parts = content
.map(|value| content_parts(value, &role, &format!("{path}.content"), is_assistant)) .map(|value| content_parts(value, &role, &format!("{path}.content"), is_assistant))
@@ -233,20 +238,23 @@ fn content_parts(
is_assistant: bool, is_assistant: bool,
) -> Result<Vec<Value>, RequestDecodeError> { ) -> Result<Vec<Value>, RequestDecodeError> {
let parts = match value { let parts = match value {
Value::String(text) => return Ok(vec![text_part(text, is_assistant)]), Value::String(text) => return Ok(vec![text_part(&text, is_assistant)]),
Value::Array(parts) => parts, Value::Array(parts) => parts,
_ => return Err(invalid_type(path, "a string or an array")), _ => return Err(invalid_type(path, "a string or an array")),
}; };
let mut result = Vec::with_capacity(parts.len()); let mut result = Vec::with_capacity(parts.len());
for (index, value) in parts.into_iter().enumerate() { for (index, value) in parts
.into_iter()
.enumerate()
.filter(|(_, part)| !empty_history_part(role, part))
{
let path = format!("{path}[{index}]"); let path = format!("{path}[{index}]");
let mut part = object(value, &path)?; let mut part = object(value, &path)?;
let kind = required_string(&mut part, "type", &format!("{path}.type"), false)?; let kind = required_string(&mut part, "type", &format!("{path}.type"), false)?;
let mut converted = match kind.as_str() { let mut converted = match kind.as_str() {
"text" | "input_text" | "output_text" => text_part( "text" | "input_text" | "output_text" => {
required_string(&mut part, "text", &format!("{path}.text"), true)?, text_part(block_text(part.get("text"), &path)?, is_assistant)
is_assistant, }
),
"image_url" if matches!(role, "user" | "tool") => image_part( "image_url" if matches!(role, "user" | "tool") => image_part(
required(&mut part, "image_url", &format!("{path}.image_url"))?, required(&mut part, "image_url", &format!("{path}.image_url"))?,
&format!("{path}.image_url"), &format!("{path}.image_url"),
@@ -278,7 +286,7 @@ fn content_parts(
Ok(result) Ok(result)
} }
fn text_part(text: String, is_assistant: bool) -> Value { fn text_part(text: &str, is_assistant: bool) -> Value {
if is_assistant { if is_assistant {
json!({"type": "output_text", "text": text, "annotations": []}) json!({"type": "output_text", "text": text, "annotations": []})
} else { } else {
@@ -376,9 +384,17 @@ fn tools(value: Value) -> Result<Vec<Value>, RequestDecodeError> {
if let Some(nested) = optional(&mut tool, &kind) { if let Some(nested) = optional(&mut tool, &kind) {
tool = object(nested, &format!("{path}.{kind}"))?; tool = object(nested, &format!("{path}.{kind}"))?;
} }
if kind == "function" && tool.get("strict").is_none_or(Value::is_null) { if tool.get("description") == Some(&Value::Null) {
// Chat 的缺省是宽松 schema,不能让 Responses 收紧参数合同 tool.remove("description");
tool.insert("strict".into(), false.into()); }
if kind == "function" {
if tool.get("parameters") == Some(&Value::Null) {
tool.remove("parameters");
}
if tool.get("strict").is_none_or(Value::is_null) {
// Chat 的缺省是宽松 schema,不能让 Responses 收紧参数合同
tool.insert("strict".into(), false.into());
}
} }
} }
// hosted 工具采用原生 Responses 结构,支持范围由选中的 Provider 决定 // hosted 工具采用原生 Responses 结构,支持范围由选中的 Provider 决定
+21 -1
View File
@@ -1,4 +1,24 @@
//! 跨协议 HTTP 传输、下游环境头分类与重试时间解析 //! 跨协议 HTTP 头分类、响应关联与重试时间解析
/// 响应关联 ID 的头名与优先级沿用官方 Codex
pub const RESPONSE_REQUEST_ID_HEADERS: [&str; 4] = [
"x-request-id",
"x-oai-request-id",
"x-openai-request-id",
"x-ms-request-id",
];
/// 从各传输容器提供的可读 HTTP 头值中选取关联 ID,空值不阻止别名回退
pub fn preferred_response_request_id<'a>(
mut header: impl FnMut(&str) -> Option<&'a str>,
) -> Option<&'a str> {
RESPONSE_REQUEST_ID_HEADERS
.iter()
.find_map(|name| header(name).filter(|value| !value.trim().is_empty()))
}
/// 上游可交给客户端的秒级与毫秒级重试等待头
pub const RETRY_AFTER_HEADERS: [&str; 2] = ["retry-after", "retry-after-ms"];
/// 解析 HTTP 和流内错误共用的 Retry-After,保留零延迟并向上取整剩余秒数 /// 解析 HTTP 和流内错误共用的 Retry-After,保留零延迟并向上取整剩余秒数
pub fn parse_retry_after_seconds(value: &str) -> Option<u64> { pub fn parse_retry_after_seconds(value: &str) -> Option<u64> {
@@ -4,7 +4,15 @@ use gateway_protocol::{
chat_completions::{CHAT_PROTOCOL, ChatError, genai, messages, parse_request, responses}, chat_completions::{CHAT_PROTOCOL, ChatError, genai, messages, parse_request, responses},
request::{request_facts, request_observation}, request::{request_facts, request_observation},
}; };
use serde_json::json; use serde_json::{Map, Value, json};
fn target_requests(body: &Map<String, Value>) -> [Result<Map<String, Value>, ChatError>; 3] {
[
responses::convert_request(body),
messages::convert_request(body, &Default::default()),
genai::convert_request(body),
]
}
#[test] #[test]
fn parsing_retains_original_protocol_and_usage_preference() { fn parsing_retains_original_protocol_and_usage_preference() {
@@ -42,7 +50,7 @@ fn invalid_envelopes_and_chat_controls_keep_safe_field_errors() {
("n", json!(2)), ("n", json!(2)),
("store", json!(true)), ("store", json!(true)),
("previous_response_id", json!("resp_previous")), ("previous_response_id", json!("resp_previous")),
("stream_options", json!({"include_usage":true})), ("stream_options", json!(true)),
] { ] {
let mut request = super::request(); let mut request = super::request();
request.insert(field.into(), value); request.insert(field.into(), value);
@@ -104,9 +112,320 @@ fn capability_facts_only_read_protocol_declarations() {
assert!(!request_facts(CHAT_PROTOCOL, &body).tools); assert!(!request_facts(CHAT_PROTOCOL, &body).tools);
} }
#[test]
fn empty_history_is_omitted_only_when_converting() {
let mut baseline = super::request();
baseline["messages"] = json!([
{"role":"developer","content":"Keep replies short."},
{"role":"user","content":"hello"}
]);
let expected = target_requests(&baseline).map(Result::unwrap);
for role in ["system", "developer", "assistant"] {
for content in [
None,
Some(Value::Null),
Some(json!("")),
Some(json!([])),
Some(json!([{"type":"text","text":""},{"type":"output_text","text":""}])),
Some(json!([{"type":"input_text","text":null}])),
Some(json!([{"type":"text","text":"","prompt_cache_breakpoint":null}])),
] {
let mut placeholder =
json!({"role":role,"tool_calls":[],"refusal":"","tool_call_id":""});
if let Some(content) = content {
placeholder["content"] = content;
}
let mut body = baseline.clone();
body["messages"]
.as_array_mut()
.unwrap()
.insert(1, placeholder.clone());
let parsed = parse_request(&serde_json::to_vec(&body).unwrap()).unwrap();
assert_eq!(parsed, body);
assert_eq!(target_requests(&parsed).map(Result::unwrap), expected);
body["messages"] = json!([placeholder]);
for error in target_requests(&body).map(Result::unwrap_err) {
assert_eq!(error.parameter(), Some("messages"));
}
}
}
}
#[test]
fn empty_history_fields_preserve_tool_calls_results_and_refusals() {
let mut body = super::request();
body["messages"] = json!([
{"role":"user","content":"hello"},
{"role":"assistant","tool_calls":[{"id":"c","type":"function","function":{"name":"f","arguments":"{}"}}]},
{"role":"tool","tool_call_id":"c","content":""},
{"role":"assistant","refusal":"declined"}
]);
let expected = target_requests(&body).map(Result::unwrap);
assert_eq!(expected[0]["input"][1]["call_id"], "c");
assert_eq!(expected[0]["input"][2]["output"], "");
assert_eq!(expected[1]["messages"][1]["content"][0]["type"], "tool_use");
assert_eq!(expected[1]["messages"][3]["content"][0]["text"], "declined");
assert_eq!(
expected[2]["contents"][2]["parts"][0]["functionResponse"]["id"],
"c"
);
assert_eq!(expected[2]["contents"][3]["parts"][0]["text"], "declined");
body["messages"][0] = json!({"role":"user","content":"hello","name":17,"refusal":"","tool_calls":[],"tool_call_id":""});
for content in [
Value::Null,
json!(""),
json!([]),
json!([{"type":"text","text":""}]),
json!([{"type":"output_text","text":null}]),
] {
body["messages"][1]["content"] = content.clone();
body["messages"][3]["content"] = content;
assert_eq!(target_requests(&body).map(Result::unwrap), expected);
}
body["messages"][2]["content"] =
json!([{"type":"text","text":""},{"type":"text","text":"x"},{"type":"text","text":""}]);
let [responses, messages, genai] = target_requests(&body).map(Result::unwrap);
assert_eq!(responses["input"][2]["output"].as_array().unwrap().len(), 3);
assert_eq!(
messages["messages"][2]["content"][0]["content"]
.as_array()
.unwrap()
.len(),
3
);
assert_eq!(
genai["contents"][2]["parts"][0]["functionResponse"]["response"]["output"],
"\nx\n"
);
body["messages"][2]["content"][0]["text"] = Value::Null;
assert_eq!(
target_requests(&body).map(Result::unwrap),
[responses, messages, genai]
);
body["messages"][2]["content"] = json!("");
body["messages"][2]["name"] = json!(17);
let parsed = parse_request(&serde_json::to_vec(&body).unwrap()).unwrap();
let [responses, messages, genai] = target_requests(&parsed);
assert_eq!(responses.unwrap_err().parameter(), Some("messages[2].name"));
assert_eq!(messages.unwrap(), expected[1]);
assert_eq!(genai.unwrap(), expected[2]);
}
#[test]
fn filters_only_plain_empty_history_parts_and_keeps_source_indices() {
let mut body = super::request();
let blank = json!({"type":"input_text","text":""});
let space = json!({"type":"text","text":" "});
for role in ["system", "developer", "assistant", "user"] {
body["messages"] = json!([{"role":role,"content":[space]}, {"role":"user","content":"hi"}]);
let expected = target_requests(&body).map(Result::unwrap);
body["messages"][0]["content"] = json!([blank, space, blank]);
let actual = target_requests(&body).map(Result::unwrap);
body["messages"][0]["content"][0]["text"] = Value::Null;
assert_eq!(target_requests(&body).map(Result::unwrap), actual);
if role == "user" {
assert_eq!(
actual[0]["input"][0]["content"].as_array().unwrap().len(),
3
);
assert_eq!(actual[1]["messages"][0]["content"][1]["text"], " ");
assert_eq!(actual[2]["contents"][0]["parts"][1]["text"], " ");
} else {
assert_eq!(actual, expected);
}
}
let marked = json!({"type":"text","text":null,"prompt_cache_breakpoint":{"mode":"explicit"}});
body["messages"][0] = json!({"role":"developer","content":[blank,marked]});
let converted = responses::convert_request(&body).unwrap();
assert_eq!(
converted["input"][0]["content"],
json!([{"type":"input_text","text":"","prompt_cache_breakpoint":{"mode":"explicit"}}])
);
body["messages"][0]["role"] = json!("assistant");
assert_eq!(
responses::convert_request(&body).unwrap_err().parameter(),
Some("messages[0].content[1].prompt_cache_breakpoint")
);
for (part, code) in [
(json!({"type":"text"}), "missing_required_parameter"),
(json!({"type":"text","text":17}), "invalid_type"),
(json!({"type":"text","text":{}}), "invalid_type"),
] {
body["messages"][0]["content"] = json!([{"type":"text","text":null},part]);
for error in target_requests(&body).map(Result::unwrap_err) {
assert_eq!(error.parameter(), Some("messages[0].content[1].text"));
assert_eq!(error.code(), code);
}
}
}
#[test]
fn null_chat_controls_fall_back_to_native_format_and_effort() {
let mut body = super::request();
let schema = json!({"type":"object","properties":{"q":{"type":"string"}}});
body.insert(
"text".into(),
json!({"format":{"type":"json_schema","name":"answer","schema":schema}}),
);
body.insert("reasoning".into(), json!({"effort":"low"}));
let expected = target_requests(&body).map(Result::unwrap);
assert_eq!(expected[1]["output_config"]["format"]["schema"], schema);
assert_eq!(
expected[2]["generationConfig"]["responseJsonSchema"],
schema
);
assert_eq!(expected[1]["thinking"]["budget_tokens"], 1024);
assert_eq!(
expected[2]["generationConfig"]["thinkingConfig"]["thinkingBudget"],
1024
);
body.insert("response_format".into(), Value::Null);
body.insert("reasoning_effort".into(), Value::Null);
assert_eq!(target_requests(&body).map(Result::unwrap), expected);
assert!(request_facts(CHAT_PROTOCOL, &body).json_schema);
body["response_format"] = json!({"type":"text"});
body["reasoning_effort"] = json!("none");
let [responses, messages, genai] = target_requests(&body).map(Result::unwrap);
assert!(!request_facts(CHAT_PROTOCOL, &body).json_schema);
assert_eq!(responses["text"]["format"]["type"], "text");
assert!(messages.get("output_config").is_none());
assert!(
genai["generationConfig"]
.get("responseJsonSchema")
.is_none()
);
assert_eq!(messages["thinking"]["type"], "disabled");
assert_eq!(
genai["generationConfig"]["thinkingConfig"]["thinkingBudget"],
0
);
body["reasoning_effort"] = json!(5);
for error in target_requests(&body).map(Result::unwrap_err) {
assert_eq!(error.parameter(), Some("reasoning_effort"));
}
}
#[test]
fn null_function_parameters_follow_each_targets_default() {
let mut body = super::request();
body.insert(
"tools".into(),
json!([{"type":"function","function":{"name":"clock"}}]),
);
let expected = target_requests(&body).map(Result::unwrap);
assert!(expected[0]["tools"][0].get("parameters").is_none());
let default_schema = json!({"type":"object","properties":{}});
assert_eq!(expected[1]["tools"][0]["input_schema"], default_schema);
assert_eq!(
expected[2]["tools"][0]["functionDeclarations"][0]["parametersJsonSchema"],
default_schema
);
body["tools"][0]["function"] =
json!({"name":"clock","parameters":null,"description":null,"strict":null});
assert_eq!(target_requests(&body).map(Result::unwrap), expected);
let schema =
json!({"type":"object","properties":{"q":{"type":["string","null"],"default":null}}});
body["tools"][0]["function"]["parameters"] = schema.clone();
let [responses, messages, genai] = target_requests(&body).map(Result::unwrap);
assert_eq!(responses["tools"][0]["parameters"], schema);
assert_eq!(messages["tools"][0]["input_schema"], schema);
assert_eq!(
genai["tools"][0]["functionDeclarations"][0]["parametersJsonSchema"],
schema
);
}
#[test]
fn stop_sequences_are_mapped_only_for_targets_that_support_them() {
let mut body = super::request();
let baseline = target_requests(&body).map(Result::unwrap);
for stop in [Value::Null, json!([])] {
body.insert("stop".into(), stop);
assert_eq!(target_requests(&body).map(Result::unwrap), baseline);
}
for (stop, expected) in [
(json!(" END"), json!([" END"])),
(json!([" END", "\n"]), json!([" END", "\n"])),
] {
body["stop"] = stop;
let [responses, messages, genai] = target_requests(&body).map(Result::unwrap);
assert_eq!(responses, baseline[0]);
assert_eq!(messages["stop_sequences"], expected);
assert_eq!(genai["generationConfig"]["stopSequences"], expected);
}
for (stop, param) in [(json!(5), "stop"), (json!(["end", null]), "stop[1]")] {
body["stop"] = stop;
let [responses, messages, genai] = target_requests(&body);
assert_eq!(responses.unwrap(), baseline[0]);
for result in [messages, genai] {
assert_eq!(result.unwrap_err().parameter(), Some(param));
}
}
}
#[test]
fn stream_options_affect_only_streaming_delivery() {
for stream in [None, Some(false), Some(true)] {
let mut body = super::request();
if let Some(stream) = stream {
body.insert("stream".into(), json!(stream));
}
let expected = target_requests(&body).map(Result::unwrap);
body.insert(
"stream_options".into(),
json!({"include_usage":true, "include_obfuscation":false}),
);
assert_eq!(target_requests(&body).map(Result::unwrap), expected);
body["stream_options"]["include_obfuscation"] = json!(true);
if stream == Some(true) {
for error in target_requests(&body).map(Result::unwrap_err) {
assert_eq!(
error.parameter(),
Some("stream_options.include_obfuscation")
);
}
} else {
assert_eq!(target_requests(&body).map(Result::unwrap), expected);
}
}
}
#[test] #[test]
fn all_targets_apply_the_same_common_request_validation() { fn all_targets_apply_the_same_common_request_validation() {
for (field, value, parameter) in [ for (field, value, parameter) in [
(
"messages",
json!([{"role":"system","content":null},{"role":"developer","content":null}]),
"messages",
),
(
"messages",
json!([{"role":"developer"},{"role":"assistant","audio":{"id":"audio"}}]),
"messages[1].audio",
),
(
"messages",
json!([{"role":"system","content":42}]),
"messages[0].content",
),
(
"messages",
json!([{"role":"system","content":null},{"role":"user","content":null}]),
"messages[1].content",
),
(
"messages",
json!([{"role":"tool","tool_call_id":"c","content":null}]),
"messages[0].content",
),
(
"messages",
json!([{"role":"system","content":null,"tool_calls":[{}]}]),
"messages[0].tool_calls",
),
( (
"messages", "messages",
json!([{"role":"assistant","content":"ok","refusal":17}]), json!([{"role":"assistant","content":"ok","refusal":17}]),
@@ -114,13 +433,18 @@ fn all_targets_apply_the_same_common_request_validation() {
), ),
( (
"messages", "messages",
json!([{"role":"user","content":"ok","name":17}]), json!([{"role":"assistant","tool_calls":{}}]),
"messages[0].name", "messages[0].tool_calls",
), ),
( (
"messages", "messages",
json!([{"role":"user","content":"ok","tool_calls":[]}]), json!([{"role":"developer","tool_call_id":"c"}]),
"messages[0].tool_calls", "messages[0].tool_call_id",
),
(
"messages",
json!([{"role":"user","content":"ok","refusal":"declined"}]),
"messages[0].refusal",
), ),
( (
"messages", "messages",
@@ -130,8 +454,8 @@ fn all_targets_apply_the_same_common_request_validation() {
("n", json!(2), "n"), ("n", json!(2), "n"),
( (
"stream_options", "stream_options",
json!({"include_usage":true}), json!({"include_usage":1}),
"stream_options", "stream_options.include_usage",
), ),
] { ] {
let mut body = super::request(); let mut body = super::request();
@@ -140,11 +464,7 @@ fn all_targets_apply_the_same_common_request_validation() {
.err() .err()
.unwrap(); .unwrap();
assert_eq!(expected.parameter(), Some(parameter)); assert_eq!(expected.parameter(), Some(parameter));
for result in [ for result in target_requests(&body) {
responses::convert_request(&body),
messages::convert_request(&body, &Default::default()),
genai::convert_request(&body),
] {
assert_eq!(result.unwrap_err(), expected); assert_eq!(result.unwrap_err(), expected);
} }
} }
+53 -1
View File
@@ -1,9 +1,61 @@
//! 验证传输头部分类,以及响应中的连接级和身份字段过滤 //! 验证传输头部分类,以及响应中的连接级和身份字段过滤
use gateway_protocol::http::{ use gateway_protocol::http::{
is_transport_managed_request_header, parse_retry_after_seconds, response_header_is_forwardable, is_transport_managed_request_header, parse_retry_after_seconds, preferred_response_request_id,
response_header_is_forwardable,
}; };
#[test]
fn response_request_ids_follow_official_header_priority() {
let names = [
"x-request-id",
"x-oai-request-id",
"x-openai-request-id",
"x-ms-request-id",
];
let mut headers = http::HeaderMap::new();
for name in names {
headers.insert(name, http::HeaderValue::from_static(name));
}
headers.insert("cf-ray", http::HeaderValue::from_static("trace-only"));
for name in names {
assert_eq!(
preferred_response_request_id(|name| headers.get(name)?.to_str().ok()),
Some(name),
);
headers.remove(name);
}
assert_eq!(
preferred_response_request_id(|name| headers.get(name)?.to_str().ok()),
None,
);
}
#[test]
fn response_request_ids_skip_unusable_first_values_without_rewriting_headers() {
let mut headers = http::HeaderMap::new();
headers.insert(
"x-request-id",
http::HeaderValue::from_bytes(b"\xff").unwrap(),
);
headers.append(
"x-request-id",
http::HeaderValue::from_static("second-value"),
);
headers.insert("x-oai-request-id", http::HeaderValue::from_static(" \t "));
headers.insert("x-openai-request-id", http::HeaderValue::from_static(""));
headers.insert(
"x-ms-request-id",
http::HeaderValue::from_static(" opaque-id "),
);
assert_eq!(
preferred_response_request_id(|name| headers.get(name)?.to_str().ok()),
Some(" opaque-id "),
);
assert_eq!(headers["x-request-id"].as_bytes(), b"\xff");
assert_eq!(headers.get_all("x-request-id").iter().count(), 2);
}
#[test] #[test]
fn retry_after_should_accept_nonnegative_seconds_and_http_dates() { fn retry_after_should_accept_nonnegative_seconds_and_http_dates() {
for (header, expected) in [ for (header, expected) in [
@@ -301,6 +301,21 @@ async fn connect(
oauth_pending, oauth_pending,
diagnostics.clone(), diagnostics.clone(),
); );
let recent_requests = if matches!(mode, StoreMode::Runtime) && !read_only {
let persistence = gateway_core::engine::RecentRequestPersistence::new(
provider_ports.account_feedback(),
Arc::new(redis::RedisRecentRequestRepository::new(
redis_connection.clone(),
REDIS_NAMESPACE,
)?),
);
if let Err(error) = persistence.restore().await {
tracing::warn!(%error, "近期请求统计恢复失败,将重新积累");
}
Some(persistence)
} else {
None
};
let worker_leader_lease = Arc::new(redis::worker_lease::RedisWorkerLeaderLeasePort::new( let worker_leader_lease = Arc::new(redis::worker_lease::RedisWorkerLeaderLeasePort::new(
credential_leases, credential_leases,
)); ));
@@ -322,6 +337,7 @@ async fn connect(
admission_release_writer, admission_release_writer,
budget_writer, budget_writer,
lease_cleanup, lease_cleanup,
recent_requests,
)?, )?,
None, None,
), ),
@@ -674,6 +674,7 @@ impl RedisProviderLeaseCoordinator {
account, account,
AccountRuntimeSignals { AccountRuntimeSignals {
in_flight: signal.in_flight, in_flight: signal.in_flight,
recent_requests: 0,
last_started_at: signal.last_started_at.map(Into::into), last_started_at: signal.last_started_at.map(Into::into),
quota_reset_at: None, quota_reset_at: None,
quota_reset_windows: None, quota_reset_windows: None,
@@ -16,6 +16,7 @@ mod native_continuation;
mod oauth_pending; mod oauth_pending;
mod provider_session_affinity; mod provider_session_affinity;
mod provider_session_exclusion; mod provider_session_exclusion;
mod recent_requests;
mod runtime_change; mod runtime_change;
pub(crate) mod worker_lease; pub(crate) mod worker_lease;
@@ -32,6 +33,7 @@ pub use native_continuation::*;
pub use oauth_pending::*; pub use oauth_pending::*;
pub use provider_session_affinity::*; pub use provider_session_affinity::*;
pub use provider_session_exclusion::*; pub use provider_session_exclusion::*;
pub use recent_requests::*;
pub use runtime_change::*; pub use runtime_change::*;
use crate::{StoreError, StoreResult, require_nonempty}; use crate::{StoreError, StoreResult, require_nonempty};
@@ -0,0 +1,69 @@
//! 原子替换单进程近期请求快照并设置过期时间
use std::time::Duration;
use futures::future::BoxFuture;
use gateway_core::account::{RecentRequestSnapshot, RecentRequestStore};
use gateway_core::error::{StoreError as CoreStoreError, StoreErrorKind};
use redis::aio::ConnectionManager;
use super::namespace;
use crate::StoreResult;
pub struct RedisRecentRequestRepository {
connection: ConnectionManager,
key: String,
}
impl RedisRecentRequestRepository {
pub fn new(connection: ConnectionManager, key_namespace: &str) -> StoreResult<Self> {
Ok(Self {
connection,
key: format!("{}:scheduler:recent-requests:v1", namespace(key_namespace)?),
})
}
}
impl RecentRequestStore for RedisRecentRequestRepository {
fn load(&self) -> BoxFuture<'_, Result<Option<RecentRequestSnapshot>, CoreStoreError>> {
Box::pin(async move {
let mut connection = self.connection.clone();
let value: Option<Vec<u8>> = redis::cmd("GET")
.arg(&self.key)
.query_async(&mut connection)
.await
.map_err(unavailable)?;
value
.map(|bytes| {
serde_json::from_slice(&bytes).map_err(|error| {
CoreStoreError::caused_by(StoreErrorKind::InvalidData, error)
})
})
.transpose()
})
}
fn save<'a>(
&'a self,
snapshot: &'a RecentRequestSnapshot,
ttl: Duration,
) -> BoxFuture<'a, Result<(), CoreStoreError>> {
Box::pin(async move {
let value = serde_json::to_vec(snapshot)
.map_err(|error| CoreStoreError::caused_by(StoreErrorKind::InvalidData, error))?;
let mut connection = self.connection.clone();
redis::cmd("SET")
.arg(&self.key)
.arg(value)
.arg("PX")
.arg(u64::try_from(ttl.as_millis()).unwrap_or(u64::MAX))
.query_async::<()>(&mut connection)
.await
.map_err(unavailable)
})
}
}
fn unavailable(error: redis::RedisError) -> CoreStoreError {
CoreStoreError::caused_by(StoreErrorKind::Unavailable, error)
}
+30 -12
View File
@@ -106,6 +106,7 @@ pub(crate) fn store_worker_contributions(
admission_release_writer: redis::ClientAdmissionReleaseWriter, admission_release_writer: redis::ClientAdmissionReleaseWriter,
budget_writer: postgres::ClientBudgetWriter, budget_writer: postgres::ClientBudgetWriter,
lease_cleanup: impl DaemonTask + 'static, lease_cleanup: impl DaemonTask + 'static,
recent_requests: Option<gateway_core::engine::RecentRequestPersistence>,
) -> StoreResult<Vec<WorkerContribution>> { ) -> StoreResult<Vec<WorkerContribution>> {
let stale_id = WorkerId::try_new(WorkerKind::StaleModelRequestRecovery, "postgres") let stale_id = WorkerId::try_new(WorkerKind::StaleModelRequestRecovery, "postgres")
.map_err(worker_definition_error)?; .map_err(worker_definition_error)?;
@@ -123,7 +124,7 @@ pub(crate) fn store_worker_contributions(
let ops_flush_restart = let ops_flush_restart =
DaemonRestartPolicy::try_new(Duration::from_secs(1), Duration::from_secs(60)) DaemonRestartPolicy::try_new(Duration::from_secs(1), Duration::from_secs(60))
.map_err(worker_definition_error)?; .map_err(worker_definition_error)?;
Ok(vec![ let mut contributions = vec![
WorkerContribution::Registration( WorkerContribution::Registration(
WorkerRegistration::try_new( WorkerRegistration::try_new(
lease_cleanup_id, lease_cleanup_id,
@@ -179,7 +180,21 @@ pub(crate) fn store_worker_contributions(
) )
.map_err(worker_definition_error)?, .map_err(worker_definition_error)?,
), ),
]) ];
if let Some(persistence) = recent_requests {
contributions.push(WorkerContribution::Registration(
WorkerRegistration::try_new(
WorkerId::try_new(WorkerKind::OpsFlush, "redis_account_load")
.map_err(worker_definition_error)?,
WorkerRunnable::Daemon {
restart: ops_flush_restart,
task: Box::new(persistence),
},
)
.map_err(worker_definition_error)?,
));
}
Ok(contributions)
} }
pub(crate) fn scheduled_worker( pub(crate) fn scheduled_worker(
@@ -225,18 +240,21 @@ pub(crate) struct StaleModelRequestRecoveryTask {
impl ScheduledTask for StaleModelRequestRecoveryTask { impl ScheduledTask for StaleModelRequestRecoveryTask {
fn run_cycle( fn run_cycle(
&self, &self,
_context: WorkerCycleContext, context: WorkerCycleContext,
) -> futures::future::BoxFuture<'_, Result<(), WorkerTaskError>> { ) -> futures::future::BoxFuture<'_, Result<(), WorkerTaskError>> {
Box::pin(async move { Box::pin(async move {
gateway_core::engine::ExecutionStore::recover_expired( context
self.execution.as_ref(), .cancellation()
SystemTime::now(), .run_until_cancelled(gateway_core::engine::ExecutionStore::recover_expired(
) self.execution.as_ref(),
.await SystemTime::now(),
.map(|_| ()) ))
.map_err(|source| { .await
WorkerTaskError::safe("stale request recovery failed").with_source(source) .transpose()
}) .map(|_| ())
.map_err(|source| {
WorkerTaskError::safe("stale request recovery failed").with_source(source)
})
}) })
} }
} }
@@ -12,4 +12,5 @@ mod native_continuation;
mod oauth_pending; mod oauth_pending;
mod provider_session_affinity; mod provider_session_affinity;
mod provider_session_exclusion; mod provider_session_exclusion;
mod recent_requests;
mod worker_lease; mod worker_lease;

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