mirror of
https://github.com/zyycn/codex-proxy-rs.git
synced 2026-12-05 08:00:53 +00:00
Compare commits
33
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0ebf6739e2 | ||
|
|
b987cca4aa | ||
|
|
72e82c565e | ||
|
|
47ccdeb737 | ||
|
|
b20b0e2013 | ||
|
|
16fc302d46 | ||
|
|
95c35d0a67 | ||
|
|
259a2e1ba0 | ||
|
|
2f51412625 | ||
|
|
32f3b11ddf | ||
|
|
c2891e14ce | ||
|
|
b28eee6e18 | ||
|
|
6bf182677a | ||
|
|
8d4b0496e2 | ||
|
|
9b08c3a50d | ||
|
|
f43e1f95c3 | ||
|
|
21cf139c96 | ||
|
|
7d6e4cc4e7 | ||
|
|
2ddcd7c936 | ||
|
|
c71e6176c5 | ||
|
|
28d3e3c2cb | ||
|
|
dd793a84ab | ||
|
|
5ed8b626d7 | ||
|
|
96d8b25d0b | ||
|
|
a193de4eba | ||
|
|
e296bef65e | ||
|
|
89092272a1 | ||
|
|
09f3b39bbc | ||
|
|
7591845f74 | ||
|
|
67ac8fd067 | ||
|
|
b232e367fc | ||
|
|
0bdaa29907 | ||
|
|
cc798e33a1 |
No files matched your search
@@ -16,6 +16,8 @@ description: Codex Proxy RS 的需求评估、排障、开发、代码审查与
|
||||
|
||||
评估功能建议、排障、开发和审查时,先按[问题与方案依据](../../../CONTRIBUTING.md#问题与方案依据)核实使用者要完成什么、当前行为造成了什么影响。反馈直接给出改法时,先弄清提出这个改法的原因
|
||||
|
||||
先确定正常使用时应得到的结果。设计校验、回退或故障恢复时,同时看它防住的具体风险和它可能挡住的正常用法。按协议、隔离要求和实际部署条件选择对正常路径影响最小的做法。只在假设的部署场景下才需要的处理,留到有相应需求时再做
|
||||
|
||||
排查故障时,从症状沿实际调用链回溯,定位行为最早偏离预期的环节,用源码、诊断或对照复现说明触发条件如何导致结果。原因尚未确定时,区分已知事实与假设,指出哪项证据能区分可能原因。确认根因后,在负责该行为的模块修复,用原触发场景验证
|
||||
|
||||
涉及 Codex 时,以对应版本的官方源码核实客户端行为,默认透明转发,只做必要适配。建议宿主接管已有决定时,指出需要它介入的网关职责或实际约束。若只是个别部署希望采用不同策略,说明不建议内置的原因。实现可行性不能证明宿主应当承担这项需求
|
||||
@@ -56,7 +58,7 @@ description: Codex Proxy RS 的需求评估、排障、开发、代码审查与
|
||||
- 移动或重命名测试时,核对受影响的场景覆盖是否保留;涉及子进程调用或名称过滤时,同步更新调用入口并实际运行,确认目标用例确实执行且行为断言通过
|
||||
- 清理只证明旧字段、旧路由或旧实现已经消失的用例与附带断言;未知字段校验使用合法请求基线加无业务含义的未知字段,避免因缺少必填项等其他错误而误通过
|
||||
- 同一层对同一行为的重复覆盖合并为清晰的场景矩阵,复用相邻测试夹具;跨层测试确有不同职责或失败路径时保留,不为统一而扩大测试辅助抽象
|
||||
- 断言可观察的行为与业务不变量,避免复述结构体赋值、罗列表列或字段清单、匹配 SQL 文本与源码布局
|
||||
- 断言可观察的行为与业务不变量,避免复述实现细节。验收上游兼容行为时,先从对应版本的上游实现确定预期,再核对网关对同一输入的处理。例如历史应增量续接时,要看出站请求是否只含预期的增量,因为回退全量也可能返回成功
|
||||
- 维护项目明确要求的架构边界检查;发现漏检时,对照规则核实扫描范围、排除项与被检查的依赖关系,优先补齐现有检查中能稳定判定的缺口
|
||||
- 当前协议兼容、数据读取兼容、安全边界、并发和资源生命周期仍需覆盖,不按 `old`、`legacy` 等名称机械删除,也不能用改名代替无效用例清理
|
||||
- 不在仓库中新增或保留迁移 SQL 专项测试,包括迁移文本、schema 演变与指定版本升级用例;需要验证迁移执行、数据保留或回滚时,在临时目录编写一次性验证并使用隔离数据库,测试通过即可,临时脚本不纳入维护测试集
|
||||
|
||||
@@ -20,7 +20,7 @@
|
||||
|
||||
调用入口前重新核对当前脚本的副作用、目标版本和待推送提交,保留无关工作区内容,不自动清理或暂存用户文件。
|
||||
先编辑 `release/notes.md`,保留为未提交改动(已暂存或未暂存均可);其他已跟踪文件的改动应先单独提交。
|
||||
脚本只改 `release/version.yaml` 的顶层 `version`,按[接口弃用规则](../../../../backend/crates/gateway-plugin/sdk/docs/manifest.md#接口弃用)校验并维护 `plugin-api-deprecations.json`,将这些差异与最终工作区中的发布说明一起提交为 `chore: bump version to <version>`。
|
||||
脚本更新 `release/version.yaml` 的顶层 `version`,按[接口弃用规则](../../../../backend/crates/gateway-plugin/sdk/docs/manifest.md#接口弃用)校验并维护 `plugin-api-deprecations.json`,生成发布说明的自动区块,将这些差异与手写正文一起提交为 `chore: bump version to <version>`。
|
||||
不要提前单独提交说明或把版本文件改成目标版本;脚本要求说明相对 HEAD 有改动,并自行更新版本号。
|
||||
本任务需要的提交按[项目约定](../../../../CONTRIBUTING.md#项目约定)保留英文 Conventional Commits 与相应署名。
|
||||
|
||||
@@ -31,7 +31,7 @@ release/publish "$release_version"
|
||||
```
|
||||
|
||||
该命令会创建上述版本提交与 annotated tag,原子推送分支和 tag,再从长期分支手动触发 `release.yml`。
|
||||
只读预检使用 `release/publish --check "$release_version"`。发布工作流读取 tag 中的说明,修改 tag 之后的本地文件不会改变该次构建。
|
||||
只读预检使用 `release/publish --check "$release_version"`。发布工作流读取 tag 中已经生成的完整说明,不再查询 PR 或附加另一份自动日志;修改 tag 之后的本地文件不会改变该次构建。
|
||||
|
||||
只调整已发布页面的标题或正文时,编辑对应 GitHub Release 的 `name` 或 `body` 并回读核对;
|
||||
保持已有 tag、源码提交、附件和预发行状态,不重新执行发布入口。
|
||||
@@ -60,7 +60,8 @@ release/publish "$release_version"
|
||||
### 验收
|
||||
|
||||
- 发布完成后核对 GitHub Release 的版本、正式版/预发行状态和中文变更正文;对照平台清单与工作流确认归档、校验和及镜像产物。
|
||||
工作流附加的安装说明和自动提交列表按其当前配置处理,不用它们替代手写的中文变更说明。
|
||||
正文应与 tag 内的说明一致,正式版的 `Full Changelog` 从上一正式版开始,PR 和直接提交覆盖本次范围;自动列表不替代手写的中文变更说明
|
||||
- 核对 `backend-validation` 的结果。复用时检查摘要中的源码提交和成功 CI 链接,确认发行提交仅修改版本与说明;未满足复用条件时检查本次完整后端任务,不能把 `quality / backend` 的跳过单独记为测试通过
|
||||
- 回读 `main:release/version.yaml` 的 `published`。正式版参与同一大版本四个普通通道的比较;RC 参与 RC、Beta、Alpha,Beta 参与 Beta、Alpha,Alpha 只参与自身。实验版只推进 `exp["X.Y.Z"]`。有通道推进时应有 `chore(release): update release channels to <version>` 提交;重复执行或较旧版本未推进任何通道时无提交
|
||||
- 正式版提升或恢复后,回读 GitHub Latest 的 tag 与镜像 `latest` 的摘要,核对两者均指向预期正式版
|
||||
- 保留 v3.42.0 在线升级使用的 `update-index` 页面和 v3.42.1 的 `version.yaml` 附件
|
||||
|
||||
@@ -9,12 +9,21 @@
|
||||
3. 使用用户确定的目标版本,建议版本时说明兼容性、能力或修复依据;同名 tag 先区分重试与新发行,不递增版本掩盖冲突
|
||||
4. 命名与晋级按[版本命名与升级规则](../../../../deploy/README.md#版本命名与升级规则),实验版另读[实验流程](experimental.md#分支与版本)
|
||||
|
||||
对比基线选自已公开且 tag 位于目标提交历史内的 GitHub Release
|
||||
|
||||
- 推荐正式版号和编写发布说明时,都核对上一正式版到目标提交的最终差异,覆盖期间全部预发行。对于向后兼容的变更,只要有用户可用的新功能,就从上一正式版递增 minor 并将 patch 归零,仅含修复则递增 patch
|
||||
- alpha、beta、rc 优先对比同一 `X.Y.Z` 的上一常规预发行,没有时对比上一正式版
|
||||
- exp 对比同一 `X.Y.Z` 的上一实验版,首次实验对比同号正式版
|
||||
- 没有前序发行的首次发布从仓库起点核对
|
||||
|
||||
## 发布说明
|
||||
|
||||
读取当前 [notes.md](../../../../release/notes.md)与[项目约定](../../../../CONTRIBUTING.md#项目约定)中的发布说明条目
|
||||
|
||||
- 只在发布说明任务中修改 `release/notes.md`,替换为本次版本内容,首行为目标 tag,正文使用中文
|
||||
- 常规版本按「新增功能」「优化改进」「问题修复」「升级须知」归类,省略空章节;单一改动可直接写一句。安装命令和文档入口由工作流附加
|
||||
- 常规版本的手写正文按「新增功能」「优化改进」「问题修复」「升级须知」归类,省略空章节;单一改动可直接写一句
|
||||
- `release/publish` 生成安装入口、文档链接和变更列表,保存到说明末尾的 `cpr-release:generated` 标记区块;重新准备说明时整块保留或移除,不在区块中手写内容
|
||||
- 自动列表按实际提交中的 PR 编号补齐 GitHub 遗漏的合并记录,并列出直接提交;仍需对照完整 diff 核实中文正文,剔除回退或重复的用户影响
|
||||
- 每条用一句短语讲清一个用户可感知的结果,不加句号,例如「系统更新:确认当前平台有安装包后才提示升级」
|
||||
- 同一变化只写一次,保留会影响使用或升级的默认值和限制,不展开实现过程、逐条翻译提交或写未经验证的承诺
|
||||
- 剔除回退、重复及未进入发行范围的内容,升级事项须能追溯到实际迁移、配置或兼容变化
|
||||
@@ -31,7 +40,8 @@
|
||||
在上一发行基线到 HEAD 的提交中检查是否已有目标版本的备版提交(`chore: bump version to <version>`;查历史时也匹配 `chore(release): prepare v<version>` 和 `chore(release): v<version>`),即使同名 tag 已不存在也要查。命中时先核对该提交对应的发行状态,按[失败恢复](operations.md#恢复与验收)处理,不在旧提交上再叠一个同名提交
|
||||
|
||||
发布说明准备好、其他代码已提交后,执行 `release/publish --check <version>`,检查版本、说明、工作区、远端分支与 tag、工具链和插件兼容窗口。
|
||||
预检不修改文件、Git 引用或远端状态;远端存在本地未知提交时先同步再检查。它不替代 CI、发行物验证或实际发布授权
|
||||
预检输出基线、目标提交和完整正文,核对 `Full Changelog` 范围、PR 列表及直接提交;正式执行也使用相同生成入口,将最终正文随版本提交保存
|
||||
预检不修改文件、Git 引用或远端状态;远端存在本地未知提交或缺少已发布的基线 tag 时,先同步再检查。它不替代 CI、发行物验证或实际发布授权
|
||||
|
||||
按[验证要求](../../../../CONTRIBUTING.md#验证)核对目标提交的证据,区分通过、失败、跳过与未执行
|
||||
数据库变更同时读取[迁移冻结规则](../../../../backend/migrations/README.md#冻结规则):
|
||||
|
||||
@@ -97,11 +97,6 @@ module ReleaseMetadata
|
||||
validate_notes(value)
|
||||
entries = platforms
|
||||
docker, native = entries.partition { |entry| entry['docker'] == true }
|
||||
previous = git('tag', '--list', 'v*', '--merged', 'HEAD').lines.map(&:strip).filter_map do |candidate|
|
||||
next unless candidate.delete_prefix('v').match?(SEMVER)
|
||||
key = sort_key(candidate)
|
||||
[key, candidate] if key < sort_key(value)
|
||||
end.max_by(&:first)&.last
|
||||
{
|
||||
'tag' => tag,
|
||||
'version' => value,
|
||||
@@ -112,7 +107,6 @@ module ReleaseMetadata
|
||||
'non_docker_matrix' => JSON.generate('include' => native),
|
||||
'windows_matrix' => JSON.generate('include' => entries.select { |entry| entry['os'] == 'windows' }),
|
||||
'docker_platforms' => docker.map { |entry| entry['dockerPlatform'] }.join(','),
|
||||
'previous_tag' => previous,
|
||||
'prerelease' => prerelease?(value),
|
||||
'build_type' => value.split('+', 2).first.include?('-exp.') ? 'experimental' : 'release'
|
||||
}
|
||||
|
||||
@@ -0,0 +1,179 @@
|
||||
require_relative 'release-metadata'
|
||||
|
||||
# 预检与发布共用日志范围;生成结果随版本提交保存,构建时不再查询可变的 PR 信息
|
||||
module ReleaseNotes
|
||||
START = '<!-- cpr-release:generated -->'
|
||||
FINISH = '<!-- /cpr-release:generated -->'
|
||||
|
||||
def self.manual_body(document)
|
||||
body = document.lines.drop(1).join.strip
|
||||
return body unless body.include?(START) || body.include?(FINISH)
|
||||
unless body.scan(START).length == 1 && body.scan(FINISH).length == 1 && body.end_with?(FINISH) &&
|
||||
body.index(START) < body.index(FINISH)
|
||||
raise 'Invalid generated release notes block; keep the complete block at the end or remove it'
|
||||
end
|
||||
body.split(START, 2).first.rstrip
|
||||
end
|
||||
|
||||
def self.body(value)
|
||||
ReleaseMetadata.validate_notes(value)
|
||||
document = File.read('release/notes.md')
|
||||
manual_body(document)
|
||||
unless value.include?('-exp.') || document.include?(START)
|
||||
raise 'Release notes are not prepared; use release/publish to generate and commit the final body'
|
||||
end
|
||||
document.lines.drop(1).join.strip + "\n"
|
||||
end
|
||||
|
||||
# 只选已公开且属于目标历史的发行;首次实验版可以以同号正式版为基线
|
||||
def self.previous_tag(value, releases, reachable)
|
||||
core, stage = value.split('-', 2)
|
||||
candidates = releases.select do |release|
|
||||
tag = release.fetch('tag_name')
|
||||
raw = tag.delete_prefix('v')
|
||||
tag == "v#{raw}" && raw.match?(ReleaseMetadata::SEMVER) && !raw.include?('+') &&
|
||||
!release.fetch('draft') && release.fetch('prerelease') == ReleaseMetadata.prerelease?(raw) &&
|
||||
reachable.include?(tag)
|
||||
end.map { |release| release.fetch('tag_name') }
|
||||
lower = candidates.select { |tag| ReleaseMetadata.sort_key(tag) < ReleaseMetadata.sort_key(value) }
|
||||
if stage
|
||||
same_line = lower.select do |tag|
|
||||
previous_core, previous_stage = tag.delete_prefix('v').split('-', 2)
|
||||
previous_core == core && previous_stage &&
|
||||
previous_stage.start_with?('exp.') == stage.start_with?('exp.')
|
||||
end
|
||||
return same_line.max_by { |tag| ReleaseMetadata.sort_key(tag) } unless same_line.empty?
|
||||
return candidates.find { |tag| tag == "v#{core}" } if stage.start_with?('exp.')
|
||||
end
|
||||
lower.reject { |tag| ReleaseMetadata.prerelease?(tag) }.max_by { |tag| ReleaseMetadata.sort_key(tag) }
|
||||
end
|
||||
|
||||
class Generator
|
||||
def initialize(repository)
|
||||
raise 'Invalid GitHub repository' unless repository.match?(%r{\A[\w.-]+/[\w.-]+\z})
|
||||
@repository = repository
|
||||
@endpoint = "repos/#{repository}"
|
||||
@url = "https://github.com/#{repository}"
|
||||
end
|
||||
|
||||
def api(path, data: nil, paginate: false)
|
||||
args = ['gh', 'api', "#{@endpoint}/#{path}"]
|
||||
args.concat(['--method', 'POST', '--input', '-']) if data
|
||||
args.concat(['--paginate', '--jq', '.[] | @json']) if paginate
|
||||
output, error, status = Open3.capture3(*args, stdin_data: data ? JSON.generate(data) : '')
|
||||
raise "Cannot read release information: #{error.strip}" unless status.success?
|
||||
paginate ? output.lines.map { |line| JSON.parse(line) } : JSON.parse(output)
|
||||
end
|
||||
|
||||
def commits(base, head)
|
||||
range = base ? "#{base}..#{head}" : head
|
||||
ReleaseMetadata.git('log', '--first-parent', '--reverse', '--format=%H %s', range, '--').lines.map do |line|
|
||||
sha, subject = line.strip.split(' ', 2)
|
||||
[sha, subject]
|
||||
end.reject do |sha, _|
|
||||
paths = ReleaseMetadata.git('diff-tree', '--root', '--no-commit-id', '--name-only', '-r', sha).lines.map(&:strip)
|
||||
!paths.empty? && (paths - %w[release/version.yaml release/notes.md]).empty?
|
||||
end
|
||||
end
|
||||
|
||||
def markdown(text)
|
||||
text.gsub(/[\\`*_\[\]<>]/) { |character| "\\#{character}" }
|
||||
end
|
||||
|
||||
def changelog(base, head, value, github_head)
|
||||
# 没有前序发行时从仓库起点列举,不让 GitHub 自动猜测另一条发行线
|
||||
# 未推送的提交由本地历史补齐,避免要求预检先写远端
|
||||
github_range = base && ReleaseMetadata.git('merge-base', base, github_head) == ReleaseMetadata.git('rev-parse', "#{base}^{commit}")
|
||||
generated = if github_range
|
||||
api('releases/generate-notes', data: {
|
||||
tag_name: "v#{value}", target_commitish: github_head, previous_tag_name: base
|
||||
}).fetch('body').gsub("\r\n", "\n").strip
|
||||
else
|
||||
''
|
||||
end
|
||||
listed = generated.scan(%r{#{Regexp.escape(@url)}/pull/(\d+)\b}).flatten.map(&:to_i).uniq
|
||||
missing = []
|
||||
direct = []
|
||||
commits(base, head).each do |sha, subject|
|
||||
# 只识别合并提交格式,不把正文中的 Issue 引用猜成 PR
|
||||
number = subject[/\(#(\d+)\)\z/, 1] || subject[/\AMerge pull request #(\d+)\b/, 1]
|
||||
unless number
|
||||
direct << "* #{markdown(subject)} ([#{sha[0, 9]}](#{@url}/commit/#{sha}))"
|
||||
next
|
||||
end
|
||||
number = number.to_i
|
||||
next if listed.include?(number)
|
||||
pull = api("pulls/#{number}")
|
||||
raise "Referenced PR ##{number} is not merged" unless pull.fetch('merged')
|
||||
missing << "* #{markdown(pull.fetch('title'))} by @#{pull.fetch('user').fetch('login')} in #{@url}/pull/#{number}"
|
||||
listed << number
|
||||
end
|
||||
unless missing.empty?
|
||||
heading = "## What's Changed"
|
||||
generated = if generated.include?(heading)
|
||||
generated.sub(heading, "#{heading}\n#{missing.join("\n")}")
|
||||
else
|
||||
["#{heading}\n#{missing.join("\n")}", generated].reject(&:empty?).join("\n\n")
|
||||
end
|
||||
end
|
||||
# 直接提交也有明确链接,不能把 PR 列表当成完整变更范围
|
||||
generated += "\n\n## 其他提交\n#{direct.join("\n")}" unless direct.empty?
|
||||
link = base ? "#{@url}/compare/#{base}...v#{value}" : "#{@url}/commits/#{head}"
|
||||
generated += "\n\n**Full Changelog**: #{link}" unless generated.include?(link)
|
||||
warn "日志范围:#{base || '仓库起点'} → #{head};#{listed.length} 个 PR,#{direct.length} 个直接提交"
|
||||
warn "已补齐自动列表遗漏:#{missing.join("\n")}" unless missing.empty?
|
||||
generated.strip
|
||||
end
|
||||
|
||||
def prepare(value, head: 'HEAD', github_head: head)
|
||||
value = ReleaseMetadata.release_version(value)
|
||||
ReleaseMetadata.validate_notes(value)
|
||||
head = ReleaseMetadata.git('rev-parse', '--verify', "#{head}^{commit}")
|
||||
github_head = ReleaseMetadata.git('rev-parse', '--verify', "#{github_head}^{commit}")
|
||||
unless ReleaseMetadata.git('merge-base', head, github_head) == github_head
|
||||
raise 'GitHub source commit must be an ancestor of the release source'
|
||||
end
|
||||
reachable = ReleaseMetadata.git('tag', '--list', 'v*', '--merged', head).lines.map(&:strip)
|
||||
releases = api('releases?per_page=100', paginate: true)
|
||||
unknown = releases.map { |release| release.fetch('tag_name') } - ReleaseMetadata.git('tag', '--list', 'v*').lines.map(&:strip)
|
||||
base = ReleaseNotes.previous_tag(value, releases, reachable + unknown)
|
||||
raise "Published baseline tag #{base} is missing locally; fetch remote tags before preparing notes" if unknown.include?(base)
|
||||
manual = ReleaseNotes.manual_body(File.read('release/notes.md'))
|
||||
raise 'Release notes must contain a handwritten description' if manual.empty?
|
||||
warn "发布基线:#{base || '仓库起点'};目标:v#{value};源码:#{head}"
|
||||
return "# v#{value}\n\n#{manual}\n" if value.include?('-exp.')
|
||||
installation = <<~MARKDOWN.strip
|
||||
## Linux 一键安装(Docker Compose)
|
||||
|
||||
```bash
|
||||
curl -fsSLO #{@url.sub('github.com', 'raw.githubusercontent.com')}/v#{value}/deploy/install.sh && CPR_RELEASE_TAG=v#{value} bash install.sh
|
||||
```
|
||||
|
||||
## 📚 文档
|
||||
|
||||
- [GitHub 仓库](#{@url})
|
||||
- [部署指南](#{@url}/blob/v#{value}/deploy/README.md)
|
||||
MARKDOWN
|
||||
"# v#{value}\n\n#{manual}\n\n#{START}\n#{installation}\n\n#{changelog(base, head, value, github_head)}\n#{FINISH}\n"
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
if $PROGRAM_NAME == __FILE__
|
||||
begin
|
||||
command, value, repository, github_head = ARGV
|
||||
case command
|
||||
when 'prepare'
|
||||
raise 'prepare requires VERSION REPOSITORY GITHUB_HEAD' unless ARGV.length == 4
|
||||
puts ReleaseNotes::Generator.new(repository).prepare(value, github_head: github_head)
|
||||
when 'body'
|
||||
raise 'body requires VERSION' unless ARGV.length == 2
|
||||
puts ReleaseNotes.body(value)
|
||||
else
|
||||
raise 'usage: release-notes.rb prepare VERSION REPOSITORY GITHUB_HEAD | body VERSION'
|
||||
end
|
||||
rescue StandardError => error
|
||||
warn "error: #{error.message}"
|
||||
exit 1
|
||||
end
|
||||
end
|
||||
@@ -25,7 +25,7 @@ module ReleaseQuality
|
||||
rows = capture('gh', 'api', '--paginate', "repos/#{repository}/actions/runs/#{run.fetch('id')}/jobs?per_page=100", '--jq', '.jobs[] | @json')
|
||||
job = rows.lines.map { |line| JSON.parse(line) }.find { |entry| entry.fetch('name') == 'quality / backend' }
|
||||
return nil unless job && job.fetch('conclusion') == 'success'
|
||||
job.fetch('html_url')
|
||||
{ 'sha' => parent, 'url' => job.fetch('html_url') }
|
||||
end
|
||||
end
|
||||
|
||||
@@ -37,8 +37,10 @@ if $PROGRAM_NAME == __FILE__
|
||||
evidence = nil
|
||||
end
|
||||
puts "run_backend=#{evidence.nil?}"
|
||||
puts "backend_source_sha=#{evidence ? evidence.fetch('sha') : ReleaseQuality.capture('git', 'rev-parse', 'HEAD').strip}"
|
||||
puts "backend_evidence_url=#{evidence ? evidence.fetch('url') : ''}"
|
||||
if ENV['GITHUB_STEP_SUMMARY']
|
||||
message = evidence ? "后端质量检查复用版本提交父提交的 [CI 结果](#{evidence});仅版本与发布说明不同" : '未找到可复用的后端 CI 结果,完整检查发行提交'
|
||||
message = evidence ? "后端质量检查复用 `#{evidence.fetch('sha')}` 的[成功 CI](#{evidence.fetch('url')});仅版本与发布说明不同" : '未找到可复用的后端 CI 结果,完整检查发行提交'
|
||||
File.open(ENV.fetch('GITHUB_STEP_SUMMARY'), 'a') { |file| file.puts(message) }
|
||||
end
|
||||
end
|
||||
@@ -45,12 +45,13 @@ jobs:
|
||||
non_docker_matrix: ${{ steps.version.outputs.non_docker_matrix }}
|
||||
windows_matrix: ${{ steps.version.outputs.windows_matrix }}
|
||||
docker_platforms: ${{ steps.version.outputs.docker_platforms }}
|
||||
previous_tag: ${{ steps.version.outputs.previous_tag }}
|
||||
prerelease: ${{ steps.version.outputs.prerelease }}
|
||||
build_type: ${{ steps.version.outputs.build_type }}
|
||||
rust: ${{ steps.toolchains.outputs.rust }}
|
||||
rust_image: ${{ steps.toolchains.outputs.rust_image }}
|
||||
run_backend: ${{ steps.quality.outputs.run_backend }}
|
||||
backend_source_sha: ${{ steps.quality.outputs.backend_source_sha }}
|
||||
backend_evidence_url: ${{ steps.quality.outputs.backend_evidence_url }}
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
@@ -75,6 +76,11 @@ jobs:
|
||||
id: toolchains
|
||||
run: ruby .github/scripts/toolchains.rb >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Verify committed release notes
|
||||
env:
|
||||
VERSION: ${{ steps.version.outputs.version }}
|
||||
run: ruby .github/scripts/release-notes.rb body "$VERSION" >> "$GITHUB_STEP_SUMMARY"
|
||||
|
||||
- name: Check reusable backend CI evidence
|
||||
id: quality
|
||||
env:
|
||||
@@ -97,6 +103,31 @@ jobs:
|
||||
run_backend: ${{ needs.release-info.outputs.run_backend == 'true' }}
|
||||
run_frontend: false
|
||||
|
||||
backend-validation:
|
||||
name: backend-validation (${{ needs.release-info.outputs.run_backend == 'true' && 'current release' || 'reused CI' }})
|
||||
needs: [release-info, quality]
|
||||
if: ${{ !cancelled() && needs.release-info.result == 'success' }}
|
||||
runs-on: ubuntu-26.04
|
||||
timeout-minutes: 5
|
||||
steps:
|
||||
- name: Report backend validation evidence
|
||||
env:
|
||||
QUALITY_RESULT: ${{ needs.quality.result }}
|
||||
RUN_BACKEND: ${{ needs.release-info.outputs.run_backend }}
|
||||
SOURCE_SHA: ${{ needs.release-info.outputs.backend_source_sha }}
|
||||
EVIDENCE_URL: ${{ needs.release-info.outputs.backend_evidence_url }}
|
||||
run: |
|
||||
if [ "$QUALITY_RESULT" != success ]; then
|
||||
echo "后端质量检查未通过:$QUALITY_RESULT" | tee -a "$GITHUB_STEP_SUMMARY"
|
||||
exit 1
|
||||
fi
|
||||
if [ "$RUN_BACKEND" = true ]; then
|
||||
echo "后端质量检查已执行并通过,提交:\`$SOURCE_SHA\`" | tee -a "$GITHUB_STEP_SUMMARY"
|
||||
else
|
||||
test -n "$EVIDENCE_URL"
|
||||
echo "后端质量检查复用 \`$SOURCE_SHA\` 的[成功 CI]($EVIDENCE_URL);发行提交仅版本与发布说明不同" | tee -a "$GITHUB_STEP_SUMMARY"
|
||||
fi
|
||||
|
||||
windows:
|
||||
needs: release-info
|
||||
name: windows-tests (${{ matrix.arch }})
|
||||
@@ -411,7 +442,7 @@ jobs:
|
||||
group: release-publication
|
||||
queue: max
|
||||
# 产物准备可与测试重叠,版本标签和 GitHub Release 必须等全部质量与镜像验证通过
|
||||
needs: [release-info, quality, windows, security, package-assets, build-docker-image]
|
||||
needs: [release-info, backend-validation, windows, security, package-assets, build-docker-image]
|
||||
runs-on: ubuntu-26.04
|
||||
timeout-minutes: 20
|
||||
permissions:
|
||||
@@ -522,25 +553,8 @@ jobs:
|
||||
- name: Prepare release notes
|
||||
shell: bash
|
||||
env:
|
||||
BUILD_TYPE: ${{ needs.release-info.outputs.build_type }}
|
||||
INSTALLATION_NOTES: |
|
||||
## Linux 一键安装(Docker Compose)
|
||||
|
||||
```bash
|
||||
curl -fsSLO https://raw.githubusercontent.com/${{ github.repository }}/${{ needs.release-info.outputs.tag }}/deploy/install.sh && CPR_RELEASE_TAG=${{ needs.release-info.outputs.tag }} bash install.sh
|
||||
```
|
||||
|
||||
## 📚 文档
|
||||
|
||||
- [GitHub 仓库](https://github.com/${{ github.repository }})
|
||||
- [部署指南](https://github.com/${{ github.repository }}/blob/${{ needs.release-info.outputs.tag }}/deploy/README.md)
|
||||
run: |
|
||||
ruby <<'RUBY'
|
||||
notes = File.readlines('release/notes.md').drop(1).join.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')
|
||||
File.write(output, "#{notes}\n")
|
||||
RUBY
|
||||
VERSION: ${{ needs.release-info.outputs.version }}
|
||||
run: ruby .github/scripts/release-notes.rb body "$VERSION" > "$RUNNER_TEMP/release-notes.md"
|
||||
|
||||
- name: Generate release asset provenance
|
||||
uses: actions/attest@1e69f48acb82d1966a394da916b4c1698aa569d6 # v4.2.2
|
||||
@@ -552,8 +566,7 @@ jobs:
|
||||
uses: softprops/action-gh-release@8a0cd651e5b2365bd640854a3fa5dfc70e4875f3 # v3.0.4
|
||||
with:
|
||||
tag_name: ${{ needs.release-info.outputs.tag }}
|
||||
generate_release_notes: ${{ needs.release-info.outputs.build_type != 'experimental' }}
|
||||
previous_tag: ${{ needs.release-info.outputs.previous_tag }}
|
||||
generate_release_notes: false
|
||||
prerelease: ${{ needs.release-info.outputs.prerelease == 'true' }}
|
||||
# action 保留已公开 Release 的状态,新 Release 上传完成后仍保持草稿
|
||||
draft: true
|
||||
|
||||
+2
-2
@@ -122,7 +122,7 @@ PR 不接受以下协作规则文件的新增、修改、删除或重命名:
|
||||
- 业务数据的解析、校验和展示优先复用已有逻辑。新增抽象放在拥有该职责的模块,避免重复事实源或无实际需求的通用层
|
||||
- 新增代码注释使用中文。提交信息使用英文 Conventional Commits,参考近期历史,按完整功能归并
|
||||
- AI 参与的提交按实际助手添加 `Co-authored-by: 名称 <邮箱>`,名称与邮箱采用该助手已知的署名身份,并保留其他实际共同作者署名;PR 的 AI 使用披露不替代提交署名
|
||||
- 发布说明写入 `release/notes.md`,标题首行为目标版本的 `# vX.Y.Z`,章节标题和正文使用中文;命令、配置键、协议名等保留原文。只说明本次版本的实际变化,按影响交代升级事项
|
||||
- 发布说明写入 `release/notes.md`,标题首行为目标版本的 `# vX.Y.Z`,手写章节标题和正文使用中文;命令、配置键、协议名等保留原文。只说明本次版本的实际变化,按影响交代升级事项。发行入口将自动变更列表和安装入口保存到末尾的生成区块,工作流按提交中的完整正文发布,基线与预检要求见[版本与说明准备](.agents/skills/cpr-release/references/preparation.md)
|
||||
- PR 聚焦目标;无关格式化、重构和依赖升级单独处理
|
||||
|
||||
## 文档职责与更新条件
|
||||
@@ -229,7 +229,7 @@ git diff --check
|
||||
|
||||
常规容器检查与发行构建共用二进制构建入口,并复用已检查的前端产物;Dockerfile、工具链、依赖或构建配置变化时执行完整源码镜像构建,定期安全检查也覆盖源码构建。两条路径均验证容器运行、安全扫描与关闭行为
|
||||
|
||||
发行构建与质量检查并行,Windows 两种架构的插件与系统更新测试独立运行。仅当发行提交只修改版本与发布说明,且其父提交有本仓库主分支成功的后端 CI 时复用该结果;缺少证据则完整重跑。对外发布等待质量、Windows 测试、依赖审计和镜像验证全部成功,构建耗时与测试报告保留 7 天
|
||||
发行构建与质量检查并行,Windows 两种架构的插件与系统更新测试独立运行。仅当发行提交只修改版本与发布说明,且其父提交有本仓库主分支成功的后端 CI 时复用该结果;缺少证据则完整重跑。`backend-validation` 明确报告本次执行或复用结果,复用时列出被验证的源码提交和 CI 链接。对外发布等待质量、Windows 测试、依赖审计和镜像验证全部成功,构建耗时与测试报告保留 7 天
|
||||
|
||||
新增自动规则优先使用现有工具,要求依据明确、结果稳定、误报可控;无法可靠判定的设计与视觉问题保留审查判断,避免把具体源码写法锁成测试
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
[](https://github.com/zyycn/codex-proxy-rs/pkgs/container/codex-proxy-rs)
|
||||
[](LICENSE)
|
||||
|
||||
[快速预览](#快速预览) · [快速开始](#快速开始) · [文档](#文档) · [社区](#社区) · [贡献者](#贡献者) · [Star History](#star-history) · [支持项目](#支持项目) · [许可证](#许可证)
|
||||
[快速预览](#快速预览) · [快速开始](#快速开始) · [文档](#文档) · [贡献者](#贡献者) · [Star History](#star-history) · [社区](#社区) · [支持项目](#支持项目) · [许可证](#许可证)
|
||||
|
||||
</div>
|
||||
|
||||
@@ -49,12 +49,6 @@ curl -fsSL https://raw.githubusercontent.com/zyycn/codex-proxy-rs/main/deploy/in
|
||||
| 开发宿主 | [开发与源码联调](docs/development.md) · [系统架构](docs/architecture.md) · [管理端主题](docs/theme.md) · [数据库迁移](backend/migrations/README.md) |
|
||||
| 参与协作 | [贡献、审查与验证](CONTRIBUTING.md) |
|
||||
|
||||
## 社区
|
||||
|
||||
问题反馈与功能建议请使用 [GitHub Issues](https://github.com/zyycn/codex-proxy-rs/issues),填写要求见 [贡献说明](CONTRIBUTING.md#提交-issue)
|
||||
|
||||
感谢 [LINUX DO](https://linux.do) 社区提供开放、友善的技术交流平台
|
||||
|
||||
## 贡献者
|
||||
|
||||
[<img src="https://contrib.rocks/image?repo=zyycn/codex-proxy-rs&columns=10" alt="查看 GitHub 贡献者列表" width="480">](https://github.com/zyycn/codex-proxy-rs/graphs/contributors)
|
||||
@@ -68,6 +62,18 @@ curl -fsSL https://raw.githubusercontent.com/zyycn/codex-proxy-rs/main/deploy/in
|
||||
</picture>
|
||||
</a>
|
||||
|
||||
## 社区
|
||||
|
||||
点击或扫码加入 Telegram 群 [小酒馆][telegram-group]
|
||||
|
||||
[<img src="docs/community/telegram-qr.png" alt="扫码加入小酒馆 Telegram 群" width="138">][telegram-group]
|
||||
|
||||
[telegram-group]: https://t.me/+9tk761zbNAMyNWY9
|
||||
|
||||
问题反馈与功能建议请使用 [GitHub Issues](https://github.com/zyycn/codex-proxy-rs/issues),填写要求见 [贡献说明](CONTRIBUTING.md#提交-issue)
|
||||
|
||||
感谢 [LINUX DO](https://linux.do) 社区提供开放、友善的技术交流平台
|
||||
|
||||
## 支持项目
|
||||
|
||||
如果 Codex Proxy RS 帮助到你了,欢迎请我喝杯咖啡 ☕
|
||||
|
||||
@@ -79,7 +79,11 @@ impl Providers {
|
||||
)
|
||||
.await?;
|
||||
environment.host.report_startup_ready("OpenAI Provider");
|
||||
let antigravity = provider_antigravity::initialize(ports.clone()).await?;
|
||||
let antigravity = provider_antigravity::initialize(
|
||||
ports.clone(),
|
||||
environment.host.runtime_data_dir().join("antigravity"),
|
||||
)
|
||||
.await?;
|
||||
environment
|
||||
.host
|
||||
.report_startup_ready("Antigravity Provider");
|
||||
|
||||
@@ -92,6 +92,9 @@ pub struct AccountListQuery {
|
||||
/// Admin query service 从运行态存储取得的当前账号冷却快照
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct AccountRuntimeSnapshot {
|
||||
/// 模型维度冷却独立于整账号冷却,不能据此阻断其他模型
|
||||
pub model_cooldowns:
|
||||
BTreeMap<String, Vec<gateway_core::provider_ports::ProviderScopedCooldown>>,
|
||||
pub protection_rules: BTreeMap<String, Vec<gateway_core::account::AccountProtectionMatch>>,
|
||||
pub cooldown: BTreeMap<String, gateway_core::account::AccountCooldown>,
|
||||
/// `None` 表示实时 lease 存储不可用;`Some` 中未出现的账号当前使用量为零
|
||||
@@ -223,6 +226,7 @@ pub struct AccountPage {
|
||||
/// 同一状态快照下的账号事实与唯一状态投影
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct AccountPageItem {
|
||||
pub model_cooldowns: Vec<gateway_core::provider_ports::ProviderScopedCooldown>,
|
||||
pub platform_icon: Option<String>,
|
||||
pub protection_rules: Vec<gateway_core::account::AccountProtectionMatch>,
|
||||
pub account: AccountRecord,
|
||||
|
||||
@@ -1319,6 +1319,7 @@ impl fmt::Debug for ProviderExport {
|
||||
/// 统一账号目录的一行完整结果
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct AccountDirectoryItem {
|
||||
pub model_cooldowns: Vec<gateway_core::provider_ports::ProviderScopedCooldown>,
|
||||
pub platform_icon: Option<String>,
|
||||
pub protection_rules: Vec<gateway_core::account::AccountProtectionMatch>,
|
||||
pub account: AccountRecord,
|
||||
|
||||
@@ -513,6 +513,7 @@ impl DefaultAccountsService {
|
||||
lookback,
|
||||
);
|
||||
Ok(AccountDirectoryItem {
|
||||
model_cooldowns: stored.model_cooldowns,
|
||||
platform_icon: stored.platform_icon,
|
||||
protection_rules: stored.protection_rules,
|
||||
capacity: super::peer_link::upstream::account_capacity(
|
||||
@@ -648,6 +649,7 @@ impl AccountsService for DefaultAccountsService {
|
||||
lookback,
|
||||
);
|
||||
Ok(AccountDirectoryItem {
|
||||
model_cooldowns: item.model_cooldowns,
|
||||
platform_icon: item.platform_icon,
|
||||
protection_rules: item.protection_rules,
|
||||
capacity: crate::model::accounts::AccountCapacity {
|
||||
|
||||
@@ -315,6 +315,7 @@ impl AccountRuntimeStore for FakeRuntimeStore {
|
||||
) -> AdminStoreResult<AccountRuntimeSnapshot> {
|
||||
*self.requested_accounts.lock().expect("requested accounts") = account_ids.to_vec();
|
||||
Ok(AccountRuntimeSnapshot {
|
||||
model_cooldowns: BTreeMap::new(),
|
||||
protection_rules: std::collections::BTreeMap::new(),
|
||||
cooldown: BTreeMap::from([(
|
||||
"acct_limited".to_owned(),
|
||||
|
||||
@@ -740,6 +740,7 @@ impl FakeAccountStore {
|
||||
last_error_message: account.last_error_message.clone(),
|
||||
};
|
||||
AccountPageItem {
|
||||
model_cooldowns: Vec::new(),
|
||||
platform_icon: None,
|
||||
protection_rules: Vec::new(),
|
||||
capacity: gateway_admin::model::accounts::AccountCapacity {
|
||||
|
||||
@@ -67,6 +67,7 @@ pub(super) fn account_view(
|
||||
time: crate::time::TimePresenter,
|
||||
) -> AccountView {
|
||||
let AccountDirectoryItem {
|
||||
model_cooldowns,
|
||||
platform_icon,
|
||||
account,
|
||||
capacity,
|
||||
@@ -111,6 +112,17 @@ pub(super) fn account_view(
|
||||
.map(|value| super::upstream_info::view(value, now, time));
|
||||
let (mut quota, refresh_token_expires_at) = account_quota_view(quota, cooldown, now, time);
|
||||
quota.protection_rules = protection_rules;
|
||||
quota.model_rate_limits = model_cooldowns
|
||||
.into_iter()
|
||||
.map(|cooldown| {
|
||||
let until: DateTime<Utc> = cooldown.until().into();
|
||||
AccountModelRateLimitView {
|
||||
model: cooldown.scope().value().to_owned(),
|
||||
until: time.rfc3339(&until),
|
||||
until_display: time.datetime(&until),
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
AccountView {
|
||||
platform_icon,
|
||||
quota_settings: account.quota_settings,
|
||||
@@ -271,6 +283,7 @@ pub(super) fn account_quota_view(
|
||||
let recovery_probe_required = cooldown.is_some_and(|value| value.kind.requires_probe());
|
||||
(
|
||||
AccountQuotaView {
|
||||
model_rate_limits: Vec::new(),
|
||||
paused_windows: quota.paused_windows,
|
||||
refreshed_at: quota.observed_at.map(|value| time.rfc3339(&value)),
|
||||
refreshed_at_relative: quota
|
||||
|
||||
@@ -382,6 +382,7 @@ pub use crate::admin::account_groups::AccountGroupRefView;
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AccountQuotaView {
|
||||
pub model_rate_limits: Vec<AccountModelRateLimitView>,
|
||||
pub paused_windows: Vec<String>,
|
||||
pub refreshed_at: Option<String>,
|
||||
pub refreshed_at_relative: Option<crate::time::RelativeTimeView>,
|
||||
@@ -397,6 +398,14 @@ pub struct AccountQuotaView {
|
||||
pub credits: Option<AccountQuotaCreditsView>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AccountModelRateLimitView {
|
||||
pub model: String,
|
||||
pub until: String,
|
||||
pub until_display: String,
|
||||
}
|
||||
|
||||
/// 上游点数安全视图,不透出额度响应中的其他 Provider 字段
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
|
||||
@@ -484,7 +484,6 @@ impl TryFrom<(ClientKeyPage, crate::time::TimePresenter)> for ClientKeyListData
|
||||
let next_cursor = page
|
||||
.next_cursor
|
||||
.map(wire_cursor)
|
||||
.transpose()?
|
||||
.as_ref()
|
||||
.map(encode_client_key_cursor)
|
||||
.transpose()?;
|
||||
@@ -597,7 +596,8 @@ impl From<ClientKeyMutation> for MutatedClientKeyData {
|
||||
}
|
||||
|
||||
/// 解码后的 Client Key 游标字段
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct ClientKeyCursorData {
|
||||
pub sort: ClientKeySort,
|
||||
pub value: ClientKeyCursorValue,
|
||||
@@ -614,25 +614,12 @@ pub enum ClientKeyCursorValue {
|
||||
LastUsedAt(Option<DateTime<Utc>>),
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
struct CursorWire {
|
||||
sort: ClientKeySort,
|
||||
value: ClientKeyCursorValue,
|
||||
id: String,
|
||||
}
|
||||
|
||||
/// 把 owner 游标编码为不透明 wire 值
|
||||
pub fn encode_client_key_cursor(
|
||||
cursor: &ClientKeyCursorData,
|
||||
) -> Result<String, WireValidationError> {
|
||||
validate_client_key_cursor(cursor)?;
|
||||
let bytes = serde_json::to_vec(&CursorWire {
|
||||
sort: cursor.sort,
|
||||
value: cursor.value.clone(),
|
||||
id: cursor.id.clone(),
|
||||
})
|
||||
.map_err(|_| WireValidationError::new("cursor"))?;
|
||||
let bytes = serde_json::to_vec(cursor).map_err(|_| WireValidationError::new("cursor"))?;
|
||||
Ok(URL_SAFE_NO_PAD.encode(bytes))
|
||||
}
|
||||
|
||||
@@ -644,13 +631,8 @@ pub fn decode_client_key_cursor(encoded: &str) -> Result<ClientKeyCursorData, Wi
|
||||
let bytes = URL_SAFE_NO_PAD
|
||||
.decode(encoded)
|
||||
.map_err(|_| WireValidationError::new("cursor"))?;
|
||||
let cursor: CursorWire =
|
||||
let cursor: ClientKeyCursorData =
|
||||
serde_json::from_slice(&bytes).map_err(|_| WireValidationError::new("cursor"))?;
|
||||
let cursor = ClientKeyCursorData {
|
||||
sort: cursor.sort,
|
||||
value: cursor.value,
|
||||
id: cursor.id,
|
||||
};
|
||||
validate_client_key_cursor(&cursor)?;
|
||||
Ok(cursor)
|
||||
}
|
||||
@@ -724,20 +706,18 @@ fn domain_cursor(cursor: ClientKeyCursorData) -> Result<ClientKeyCursor, WireVal
|
||||
})
|
||||
}
|
||||
|
||||
fn wire_cursor(cursor: ClientKeyCursor) -> Result<ClientKeyCursorData, WireValidationError> {
|
||||
fn wire_cursor(cursor: ClientKeyCursor) -> ClientKeyCursorData {
|
||||
let value = match cursor.value {
|
||||
DomainCursorValue::Name(value) => ClientKeyCursorValue::Name(value),
|
||||
DomainCursorValue::Enabled(value) => ClientKeyCursorValue::Enabled(value),
|
||||
DomainCursorValue::CreatedAt(value) => ClientKeyCursorValue::CreatedAt(value),
|
||||
DomainCursorValue::LastUsedAt(value) => ClientKeyCursorValue::LastUsedAt(value),
|
||||
};
|
||||
let cursor = ClientKeyCursorData {
|
||||
ClientKeyCursorData {
|
||||
sort: wire_sort(cursor.sort),
|
||||
value,
|
||||
id: cursor.id.to_string(),
|
||||
};
|
||||
validate_client_key_cursor(&cursor)?;
|
||||
Ok(cursor)
|
||||
}
|
||||
}
|
||||
|
||||
fn client_key_id(
|
||||
|
||||
@@ -119,22 +119,24 @@ pub fn gateway_error_response(error: &GatewayError) -> Response {
|
||||
}
|
||||
let mut response = (status, Json(body)).into_response();
|
||||
response.extensions_mut().insert(error.clone());
|
||||
if let Some(delay) = error.retry_after()
|
||||
&& let Ok(value) = HeaderValue::from_str(
|
||||
&delay
|
||||
.as_secs()
|
||||
.saturating_add(u64::from(delay.subsec_nanos() > 0))
|
||||
.max(1)
|
||||
.to_string(),
|
||||
)
|
||||
{
|
||||
if let Some(seconds) = retry_after_seconds(error) {
|
||||
response
|
||||
.headers_mut()
|
||||
.insert(axum::http::header::RETRY_AFTER, value);
|
||||
.insert(axum::http::header::RETRY_AFTER, HeaderValue::from(seconds));
|
||||
}
|
||||
response
|
||||
}
|
||||
|
||||
/// HTTP 和 WS 的等待秒数均向上取整,避免客户端在冷却到期前重新发起请求
|
||||
pub(crate) fn retry_after_seconds(error: &GatewayError) -> Option<u64> {
|
||||
error.retry_after().map(|delay| {
|
||||
delay
|
||||
.as_secs()
|
||||
.saturating_add(u64::from(delay.subsec_nanos() > 0))
|
||||
.max(1)
|
||||
})
|
||||
}
|
||||
|
||||
/// Gateway 错误稳定映射,供 HTTP、SSE 和 WebSocket 共用
|
||||
#[must_use]
|
||||
pub const fn gateway_error_contract(
|
||||
|
||||
@@ -185,6 +185,9 @@ pub(super) fn initial_engine_error_event(
|
||||
response_event_headers(response_headers)
|
||||
};
|
||||
if upstream.is_none() {
|
||||
if let Some(seconds) = crate::client_error::retry_after_seconds(&gateway) {
|
||||
headers.insert("retry-after".to_owned(), Value::String(seconds.to_string()));
|
||||
}
|
||||
// 会话 opening 身份不证明当前失败属于该请求;仅保留其他允许的会话头
|
||||
for name in RESPONSE_REQUEST_ID_HEADERS {
|
||||
headers.remove(name);
|
||||
|
||||
@@ -255,6 +255,18 @@ async fn account_cooldown_returns_an_instant_and_server_formatted_recovery() {
|
||||
last_error_message: None,
|
||||
};
|
||||
let mut item = account_page_item(facts, now, "oauth");
|
||||
let model_until = now + Duration::seconds(8);
|
||||
item.model_cooldowns = vec![gateway_core::provider_ports::ProviderScopedCooldown::new(
|
||||
gateway_core::account::ProviderAccountId::new(item.account.id.clone()).unwrap(),
|
||||
gateway_core::account::CredentialRevision::new(
|
||||
item.account.credential_revision.get(),
|
||||
)
|
||||
.unwrap(),
|
||||
gateway_core::provider_ports::ProviderCooldownScope::upstream_model(
|
||||
gateway_core::routing::UpstreamModelId::new("gpt-5.4").unwrap(),
|
||||
),
|
||||
model_until.into(),
|
||||
)];
|
||||
if kind.is_error_protection() {
|
||||
item.protection_rules = vec![gateway_core::account::AccountProtectionMatch {
|
||||
id: "removed-rule".to_owned(),
|
||||
@@ -278,6 +290,14 @@ async fn account_cooldown_returns_an_instant_and_server_formatted_recovery() {
|
||||
let body = to_bytes(response.into_body(), 32768).await.unwrap();
|
||||
let value: serde_json::Value = serde_json::from_slice(&body).unwrap();
|
||||
let quota = &value["data"]["items"][0]["quota"];
|
||||
assert_eq!(
|
||||
quota["modelRateLimits"],
|
||||
serde_json::json!([{
|
||||
"model": "gpt-5.4",
|
||||
"until": zone.local(model_until).to_rfc3339(),
|
||||
"untilDisplay": zone.local(model_until).format("%Y-%m-%d %H:%M:%S").to_string(),
|
||||
}])
|
||||
);
|
||||
if kind.is_error_protection() {
|
||||
assert_eq!(quota["rateLimitReason"], "error_protection");
|
||||
assert_eq!(
|
||||
@@ -411,6 +431,7 @@ fn account_page_item(
|
||||
use gateway_core::account::resolve_account_status;
|
||||
|
||||
AccountPageItem {
|
||||
model_cooldowns: Vec::new(),
|
||||
platform_icon: None,
|
||||
protection_rules: Vec::new(),
|
||||
account: AccountRecord {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! 验证 Client Key 管理接口的预算、密钥输入与查询合同
|
||||
|
||||
use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
|
||||
use chrono::{DateTime, TimeZone as _, Utc};
|
||||
use gateway_api::admin::client_keys::{
|
||||
self, ClientKeyCursorData, ClientKeyCursorValue, ClientKeyListData, ClientKeyMutationRequest,
|
||||
@@ -475,12 +476,41 @@ fn client_key_cursor_should_round_trip_and_reject_noncanonical_input() {
|
||||
};
|
||||
let encoded = encode_client_key_cursor(&cursor).expect("encode cursor");
|
||||
let decoded = decode_client_key_cursor(&encoded).expect("decode cursor");
|
||||
let wire = json!({
|
||||
"sort": { "field": "createdAt", "direction": "desc" },
|
||||
"value": { "kind": "createdAt", "value": "2026-07-18T08:00:00Z" },
|
||||
"id": "key_cursor"
|
||||
});
|
||||
|
||||
assert_eq!(decoded, cursor);
|
||||
assert_eq!(
|
||||
serde_json::from_slice::<serde_json::Value>(&URL_SAFE_NO_PAD.decode(&encoded).unwrap())
|
||||
.unwrap(),
|
||||
wire
|
||||
);
|
||||
assert!(!encoded.contains("key_cursor"));
|
||||
for invalid in ["", "not-base64!", "e30"] {
|
||||
assert!(decode_client_key_cursor(invalid).is_err());
|
||||
}
|
||||
for (field, value) in [
|
||||
("unknownField", json!(true)),
|
||||
("id", json!(" ")),
|
||||
("value", json!({ "kind": "enabled", "value": true })),
|
||||
(
|
||||
"sort",
|
||||
json!({ "field": "createdAt", "direction": "desc", "unknownField": true }),
|
||||
),
|
||||
] {
|
||||
let mut invalid = wire.clone();
|
||||
invalid[field] = value;
|
||||
let encoded = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&invalid).unwrap());
|
||||
assert_eq!(
|
||||
decode_client_key_cursor(&encoded)
|
||||
.expect_err("reject invalid cursor fields")
|
||||
.field(),
|
||||
"cursor"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -564,6 +564,7 @@ mod provider {
|
||||
last_error_message: None,
|
||||
};
|
||||
AccountPageItem {
|
||||
model_cooldowns: Vec::new(),
|
||||
platform_icon: None,
|
||||
protection_rules: Vec::new(),
|
||||
capacity: gateway_admin::model::accounts::AccountCapacity {
|
||||
|
||||
@@ -1484,6 +1484,7 @@ impl AccountRuntimeStore for UnusedStore {
|
||||
|
||||
async fn active_rate_limits(&self) -> AdminStoreResult<AccountRuntimeSnapshot> {
|
||||
Ok(AccountRuntimeSnapshot {
|
||||
model_cooldowns: BTreeMap::new(),
|
||||
cooldown: BTreeMap::new(),
|
||||
protection_rules: BTreeMap::new(),
|
||||
in_flight: Some(BTreeMap::new()),
|
||||
@@ -1492,6 +1493,7 @@ impl AccountRuntimeStore for UnusedStore {
|
||||
|
||||
async fn account_runtime(&self, _: &[String]) -> AdminStoreResult<AccountRuntimeSnapshot> {
|
||||
Ok(AccountRuntimeSnapshot {
|
||||
model_cooldowns: BTreeMap::new(),
|
||||
cooldown: BTreeMap::new(),
|
||||
protection_rules: BTreeMap::new(),
|
||||
in_flight: Some(BTreeMap::new()),
|
||||
|
||||
@@ -262,7 +262,8 @@ async fn request_middleware_sees_original_chat_and_preserves_the_endpoint() {
|
||||
{"role":"developer","content":"brief"},
|
||||
{"role":"system","content":null},
|
||||
{"role":"assistant","tool_calls":[]},
|
||||
{"role":"user","content":[{"type":"text","text":null},{"type":"text","text":"hello"}]}
|
||||
{"role":"user","content":[{"type":"text","text":null},{"type":"text","text":"hello"}]},
|
||||
{"role":"tool","name":"notifications","namespace":"agent","content":"notice"}
|
||||
]);
|
||||
let response = fixture.post(request.clone()).await;
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
|
||||
@@ -384,10 +384,14 @@ fn engine_provider_error_should_preserve_retry_classification() {
|
||||
|
||||
#[test]
|
||||
fn local_provider_capacity_exhaustion_should_map_to_service_unavailable() {
|
||||
let error = EngineError::Provider(ProviderError::new(
|
||||
ProviderErrorKind::AccountCapacityUnavailable,
|
||||
UpstreamSendState::NotSent,
|
||||
));
|
||||
let error = EngineError::Provider(
|
||||
ProviderError::new(
|
||||
ProviderErrorKind::AccountCapacityUnavailable,
|
||||
UpstreamSendState::NotSent,
|
||||
)
|
||||
.with_retry_after(std::time::Duration::from_millis(7100)),
|
||||
);
|
||||
assert_eq!(engine_error_response(&error).headers()["retry-after"], "8");
|
||||
|
||||
let projected = gateway_error_from_engine(&error);
|
||||
assert_eq!(
|
||||
|
||||
@@ -91,6 +91,7 @@ async fn fixture(sharing: ClientPeerSharing, plaintext: &str) -> (AdminTestFixtu
|
||||
last_error_message: None,
|
||||
};
|
||||
*fixture.account.lock().unwrap() = Some(AccountPageItem {
|
||||
model_cooldowns: Vec::new(),
|
||||
platform_icon: None,
|
||||
protection_rules: Vec::new(),
|
||||
capacity: AccountCapacity {
|
||||
|
||||
@@ -1586,6 +1586,11 @@ impl GatewayError {
|
||||
),
|
||||
};
|
||||
let mut gateway = gateway;
|
||||
if gateway.kind() == GatewayErrorKind::AccountCapacityUnavailable
|
||||
&& let Some(delay) = error.retry_after()
|
||||
{
|
||||
gateway = gateway.with_retry_after(delay);
|
||||
}
|
||||
if gateway.kind() == GatewayErrorKind::InvalidRequest
|
||||
&& let Some(details) = error
|
||||
.failure_observation
|
||||
|
||||
@@ -113,6 +113,7 @@ pub struct ProviderScopedCooldown {
|
||||
credential_revision: CredentialRevision,
|
||||
scope: ProviderCooldownScope,
|
||||
until: SystemTime,
|
||||
rate_limited_until: Option<SystemTime>,
|
||||
}
|
||||
|
||||
impl ProviderScopedCooldown {
|
||||
@@ -128,6 +129,7 @@ impl ProviderScopedCooldown {
|
||||
credential_revision,
|
||||
scope,
|
||||
until,
|
||||
rate_limited_until: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -141,6 +143,18 @@ impl ProviderScopedCooldown {
|
||||
self.credential_revision
|
||||
}
|
||||
|
||||
/// 选号冷却可能还包含模型拒绝;目录只展示实际限流期限
|
||||
#[must_use]
|
||||
pub fn with_rate_limited_until(mut self, until: Option<SystemTime>) -> Self {
|
||||
self.rate_limited_until = until.map(|until| until.min(self.until));
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn rate_limited_until(&self) -> Option<SystemTime> {
|
||||
self.rate_limited_until
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn scope(&self) -> &ProviderCooldownScope {
|
||||
&self.scope
|
||||
|
||||
@@ -117,6 +117,11 @@ pub async fn initialize_command_line(mut config: HostConfig) -> Result<HostBundl
|
||||
}
|
||||
|
||||
impl HostBundle {
|
||||
/// 宿主配置解析后的运行数据目录,供需要磁盘空间的内置服务使用。
|
||||
pub fn runtime_data_dir(&self) -> &std::path::Path {
|
||||
self.config.runtime_data_dir()
|
||||
}
|
||||
|
||||
/// 向启动控制台报告一个组装阶段已就绪
|
||||
pub fn report_startup_ready(&self, service: &'static str) {
|
||||
tracing::info!(target: "gateway_startup", service, "服务启动正常");
|
||||
|
||||
@@ -416,6 +416,11 @@ impl HttpBody {
|
||||
return Err(HttpError::sent("read size"));
|
||||
}
|
||||
loop {
|
||||
if self.received > 32 * 1024 * 1024 {
|
||||
// 累计量封存超限结果,后续读取不能交付已拒绝的缓冲
|
||||
self.pending = Bytes::new();
|
||||
return Err(HttpError::sent("response size"));
|
||||
}
|
||||
// 已缓冲的数据和就绪帧也受本次期限约束,不能绕过 owner 的读取预算
|
||||
if Instant::now() >= deadline {
|
||||
return Err(HttpError::sent("response deadline").with_kind(HttpErrorKind::Timeout));
|
||||
@@ -445,9 +450,6 @@ impl HttpBody {
|
||||
}
|
||||
};
|
||||
self.received = self.received.saturating_add(self.pending.len());
|
||||
if self.received > 32 * 1024 * 1024 {
|
||||
return Err(HttpError::sent("response size"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -158,6 +158,60 @@ async fn managed_http_caps_chunks_and_recovers_capacity_after_body_drop() {
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn managed_http_body_limit_rejects_all_reads_after_exceeding_capacity() {
|
||||
let limit = 32 * 1024 * 1024;
|
||||
let server = MockServer::start().await;
|
||||
let client = HttpClient::new().unwrap();
|
||||
for size in [limit, limit + 1] {
|
||||
server.reset().await;
|
||||
Mock::given(any())
|
||||
.respond_with(ResponseTemplate::new(200).set_body_bytes(vec![42; size]))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let mut response = client
|
||||
.open(
|
||||
request(server.uri()),
|
||||
None,
|
||||
&local_network(),
|
||||
Duration::from_secs(10),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let mut received = 0;
|
||||
let result = loop {
|
||||
match response.body.read(64 * 1024).await {
|
||||
Ok(Some(chunk)) => received += chunk.len(),
|
||||
result => break result,
|
||||
}
|
||||
};
|
||||
if size == limit {
|
||||
assert!(result.unwrap().is_none());
|
||||
assert_eq!(received, limit);
|
||||
} else {
|
||||
assert!(received <= limit);
|
||||
let error = result.unwrap_err();
|
||||
assert_eq!(error.kind(), HttpErrorKind::Response);
|
||||
assert_eq!(error.send_state, UpstreamSendState::Sent);
|
||||
assert_eq!(error.reason(), "response size");
|
||||
assert_eq!(
|
||||
response.body.read(1).await.unwrap_err().reason(),
|
||||
"response size"
|
||||
);
|
||||
assert_eq!(
|
||||
response
|
||||
.body
|
||||
.read_with_timeout(1, Duration::from_secs(1))
|
||||
.await
|
||||
.unwrap_err()
|
||||
.reason(),
|
||||
"response size"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn managed_http_deadline_and_invalid_headers_preserve_send_facts() {
|
||||
let server = MockServer::start().await;
|
||||
|
||||
@@ -59,11 +59,13 @@ pub fn validate_request(body: &Map<String, Value>) -> Result<(), ChatError> {
|
||||
}
|
||||
}
|
||||
if role == "tool" {
|
||||
string(
|
||||
message.get("tool_call_id"),
|
||||
&format!("{path}.tool_call_id"),
|
||||
false,
|
||||
)?;
|
||||
// Responses 的独立工具输出通过名称标识,不依赖前序调用
|
||||
let field = if message.get("tool_call_id").is_none_or(Value::is_null) {
|
||||
"name"
|
||||
} else {
|
||||
"tool_call_id"
|
||||
};
|
||||
string(message.get(field), &format!("{path}.{field}"), false)?;
|
||||
} else if message
|
||||
.get("tool_call_id")
|
||||
.is_some_and(|v| !v.is_null() && v != "")
|
||||
|
||||
@@ -166,12 +166,7 @@ fn messages(value: Value) -> Result<Vec<Value>, RequestDecodeError> {
|
||||
let mut message = object(value, &path)?;
|
||||
let role = required_string(&mut message, "role", &format!("{path}.role"), false)?;
|
||||
if role == "tool" {
|
||||
let call_id = required_string(
|
||||
&mut message,
|
||||
"tool_call_id",
|
||||
&format!("{path}.tool_call_id"),
|
||||
false,
|
||||
)?;
|
||||
let call_id = optional(&mut message, "tool_call_id");
|
||||
let content_path = format!("{path}.content");
|
||||
let content = required(&mut message, "content", &content_path)?;
|
||||
let output = if content.is_string() {
|
||||
@@ -179,15 +174,24 @@ fn messages(value: Value) -> Result<Vec<Value>, RequestDecodeError> {
|
||||
} else {
|
||||
content_parts(content, &role, &content_path, false)?.into()
|
||||
};
|
||||
let kind = if custom_calls.contains(&call_id) {
|
||||
let kind = if call_id
|
||||
.as_ref()
|
||||
.and_then(Value::as_str)
|
||||
.is_some_and(|id| custom_calls.contains(id))
|
||||
{
|
||||
"custom_tool_call_output"
|
||||
} else {
|
||||
"function_call_output"
|
||||
};
|
||||
let mut item = json!({"type": kind, "call_id": call_id, "output": output});
|
||||
if let Some(name) = optional(&mut message, "name").filter(|name| name != "") {
|
||||
string(&name, &format!("{path}.name"), true)?;
|
||||
item["name"] = name;
|
||||
let mut item = json!({"type": kind, "output": output});
|
||||
if let Some(call_id) = call_id {
|
||||
item["call_id"] = call_id;
|
||||
}
|
||||
for field in ["name", "namespace"] {
|
||||
if let Some(value) = optional(&mut message, field).filter(|value| value != "") {
|
||||
string(&value, &format!("{path}.{field}"), true)?;
|
||||
item[field] = value;
|
||||
}
|
||||
}
|
||||
input.push(item);
|
||||
continue;
|
||||
@@ -377,12 +381,13 @@ fn tools(value: Value) -> Result<Vec<Value>, RequestDecodeError> {
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(index, value)| {
|
||||
let path = format!("tools[{index}]");
|
||||
let mut path = format!("tools[{index}]");
|
||||
let mut tool = object(value, &path)?;
|
||||
let kind = required_string(&mut tool, "type", &format!("{path}.type"), false)?;
|
||||
if matches!(kind.as_str(), "function" | "custom") {
|
||||
if let Some(nested) = optional(&mut tool, &kind) {
|
||||
tool = object(nested, &format!("{path}.{kind}"))?;
|
||||
path = format!("{path}.{kind}");
|
||||
tool = object(nested, &path)?;
|
||||
}
|
||||
if tool.get("description") == Some(&Value::Null) {
|
||||
tool.remove("description");
|
||||
@@ -395,6 +400,14 @@ fn tools(value: Value) -> Result<Vec<Value>, RequestDecodeError> {
|
||||
// Chat 的缺省是宽松 schema,不能让 Responses 收紧参数合同
|
||||
tool.insert("strict".into(), false.into());
|
||||
}
|
||||
} else if let Some(format) = tool.get_mut("format").and_then(Value::as_object_mut)
|
||||
&& format.get("type").and_then(Value::as_str) == Some("grammar")
|
||||
&& let Some(grammar) = optional(format, "grammar")
|
||||
{
|
||||
// Chat 将语法嵌套在 grammar,Responses 使用同层的 syntax 和 definition
|
||||
let grammar = object(grammar, &format!("{path}.format.grammar"))?;
|
||||
format.extend(grammar);
|
||||
format.insert("type".into(), "grammar".into());
|
||||
}
|
||||
}
|
||||
// hosted 工具采用原生 Responses 结构,支持范围由选中的 Provider 决定
|
||||
|
||||
@@ -63,14 +63,48 @@ fn invalid_envelopes_and_chat_controls_keep_safe_field_errors() {
|
||||
|
||||
#[test]
|
||||
fn invalid_tool_history_reports_source_path() {
|
||||
let request = json!({"model":"m","messages":[{"role":"tool","content":"ok"}]});
|
||||
assert_eq!(
|
||||
parse_request(&serde_json::to_vec(&request).unwrap())
|
||||
.err()
|
||||
for (identity, parameter) in [
|
||||
(json!({}), "messages[0].name"),
|
||||
(json!({"name":null}), "messages[0].name"),
|
||||
(json!({"name":" "}), "messages[0].name"),
|
||||
(json!({"name":17}), "messages[0].name"),
|
||||
(
|
||||
json!({"name":"notifications","tool_call_id":""}),
|
||||
"messages[0].tool_call_id",
|
||||
),
|
||||
(
|
||||
json!({"name":"notifications","tool_call_id":17}),
|
||||
"messages[0].tool_call_id",
|
||||
),
|
||||
] {
|
||||
let mut message = json!({"role":"tool","content":"ok"});
|
||||
message
|
||||
.as_object_mut()
|
||||
.unwrap()
|
||||
.parameter(),
|
||||
Some("messages[0].tool_call_id")
|
||||
);
|
||||
.extend(identity.as_object().unwrap().clone());
|
||||
let request = json!({"model":"m","messages":[message]});
|
||||
let error = parse_request(&serde_json::to_vec(&request).unwrap()).unwrap_err();
|
||||
assert_eq!(error.parameter(), Some(parameter));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn named_tool_outputs_preserve_the_original_request_and_target_requirements() {
|
||||
let request = json!({"model":"m","messages":[
|
||||
{"role":"tool","name":"notifications","namespace":"agent","content":"notice"}
|
||||
]});
|
||||
let parsed = parse_request(&serde_json::to_vec(&request).unwrap()).unwrap();
|
||||
assert_eq!(&parsed, request.as_object().unwrap());
|
||||
assert!(responses::convert_request(&parsed).is_ok());
|
||||
for result in [
|
||||
messages::convert_request(&parsed, &Default::default()),
|
||||
genai::convert_request(&parsed),
|
||||
] {
|
||||
assert_eq!(
|
||||
result.unwrap_err().parameter(),
|
||||
Some("messages[0].tool_call_id")
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -472,11 +506,14 @@ fn all_targets_apply_the_same_common_request_validation() {
|
||||
|
||||
#[test]
|
||||
fn custom_format_constraints_are_preserved_or_rejected_by_the_target() {
|
||||
for format in [
|
||||
json!(null),
|
||||
json!({"type":"text"}),
|
||||
json!({"type":"grammar","grammar":{"syntax":"lark","definition":"PRIVATE_GRAMMAR"}}),
|
||||
json!(17),
|
||||
for (format, expected) in [
|
||||
(json!(null), json!(null)),
|
||||
(json!({"type":"text"}), json!({"type":"text"})),
|
||||
(
|
||||
json!({"type":"grammar","grammar":{"syntax":"lark","definition":"PRIVATE_GRAMMAR"}}),
|
||||
json!({"type":"grammar","syntax":"lark","definition":"PRIVATE_GRAMMAR"}),
|
||||
),
|
||||
(json!(17), json!(17)),
|
||||
] {
|
||||
let mut body = super::request();
|
||||
body.insert(
|
||||
@@ -484,7 +521,7 @@ fn custom_format_constraints_are_preserved_or_rejected_by_the_target() {
|
||||
json!([{"type":"custom","custom":{"name":"run","format":format}}]),
|
||||
);
|
||||
let responses = responses::convert_request(&body).unwrap();
|
||||
assert_eq!(responses["tools"][0]["format"], format);
|
||||
assert_eq!(responses["tools"][0]["format"], expected);
|
||||
for result in [
|
||||
messages::convert_request(&body, &Default::default()),
|
||||
genai::convert_request(&body),
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Chat 到 Responses 的字段、媒体和工具映射回归
|
||||
//! Chat 到 Responses 的字段、媒体和工具映射
|
||||
|
||||
use gateway_protocol::chat_completions::responses::convert_request;
|
||||
use serde_json::{Value, json};
|
||||
@@ -53,6 +53,31 @@ fn preserves_ordered_roles_images_and_modern_tool_round_trip() {
|
||||
assert!(converted.get("previous_response_id").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn named_tool_outputs_preserve_unpaired_identity_and_order() {
|
||||
for call_id in [None, Some(Value::Null)] {
|
||||
let mut notice = json!({"role":"tool","name":"lookup","namespace":"agent","content":[{"type":"text","text":"independent notice"}]});
|
||||
if let Some(call_id) = call_id {
|
||||
notice["tool_call_id"] = call_id;
|
||||
}
|
||||
let converted = convert(json!({"model":"model-a","messages":[
|
||||
{"role":"assistant","tool_calls":[{"id":"call_lookup","type":"custom","custom":{"name":"lookup","input":"query"}}]},
|
||||
notice,
|
||||
{"role":"tool","tool_call_id":"call_lookup","content":"matched result"},
|
||||
{"role":"tool","name":"notifications","content":"another notice"}
|
||||
]}));
|
||||
assert_eq!(
|
||||
converted["input"],
|
||||
json!([
|
||||
{"type":"custom_tool_call","call_id":"call_lookup","name":"lookup","input":"query"},
|
||||
{"type":"function_call_output","name":"lookup","namespace":"agent","output":[{"type":"input_text","text":"independent notice"}]},
|
||||
{"type":"custom_tool_call_output","call_id":"call_lookup","output":"matched result"},
|
||||
{"type":"function_call_output","name":"notifications","output":"another notice"}
|
||||
])
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn web_search_options_require_a_hosted_search_and_flatten_location() {
|
||||
for (options, expected) in [
|
||||
@@ -278,7 +303,7 @@ fn custom_tools_keep_native_input_and_mixed_call_families_through_history() {
|
||||
]}));
|
||||
assert_eq!(
|
||||
converted["tools"][0],
|
||||
json!({"type":"custom", "name":"patch", "format":schema})
|
||||
json!({"type":"custom", "name":"patch", "format":{"type":"grammar","syntax":"lark","definition":"start: /.+/"}})
|
||||
);
|
||||
assert_eq!(
|
||||
converted["tool_choice"],
|
||||
@@ -293,6 +318,40 @@ fn custom_tools_keep_native_input_and_mixed_call_families_through_history() {
|
||||
assert_eq!(converted["input"][5]["type"], "function_call_output");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_grammar_formats_keep_their_constraints_and_source_paths() {
|
||||
for nested in [false, true] {
|
||||
for syntax in ["lark", "regex"] {
|
||||
let format =
|
||||
json!({"type":"grammar","syntax":syntax,"definition":"OK","future_field":true});
|
||||
let definition = json!({"name":"probe","format":format});
|
||||
let tool = if nested {
|
||||
json!({"type":"custom","custom":definition})
|
||||
} else {
|
||||
json!({"type":"custom","name":"probe","format":format})
|
||||
};
|
||||
let mut body =
|
||||
json!({"model":"m","messages":[{"role":"user","content":"hello"}],"tools":[tool]});
|
||||
assert_eq!(convert(body.clone())["tools"][0]["format"], format);
|
||||
let declaration = if nested {
|
||||
&mut body["tools"][0]["custom"]
|
||||
} else {
|
||||
&mut body["tools"][0]
|
||||
};
|
||||
declaration["format"] = json!({"type":"grammar","grammar":false});
|
||||
let error = convert_request(body.as_object().unwrap()).unwrap_err();
|
||||
assert_eq!(
|
||||
error.parameter(),
|
||||
Some(if nested {
|
||||
"tools[0].custom.format.grammar"
|
||||
} else {
|
||||
"tools[0].format.grammar"
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn files_and_audio_are_preserved_as_inputs_instead_of_losing_the_user_turn() {
|
||||
for file in [
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Responses 到 Chat 的完整响应、SSE增量及历史字段回归
|
||||
//! Responses 到 Chat 的完整响应、流式增量、用量与错误投影
|
||||
|
||||
use gateway_protocol::chat_completions::{
|
||||
ChatAccumulator, ChatError, ChatIdentity,
|
||||
@@ -7,86 +7,67 @@ use gateway_protocol::chat_completions::{
|
||||
use serde_json::{Value, json};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
struct Session(Vec<Value>);
|
||||
impl Session {
|
||||
fn new(events: Vec<Value>) -> Self {
|
||||
Self(events)
|
||||
}
|
||||
fn with_batch(mut self, events: Vec<Value>) -> Self {
|
||||
self.0.extend(events);
|
||||
self
|
||||
}
|
||||
}
|
||||
struct Fixture(Session);
|
||||
struct Projection {
|
||||
json: Option<Value>,
|
||||
chunks: Vec<Value>,
|
||||
error: Option<ChatError>,
|
||||
}
|
||||
impl Fixture {
|
||||
fn new(events: Session) -> Self {
|
||||
Self(events)
|
||||
}
|
||||
fn post(&self, request: Value) -> Projection {
|
||||
let identity = chat_identity();
|
||||
let mut result = Projection {
|
||||
json: None,
|
||||
chunks: Vec::new(),
|
||||
error: None,
|
||||
};
|
||||
if request["stream"] == true {
|
||||
let mut encoder = ChatStreamEncoder::new(
|
||||
identity,
|
||||
request["stream_options"]["include_usage"] == true,
|
||||
);
|
||||
for event in &self.0.0 {
|
||||
match encoder.push_event(event["type"].as_str(), event) {
|
||||
Ok(chunks) => result.chunks.extend(chunks),
|
||||
Err(error) => {
|
||||
result.error = Some(error);
|
||||
return result;
|
||||
}
|
||||
fn project_events(events: &[Value], streaming: bool, include_usage: bool) -> Projection {
|
||||
let identity = chat_identity();
|
||||
let mut result = Projection {
|
||||
json: None,
|
||||
chunks: Vec::new(),
|
||||
error: None,
|
||||
};
|
||||
if streaming {
|
||||
let mut encoder = ChatStreamEncoder::new(identity, include_usage);
|
||||
for event in events {
|
||||
match encoder.push_event(event["type"].as_str(), event) {
|
||||
Ok(chunks) => result.chunks.extend(chunks),
|
||||
Err(error) => {
|
||||
result.error = Some(error);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
match encoder.finish() {
|
||||
Ok(chunks) => result.chunks.extend(chunks),
|
||||
Err(error) => result.error = Some(error),
|
||||
}
|
||||
}
|
||||
match encoder.finish() {
|
||||
Ok(chunks) => result.chunks.extend(chunks),
|
||||
Err(error) => result.error = Some(error),
|
||||
}
|
||||
} else {
|
||||
let projected = if events.len() == 1 {
|
||||
events[0]
|
||||
.get("response")
|
||||
.ok_or(ChatError::IncompleteStream)
|
||||
.and_then(|value| project_response(value, &identity))
|
||||
} else {
|
||||
let projected = if self.0.0.len() == 1 {
|
||||
self.0.0[0]
|
||||
.get("response")
|
||||
.ok_or(ChatError::IncompleteStream)
|
||||
.and_then(|value| project_response(value, &identity))
|
||||
} else {
|
||||
let mut encoder = ChatStreamEncoder::new(identity, true);
|
||||
let mut accumulator = ChatAccumulator::default();
|
||||
let mut collect = || {
|
||||
for event in &self.0.0 {
|
||||
for chunk in encoder.push_event(event["type"].as_str(), event)? {
|
||||
accumulator.push(&chunk)?;
|
||||
}
|
||||
}
|
||||
for chunk in encoder.finish()? {
|
||||
let mut encoder = ChatStreamEncoder::new(identity, true);
|
||||
let mut accumulator = ChatAccumulator::default();
|
||||
let mut collect = || {
|
||||
for event in events {
|
||||
for chunk in encoder.push_event(event["type"].as_str(), event)? {
|
||||
accumulator.push(&chunk)?;
|
||||
}
|
||||
Ok::<_, ChatError>(())
|
||||
};
|
||||
collect().and_then(|()| accumulator.finish())
|
||||
}
|
||||
for chunk in encoder.finish()? {
|
||||
accumulator.push(&chunk)?;
|
||||
}
|
||||
Ok::<_, ChatError>(())
|
||||
};
|
||||
match projected {
|
||||
Ok(value) => result.json = Some(value),
|
||||
Err(error) => result.error = Some(error),
|
||||
}
|
||||
collect().and_then(|()| accumulator.finish())
|
||||
};
|
||||
match projected {
|
||||
Ok(value) => result.json = Some(value),
|
||||
Err(error) => result.error = Some(error),
|
||||
}
|
||||
result
|
||||
}
|
||||
result
|
||||
}
|
||||
fn json_body(response: Projection) -> Value {
|
||||
assert!(response.error.is_none(), "{:?}", response.error);
|
||||
response.json.unwrap()
|
||||
}
|
||||
fn sse_body(response: Projection) -> (String, Vec<Value>) {
|
||||
fn stream_chunks(response: Projection) -> (String, Vec<Value>) {
|
||||
assert!(response.error.is_none(), "{:?}", response.error);
|
||||
(
|
||||
serde_json::to_string(&response.chunks).unwrap(),
|
||||
@@ -100,9 +81,6 @@ fn chat_identity() -> ChatIdentity {
|
||||
model: "model-a".to_owned(),
|
||||
}
|
||||
}
|
||||
fn chat_request(stream: bool) -> Value {
|
||||
json!({"model":"model-a","messages":[{"role":"user","content":"hello"}],"stream":stream})
|
||||
}
|
||||
fn wire(kind: &str, mut value: Value) -> Value {
|
||||
value["type"] = json!(kind);
|
||||
value
|
||||
@@ -135,8 +113,8 @@ fn tool(id: &str, call_id: &str, name: &str, arguments: &str) -> Value {
|
||||
|
||||
#[test]
|
||||
fn json_projects_public_identity_text_and_actual_usage() {
|
||||
let fixture = Fixture::new(Session::new(vec![completed(json!([message("你好 🌍")]))]));
|
||||
let response = fixture.post(chat_request(false));
|
||||
let events = vec![completed(json!([message("你好 🌍")]))];
|
||||
let response = project_events(&events, false, false);
|
||||
let body = json_body(response);
|
||||
assert_eq!(body["object"], "chat.completion");
|
||||
assert!(body["id"].as_str().unwrap().starts_with("chatcmpl-"));
|
||||
@@ -164,7 +142,7 @@ fn web_search_projects_citations_in_json_and_streams_the_original_links() {
|
||||
let mut answer = message(&text);
|
||||
answer["content"][0]["annotations"] = json!([citation]);
|
||||
for stream in [false, true] {
|
||||
let fixture = Fixture::new(Session::new(vec![
|
||||
let events = vec![
|
||||
created(),
|
||||
wire(
|
||||
"response.output_item.done",
|
||||
@@ -189,13 +167,11 @@ fn web_search_projects_citations_in_json_and_streams_the_original_links() {
|
||||
json!({"output_index":2,"item":answer}),
|
||||
),
|
||||
completed(json!([])),
|
||||
]));
|
||||
let mut request = chat_request(stream);
|
||||
request["web_search_options"] = json!({});
|
||||
let response = fixture.post(request);
|
||||
];
|
||||
let response = project_events(&events, stream, false);
|
||||
let expected = format!("🌍 {text}");
|
||||
if stream {
|
||||
let (_, chunks) = sse_body(response);
|
||||
let (_, chunks) = stream_chunks(response);
|
||||
assert_eq!(combined(&chunks, "content"), expected);
|
||||
assert_eq!(
|
||||
chunks.last().unwrap()["choices"][0]["finish_reason"],
|
||||
@@ -223,8 +199,8 @@ fn json_tool_arguments_and_refusal_do_not_become_assistant_text() {
|
||||
{"type":"message","id":"refusal1","role":"assistant","status":"completed",
|
||||
"content":[{"type":"refusal","refusal":"cannot help"}]}]),
|
||||
] {
|
||||
let fixture = Fixture::new(Session::new(vec![completed(output.clone())]));
|
||||
let response = fixture.post(chat_request(false));
|
||||
let events = vec![completed(output.clone())];
|
||||
let response = project_events(&events, false, false);
|
||||
let body = json_body(response);
|
||||
let choice = &body["choices"][0];
|
||||
assert_eq!(choice["message"]["content"], Value::Null);
|
||||
@@ -245,7 +221,7 @@ fn json_tool_arguments_and_refusal_do_not_become_assistant_text() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sse_deduplicates_text_snapshots_and_emits_usage_only_when_requested() {
|
||||
fn stream_deduplicates_text_snapshots_and_emits_usage_only_when_requested() {
|
||||
for include_usage in [false, true] {
|
||||
let terminal = completed(json!([message("你好 🌍")]));
|
||||
let events = [
|
||||
@@ -316,7 +292,7 @@ fn sse_deduplicates_text_snapshots_and_emits_usage_only_when_requested() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sse_preserves_interleaved_tools_and_reordered_terminal_snapshots() {
|
||||
fn stream_preserves_interleaved_tools_and_reordered_terminal_snapshots() {
|
||||
let first = tool(
|
||||
"fc_first",
|
||||
"call_first",
|
||||
@@ -324,7 +300,7 @@ fn sse_preserves_interleaved_tools_and_reordered_terminal_snapshots() {
|
||||
"{ \"city\": \"北京\" }",
|
||||
);
|
||||
let second = tool("fc_second", "call_second", "search", "{\"query\":\"Rust\"}");
|
||||
let fixture = Fixture::new(Session::new(vec![
|
||||
let events = vec![
|
||||
created(),
|
||||
wire(
|
||||
"response.output_item.added",
|
||||
@@ -355,8 +331,8 @@ fn sse_preserves_interleaved_tools_and_reordered_terminal_snapshots() {
|
||||
json!({"output_index":2,"item":first}),
|
||||
),
|
||||
completed(json!([second, first])),
|
||||
]));
|
||||
let (_, chunks) = sse_body(fixture.post(chat_request(true)));
|
||||
];
|
||||
let (_, chunks) = stream_chunks(project_events(&events, true, false));
|
||||
let mut tools = BTreeMap::<u64, (String, String, String)>::new();
|
||||
for chunk in &chunks {
|
||||
if let Some(calls) = chunk["choices"][0]["delta"]["tool_calls"].as_array() {
|
||||
@@ -406,7 +382,7 @@ fn extra_attributes_and_auxiliary_events_preserve_existing_chat_results() {
|
||||
let mut text = message("preserved");
|
||||
text["future_optional"] = json!({"opaque":true});
|
||||
text["content"][0]["future_attribute"] = json!([1, 2, 3]);
|
||||
let fixture = Fixture::new(Session::new(vec![
|
||||
let events = vec![
|
||||
wire("response.future_auxiliary", json!({"future":true})),
|
||||
wire(
|
||||
"response.future_reasoning.delta",
|
||||
@@ -414,8 +390,8 @@ fn extra_attributes_and_auxiliary_events_preserve_existing_chat_results() {
|
||||
),
|
||||
created(),
|
||||
completed(json!([text])),
|
||||
]));
|
||||
let (_, chunks) = sse_body(fixture.post(chat_request(true)));
|
||||
];
|
||||
let (_, chunks) = stream_chunks(project_events(&events, true, false));
|
||||
assert_eq!(combined(&chunks, "content"), "preserved");
|
||||
assert!(
|
||||
!chunks
|
||||
@@ -430,7 +406,7 @@ fn compaction_state_preserves_chat_answer_without_exposing_ciphertext() {
|
||||
for streaming in [false, true] {
|
||||
let state =
|
||||
json!({"type":kind,"id":"ctx_1","encrypted_content":"opaque-private-state"});
|
||||
let fixture = Fixture::new(Session::new(vec![
|
||||
let events = vec![
|
||||
created(),
|
||||
wire(
|
||||
"response.output_item.added",
|
||||
@@ -441,10 +417,10 @@ fn compaction_state_preserves_chat_answer_without_exposing_ciphertext() {
|
||||
json!({"output_index":0,"item":state}),
|
||||
),
|
||||
completed(json!([state, message("preserved")])),
|
||||
]));
|
||||
let response = fixture.post(chat_request(streaming));
|
||||
];
|
||||
let response = project_events(&events, streaming, false);
|
||||
if streaming {
|
||||
let (text, chunks) = sse_body(response);
|
||||
let (text, chunks) = stream_chunks(response);
|
||||
assert_eq!(combined(&chunks, "content"), "preserved");
|
||||
assert!(!text.contains("opaque-private-state"));
|
||||
assert_eq!(
|
||||
@@ -474,10 +450,10 @@ fn incomplete_projects_only_supported_finish_reasons() {
|
||||
"id":"resp_chat_test","status":"incomplete","output":[message("partial")],
|
||||
"incomplete_details":{"reason":reason}}}),
|
||||
);
|
||||
let fixture = Fixture::new(Session::new(vec![created(), event]));
|
||||
let response = fixture.post(chat_request(streaming));
|
||||
let events = vec![created(), event];
|
||||
let response = project_events(&events, streaming, false);
|
||||
if streaming {
|
||||
let (_, chunks) = sse_body(response);
|
||||
let (_, chunks) = stream_chunks(response);
|
||||
assert_eq!(
|
||||
chunks.last().unwrap()["choices"][0]["finish_reason"],
|
||||
expected
|
||||
@@ -497,7 +473,7 @@ fn encrypted_reasoning_stays_private_while_public_text_and_usage_are_projected()
|
||||
"encrypted_content":"OPAQUE_ENCRYPTED_REASONING_MARKER"
|
||||
});
|
||||
for streaming in [false, true] {
|
||||
let fixture = Fixture::new(Session::new(vec![
|
||||
let events = vec![
|
||||
created(),
|
||||
wire(
|
||||
"response.output_item.added",
|
||||
@@ -525,14 +501,10 @@ fn encrypted_reasoning_stays_private_while_public_text_and_usage_are_projected()
|
||||
"output_tokens_details":{"reasoning_tokens":2,"accepted_prediction_tokens":1}}
|
||||
}}),
|
||||
),
|
||||
]));
|
||||
let mut request = chat_request(streaming);
|
||||
if streaming {
|
||||
request["stream_options"] = json!({"include_usage":true});
|
||||
}
|
||||
let response = fixture.post(request);
|
||||
];
|
||||
let response = project_events(&events, streaming, true);
|
||||
let (body, content, usage) = if streaming {
|
||||
let (body, chunks) = sse_body(response);
|
||||
let (body, chunks) = stream_chunks(response);
|
||||
let usage = chunks
|
||||
.iter()
|
||||
.find(|chunk| chunk["choices"] == json!([]))
|
||||
@@ -572,12 +544,8 @@ fn unrepresentable_business_output_fails_without_successful_chat_completion() {
|
||||
json!({"id":"action_native","type":"computer_call","status":"completed","call_id":"call_action","action":{"type":"click","x":1,"y":2}}),
|
||||
] {
|
||||
for streaming in [false, true] {
|
||||
let fixture = Fixture::new(Session::new(vec![created(), completed(json!([output]))]));
|
||||
let mut request = chat_request(streaming);
|
||||
if streaming {
|
||||
request["stream_options"] = json!({"include_usage":true});
|
||||
}
|
||||
let response = fixture.post(request);
|
||||
let events = vec![created(), completed(json!([output]))];
|
||||
let response = project_events(&events, streaming, true);
|
||||
assert_eq!(response.error, Some(ChatError::InvalidResponse));
|
||||
assert!(
|
||||
!response
|
||||
@@ -592,16 +560,15 @@ fn unrepresentable_business_output_fails_without_successful_chat_completion() {
|
||||
|
||||
#[test]
|
||||
fn stream_without_terminal_does_not_emit_a_successful_finish_or_usage() {
|
||||
let fixture = Fixture::new(Session::new(vec![
|
||||
let events = vec![
|
||||
created(),
|
||||
wire(
|
||||
"response.output_text.delta",
|
||||
json!({"item_id":"msg_chat_test","output_index":0,"content_index":0,"delta":"partial"}),
|
||||
),
|
||||
]));
|
||||
let mut body = chat_request(true);
|
||||
body["stream_options"] = json!({"include_usage":true});
|
||||
let response = fixture.post(body);
|
||||
];
|
||||
|
||||
let response = project_events(&events, true, true);
|
||||
assert_eq!(response.error, Some(ChatError::IncompleteStream));
|
||||
assert!(
|
||||
!response
|
||||
@@ -618,16 +585,15 @@ fn stream_without_terminal_does_not_emit_a_successful_finish_or_usage() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn first_batch_terminal_can_finish_without_creating_usage_facts() {
|
||||
let fixture = Fixture::new(Session::new(vec![wire(
|
||||
fn completed_event_without_usage_does_not_invent_usage() {
|
||||
let events = vec![wire(
|
||||
"response.completed",
|
||||
json!({"response":{
|
||||
"id":"resp_chat_test","status":"completed","output":[message("done only")]
|
||||
}}),
|
||||
)]));
|
||||
let mut body = chat_request(true);
|
||||
body["stream_options"] = json!({"include_usage":true});
|
||||
let (_, chunks) = sse_body(fixture.post(body));
|
||||
)];
|
||||
|
||||
let (_, chunks) = stream_chunks(project_events(&events, true, true));
|
||||
assert_eq!(combined(&chunks, "content"), "done only");
|
||||
assert_eq!(
|
||||
chunks
|
||||
@@ -643,7 +609,7 @@ fn first_batch_terminal_can_finish_without_creating_usage_facts() {
|
||||
fn refusal_deltas_and_done_snapshots_produce_only_standard_refusal() {
|
||||
let output = json!({"id":"msg_refusal","type":"message","role":"assistant","status":"completed",
|
||||
"content":[{"type":"refusal","refusal":"cannot help"}]});
|
||||
let fixture = Fixture::new(Session::new(vec![
|
||||
let events = vec![
|
||||
created(),
|
||||
wire(
|
||||
"response.refusal.delta",
|
||||
@@ -654,8 +620,8 @@ fn refusal_deltas_and_done_snapshots_produce_only_standard_refusal() {
|
||||
json!({"item_id":"msg_refusal","output_index":0,"content_index":0,"refusal":"cannot help"}),
|
||||
),
|
||||
completed(json!([output])),
|
||||
]));
|
||||
let (_, chunks) = sse_body(fixture.post(chat_request(true)));
|
||||
];
|
||||
let (_, chunks) = stream_chunks(project_events(&events, true, false));
|
||||
assert_eq!(combined(&chunks, "refusal"), "cannot help");
|
||||
assert_eq!(combined(&chunks, "content"), "");
|
||||
assert_eq!(
|
||||
@@ -667,23 +633,20 @@ fn refusal_deltas_and_done_snapshots_produce_only_standard_refusal() {
|
||||
#[test]
|
||||
fn auxiliary_events_after_completed_preserve_exactly_one_finish_and_usage() {
|
||||
for with_created in [false, true] {
|
||||
// 终态与辅助事件同属一批 Core 交付 不构造已终结会话继续产出事件的另一种异常
|
||||
let session = Session::new(if with_created {
|
||||
let mut events = if with_created {
|
||||
vec![created()]
|
||||
} else {
|
||||
Vec::new()
|
||||
})
|
||||
.with_batch(vec![
|
||||
};
|
||||
events.extend([
|
||||
completed(json!([message("completed text")])),
|
||||
wire(
|
||||
"response.future_metadata",
|
||||
json!({"response_id":"resp_chat_test","future":{"kept":true}}),
|
||||
),
|
||||
]);
|
||||
let fixture = Fixture::new(session);
|
||||
let mut body = chat_request(true);
|
||||
body["stream_options"] = json!({"include_usage":true});
|
||||
let (_, chunks) = sse_body(fixture.post(body));
|
||||
|
||||
let (_, chunks) = stream_chunks(project_events(&events, true, true));
|
||||
assert_eq!(combined(&chunks, "content"), "completed text");
|
||||
assert_eq!(
|
||||
chunks
|
||||
@@ -727,10 +690,9 @@ fn wire_failures_preserve_existing_recovery_fields_without_success_chunks() {
|
||||
failure
|
||||
}
|
||||
};
|
||||
let fixture = Fixture::new(Session::new(vec![created(), failure]));
|
||||
let mut body = chat_request(true);
|
||||
body["stream_options"] = json!({"include_usage":true});
|
||||
let (_, chunks) = sse_body(fixture.post(body));
|
||||
let events = vec![created(), failure];
|
||||
|
||||
let (_, chunks) = stream_chunks(project_events(&events, true, true));
|
||||
let errors = chunks
|
||||
.iter()
|
||||
.filter_map(|chunk| chunk.get("error"))
|
||||
@@ -749,15 +711,15 @@ fn wire_failures_preserve_existing_recovery_fields_without_success_chunks() {
|
||||
|
||||
#[test]
|
||||
fn conflicting_text_snapshot_fails_instead_of_appending_replacement_content() {
|
||||
let fixture = Fixture::new(Session::new(vec![
|
||||
let events = vec![
|
||||
created(),
|
||||
wire(
|
||||
"response.output_text.delta",
|
||||
json!({"item_id":"msg_chat_test","output_index":0,"content_index":0,"delta":"already sent"}),
|
||||
),
|
||||
completed(json!([message("different result")])),
|
||||
]));
|
||||
let response = fixture.post(chat_request(true));
|
||||
];
|
||||
let response = project_events(&events, true, false);
|
||||
assert_eq!(response.error, Some(ChatError::InvalidResponse));
|
||||
assert_eq!(combined(&response.chunks, "content"), "already sent");
|
||||
assert!(
|
||||
@@ -795,7 +757,7 @@ fn custom_and_function_calls_keep_distinct_shapes_in_json_and_interleaved_stream
|
||||
initial_custom["input"] = json!("");
|
||||
let mut initial_function = function.clone();
|
||||
initial_function["arguments"] = json!("");
|
||||
let fixture = Fixture::new(Session::new(vec![
|
||||
let events = vec![
|
||||
created(),
|
||||
wire(
|
||||
"response.output_item.added",
|
||||
@@ -818,10 +780,10 @@ fn custom_and_function_calls_keep_distinct_shapes_in_json_and_interleaved_stream
|
||||
json!({"output_index":0,"item_id":"ct_1","input":"first\nsecond"}),
|
||||
),
|
||||
completed(output.clone()),
|
||||
]));
|
||||
let response = fixture.post(chat_request(streaming));
|
||||
];
|
||||
let response = project_events(&events, streaming, false);
|
||||
if streaming {
|
||||
let (body, chunks) = sse_body(response);
|
||||
let (body, chunks) = stream_chunks(response);
|
||||
assert_eq!(combined(&chunks, "refusal"), "no");
|
||||
assert_eq!(combined(&chunks, "reasoning_content"), "thought");
|
||||
assert!(!body.contains("PRIVATE_REASONING"));
|
||||
@@ -870,7 +832,7 @@ fn custom_and_function_calls_keep_distinct_shapes_in_json_and_interleaved_stream
|
||||
fn image_previews_and_final_images_are_projected_once_per_distinct_snapshot() {
|
||||
let image = json!({"id":"ig_one","type":"image_generation_call","status":"completed","result":"ZmluYWw=","output_format":"webp"});
|
||||
for streaming in [false, true] {
|
||||
let fixture = Fixture::new(Session::new(vec![
|
||||
let events = vec![
|
||||
created(),
|
||||
wire(
|
||||
"response.image_generation_call.partial_image",
|
||||
@@ -881,10 +843,10 @@ fn image_previews_and_final_images_are_projected_once_per_distinct_snapshot() {
|
||||
json!({"output_index":0,"item":image}),
|
||||
),
|
||||
completed(json!([image, message("created")])),
|
||||
]));
|
||||
let response = fixture.post(chat_request(streaming));
|
||||
];
|
||||
let response = project_events(&events, streaming, false);
|
||||
if streaming {
|
||||
let (_, chunks) = sse_body(response);
|
||||
let (_, chunks) = stream_chunks(response);
|
||||
let images = chunks
|
||||
.iter()
|
||||
.filter_map(|chunk| chunk["choices"][0]["delta"]["images"].as_array())
|
||||
@@ -913,7 +875,7 @@ fn output_logprobs_survive_json_projection_and_stream_snapshot_deduplication() {
|
||||
let mut output = message("hello");
|
||||
output["content"][0]["logprobs"] = probabilities.clone();
|
||||
for streaming in [false, true] {
|
||||
let fixture = Fixture::new(Session::new(vec![
|
||||
let events = vec![
|
||||
created(),
|
||||
wire(
|
||||
"response.output_text.delta",
|
||||
@@ -924,10 +886,10 @@ fn output_logprobs_survive_json_projection_and_stream_snapshot_deduplication() {
|
||||
json!({"output_index":0,"content_index":0,"item_id":"msg_chat_test","text":"hello","logprobs":probabilities}),
|
||||
),
|
||||
completed(json!([output])),
|
||||
]));
|
||||
let response = fixture.post(chat_request(streaming));
|
||||
];
|
||||
let response = project_events(&events, streaming, false);
|
||||
if streaming {
|
||||
let (_, chunks) = sse_body(response);
|
||||
let (_, chunks) = stream_chunks(response);
|
||||
let values = chunks
|
||||
.iter()
|
||||
.filter_map(|chunk| chunk["choices"][0]["logprobs"]["content"].as_array())
|
||||
@@ -951,7 +913,7 @@ fn streaming_citation_offsets_follow_delivered_text_when_messages_interleave() {
|
||||
first["content"][0]["annotations"] = json!([citation]);
|
||||
let mut second = message("xy");
|
||||
second["id"] = json!("msg_second");
|
||||
let fixture = Fixture::new(Session::new(vec![
|
||||
let events = vec![
|
||||
created(),
|
||||
wire(
|
||||
"response.output_text.delta",
|
||||
@@ -970,8 +932,8 @@ fn streaming_citation_offsets_follow_delivered_text_when_messages_interleave() {
|
||||
json!({"output_index":0,"content_index":0,"item_id":"msg_chat_test","annotation_index":0,"annotation":citation}),
|
||||
),
|
||||
completed(json!([first, second])),
|
||||
]));
|
||||
let (_, chunks) = sse_body(fixture.post(chat_request(true)));
|
||||
];
|
||||
let (_, chunks) = stream_chunks(project_events(&events, true, false));
|
||||
assert_eq!(combined(&chunks, "content"), "abxycd");
|
||||
let annotations = chunks
|
||||
.iter()
|
||||
|
||||
@@ -69,7 +69,9 @@ impl ClientAdmissionRecoveryRepository for PgClientAdmissionRecoveryRepository {
|
||||
lease.lease_expires_at, request.outcome
|
||||
from model_requests request
|
||||
left join model_request_leases lease on lease.request_id = request.id
|
||||
where request.started_at >= $1 or request.outcome = 'running'
|
||||
where (request.started_at >= $1 or request.outcome = 'running')
|
||||
and (request.client_transport, request.request_kind)
|
||||
is distinct from ('internal_plugin', 'plugin_child_model')
|
||||
order by request.client_api_key_ref, request.started_at, request.id",
|
||||
)
|
||||
.bind(window_started_at)
|
||||
|
||||
@@ -325,19 +325,36 @@ impl AccountStore for PgAdminAccountStore {
|
||||
));
|
||||
}
|
||||
let now = Utc::now();
|
||||
let cooldown = runtime.cooldown;
|
||||
let now_system_time = std::time::SystemTime::from(now);
|
||||
let active_rate_limited_ids = cooldown
|
||||
let active_rate_limited_ids = runtime
|
||||
.cooldown
|
||||
.iter()
|
||||
.filter(|(_, cooldown)| cooldown.is_active(now_system_time))
|
||||
.map(|(account_id, _)| account_id.clone())
|
||||
.collect::<Vec<_>>();
|
||||
let active_model_revisions = runtime
|
||||
.model_cooldowns
|
||||
.iter()
|
||||
.flat_map(|(account, models)| {
|
||||
models
|
||||
.iter()
|
||||
.filter(|model| model.until() > now_system_time)
|
||||
.filter_map(|model| {
|
||||
i64::try_from(model.credential_revision().get())
|
||||
.ok()
|
||||
.map(|revision| (account.clone(), revision))
|
||||
})
|
||||
})
|
||||
.collect::<std::collections::BTreeSet<_>>()
|
||||
.into_iter()
|
||||
.collect();
|
||||
let page = load_admin_account_page(
|
||||
&self.pool,
|
||||
&self.query_budget,
|
||||
&query,
|
||||
now,
|
||||
active_rate_limited_ids,
|
||||
active_model_revisions,
|
||||
)
|
||||
.await?;
|
||||
let item_ids = page
|
||||
@@ -351,14 +368,12 @@ impl AccountStore for PgAdminAccountStore {
|
||||
.into_iter()
|
||||
.map(|(summary, platform_icon)| {
|
||||
let account_id = summary.id.clone();
|
||||
let projection = account_status_projection(
|
||||
&summary,
|
||||
now.into(),
|
||||
cooldown.get(&account_id).copied(),
|
||||
);
|
||||
let (projection, model_cooldowns) =
|
||||
super::runtime::account_directory_projection(&summary, now.into(), &runtime);
|
||||
let mut account = admin_account_record(summary)?;
|
||||
account.groups = groups_by_account.remove(&account_id).unwrap_or_default();
|
||||
Ok(AccountPageItem {
|
||||
model_cooldowns,
|
||||
platform_icon,
|
||||
protection_rules: runtime
|
||||
.protection_rules
|
||||
@@ -397,8 +412,8 @@ impl AccountStore for PgAdminAccountStore {
|
||||
return Ok(None);
|
||||
};
|
||||
let now = Utc::now();
|
||||
let cooldown = runtime.cooldown.get(account_id).copied();
|
||||
let projection = account_status_projection(&record.summary, now.into(), cooldown);
|
||||
let (projection, model_cooldowns) =
|
||||
super::runtime::account_directory_projection(&record.summary, now.into(), &runtime);
|
||||
let account_id = record.summary.id.clone();
|
||||
let mut groups = self
|
||||
.account_groups_by_account(std::slice::from_ref(&account_id))
|
||||
@@ -424,6 +439,7 @@ impl AccountStore for PgAdminAccountStore {
|
||||
)
|
||||
})?;
|
||||
Ok(Some(AccountPageItem {
|
||||
model_cooldowns,
|
||||
platform_icon,
|
||||
protection_rules: runtime
|
||||
.protection_rules
|
||||
|
||||
@@ -16,7 +16,10 @@ pub(crate) async fn load_admin_account_page(
|
||||
query: &AdminAccountListQuery,
|
||||
now: DateTime<Utc>,
|
||||
active_rate_limited_ids: Vec<String>,
|
||||
active_model_revisions: Vec<(String, i64)>,
|
||||
) -> AdminStoreResult<AdminAccountPageRows> {
|
||||
let (model_account_ids, model_revisions): (Vec<_>, Vec<_>) =
|
||||
active_model_revisions.into_iter().unzip();
|
||||
validate_group_filter(pool, query.group_filter.as_ref()).await?;
|
||||
|
||||
let provider_kind = query
|
||||
@@ -56,7 +59,10 @@ pub(crate) async fn load_admin_account_page(
|
||||
when a.credential_state <> 'ready'
|
||||
or a.access_token_expires_at <= $2 then 'error'
|
||||
when a.quota_access_state = 'exhausted' then 'quota_exhausted'
|
||||
when a.id = any($1::text[]) then 'rate_limited'
|
||||
when a.id = any($1::text[]) or exists (
|
||||
select 1 from unnest($13::text[], $14::bigint[]) as limits(account_id, revision)
|
||||
where limits.account_id = a.id and limits.revision = a.credential_revision
|
||||
) then 'rate_limited'
|
||||
when a.quota_paused then 'quota_paused'
|
||||
else 'normal'
|
||||
end as admin_status
|
||||
@@ -165,6 +171,8 @@ pub(crate) async fn load_admin_account_page(
|
||||
.bind(usage_ids)
|
||||
.bind(usage_tokens)
|
||||
.bind(usage_latest)
|
||||
.bind(model_account_ids)
|
||||
.bind(model_revisions)
|
||||
.fetch_all(&mut *snapshot.tx)
|
||||
.await
|
||||
.map_err(|source| postgres_unavailable("load admin account page", source))?;
|
||||
|
||||
@@ -12,6 +12,40 @@ use gateway_core::{
|
||||
|
||||
use super::ProviderAccountSummary;
|
||||
|
||||
pub(crate) fn account_directory_projection(
|
||||
account: &ProviderAccountSummary,
|
||||
now: SystemTime,
|
||||
runtime: &gateway_admin::model::accounts::AccountRuntimeSnapshot,
|
||||
) -> (
|
||||
AccountStatusProjection,
|
||||
Vec<gateway_core::provider_ports::ProviderScopedCooldown>,
|
||||
) {
|
||||
let models = runtime
|
||||
.model_cooldowns
|
||||
.get(&account.id)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter(|cooldown| {
|
||||
cooldown.credential_revision().get() == account.credential_revision.get()
|
||||
&& cooldown.until() > now
|
||||
})
|
||||
.cloned()
|
||||
.collect::<Vec<_>>();
|
||||
let mut projection =
|
||||
account_status_projection(account, now, runtime.cooldown.get(&account.id).copied());
|
||||
// 目录汇总展示部分模型受限,不将其写入整账号 cooldown 或用于其他模型的调度
|
||||
if !models.is_empty()
|
||||
&& matches!(
|
||||
projection.status,
|
||||
gateway_core::account::AccountStatus::Normal
|
||||
| gateway_core::account::AccountStatus::QuotaPaused
|
||||
)
|
||||
{
|
||||
projection.status = gateway_core::account::AccountStatus::RateLimited;
|
||||
}
|
||||
(projection, models)
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub(crate) fn account_status_projection(
|
||||
account: &ProviderAccountSummary,
|
||||
|
||||
@@ -155,8 +155,6 @@ impl ClientAdmissionRequest {
|
||||
return Err(invalid("lease TTL must be positive"));
|
||||
}
|
||||
redis_duration_millis(self.lease_ttl)?;
|
||||
redis_integer(self.limits.max_concurrency, "maximum concurrency")?;
|
||||
redis_integer(self.limits.requests_per_minute, "requests per minute")?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -287,6 +285,7 @@ impl ClientAdmissionRepository for RedisClientAdmissionRepository {
|
||||
.key(&keys[1])
|
||||
.arg(&request.model_request_id)
|
||||
.arg(lease_ttl_ms)
|
||||
// ZCARD 的取值都能精确表示,超过 Lua 精确范围的限额始终大于实际计数
|
||||
.arg(request.limits.max_concurrency)
|
||||
.arg(request.limits.requests_per_minute)
|
||||
.arg(MAX_REDIS_EXACT_INTEGER)
|
||||
|
||||
@@ -11,7 +11,7 @@ use gateway_core::{
|
||||
},
|
||||
};
|
||||
use redis::{Script, aio::ConnectionManager};
|
||||
use std::{collections::BTreeMap, sync::LazyLock};
|
||||
use std::{collections::BTreeMap, sync::LazyLock, time::SystemTime};
|
||||
|
||||
use crate::{Revision, StoreError, StoreResult, redis_unavailable, require_nonempty};
|
||||
|
||||
@@ -55,6 +55,42 @@ static WRITE_ACCOUNT: LazyLock<Script> = LazyLock::new(|| {
|
||||
)
|
||||
});
|
||||
|
||||
// 模型事实与目录索引同次写入;普通成功只清整账号冷却,不触碰这里的期限
|
||||
const WRITE_SCOPED: &str = r#"
|
||||
local current = tonumber(redis.call('HGET', KEYS[1], 'revision') or '0')
|
||||
local incoming = tonumber(ARGV[1])
|
||||
local until_ms = tonumber(ARGV[2])
|
||||
local limited_ms = tonumber(ARGV[4])
|
||||
local clock = redis.call('TIME')
|
||||
local now_ms = tonumber(clock[1]) * 1000 + math.floor(tonumber(clock[2]) / 1000)
|
||||
if current > incoming or until_ms <= now_ms then return 0 end
|
||||
if current == incoming then
|
||||
local previous = tonumber(redis.call('HGET', KEYS[1], 'until_ms') or '0')
|
||||
local limited = tonumber(redis.call('HGET', KEYS[1], 'rate_limited_until_ms') or '0')
|
||||
if previous >= until_ms and limited >= limited_ms then return 0 end
|
||||
until_ms = math.max(previous, until_ms)
|
||||
limited_ms = math.max(limited, limited_ms)
|
||||
end
|
||||
redis.call('HSET', KEYS[1], 'revision', incoming, 'until_ms', until_ms, 'rate_limited_until_ms', limited_ms)
|
||||
redis.call('PEXPIREAT', KEYS[1], until_ms + 60000)
|
||||
if limited_ms > now_ms then
|
||||
redis.call('ZADD', KEYS[2], limited_ms, ARGV[3])
|
||||
local latest = redis.call('ZRANGE', KEYS[2], -1, -1, 'WITHSCORES')
|
||||
redis.call('PEXPIREAT', KEYS[2], tonumber(latest[2]) + 60000)
|
||||
redis.call('ZADD', KEYS[3], 'GT', latest[2], ARGV[5])
|
||||
else
|
||||
redis.call('ZREM', KEYS[2], ARGV[3])
|
||||
end
|
||||
return 1
|
||||
"#;
|
||||
|
||||
const ACTIVE_SCOPES: &str = r#"
|
||||
local clock = redis.call('TIME')
|
||||
local now_ms = tonumber(clock[1]) * 1000 + math.floor(tonumber(clock[2]) / 1000)
|
||||
redis.call('ZREMRANGEBYSCORE', KEYS[1], '-inf', now_ms)
|
||||
return redis.call('ZRANGE', KEYS[1], 0, -1)
|
||||
"#;
|
||||
|
||||
const READ_SCOPED: &str = r#"
|
||||
local revision = redis.call('HGET', KEYS[1], 'revision')
|
||||
local until_ms = redis.call('HGET', KEYS[1], 'until_ms')
|
||||
@@ -62,9 +98,9 @@ local clock = redis.call('TIME')
|
||||
local now_ms = (tonumber(clock[1]) * 1000) + math.floor(tonumber(clock[2]) / 1000)
|
||||
if not revision or not until_ms or tonumber(until_ms) <= now_ms then
|
||||
redis.call('DEL', KEYS[1])
|
||||
return {0, '0', '0'}
|
||||
return {0, '0', '0', '0'}
|
||||
end
|
||||
return {1, revision, until_ms}
|
||||
return {1, revision, until_ms, redis.call('HGET', KEYS[1], 'rate_limited_until_ms') or '0'}
|
||||
"#;
|
||||
|
||||
const INVALIDATE_SCRIPT: &str = r#"
|
||||
@@ -132,6 +168,73 @@ impl RedisCredentialCooldownRepository {
|
||||
format!("{}:account:active-cooldowns", self.namespace)
|
||||
}
|
||||
|
||||
fn model_index_key(&self, account: &str) -> StoreResult<String> {
|
||||
Ok(format!("{}:models", self.key(account)?))
|
||||
}
|
||||
|
||||
fn active_model_index_key(&self) -> String {
|
||||
format!("{}:account:active-model-cooldowns", self.namespace)
|
||||
}
|
||||
|
||||
async fn read_model_cooldowns(
|
||||
&self,
|
||||
account: &str,
|
||||
) -> StoreResult<Vec<ProviderScopedCooldown>> {
|
||||
let models: Vec<String> = Script::new(ACTIVE_SCOPES)
|
||||
.key(self.model_index_key(account)?)
|
||||
.invoke_async(&mut self.connection.clone())
|
||||
.await
|
||||
.map_err(|source| redis_unavailable("list account model cooldowns", source))?;
|
||||
let account =
|
||||
ProviderAccountId::new(account).map_err(|_| invalid("invalid cooldown account"))?;
|
||||
let scopes = models
|
||||
.into_iter()
|
||||
.map(|model| {
|
||||
gateway_core::routing::UpstreamModelId::new(model)
|
||||
.map(ProviderCooldownScope::upstream_model)
|
||||
.map_err(|_| invalid("invalid cooldown model"))
|
||||
})
|
||||
.collect::<StoreResult<Vec<_>>>()?;
|
||||
let mut cooldowns = Vec::new();
|
||||
for scopes in scopes.chunks(COOLDOWN_READ_BATCH_SIZE) {
|
||||
let script = Script::new(READ_SCOPED);
|
||||
let commands = scopes
|
||||
.iter()
|
||||
.map(|scope| {
|
||||
let mut command = redis::cmd("EVALSHA");
|
||||
command
|
||||
.arg(script.get_hash())
|
||||
.arg(1)
|
||||
.arg(self.scoped_key(account.as_str(), scope)?);
|
||||
Ok(command)
|
||||
})
|
||||
.collect();
|
||||
for (scope, value) in scopes
|
||||
.iter()
|
||||
.zip(self.read_script_batch(&script, commands).await)
|
||||
{
|
||||
let value = redis::from_redis_value(value?)
|
||||
.map_err(|source| redis_unavailable("decode model cooldown", source))?;
|
||||
if let Some(cooldown) = parse_scoped_cooldown(value, &account, scope)?
|
||||
&& let Some(until) = cooldown
|
||||
.rate_limited_until()
|
||||
.filter(|until| *until > SystemTime::now())
|
||||
{
|
||||
cooldowns.push(
|
||||
ProviderScopedCooldown::new(
|
||||
account.clone(),
|
||||
cooldown.credential_revision(),
|
||||
scope.clone(),
|
||||
until,
|
||||
)
|
||||
.with_rate_limited_until(Some(until)),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(cooldowns)
|
||||
}
|
||||
|
||||
fn capacity_failures_key(&self, provider_account_id: &str) -> StoreResult<String> {
|
||||
let fingerprint = resource_fingerprint("credential cooldown", provider_account_id)?;
|
||||
Ok(format!(
|
||||
@@ -168,49 +271,27 @@ impl RedisCredentialCooldownRepository {
|
||||
credential_revision: Revision,
|
||||
cooldown_until: DateTime<Utc>,
|
||||
kind: ProviderCooldownKind,
|
||||
index_member: Option<&str>,
|
||||
index_member: &str,
|
||||
) -> StoreResult<bool> {
|
||||
let until_ms = cooldown_until.timestamp_millis();
|
||||
if until_ms <= 0 {
|
||||
return Err(invalid("cooldown expiry must be positive"));
|
||||
}
|
||||
let mut connection = self.connection.clone();
|
||||
let written = if let Some(index_member) = index_member {
|
||||
WRITE_ACCOUNT
|
||||
.key(key)
|
||||
.key(self.active_index_key())
|
||||
.key(self.protection_key(index_member)?)
|
||||
.key(self.protection_index_key())
|
||||
.arg(credential_revision.get())
|
||||
.arg(until_ms)
|
||||
.arg(index_member)
|
||||
.arg(kind.as_str())
|
||||
.arg(uuid::Uuid::new_v4().to_string())
|
||||
.invoke_async::<i64>(&mut connection)
|
||||
.await
|
||||
} else {
|
||||
Script::new(WRITE_SCRIPT)
|
||||
.key(key)
|
||||
.arg(credential_revision.get())
|
||||
.arg(until_ms)
|
||||
.arg("")
|
||||
.arg(kind.as_str())
|
||||
.arg(uuid::Uuid::new_v4().to_string())
|
||||
.invoke_async::<i64>(&mut connection)
|
||||
.await
|
||||
}
|
||||
.map_err(|source| redis_unavailable("cache credential cooldown", source))?;
|
||||
Ok(written == 1)
|
||||
}
|
||||
|
||||
async fn read_scoped_key(&self, key: String) -> StoreResult<Option<(Revision, DateTime<Utc>)>> {
|
||||
let result = Script::new(READ_SCOPED)
|
||||
let written = WRITE_ACCOUNT
|
||||
.key(key)
|
||||
.invoke_async(&mut self.connection.clone())
|
||||
.await;
|
||||
parse_scoped_cooldown(
|
||||
result.map_err(|source| redis_unavailable("read credential cooldown", source))?,
|
||||
)
|
||||
.key(self.active_index_key())
|
||||
.key(self.protection_key(index_member)?)
|
||||
.key(self.protection_index_key())
|
||||
.arg(credential_revision.get())
|
||||
.arg(until_ms)
|
||||
.arg(index_member)
|
||||
.arg(kind.as_str())
|
||||
.arg(uuid::Uuid::new_v4().to_string())
|
||||
.invoke_async::<i64>(&mut connection)
|
||||
.await
|
||||
.map_err(|source| redis_unavailable("cache credential cooldown", source))?;
|
||||
Ok(written == 1)
|
||||
}
|
||||
|
||||
/// 保留每条命令的错误,脚本失效时只补发尚未执行的 NOSCRIPT 项
|
||||
@@ -294,26 +375,18 @@ impl RedisCredentialCooldownRepository {
|
||||
&self,
|
||||
key: String,
|
||||
through_revision: Revision,
|
||||
index_member: Option<&str>,
|
||||
index_key: String,
|
||||
index_member: &str,
|
||||
) -> StoreResult<bool> {
|
||||
let mut connection = self.connection.clone();
|
||||
let removed = if let Some(index_member) = index_member {
|
||||
Script::new(INVALIDATE_SCRIPT)
|
||||
.key(key)
|
||||
.key(self.active_index_key())
|
||||
.arg(through_revision.get())
|
||||
.arg(index_member)
|
||||
.invoke_async::<i64>(&mut connection)
|
||||
.await
|
||||
} else {
|
||||
Script::new(INVALIDATE_SCRIPT)
|
||||
.key(key)
|
||||
.arg(through_revision.get())
|
||||
.arg("")
|
||||
.invoke_async::<i64>(&mut connection)
|
||||
.await
|
||||
}
|
||||
.map_err(|source| redis_unavailable("invalidate credential cooldown", source))?;
|
||||
let removed = Script::new(INVALIDATE_SCRIPT)
|
||||
.key(key)
|
||||
.key(index_key)
|
||||
.arg(through_revision.get())
|
||||
.arg(index_member)
|
||||
.invoke_async::<i64>(&mut connection)
|
||||
.await
|
||||
.map_err(|source| redis_unavailable("invalidate credential cooldown", source))?;
|
||||
Ok(removed == 1)
|
||||
}
|
||||
|
||||
@@ -337,8 +410,16 @@ impl RedisCredentialCooldownRepository {
|
||||
}
|
||||
|
||||
pub(crate) async fn active_cooldowns(&self) -> StoreResult<AccountRuntimeSnapshot> {
|
||||
self.read_cooldown_accounts(self.all_cooldown_accounts().await?)
|
||||
let mut accounts = self.all_cooldown_accounts().await?;
|
||||
let model_accounts: Vec<String> = Script::new(ACTIVE_SCOPES)
|
||||
.key(self.active_model_index_key())
|
||||
.invoke_async(&mut self.connection.clone())
|
||||
.await
|
||||
.map_err(|source| redis_unavailable("list model cooldown accounts", source))?;
|
||||
accounts.extend(model_accounts);
|
||||
accounts.sort_unstable();
|
||||
accounts.dedup();
|
||||
self.read_cooldown_accounts(accounts).await
|
||||
}
|
||||
|
||||
pub(crate) async fn account_cooldowns(
|
||||
@@ -349,13 +430,16 @@ impl RedisCredentialCooldownRepository {
|
||||
return Ok(AccountRuntimeSnapshot::default());
|
||||
}
|
||||
// 索引与冷却事实由 Lua 原子维护,只读取范围内实际有状态的账号
|
||||
let (cooldowns, protections): (Vec<Option<f64>>, Vec<Option<f64>>) = redis::pipe()
|
||||
let [cooldowns, protections, models]: [Vec<Option<f64>>; 3] = redis::pipe()
|
||||
.cmd("ZMSCORE")
|
||||
.arg(self.active_index_key())
|
||||
.arg(accounts)
|
||||
.cmd("ZMSCORE")
|
||||
.arg(self.protection_index_key())
|
||||
.arg(accounts)
|
||||
.cmd("ZMSCORE")
|
||||
.arg(self.active_model_index_key())
|
||||
.arg(accounts)
|
||||
.query_async(&mut self.connection.clone())
|
||||
.await
|
||||
.map_err(|error| redis_unavailable("read scoped account cooldown index", error))?;
|
||||
@@ -363,8 +447,11 @@ impl RedisCredentialCooldownRepository {
|
||||
.iter()
|
||||
.zip(cooldowns)
|
||||
.zip(protections)
|
||||
.filter(|((_, cooldown), protection)| cooldown.is_some() || protection.is_some())
|
||||
.map(|((account, _), _)| account.clone())
|
||||
.zip(models)
|
||||
.filter(|(((_, cooldown), protection), model)| {
|
||||
cooldown.is_some() || protection.is_some() || model.is_some()
|
||||
})
|
||||
.map(|(((account, _), _), _)| account.clone())
|
||||
.collect();
|
||||
self.read_cooldown_accounts(active).await
|
||||
}
|
||||
@@ -376,15 +463,20 @@ impl RedisCredentialCooldownRepository {
|
||||
use futures::{StreamExt as _, TryStreamExt as _};
|
||||
let reads = futures::stream::iter(accounts)
|
||||
.map(|account| async move {
|
||||
self.read_account_runtime(&account)
|
||||
.await
|
||||
.map(|runtime| (account, runtime))
|
||||
let (runtime, models) = tokio::try_join!(
|
||||
self.read_account_runtime(&account),
|
||||
self.read_model_cooldowns(&account),
|
||||
)?;
|
||||
Ok((account, runtime, models))
|
||||
})
|
||||
.buffer_unordered(32)
|
||||
.try_collect::<Vec<_>>()
|
||||
.await?;
|
||||
let mut snapshot = AccountRuntimeSnapshot::default();
|
||||
for (account, (cooldown, freeze)) in reads {
|
||||
for (account, (cooldown, freeze), models) in reads {
|
||||
if !models.is_empty() {
|
||||
snapshot.model_cooldowns.insert(account.clone(), models);
|
||||
}
|
||||
if let Some(cooldown) = cooldown {
|
||||
snapshot.cooldown.insert(
|
||||
account.clone(),
|
||||
@@ -446,7 +538,7 @@ impl CredentialCooldownRepository for RedisCredentialCooldownRepository {
|
||||
cooldown.credential_revision,
|
||||
cooldown.cooldown_until,
|
||||
cooldown.kind,
|
||||
Some(&cooldown.provider_account_id),
|
||||
&cooldown.provider_account_id,
|
||||
)
|
||||
.await
|
||||
}
|
||||
@@ -480,7 +572,8 @@ impl CredentialCooldownRepository for RedisCredentialCooldownRepository {
|
||||
.invalidate_at_key(
|
||||
self.key(provider_account_id)?,
|
||||
through_revision,
|
||||
Some(provider_account_id),
|
||||
self.active_index_key(),
|
||||
provider_account_id,
|
||||
)
|
||||
.await?;
|
||||
Ok(protection_cleared || cooldown_cleared)
|
||||
@@ -530,6 +623,7 @@ impl CredentialCooldownRepository for RedisCredentialCooldownRepository {
|
||||
local removed = 0
|
||||
for i = 2, #KEYS do removed = removed + redis.call('DEL', KEYS[i]) end
|
||||
redis.call('ZREM', ARGV[2], ARGV[1])
|
||||
redis.call('ZREM', ARGV[3], ARGV[1])
|
||||
return removed + redis.call('ZREM', KEYS[1], ARGV[1])
|
||||
"#,
|
||||
)
|
||||
@@ -537,6 +631,7 @@ impl CredentialCooldownRepository for RedisCredentialCooldownRepository {
|
||||
.key(keys)
|
||||
.arg(provider_account_id)
|
||||
.arg(self.protection_index_key())
|
||||
.arg(self.active_model_index_key())
|
||||
.invoke_async(&mut connection)
|
||||
.await
|
||||
.map_err(|source| redis_unavailable("delete account cooldowns and index", source))?;
|
||||
@@ -686,18 +781,37 @@ impl ProviderCooldownPort for RedisCredentialCooldownRepository {
|
||||
Box::pin(async move {
|
||||
let revision = Revision::new(cooldown.credential_revision().get())
|
||||
.map_err(|_| provider_invalid("encode scoped credential cooldown"))?;
|
||||
self.cache_at_key(
|
||||
self.scoped_key(cooldown.account_id().as_str(), cooldown.scope())
|
||||
.map_err(|_| provider_invalid("encode scoped credential cooldown"))?,
|
||||
revision,
|
||||
cooldown.until().into(),
|
||||
ProviderCooldownKind::RateLimit,
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.map_err(|source| {
|
||||
crate::provider_unavailable("cache scoped credential cooldown", source)
|
||||
})
|
||||
let account = cooldown.account_id().as_str();
|
||||
let key = self
|
||||
.scoped_key(account, cooldown.scope())
|
||||
.map_err(|_| provider_invalid("encode scoped credential cooldown"))?;
|
||||
let index = self
|
||||
.model_index_key(account)
|
||||
.map_err(|_| provider_invalid("encode model cooldown index"))?;
|
||||
let until: DateTime<Utc> = cooldown.until().into();
|
||||
let written: i64 = Script::new(WRITE_SCOPED)
|
||||
.key(key)
|
||||
.key(index)
|
||||
.key(self.active_model_index_key())
|
||||
.arg(revision.get())
|
||||
.arg(until.timestamp_millis())
|
||||
.arg(cooldown.scope().value())
|
||||
.arg(
|
||||
cooldown
|
||||
.rate_limited_until()
|
||||
.map(DateTime::<Utc>::from)
|
||||
.map_or(0, |time| time.timestamp_millis()),
|
||||
)
|
||||
.arg(account)
|
||||
.invoke_async(&mut self.connection.clone())
|
||||
.await
|
||||
.map_err(|source| {
|
||||
crate::provider_unavailable(
|
||||
"cache scoped credential cooldown",
|
||||
redis_unavailable("write model cooldown", source),
|
||||
)
|
||||
})?;
|
||||
Ok(written == 1)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -708,24 +822,18 @@ impl ProviderCooldownPort for RedisCredentialCooldownRepository {
|
||||
) -> futures::future::BoxFuture<'a, Result<Option<ProviderScopedCooldown>, ProviderStoreError>>
|
||||
{
|
||||
Box::pin(async move {
|
||||
self.read_scoped_key(
|
||||
self.scoped_key(account_id.as_str(), scope)
|
||||
.map_err(|_| provider_invalid("encode scoped credential cooldown"))?,
|
||||
)
|
||||
.await
|
||||
.map_err(|source| {
|
||||
let key = self
|
||||
.scoped_key(account_id.as_str(), scope)
|
||||
.map_err(|_| provider_invalid("encode scoped credential cooldown"))?;
|
||||
let value = Script::new(READ_SCOPED)
|
||||
.key(key)
|
||||
.invoke_async(&mut self.connection.clone())
|
||||
.await
|
||||
.map_err(|source| redis_unavailable("read scoped cooldown", source))
|
||||
.and_then(|value| parse_scoped_cooldown(value, account_id, scope));
|
||||
value.map_err(|source| {
|
||||
crate::provider_unavailable("read scoped credential cooldown", source)
|
||||
})?
|
||||
.map(|(revision, until)| {
|
||||
Ok(ProviderScopedCooldown::new(
|
||||
account_id.clone(),
|
||||
CredentialRevision::new(revision.get())
|
||||
.map_err(|_| provider_invalid("decode scoped credential cooldown"))?,
|
||||
scope.clone(),
|
||||
until.into(),
|
||||
))
|
||||
})
|
||||
.transpose()
|
||||
})
|
||||
}
|
||||
|
||||
@@ -754,28 +862,16 @@ impl ProviderCooldownPort for RedisCredentialCooldownRepository {
|
||||
.collect();
|
||||
let values = self.read_script_batch(&script, commands).await;
|
||||
results.extend(batch.iter().zip(values).map(|(account, value)| {
|
||||
let value = value
|
||||
value
|
||||
.and_then(|value| {
|
||||
redis::from_redis_value(value).map_err(|source| {
|
||||
redis_unavailable("decode scoped cooldown", source)
|
||||
})
|
||||
})
|
||||
.and_then(parse_scoped_cooldown)
|
||||
.and_then(|value| parse_scoped_cooldown(value, account, scope))
|
||||
.map_err(|source| {
|
||||
crate::provider_unavailable("read scoped credential cooldown", source)
|
||||
})?;
|
||||
value
|
||||
.map(|(revision, until)| {
|
||||
Ok(ProviderScopedCooldown::new(
|
||||
account.clone(),
|
||||
CredentialRevision::new(revision.get()).map_err(|_| {
|
||||
provider_invalid("decode scoped credential cooldown")
|
||||
})?,
|
||||
scope.clone(),
|
||||
until.into(),
|
||||
))
|
||||
})
|
||||
.transpose()
|
||||
}));
|
||||
}
|
||||
results
|
||||
@@ -795,7 +891,9 @@ impl ProviderCooldownPort for RedisCredentialCooldownRepository {
|
||||
self.scoped_key(account_id.as_str(), scope)
|
||||
.map_err(|_| provider_invalid("encode scoped credential cooldown"))?,
|
||||
revision,
|
||||
None,
|
||||
self.model_index_key(account_id.as_str())
|
||||
.map_err(|_| provider_invalid("encode model cooldown index"))?,
|
||||
scope.value(),
|
||||
)
|
||||
.await
|
||||
.map_err(|source| {
|
||||
@@ -858,21 +956,35 @@ pub(super) fn invalid(message: &str) -> StoreError {
|
||||
}
|
||||
}
|
||||
|
||||
type ScopedCooldownReply = (i64, String, i64, i64);
|
||||
|
||||
fn parse_scoped_cooldown(
|
||||
(present, revision, until_ms): (i64, String, String),
|
||||
) -> StoreResult<Option<(Revision, DateTime<Utc>)>> {
|
||||
(present, revision, until_ms, limited_ms): ScopedCooldownReply,
|
||||
account: &ProviderAccountId,
|
||||
scope: &ProviderCooldownScope,
|
||||
) -> StoreResult<Option<ProviderScopedCooldown>> {
|
||||
if present == 0 {
|
||||
return Ok(None);
|
||||
}
|
||||
let revision = revision
|
||||
.parse::<u64>()
|
||||
.map_err(|source| invalid("cached cooldown revision is invalid").with_source(source))?;
|
||||
let until_ms = until_ms
|
||||
.parse::<i64>()
|
||||
.map_err(|source| invalid("cached cooldown expiry is invalid").with_source(source))?;
|
||||
let cooldown_until = DateTime::from_timestamp_millis(until_ms)
|
||||
.ok_or_else(|| invalid("cached cooldown expiry is invalid"))?;
|
||||
Ok(Some((Revision::new(revision)?, cooldown_until)))
|
||||
let revision =
|
||||
CredentialRevision::new(revision).map_err(|_| invalid("invalid cooldown revision"))?;
|
||||
let deadline = |ms| {
|
||||
DateTime::from_timestamp_millis(ms)
|
||||
.map(SystemTime::from)
|
||||
.ok_or_else(|| invalid("cached cooldown expiry is invalid"))
|
||||
};
|
||||
Ok(Some(
|
||||
ProviderScopedCooldown::new(
|
||||
account.clone(),
|
||||
revision,
|
||||
scope.clone(),
|
||||
deadline(until_ms)?,
|
||||
)
|
||||
.with_rate_limited_until((limited_ms > 0).then(|| deadline(limited_ms)).transpose()?),
|
||||
))
|
||||
}
|
||||
|
||||
fn provider_cooldown(record: CredentialCooldown) -> Result<ProviderCooldown, ProviderStoreError> {
|
||||
|
||||
@@ -62,6 +62,23 @@ async fn recovery_loads_precise_window_and_running_request_facts() {
|
||||
.await
|
||||
.expect("remove missing lease fixture");
|
||||
|
||||
seed_request(
|
||||
&database.pool,
|
||||
"nested-child",
|
||||
now - Duration::seconds(8),
|
||||
now + Duration::seconds(30),
|
||||
"running",
|
||||
)
|
||||
.await;
|
||||
sqlx::query(
|
||||
"update model_requests set client_transport = 'internal_plugin',
|
||||
request_kind = case id when 'recent-running' then 'plugin_bound_model' else 'plugin_child_model' end
|
||||
where id in ('nested-child', 'recent-running')",
|
||||
)
|
||||
.execute(&database.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let repository = PgClientAdmissionRecoveryRepository::new(database.pool.clone());
|
||||
let actual = repository
|
||||
.load_client_admission_recovery(window_started_at)
|
||||
|
||||
@@ -2,6 +2,76 @@
|
||||
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn model_cooldown_status_filter_and_details_share_revision_and_expiry_rules() {
|
||||
use gateway_core::provider_ports::{ProviderCooldownScope, ProviderScopedCooldown};
|
||||
let Some(database) = TestDatabase::create("account_model_cooldown").await else {
|
||||
return;
|
||||
};
|
||||
let repository = PgProviderAccountRepository::new(database.pool.clone());
|
||||
let ids = ["acct_active", "acct_stale", "acct_expired", "acct_disabled"];
|
||||
for id in ids {
|
||||
let mut record = account(id, id);
|
||||
record.enabled = id != "acct_disabled";
|
||||
repository.insert_provider_account(record).await.unwrap();
|
||||
}
|
||||
let mut runtime = AccountRuntimeSnapshot::default();
|
||||
for id in ids {
|
||||
let stored = repository.load_provider_account(id).await.unwrap().unwrap();
|
||||
let revision = stored.summary.credential_revision.get();
|
||||
let revision = if id == "acct_stale" {
|
||||
revision + 1
|
||||
} else {
|
||||
revision
|
||||
};
|
||||
let until = Utc::now() + TimeDelta::seconds(if id == "acct_expired" { -1 } else { 60 });
|
||||
runtime.model_cooldowns.insert(
|
||||
id.into(),
|
||||
vec![ProviderScopedCooldown::new(
|
||||
ProviderAccountId::new(id).unwrap(),
|
||||
gateway_core::account::CredentialRevision::new(revision).unwrap(),
|
||||
ProviderCooldownScope::upstream_model(
|
||||
gateway_core::routing::UpstreamModelId::new("gpt-5.4").unwrap(),
|
||||
),
|
||||
until.into(),
|
||||
)],
|
||||
);
|
||||
}
|
||||
let store = admin_account_store(&database.pool);
|
||||
let page = store
|
||||
.list_accounts(
|
||||
AccountListQuery {
|
||||
page: 1,
|
||||
page_size: PageSize::new(20).unwrap(),
|
||||
provider_kind: None,
|
||||
group_filter: None,
|
||||
search: None,
|
||||
status: Some(AccountStatus::RateLimited),
|
||||
sort: None,
|
||||
},
|
||||
runtime.clone(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(page.total, 1);
|
||||
assert_eq!(page.summary.rate_limited, 1);
|
||||
assert_eq!(page.summary.normal, 2);
|
||||
assert_eq!(page.summary.disabled, 1);
|
||||
let item = &page.items[0];
|
||||
assert_eq!(item.account.id, "acct_active");
|
||||
assert_eq!(item.projection.status, AccountStatus::RateLimited);
|
||||
assert!(item.projection.cooldown.is_none());
|
||||
assert_eq!(item.model_cooldowns.len(), 1);
|
||||
let detail = store
|
||||
.load_account("acct_active", runtime)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(detail.projection, item.projection);
|
||||
assert_eq!(detail.model_cooldowns, item.model_cooldowns);
|
||||
database.close().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn import_name_only_overrides_a_single_account_and_keeps_batch_names() {
|
||||
use gateway_admin::model::accounts::AccountImportSettings;
|
||||
|
||||
@@ -940,6 +940,7 @@ async fn terminal_admin_list_filters_and_sorts_before_pagination_with_retained_u
|
||||
sort: None,
|
||||
},
|
||||
AccountRuntimeSnapshot {
|
||||
model_cooldowns: BTreeMap::new(),
|
||||
protection_rules: std::collections::BTreeMap::new(),
|
||||
cooldown: BTreeMap::from([(
|
||||
"acct_alpha".to_owned(),
|
||||
|
||||
@@ -18,11 +18,19 @@ fn client_admission_rejects_zero_ttl() {
|
||||
assert!(request.validate().is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn client_admission_rejects_values_outside_redis_exact_integer_range() {
|
||||
let mut request = admission_request("request-1", "key-1", Duration::from_secs(30));
|
||||
#[tokio::test]
|
||||
async fn configured_limits_above_lua_integer_precision_allow_requests() {
|
||||
let Some((repository, mut connection, namespace)) = repository().await else {
|
||||
return;
|
||||
};
|
||||
let mut request = admission_request("req_large_limits", "key-1", Duration::from_secs(30));
|
||||
request.limits.max_concurrency = 1_u64 << 53;
|
||||
assert!(request.validate().is_err());
|
||||
request.limits.requests_per_minute = i64::MAX as u64;
|
||||
assert_eq!(
|
||||
repository.admit_client_request(&request).await.unwrap(),
|
||||
ClientAdmissionDecision::Granted
|
||||
);
|
||||
delete_namespace_keys(&mut connection, &namespace).await;
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -313,7 +313,12 @@ async fn scoped_cooldown_isolated_by_model_and_revision_fenced() {
|
||||
.is_some()
|
||||
);
|
||||
let keys = namespace_keys(&mut connection, &namespace).await;
|
||||
assert_eq!(keys.len(), 1);
|
||||
assert_eq!(
|
||||
keys.iter()
|
||||
.filter(|key| key.contains(":cooldown:model:"))
|
||||
.count(),
|
||||
1
|
||||
);
|
||||
assert!(!keys[0].contains(account_id.as_str()));
|
||||
assert!(!keys[0].contains(model_b.value()));
|
||||
}
|
||||
@@ -516,6 +521,142 @@ fn runtime_store(
|
||||
)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn model_cooldowns_are_visible_in_runtime_without_blocking_the_entire_account() {
|
||||
use gateway_admin::ports::store::AccountRuntimeStore as _;
|
||||
let Some((repository, connection, namespace)) = repository().await else {
|
||||
return;
|
||||
};
|
||||
let runtime = runtime_store(&repository, connection, &namespace);
|
||||
let id = ProviderAccountId::new("acct_model_limit").unwrap();
|
||||
let revision = CredentialRevision::new(1).unwrap();
|
||||
let models = ["gpt-5.4", "gpt-5.5"].map(|model| {
|
||||
ProviderCooldownScope::upstream_model(
|
||||
gateway_core::routing::UpstreamModelId::new(model).unwrap(),
|
||||
)
|
||||
});
|
||||
let until: SystemTime = millisecond_precision(Utc::now() + Duration::seconds(60)).into();
|
||||
// 不支持的模型仍影响选号,但不能让目录误报限流;两种期限可重叠
|
||||
let unsupported_until = until + std::time::Duration::from_secs(1800);
|
||||
repository
|
||||
.put_scoped_if_later(ProviderScopedCooldown::new(
|
||||
id.clone(),
|
||||
revision,
|
||||
models[0].clone(),
|
||||
unsupported_until,
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
runtime
|
||||
.active_rate_limits()
|
||||
.await
|
||||
.unwrap()
|
||||
.model_cooldowns
|
||||
.is_empty()
|
||||
);
|
||||
for scope in &models {
|
||||
repository
|
||||
.put_scoped_if_later(
|
||||
ProviderScopedCooldown::new(id.clone(), revision, scope.clone(), until)
|
||||
.with_rate_limited_until(Some(until)),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
repository.clear_after_success(&id, revision).await.unwrap();
|
||||
let snapshot = runtime.active_rate_limits().await.unwrap();
|
||||
assert!(snapshot.cooldown.is_empty());
|
||||
assert_eq!(snapshot.model_cooldowns[id.as_str()].len(), 2);
|
||||
assert!(
|
||||
snapshot.model_cooldowns[id.as_str()]
|
||||
.iter()
|
||||
.all(|model| model.until() == until)
|
||||
);
|
||||
assert_eq!(
|
||||
repository
|
||||
.read_scoped(&id, &models[0])
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.until(),
|
||||
unsupported_until
|
||||
);
|
||||
let scoped = runtime
|
||||
.account_rate_limits(&[id.to_string()])
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(scoped.model_cooldowns, snapshot.model_cooldowns);
|
||||
repository
|
||||
.clear_scoped(&id, &models[0], revision)
|
||||
.await
|
||||
.unwrap();
|
||||
let snapshot = runtime.active_rate_limits().await.unwrap();
|
||||
assert_eq!(snapshot.model_cooldowns[id.as_str()].len(), 1);
|
||||
assert_eq!(snapshot.model_cooldowns[id.as_str()][0].scope(), &models[1]);
|
||||
repository
|
||||
.delete_account_cooldowns(id.as_str())
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
runtime
|
||||
.active_rate_limits()
|
||||
.await
|
||||
.unwrap()
|
||||
.model_cooldowns
|
||||
.is_empty()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn expired_model_cooldown_disappears_from_the_directory_even_during_redis_grace() {
|
||||
use gateway_admin::ports::store::AccountRuntimeStore as _;
|
||||
let Some((repository, mut connection, namespace)) = repository().await else {
|
||||
return;
|
||||
};
|
||||
let runtime = runtime_store(&repository, connection.clone(), &namespace);
|
||||
let id = ProviderAccountId::new("acct_model_expired").unwrap();
|
||||
let until = (Utc::now() + Duration::minutes(1)).into();
|
||||
repository
|
||||
.put_scoped_if_later(
|
||||
ProviderScopedCooldown::new(
|
||||
id.clone(),
|
||||
CredentialRevision::new(1).unwrap(),
|
||||
ProviderCooldownScope::upstream_model(
|
||||
gateway_core::routing::UpstreamModelId::new("gpt-5.4").unwrap(),
|
||||
),
|
||||
until,
|
||||
)
|
||||
.with_rate_limited_until(Some(until)),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let key = namespace_keys(&mut connection, &namespace)
|
||||
.await
|
||||
.into_iter()
|
||||
.find(|key| key.contains(":cooldown:model:"))
|
||||
.unwrap();
|
||||
redis::cmd("HSET")
|
||||
.arg(key)
|
||||
.arg("until_ms")
|
||||
.arg(Utc::now().timestamp_millis() - 1000)
|
||||
.query_async::<i64>(&mut connection)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
runtime
|
||||
.active_rate_limits()
|
||||
.await
|
||||
.unwrap()
|
||||
.model_cooldowns
|
||||
.is_empty()
|
||||
);
|
||||
repository
|
||||
.delete_account_cooldowns(id.as_str())
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn capacity_freeze_survives_due_time_and_runtime_restart_until_probe_succeeds() {
|
||||
use gateway_admin::ports::store::AccountRuntimeStore as _;
|
||||
|
||||
@@ -9,17 +9,23 @@ mod transport;
|
||||
|
||||
use gateway_admin::ports::provider::ProviderBundle;
|
||||
use gateway_core::{provider_ports::ProviderStorePorts, routing::ProviderKind};
|
||||
use std::sync::Arc;
|
||||
use std::{path::PathBuf, sync::Arc};
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
#[error("Antigravity Provider 初始化失败")]
|
||||
pub struct ConfigError;
|
||||
|
||||
pub async fn initialize(ports: ProviderStorePorts) -> Result<ProviderBundle, ConfigError> {
|
||||
pub async fn initialize(
|
||||
ports: ProviderStorePorts,
|
||||
artifact_dir: PathBuf,
|
||||
) -> Result<ProviderBundle, ConfigError> {
|
||||
let kind = ProviderKind::new("antigravity").map_err(|_| ConfigError)?;
|
||||
let oauth = Arc::new(credential::GoogleOAuth::for_provider()?);
|
||||
let origin = oauth.resource_origin().clone();
|
||||
let release = Arc::new(profile::ReleaseService::new(ports.artifact_profiles())?);
|
||||
let release = Arc::new(profile::ReleaseService::new(
|
||||
ports.artifact_profiles(),
|
||||
artifact_dir,
|
||||
)?);
|
||||
release.restore().await;
|
||||
let credentials = Arc::new(credential::CredentialService::new(
|
||||
kind.clone(),
|
||||
|
||||
@@ -308,6 +308,7 @@ pub(crate) async fn download(
|
||||
client: &Client,
|
||||
url: &str,
|
||||
sha512: Option<&str>,
|
||||
artifact_dir: &std::path::Path,
|
||||
) -> Result<std::fs::File, WorkerTaskError> {
|
||||
let mut response = client
|
||||
.get(url)
|
||||
@@ -323,7 +324,11 @@ pub(crate) async fn download(
|
||||
{
|
||||
return Err(invalid());
|
||||
}
|
||||
let file = tempfile::tempfile().map_err(|e| invalid().with_source(e))?;
|
||||
// 官方包可能大于容器的 /tmp;匿名文件随句柄释放,失败和取消也不会留下半包。
|
||||
tokio::fs::create_dir_all(artifact_dir)
|
||||
.await
|
||||
.map_err(|e| invalid().with_source(e))?;
|
||||
let file = tempfile::tempfile_in(artifact_dir).map_err(|e| invalid().with_source(e))?;
|
||||
let mut file = tokio::fs::File::from_std(file);
|
||||
let mut count = 0u64;
|
||||
let mut digest = Sha512::new();
|
||||
|
||||
@@ -23,6 +23,7 @@ pub(crate) async fn verify(
|
||||
version: &str,
|
||||
url: &str,
|
||||
sha512: Option<&str>,
|
||||
artifact_dir: &std::path::Path,
|
||||
) -> Result<u64, WorkerTaskError> {
|
||||
match (target.client, target.platform) {
|
||||
(ClientKind::Desktop, Platform::Macos) => {
|
||||
@@ -50,7 +51,7 @@ pub(crate) async fn verify(
|
||||
.await
|
||||
}
|
||||
_ => {
|
||||
let file = download(client, url, sha512).await?;
|
||||
let file = download(client, url, sha512, artifact_dir).await?;
|
||||
// 取消 worker 时同步中止阻塞解包,临时文件由解析任务退出时关闭
|
||||
let (file, _guard) = CancellableFile::new(file);
|
||||
let version = version.to_owned();
|
||||
|
||||
@@ -13,6 +13,7 @@ use gateway_core::{provider_ports::ProviderArtifactProfileCachePort, routing::Pr
|
||||
use serde::Deserialize;
|
||||
use std::{
|
||||
collections::{BTreeMap, BTreeSet},
|
||||
path::PathBuf,
|
||||
sync::{Arc, Mutex, RwLock},
|
||||
time::Duration,
|
||||
};
|
||||
@@ -74,6 +75,7 @@ pub(crate) struct ReleaseService {
|
||||
impl ReleaseService {
|
||||
pub(crate) fn new(
|
||||
cache: Arc<dyn ProviderArtifactProfileCachePort>,
|
||||
artifact_dir: PathBuf,
|
||||
) -> Result<Self, ConfigError> {
|
||||
let client = gateway_egress::http_client(None)
|
||||
.map_err(|_| ConfigError)?
|
||||
@@ -89,6 +91,7 @@ impl ReleaseService {
|
||||
verification: VerificationCache::new(
|
||||
ProviderKind::new("antigravity").map_err(|_| ConfigError)?,
|
||||
cache,
|
||||
artifact_dir,
|
||||
),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ use gateway_core::{
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{
|
||||
path::PathBuf,
|
||||
sync::Arc,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
@@ -39,13 +40,19 @@ struct Payload {
|
||||
pub(crate) struct VerificationCache {
|
||||
provider: ProviderKind,
|
||||
cache: Arc<dyn ProviderArtifactProfileCachePort>,
|
||||
artifact_dir: PathBuf,
|
||||
}
|
||||
impl VerificationCache {
|
||||
pub(crate) fn new(
|
||||
provider: ProviderKind,
|
||||
cache: Arc<dyn ProviderArtifactProfileCachePort>,
|
||||
artifact_dir: PathBuf,
|
||||
) -> Self {
|
||||
Self { provider, cache }
|
||||
Self {
|
||||
provider,
|
||||
cache,
|
||||
artifact_dir,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn load(
|
||||
@@ -117,6 +124,7 @@ impl VerificationCache {
|
||||
&release.version,
|
||||
&release.url,
|
||||
release.sha512.as_deref(),
|
||||
&self.artifact_dir,
|
||||
)
|
||||
.await?;
|
||||
(Utc::now(), changelist)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! 为 Claude 原生生成补齐能唯一配对的工具 ID,保留其余原始 JSON 字节
|
||||
//! 按 GenAI 工具关联规则为 Claude 原生生成补齐 ID,保留其余原始 JSON 字节
|
||||
|
||||
use std::{borrow::Cow, collections::BTreeMap};
|
||||
|
||||
@@ -83,15 +83,14 @@ fn tools<'a>(content: &Content<'a>) -> Option<Vec<Tool<'a>>> {
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Pair {
|
||||
call: Option<usize>,
|
||||
response: Option<usize>,
|
||||
ambiguous: bool,
|
||||
struct ToolGroup<'a> {
|
||||
calls: Vec<&'a Tool<'a>>,
|
||||
responses: Vec<&'a Tool<'a>>,
|
||||
}
|
||||
|
||||
pub(super) fn repair(body: Box<RawValue>) -> Result<Box<RawValue>, serde_json::Error> {
|
||||
// AGY CLI 1.5.20 的 convertToVertexV1 清空两侧 ID,见 #807
|
||||
// https://github.com/zyycn/codex-proxy-rs/issues/807
|
||||
// AGY CLI / ACP 1.5.24 的 Gateway/GenAI 路径仍清空两侧 ID,见 #807、#848
|
||||
// https://github.com/zyycn/codex-proxy-rs/issues/848
|
||||
// 客户端恢复保留 ID 后移除此补偿;不为格式错误或有歧义的历史猜测关联
|
||||
let Ok(request) = serde_json::from_str::<Request<'_>>(body.get()) else {
|
||||
return Ok(body);
|
||||
@@ -118,48 +117,62 @@ pub(super) fn repair(body: Box<RawValue>) -> Result<Box<RawValue>, serde_json::E
|
||||
}
|
||||
let calls = &turns[turn];
|
||||
let responses = &turns[turn + 1];
|
||||
let mut pairs = BTreeMap::<&str, Pair>::new();
|
||||
for (index, call) in calls.iter().enumerate() {
|
||||
let pair = pairs.entry(&call.name).or_default();
|
||||
pair.ambiguous |= pair.call.replace(index).is_some();
|
||||
let mut groups = BTreeMap::<&str, ToolGroup<'_>>::new();
|
||||
for call in calls {
|
||||
groups.entry(&call.name).or_default().calls.push(call);
|
||||
}
|
||||
for (index, response) in responses.iter().enumerate() {
|
||||
let pair = pairs.entry(&response.name).or_default();
|
||||
pair.ambiguous |= pair.response.replace(index).is_some();
|
||||
for response in responses {
|
||||
groups
|
||||
.entry(&response.name)
|
||||
.or_default()
|
||||
.responses
|
||||
.push(response);
|
||||
}
|
||||
for pair in pairs.values().filter(|pair| !pair.ambiguous) {
|
||||
let (Some(call), Some(response)) = (pair.call, pair.response) else {
|
||||
for group in groups.values() {
|
||||
if group.calls.len() != group.responses.len() {
|
||||
continue;
|
||||
};
|
||||
let (call, response) = (&calls[call], &responses[response]);
|
||||
let id = match (call.id.as_deref(), response.id.as_deref()) {
|
||||
(Some(_), Some(_)) => continue,
|
||||
(Some(id), None) | (None, Some(id)) => {
|
||||
if ids.get(id) != Some(&1) {
|
||||
continue;
|
||||
}
|
||||
id.to_owned()
|
||||
}
|
||||
(None, None) => {
|
||||
// 轮次与 part 位置使追加历史和重试保持稳定;同时避开客户端已有 ID
|
||||
let mut id = format!("toolu_cpr_{turn}_{}", call.part);
|
||||
while ids.contains_key(id.as_str()) {
|
||||
id.push('_');
|
||||
}
|
||||
id
|
||||
}
|
||||
};
|
||||
ids.insert(Cow::Owned(id.clone()), 2);
|
||||
let insertion = format!(",\"id\":{}", serde_json::to_string(&id)?);
|
||||
for tool in [call, response]
|
||||
.into_iter()
|
||||
.filter(|tool| tool.id.is_none())
|
||||
}
|
||||
// GenAI 无 ID 时按同名出现顺序配对;混有 ID 时可能按 ID 重排,不能套用顺序
|
||||
// https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/tools/function-calling#parallel_function_calling
|
||||
if group.calls.len() > 1
|
||||
&& group
|
||||
.calls
|
||||
.iter()
|
||||
.chain(&group.responses)
|
||||
.any(|tool| tool.id.is_some())
|
||||
{
|
||||
// RawValue 来自同一正文,插入点由解析器确定,不重编码参数、结果或签名
|
||||
let end = tool.raw.get().as_ptr() as usize - body.get().as_ptr() as usize
|
||||
+ tool.raw.get().len()
|
||||
- 1;
|
||||
insertions.insert(end, insertion.clone());
|
||||
continue;
|
||||
}
|
||||
for (call, response) in group.calls.iter().zip(&group.responses) {
|
||||
let id = match (call.id.as_deref(), response.id.as_deref()) {
|
||||
(Some(_), Some(_)) => continue,
|
||||
(Some(id), None) | (None, Some(id)) => {
|
||||
if ids.get(id) != Some(&1) {
|
||||
continue;
|
||||
}
|
||||
id.to_owned()
|
||||
}
|
||||
(None, None) => {
|
||||
// 轮次与 part 位置使追加历史和重试保持稳定;同时避开客户端已有 ID
|
||||
let mut id = format!("toolu_cpr_{turn}_{}", call.part);
|
||||
while ids.contains_key(id.as_str()) {
|
||||
id.push('_');
|
||||
}
|
||||
id
|
||||
}
|
||||
};
|
||||
ids.insert(Cow::Owned(id.clone()), 2);
|
||||
let insertion = format!(",\"id\":{}", serde_json::to_string(&id)?);
|
||||
for tool in [call, response]
|
||||
.into_iter()
|
||||
.filter(|tool| tool.id.is_none())
|
||||
{
|
||||
// RawValue 来自同一正文,插入点由解析器确定,不重编码参数、结果或签名
|
||||
let end = tool.raw.get().as_ptr() as usize - body.get().as_ptr() as usize
|
||||
+ tool.raw.get().len()
|
||||
- 1;
|
||||
insertions.insert(end, insertion.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -46,7 +46,11 @@ pub(super) async fn fixture() -> (MockServer, CredentialService, Arc<MemoryPorts
|
||||
runtime_policy: store.clone(),
|
||||
credential_state: store.clone(),
|
||||
release: Arc::new(
|
||||
crate::profile::ReleaseService::new(crate::support::profile::cache()).unwrap(),
|
||||
crate::profile::ReleaseService::new(
|
||||
crate::support::profile::cache(),
|
||||
std::env::temp_dir(),
|
||||
)
|
||||
.unwrap(),
|
||||
),
|
||||
oauth: Arc::new(GoogleOAuth::with_endpoints(
|
||||
config,
|
||||
|
||||
@@ -103,15 +103,31 @@ async fn complete_download_requires_the_manifest_digest() {
|
||||
let server = serve(body.to_vec(), "").await;
|
||||
let client = reqwest::Client::new();
|
||||
let digest = hex::encode(Sha512::digest(body));
|
||||
let file = download(&client, &server.uri(), Some(&digest))
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let artifact_dir = root.path().join("antigravity");
|
||||
let file = download(&client, &server.uri(), Some(&digest), &artifact_dir)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(file.metadata().unwrap().len(), body.len() as u64);
|
||||
drop(file);
|
||||
assert_eq!(std::fs::read_dir(&artifact_dir).unwrap().count(), 0);
|
||||
let blocked = root.path().join("file");
|
||||
std::fs::write(&blocked, b"").unwrap();
|
||||
assert!(
|
||||
download(&client, &server.uri(), Some(&"0".repeat(128)))
|
||||
download(&client, &server.uri(), Some(&digest), &blocked)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
download(
|
||||
&client,
|
||||
&server.uri(),
|
||||
Some(&"0".repeat(128)),
|
||||
&artifact_dir
|
||||
)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -27,7 +27,7 @@ fn fixture_release(server: &wiremock::MockServer, version: &str) -> Release {
|
||||
async fn cache_restore_and_renewal_preserve_verification_without_downloading_again() {
|
||||
let server = super::archive::serve(super::artifact::desktop_zip("2.35.1"), "").await;
|
||||
let cache = cache();
|
||||
let service = VerificationCache::new(provider(), cache.clone());
|
||||
let service = VerificationCache::new(provider(), cache.clone(), std::env::temp_dir());
|
||||
let client = reqwest::Client::new();
|
||||
let target = Selection::default().target();
|
||||
let release = fixture_release(&server, "2.35.1");
|
||||
@@ -42,7 +42,7 @@ async fn cache_restore_and_renewal_preserve_verification_without_downloading_aga
|
||||
.unwrap();
|
||||
assert_eq!(same.verified_at, first.verified_at);
|
||||
assert_eq!(cache.writes.load(Ordering::SeqCst), 1);
|
||||
let restarted = VerificationCache::new(provider(), cache.clone());
|
||||
let restarted = VerificationCache::new(provider(), cache.clone(), std::env::temp_dir());
|
||||
let restored = restarted.load(target).await.unwrap().unwrap();
|
||||
assert_eq!(restored.verified_at, first.verified_at);
|
||||
assert_eq!(first.changelist, 1_234_567_890);
|
||||
@@ -50,7 +50,7 @@ async fn cache_restore_and_renewal_preserve_verification_without_downloading_aga
|
||||
assert_eq!(cache.writes.load(Ordering::SeqCst), 1);
|
||||
assert_eq!(server.received_requests().await.unwrap().len(), requests);
|
||||
|
||||
let releases = ReleaseService::new(cache.clone()).unwrap();
|
||||
let releases = ReleaseService::new(cache.clone(), std::env::temp_dir()).unwrap();
|
||||
releases.restore().await;
|
||||
let restored = dashboard(&Selection::default(), &releases);
|
||||
assert_eq!(restored.version, release.version);
|
||||
@@ -79,7 +79,7 @@ async fn latest_profile_switches_version_and_changelist_only_after_verified_publ
|
||||
)
|
||||
.await;
|
||||
let cache = cache();
|
||||
let service = VerificationCache::new(provider(), cache.clone());
|
||||
let service = VerificationCache::new(provider(), cache.clone(), std::env::temp_dir());
|
||||
let target = Selection::default().target();
|
||||
let client = reqwest::Client::new();
|
||||
let old = service
|
||||
@@ -92,7 +92,7 @@ async fn latest_profile_switches_version_and_changelist_only_after_verified_publ
|
||||
.await
|
||||
.unwrap();
|
||||
let new_release = fixture_release(&new_server, "2.36.0");
|
||||
let releases = ReleaseService::new(cache.clone()).unwrap();
|
||||
let releases = ReleaseService::new(cache.clone(), std::env::temp_dir()).unwrap();
|
||||
releases.restore().await;
|
||||
let before = dashboard(&Selection::default(), &releases);
|
||||
let frozen = default_profile(&releases).frozen();
|
||||
@@ -131,7 +131,7 @@ async fn latest_profile_switches_version_and_changelist_only_after_verified_publ
|
||||
async fn changed_artifact_or_target_and_failed_cache_do_not_publish_verification() {
|
||||
let server = super::archive::serve(super::artifact::desktop_zip("2.35.1"), "").await;
|
||||
let cache = cache();
|
||||
let service = VerificationCache::new(provider(), cache.clone());
|
||||
let service = VerificationCache::new(provider(), cache.clone(), std::env::temp_dir());
|
||||
let client = reqwest::Client::new();
|
||||
let target = Selection::default().target();
|
||||
let release = fixture_release(&server, "2.35.1");
|
||||
@@ -189,7 +189,7 @@ async fn changed_artifact_or_target_and_failed_cache_do_not_publish_verification
|
||||
async fn version_disagreement_leaves_the_previous_cache_intact() {
|
||||
let server = super::archive::serve(super::artifact::desktop_zip("2.35.1"), "").await;
|
||||
let cache = cache();
|
||||
let service = VerificationCache::new(provider(), cache.clone());
|
||||
let service = VerificationCache::new(provider(), cache.clone(), std::env::temp_dir());
|
||||
let client = reqwest::Client::new();
|
||||
let target = Selection::default().target();
|
||||
let release = fixture_release(&server, "2.35.1");
|
||||
|
||||
@@ -67,7 +67,7 @@ async fn middleware_business_headers_survive_without_overriding_frozen_authentic
|
||||
let fixture = Fixture::new(&upstream.uri());
|
||||
let profile = profile::resolve(
|
||||
&Selection::default().configuration(),
|
||||
&ReleaseService::new(crate::support::profile::cache()).unwrap(),
|
||||
&ReleaseService::new(crate::support::profile::cache(), std::env::temp_dir()).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
Mock::given(path("/v1internal:generateContent"))
|
||||
|
||||
@@ -247,7 +247,9 @@ impl Fixture {
|
||||
store.clone(),
|
||||
store.clone(),
|
||||
);
|
||||
let release = Arc::new(ReleaseService::new(crate::support::profile::cache()).unwrap());
|
||||
let release = Arc::new(
|
||||
ReleaseService::new(crate::support::profile::cache(), std::env::temp_dir()).unwrap(),
|
||||
);
|
||||
let credentials = Arc::new(CredentialService::new(
|
||||
kind.clone(),
|
||||
&ports,
|
||||
|
||||
@@ -21,8 +21,9 @@ use wiremock::{
|
||||
async fn oauth_refresh_and_native_generate_preserve_grant_profile_and_wire_payload() {
|
||||
let server = MockServer::start().await;
|
||||
let (origin, access_token) = refreshed_credential(&server).await;
|
||||
let profile =
|
||||
profile::default_profile(&ReleaseService::new(crate::support::profile::cache()).unwrap());
|
||||
let profile = profile::default_profile(
|
||||
&ReleaseService::new(crate::support::profile::cache(), std::env::temp_dir()).unwrap(),
|
||||
);
|
||||
let user_agent = "antigravity/hub/2.37.0 (aidev_client; os_type=darwin; arch=arm64)";
|
||||
let client = CloudCodeClient::new(&origin, None, &profile).unwrap();
|
||||
let post = |p| {
|
||||
@@ -171,8 +172,9 @@ async fn oauth_refresh_and_native_generate_preserve_grant_profile_and_wire_paylo
|
||||
#[tokio::test]
|
||||
async fn streamed_text_is_projected_once_across_native_frames() {
|
||||
let server = MockServer::start().await;
|
||||
let profile =
|
||||
profile::default_profile(&ReleaseService::new(crate::support::profile::cache()).unwrap());
|
||||
let profile = profile::default_profile(
|
||||
&ReleaseService::new(crate::support::profile::cache(), std::env::temp_dir()).unwrap(),
|
||||
);
|
||||
let client = CloudCodeClient::new(&server.uri().parse().unwrap(), None, &profile).unwrap();
|
||||
let frames = [
|
||||
json!({"candidates":[{"content":{"parts":[{"text":""}]}}]}),
|
||||
@@ -249,8 +251,9 @@ async fn streamed_text_is_projected_once_across_native_frames() {
|
||||
#[tokio::test]
|
||||
async fn incomplete_native_stream_and_redirect_are_rejected() {
|
||||
let server = MockServer::start().await;
|
||||
let profile =
|
||||
profile::default_profile(&ReleaseService::new(crate::support::profile::cache()).unwrap());
|
||||
let profile = profile::default_profile(
|
||||
&ReleaseService::new(crate::support::profile::cache(), std::env::temp_dir()).unwrap(),
|
||||
);
|
||||
let client = CloudCodeClient::new(&server.uri().parse().unwrap(), None, &profile).unwrap();
|
||||
Mock::given(path("/v1internal:streamGenerateContent")).respond_with(ResponseTemplate::new(200).set_body_raw("data: {\"response\":{\"candidates\":[{\"content\":{\"parts\":[{\"text\":\"partial\"}]}}]}}\n\n","text/event-stream")).mount(&server).await;
|
||||
let res = client
|
||||
@@ -350,8 +353,9 @@ async fn compressed_response(status: u16, body: &[u8], media: &str) -> ResponseT
|
||||
async fn compressed_control_responses_keep_errors_and_decoded_size_limits() {
|
||||
use gateway_core::error::ProviderErrorKind;
|
||||
let server = MockServer::start().await;
|
||||
let profile =
|
||||
profile::default_profile(&ReleaseService::new(crate::support::profile::cache()).unwrap());
|
||||
let profile = profile::default_profile(
|
||||
&ReleaseService::new(crate::support::profile::cache(), std::env::temp_dir()).unwrap(),
|
||||
);
|
||||
let client = CloudCodeClient::new(&server.uri().parse().unwrap(), None, &profile).unwrap();
|
||||
Mock::given(path("/v1internal:loadCodeAssist"))
|
||||
.respond_with(
|
||||
|
||||
@@ -71,9 +71,9 @@ fn history(calls: Vec<Value>, responses: Vec<Value>) -> Value {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn missing_ids_pair_by_unique_name_without_reencoding_business_fields() {
|
||||
async fn missing_ids_pair_by_name_and_parallel_order_without_reencoding_business_fields() {
|
||||
let (server, client) = client().await;
|
||||
let contents = r#"[{"role":"model","parts":[{"thought":true,"text":"reason","thoughtSignature":"opaque=="},{"functionCall":{"name":"look\u0075p","args":{"large":98765432109876543210987654,"n":1e+09,"n":2}}},{"function_call":{"name":"read","args":{}}}]},{"role":"user","parts":[{"function_response":{"name":"read","response":{"output":"second"}}},{"functionResponse":{"name":"lookup","response":{"output":"first","functionCall":{"name":"nested"}}}}]}]"#;
|
||||
let contents = r#"[{"role":"model","parts":[{"thought":true,"text":"reason","thoughtSignature":"opaque=="},{"functionCall":{"name":"look\u0075p","args":{"large":98765432109876543210987654,"n":1e+09,"n":2}}},{"function_call":{"name":"read","args":{}}},{"text":"next"},{"functionCall":{"name":"lookup","args":{"key":"third"}}}]},{"role":"user","parts":[{"function_response":{"name":"read","response":{"output":"second"}}},{"functionResponse":{"name":"lookup","response":{"output":"first","functionCall":{"name":"nested"}}}},{"text":"next"},{"function_response":{"name":"lookup","response":{"output":"third"}}}]}]"#;
|
||||
let body = format!(r#"{{"contents":{contents},"unknown":1e+09,"unknown":2}}"#);
|
||||
for mode in [GenerateMode::Json, GenerateMode::Stream] {
|
||||
let outgoing = generate(&server, &client, &body, "claude-opus-5-5-medium", mode).await;
|
||||
@@ -84,8 +84,17 @@ async fn missing_ids_pair_by_unique_name_without_reencoding_business_fields() {
|
||||
let second = value["contents"][0]["parts"][2]["function_call"]["id"]
|
||||
.as_str()
|
||||
.unwrap();
|
||||
let third = value["contents"][0]["parts"][4]["functionCall"]["id"]
|
||||
.as_str()
|
||||
.unwrap();
|
||||
assert!(!first.is_empty());
|
||||
assert_ne!(first, second);
|
||||
assert_ne!(first, third);
|
||||
assert_ne!(second, third);
|
||||
assert_eq!(
|
||||
value["contents"][1]["parts"][3]["function_response"]["id"],
|
||||
third
|
||||
);
|
||||
assert_eq!(
|
||||
value["contents"][1]["parts"][1]["functionResponse"]["id"],
|
||||
first
|
||||
@@ -97,7 +106,8 @@ async fn missing_ids_pair_by_unique_name_without_reencoding_business_fields() {
|
||||
let restored = outgoing
|
||||
.get()
|
||||
.replace(&format!(",\"id\":\"{first}\""), "")
|
||||
.replace(&format!(",\"id\":\"{second}\""), "");
|
||||
.replace(&format!(",\"id\":\"{second}\""), "")
|
||||
.replace(&format!(",\"id\":\"{third}\""), "");
|
||||
assert!(restored.contains(contents));
|
||||
assert!(restored.contains(r#""unknown":1e+09,"unknown":2"#));
|
||||
assert!(
|
||||
@@ -116,11 +126,13 @@ async fn existing_ids_are_reused_and_generated_ids_survive_retries_and_appended_
|
||||
call("run", None),
|
||||
call("read", Some("existing-call")),
|
||||
call("lookup", None),
|
||||
call("run", None),
|
||||
],
|
||||
vec![
|
||||
response("lookup", Some("existing-result")),
|
||||
response("read", None),
|
||||
response("run", None),
|
||||
response("run", None),
|
||||
],
|
||||
);
|
||||
let first = generate(
|
||||
@@ -147,6 +159,13 @@ async fn existing_ids_are_reused_and_generated_ids_survive_retries_and_appended_
|
||||
first_value["contents"][0]["parts"][2]["functionCall"]["id"],
|
||||
"existing-result"
|
||||
);
|
||||
let parallel_id = &first_value["contents"][0]["parts"][3]["functionCall"]["id"];
|
||||
assert!(parallel_id.as_str().is_some_and(|id| !id.is_empty()));
|
||||
assert_ne!(parallel_id, id);
|
||||
assert_eq!(
|
||||
first_value["contents"][1]["parts"][3]["functionResponse"]["id"],
|
||||
*parallel_id
|
||||
);
|
||||
let retry = generate(
|
||||
&server,
|
||||
&client,
|
||||
@@ -185,8 +204,12 @@ async fn existing_ids_are_reused_and_generated_ids_survive_retries_and_appended_
|
||||
|
||||
// 客户端已有的 ID 即使占用补偿命名空间,也不能和新配对共用
|
||||
let collision = history(
|
||||
vec![call("run", None), call("read", Some(id))],
|
||||
vec![response("run", None), response("read", Some(id))],
|
||||
vec![call("run", None), call("read", Some(id)), call("run", None)],
|
||||
vec![
|
||||
response("run", None),
|
||||
response("read", Some(id)),
|
||||
response("run", None),
|
||||
],
|
||||
);
|
||||
let collision = generate(
|
||||
&server,
|
||||
@@ -213,12 +236,28 @@ async fn ambiguous_or_invalid_history_and_existing_ids_remain_unchanged() {
|
||||
let mut cases = vec![
|
||||
history(
|
||||
vec![call("run", None), call("run", None)],
|
||||
vec![response("run", None), response("run", None)],
|
||||
vec![response("run", None)],
|
||||
),
|
||||
history(
|
||||
vec![call("run", None)],
|
||||
vec![response("run", None), response("run", None)],
|
||||
),
|
||||
history(
|
||||
vec![call("run", Some("a")), call("run", None)],
|
||||
vec![response("run", None), response("run", None)],
|
||||
),
|
||||
history(
|
||||
vec![call("run", None), call("run", None)],
|
||||
vec![response("run", None), response("run", Some("b"))],
|
||||
),
|
||||
history(
|
||||
vec![call("run", Some("a")), call("run", None)],
|
||||
vec![response("run", None), response("run", Some("a"))],
|
||||
),
|
||||
history(
|
||||
vec![call("run", Some("a")), call("run", Some("b"))],
|
||||
vec![response("run", Some("b")), response("run", Some("a"))],
|
||||
),
|
||||
history(vec![call("run", None)], vec![response("other", None)]),
|
||||
history(
|
||||
vec![call("run", Some("a"))],
|
||||
@@ -257,7 +296,10 @@ async fn ambiguous_or_invalid_history_and_existing_ids_remain_unchanged() {
|
||||
#[tokio::test]
|
||||
async fn compatibility_is_limited_to_native_claude_generation() {
|
||||
let (server, client) = client().await;
|
||||
let body = history(vec![call("run", None)], vec![response("run", None)]);
|
||||
let body = history(
|
||||
vec![call("run", None), call("run", None)],
|
||||
vec![response("run", None), response("run", None)],
|
||||
);
|
||||
for (model, mode) in [
|
||||
("gemini-4-hydrogen", GenerateMode::Json),
|
||||
(
|
||||
|
||||
@@ -341,6 +341,11 @@ pub(super) fn map_catalog_error(error: CodexCredentialCatalogError) -> ProviderA
|
||||
.with_public_message(message)
|
||||
.with_source(source);
|
||||
}
|
||||
Error::Store(source) => {
|
||||
return provider_admin_error(Kind::Unavailable)
|
||||
.with_public_message("模型目录存储暂不可用")
|
||||
.with_source(source);
|
||||
}
|
||||
Error::InvalidEtag => (Kind::Invalid, "模型目录版本无效,请重新查询"),
|
||||
Error::NoEligibleCredential => (Kind::NotFound, "没有可查询模型的账号"),
|
||||
Error::ConcurrentUpdate => (Kind::Conflict, "模型目录正在更新,请稍后重试"),
|
||||
|
||||
@@ -689,9 +689,19 @@ impl ProviderAdmin for OpenAiAdminProvider {
|
||||
return Err(provider_admin_error(ProviderAdminErrorKind::Conflict)
|
||||
.with_public_message("凭据已更新,请刷新账号列表"));
|
||||
}
|
||||
let guards = self
|
||||
.credentials
|
||||
.acquire_refresh_guards(¤t.account)
|
||||
.await
|
||||
.map_err(map_credential_admin_error)?;
|
||||
let current = self
|
||||
.accounts
|
||||
.load_credential(&account_id, current.account.revision())
|
||||
.await
|
||||
.map_err(map_store_error)?;
|
||||
let prepared = self
|
||||
.credentials
|
||||
.manual_refresh(current)
|
||||
.manual_refresh(current, guards)
|
||||
.await
|
||||
.map_err(map_credential_admin_error)?;
|
||||
prepared_rotation(prepared, command.account.provider_kind)
|
||||
|
||||
@@ -458,6 +458,8 @@ pub(super) const IMAGE_MODELS: &[&str] = &[
|
||||
"gpt-image-2.5-sunburst-2026-09-08",
|
||||
"gpt-image-2.5-flare",
|
||||
"gpt-image-2.5-flare-2026-09-08",
|
||||
"gpt-image-2.6-sunburst",
|
||||
"gpt-image-2.6-flare",
|
||||
];
|
||||
pub(super) const IMAGE_TEXT_RATES: TokenRates = TokenRates::new(50_000, 0, 12_500);
|
||||
pub(super) const IMAGE_TOKEN_RATES: TokenRates = TokenRates::new(80_000, 300_000, 20_000);
|
||||
|
||||
@@ -1,9 +1,147 @@
|
||||
//! Chat 转换的目标档位与 fast 协议头适配
|
||||
//! Chat 转换的目标档位、工具标识与 fast 协议头适配
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use bytes::Bytes;
|
||||
use gateway_core::engine::middleware::MiddlewareHeader;
|
||||
use reqwest::header::HeaderMap;
|
||||
use serde_json::{Map, Value};
|
||||
use sha2::{Digest as _, Sha256};
|
||||
|
||||
/// 名称映射只属于本次 Chat 响应,历史调用 ID 在出站副本中保持成对关联
|
||||
pub(crate) fn normalize_translated_codex_tools(
|
||||
body: &mut Map<String, Value>,
|
||||
) -> HashMap<String, String> {
|
||||
let mut fields = Vec::new();
|
||||
for (field, value) in body.iter_mut() {
|
||||
match field.as_str() {
|
||||
"tools" | "input" => {
|
||||
if let Some(items) = value.as_array_mut() {
|
||||
for item in items {
|
||||
collect_tool_names(item, &mut fields);
|
||||
}
|
||||
}
|
||||
}
|
||||
"tool_choice" => collect_tool_names(value, &mut fields),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
// 先预留所有原名,避免别名抢占后面声明的合法名称
|
||||
let mut used = fields
|
||||
.iter()
|
||||
.filter_map(|value| value.as_str())
|
||||
.map(str::to_owned)
|
||||
.collect();
|
||||
let mut names = HashMap::new();
|
||||
for field in fields {
|
||||
let Some(name) = field.as_str() else { continue };
|
||||
if name.is_empty()
|
||||
|| name
|
||||
.bytes()
|
||||
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-'))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let alias = names.entry(name.to_owned()).or_insert_with(|| {
|
||||
let base: String = name
|
||||
.chars()
|
||||
.map(|ch| {
|
||||
if ch.is_ascii_alphanumeric() || matches!(ch, '_' | '-') {
|
||||
ch
|
||||
} else {
|
||||
'_'
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
unique_tool_alias(&base, &mut used)
|
||||
});
|
||||
*field = Value::String(alias.clone());
|
||||
}
|
||||
if let Some(input) = body.get_mut("input").and_then(Value::as_array_mut) {
|
||||
let mut used = input
|
||||
.iter()
|
||||
.filter_map(|item| item.get("call_id").and_then(Value::as_str))
|
||||
.map(str::to_owned)
|
||||
.collect();
|
||||
let mut ids = HashMap::new();
|
||||
for item in input.iter().filter(|item| {
|
||||
matches!(
|
||||
item.get("type").and_then(Value::as_str),
|
||||
Some("function_call" | "custom_tool_call")
|
||||
)
|
||||
}) {
|
||||
let Some(id) = item
|
||||
.get("call_id")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|id| id.chars().count() > 64)
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
ids.entry(id.to_owned()).or_insert_with(|| {
|
||||
let digest = hex::encode(Sha256::digest(id.as_bytes()));
|
||||
unique_tool_alias(&format!("call_{digest}"), &mut used)
|
||||
});
|
||||
}
|
||||
for item in input {
|
||||
if matches!(
|
||||
item.get("type").and_then(Value::as_str),
|
||||
Some(
|
||||
"function_call"
|
||||
| "custom_tool_call"
|
||||
| "function_call_output"
|
||||
| "custom_tool_call_output"
|
||||
)
|
||||
) && let Some(alias) = item
|
||||
.get("call_id")
|
||||
.and_then(Value::as_str)
|
||||
.and_then(|id| ids.get(id))
|
||||
{
|
||||
item["call_id"] = alias.clone().into();
|
||||
}
|
||||
}
|
||||
}
|
||||
names
|
||||
.into_iter()
|
||||
.map(|(name, alias)| (alias, name))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn collect_tool_names<'a>(tool: &'a mut Value, names: &mut Vec<&'a mut Value>) {
|
||||
match tool.get("type").and_then(Value::as_str) {
|
||||
Some(
|
||||
"function"
|
||||
| "custom"
|
||||
| "function_call"
|
||||
| "custom_tool_call"
|
||||
| "function_call_output"
|
||||
| "custom_tool_call_output",
|
||||
) => {
|
||||
if let Some(name) = tool.get_mut("name") {
|
||||
names.push(name);
|
||||
}
|
||||
}
|
||||
Some("namespace" | "allowed_tools" | "additional_tools" | "tool_search_output") => {
|
||||
if let Some(tools) = tool.get_mut("tools").and_then(Value::as_array_mut) {
|
||||
for tool in tools {
|
||||
collect_tool_names(tool, names);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn unique_tool_alias(base: &str, used: &mut HashSet<String>) -> String {
|
||||
// 调用方只传入 ASCII 名称或十六进制摘要,可按字节截取 Codex 标识上限
|
||||
let mut candidate = base[..base.len().min(64)].to_owned();
|
||||
let mut index = 0;
|
||||
while !used.insert(candidate.clone()) {
|
||||
index += 1;
|
||||
let suffix = format!("_{index}");
|
||||
candidate = format!("{}{suffix}", &base[..base.len().min(64 - suffix.len())]);
|
||||
}
|
||||
candidate
|
||||
}
|
||||
|
||||
pub(crate) fn normalize_translated_codex_service_tier(body: &mut Map<String, Value>) {
|
||||
// 转换生成的默认档位沿用 Codex 客户端的省略表达,原生 Responses 保留调用方声明
|
||||
|
||||
@@ -10,7 +10,10 @@ mod search_tools;
|
||||
use gateway_core::engine::middleware::MiddlewareHeader;
|
||||
use serde_json::{Map, Value};
|
||||
|
||||
pub(crate) use chat::{add_translated_fast_beta, normalize_translated_codex_service_tier};
|
||||
pub(crate) use chat::{
|
||||
add_translated_fast_beta, normalize_translated_codex_service_tier,
|
||||
normalize_translated_codex_tools,
|
||||
};
|
||||
pub(crate) use headers::is_non_codex_request_header;
|
||||
pub(crate) use request::normalize_codex_request_body;
|
||||
pub(crate) use search_tools::declares_hosted_search;
|
||||
|
||||
@@ -8,6 +8,7 @@ use serde_json::{Map, Value, json};
|
||||
/// 只处理已验证被拒绝的字段,不根据客户端品牌推断整份历史是否合法
|
||||
pub(super) fn normalize_non_codex_request_body(body: &mut Map<String, Value>) {
|
||||
normalize_codex_oauth_options(body);
|
||||
super::search_tools::normalize_search_tool_aliases(body);
|
||||
let Some(input) = body.get_mut("input").and_then(Value::as_array_mut) else {
|
||||
return;
|
||||
};
|
||||
@@ -132,7 +133,23 @@ fn normalize_codex_oauth_options(body: &mut Map<String, Value>) {
|
||||
///
|
||||
/// 兼容基准是 Codex Core/Desktop 的模型请求,不是公开 OpenAI Responses API
|
||||
/// 未知字段继续透传,不能因官方请求结构中没有某个字段就将其列入过滤规则
|
||||
pub(crate) fn normalize_codex_request_body(body: &mut Map<String, Value>) {
|
||||
pub(crate) fn normalize_codex_request_body(
|
||||
body: &mut Map<String, Value>,
|
||||
should_replace_none_with_low: impl FnOnce() -> bool,
|
||||
) {
|
||||
// 整个请求共用所选账号的目录判断,首次遇到显式 none 才读取快照
|
||||
let replace_none = std::cell::LazyCell::new(should_replace_none_with_low);
|
||||
let normalize_effort = |fields: &mut Map<String, Value>| {
|
||||
if let Some(effort) = fields
|
||||
.get_mut("reasoning")
|
||||
.and_then(|reasoning| reasoning.get_mut("effort"))
|
||||
&& effort.as_str() == Some("none")
|
||||
&& *replace_none
|
||||
{
|
||||
*effort = Value::from("low");
|
||||
}
|
||||
};
|
||||
normalize_effort(body);
|
||||
// 官方 Core/Desktop 显式发送 store=false;仅为缺字段的下游请求补齐,保留显式值
|
||||
body.entry("store").or_insert(Value::Bool(false));
|
||||
|
||||
@@ -158,10 +175,12 @@ pub(crate) fn normalize_codex_request_body(body: &mut Map<String, Value>) {
|
||||
let Some(item) = item.as_object_mut() else {
|
||||
continue;
|
||||
};
|
||||
if item.get("type").and_then(Value::as_str) == Some("message")
|
||||
&& item.get("role").and_then(Value::as_str) == Some("system")
|
||||
{
|
||||
item.insert("role".to_owned(), Value::String("developer".to_owned()));
|
||||
match item.get("type").and_then(Value::as_str) {
|
||||
Some("configuration_update") => normalize_effort(item),
|
||||
Some("message") if item.get("role").and_then(Value::as_str) == Some("system") => {
|
||||
item.insert("role".to_owned(), Value::String("developer".to_owned()));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,39 @@
|
||||
//! 识别普通与 Responses Lite 请求中的托管搜索声明,不改写工具配置
|
||||
//! 识别托管搜索声明并适配 Codex 的搜索工具名称
|
||||
|
||||
use serde_json::{Map, Value};
|
||||
|
||||
pub(super) fn normalize_search_tool_aliases(body: &mut Map<String, Value>) {
|
||||
for (field, value) in body {
|
||||
match field.as_str() {
|
||||
"tools" | "input" => {
|
||||
if let Some(items) = value.as_array_mut() {
|
||||
for item in items {
|
||||
normalize_search_tool(item);
|
||||
}
|
||||
}
|
||||
}
|
||||
"tool_choice" => normalize_search_tool(value),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn normalize_search_tool(tool: &mut Value) {
|
||||
match tool.get("type").and_then(Value::as_str) {
|
||||
Some("web_search_preview" | "web_search_preview_2025_03_11") => {
|
||||
tool["type"] = "web_search".into();
|
||||
}
|
||||
Some("allowed_tools" | "additional_tools" | "tool_search_output" | "namespace") => {
|
||||
if let Some(tools) = tool.get_mut("tools").and_then(Value::as_array_mut) {
|
||||
for tool in tools {
|
||||
normalize_search_tool(tool);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn declares_hosted_search(body: &Map<String, Value>) -> bool {
|
||||
body.get("tools")
|
||||
.and_then(Value::as_array)
|
||||
|
||||
@@ -281,7 +281,7 @@ pub struct PreparedCodexCredentialRotation {
|
||||
refresh_guards: Option<ProviderRefreshGuards>,
|
||||
}
|
||||
|
||||
struct ProviderRefreshGuards {
|
||||
pub(crate) struct ProviderRefreshGuards {
|
||||
_capacity: Box<dyn ProviderLeaseGuard>,
|
||||
_account: Box<dyn ProviderLeaseGuard>,
|
||||
}
|
||||
@@ -844,26 +844,13 @@ impl CodexCredentialAdminService {
|
||||
self
|
||||
}
|
||||
|
||||
/// 官方 RT exchange;结果由 App 在同一 revision/audit 事务中提交
|
||||
pub async fn manual_refresh(
|
||||
/// 调用方必须在取得租约后重新读取凭据,并让租约覆盖交换与提交
|
||||
pub(crate) async fn acquire_refresh_guards(
|
||||
&self,
|
||||
current: LoadedCredential,
|
||||
) -> Result<PreparedCodexCredentialRotation, CodexCredentialAdminError> {
|
||||
let account_id = current.account.id().clone();
|
||||
let expected_revision = current.account.revision();
|
||||
if current.account.provider().as_str() != PROVIDER_NAME {
|
||||
return Err(CodexCredentialAdminError::NotFound);
|
||||
}
|
||||
let runtime = CodexCredentialCodec::decode(¤t.credential)
|
||||
.map_err(|_| CodexCredentialAdminError::InvalidCredential)?;
|
||||
let oauth = runtime
|
||||
.authentication
|
||||
.oauth()
|
||||
.ok_or(CodexCredentialAdminError::MissingRefreshToken)?;
|
||||
let refresh_token = oauth
|
||||
.refresh_token
|
||||
.as_ref()
|
||||
.ok_or(CodexCredentialAdminError::MissingRefreshToken)?;
|
||||
account: &ProviderAccount,
|
||||
) -> Result<ProviderRefreshGuards, CodexCredentialAdminError> {
|
||||
let account_id = account.id();
|
||||
let expected_revision = account.revision();
|
||||
let policy = self
|
||||
.runtime_policy
|
||||
.load_refresh_policy()
|
||||
@@ -895,6 +882,32 @@ impl CodexCredentialAdminService {
|
||||
return Err(CodexCredentialAdminError::RefreshLeaseUnavailable);
|
||||
}
|
||||
};
|
||||
Ok(ProviderRefreshGuards {
|
||||
_capacity: capacity_guard,
|
||||
_account: account_guard,
|
||||
})
|
||||
}
|
||||
|
||||
/// 官方 RT exchange;结果由 App 在同一 revision/audit 事务中提交
|
||||
pub(crate) async fn manual_refresh(
|
||||
&self,
|
||||
current: LoadedCredential,
|
||||
guards: ProviderRefreshGuards,
|
||||
) -> Result<PreparedCodexCredentialRotation, CodexCredentialAdminError> {
|
||||
let account_id = current.account.id().clone();
|
||||
if current.account.provider().as_str() != PROVIDER_NAME {
|
||||
return Err(CodexCredentialAdminError::NotFound);
|
||||
}
|
||||
let runtime = CodexCredentialCodec::decode(¤t.credential)
|
||||
.map_err(|_| CodexCredentialAdminError::InvalidCredential)?;
|
||||
let oauth = runtime
|
||||
.authentication
|
||||
.oauth()
|
||||
.ok_or(CodexCredentialAdminError::MissingRefreshToken)?;
|
||||
let refresh_token = oauth
|
||||
.refresh_token
|
||||
.as_ref()
|
||||
.ok_or(CodexCredentialAdminError::MissingRefreshToken)?;
|
||||
let tokens = self
|
||||
.refresher
|
||||
.refresh_with_proxy(
|
||||
@@ -951,10 +964,7 @@ impl CodexCredentialAdminService {
|
||||
access_token_expires_at,
|
||||
next_refresh_at,
|
||||
)?;
|
||||
prepared.refresh_guards = Some(ProviderRefreshGuards {
|
||||
_capacity: capacity_guard,
|
||||
_account: account_guard,
|
||||
});
|
||||
prepared.refresh_guards = Some(guards);
|
||||
Ok(prepared)
|
||||
}
|
||||
|
||||
|
||||
@@ -256,20 +256,7 @@ pub(crate) fn derive_endpoint_affinity_with_headers(
|
||||
if let Some(session) = body.get(body_session_field).cloned() {
|
||||
body.entry("session_id").or_insert(session);
|
||||
}
|
||||
let session_id = account_session_with_headers(&body, payload.context(), headers)?;
|
||||
session_affinity(
|
||||
"root-session",
|
||||
&session_id,
|
||||
Some(&session_id),
|
||||
client_api_key_id,
|
||||
)
|
||||
.map(|affinity| {
|
||||
affinity.with_follow_only(follows_session_with_headers(
|
||||
&body,
|
||||
payload.context(),
|
||||
headers,
|
||||
))
|
||||
})
|
||||
session_affinity_with_headers(&body, payload.context(), headers, client_api_key_id)
|
||||
}
|
||||
|
||||
pub(crate) fn derive_live_session_affinity(
|
||||
@@ -292,19 +279,18 @@ pub(crate) fn derive_live_session_affinity(
|
||||
}),
|
||||
);
|
||||
// x-session-id 是实时通话身份,不代表根对话;只消费官方发送的 session-id
|
||||
let session_id = account_session_with_headers(&Map::new(), &Map::new(), &effective)?;
|
||||
session_affinity(
|
||||
"root-session",
|
||||
&session_id,
|
||||
Some(&session_id),
|
||||
client_api_key_id,
|
||||
)
|
||||
.map(|affinity| {
|
||||
affinity.with_follow_only(follows_session_with_headers(
|
||||
&Map::new(),
|
||||
&Map::new(),
|
||||
&effective,
|
||||
))
|
||||
session_affinity_with_headers(&Map::new(), &Map::new(), &effective, client_api_key_id)
|
||||
}
|
||||
|
||||
pub(crate) fn session_affinity_with_headers(
|
||||
body: &Map<String, Value>,
|
||||
context: &Map<String, Value>,
|
||||
headers: &[gateway_core::engine::middleware::MiddlewareHeader],
|
||||
client_api_key_id: &ClientApiKeyId,
|
||||
) -> Option<CodexSessionAffinity> {
|
||||
let session = account_session_with_headers(body, context, headers)?;
|
||||
root_session_affinity(Some(&session), client_api_key_id).map(|affinity| {
|
||||
affinity.with_follow_only(follows_session_with_headers(body, context, headers))
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@ use gateway_core::account::AccountCatalogObservation;
|
||||
use gateway_core::account::{
|
||||
CredentialRevision, CredentialState, OpaqueProviderData, ProviderAccount, ProviderAccountId,
|
||||
};
|
||||
use gateway_core::error::{StoreError, StoreErrorKind};
|
||||
use gateway_core::provider_ports::{
|
||||
ProviderCatalogCacheKey, ProviderCatalogCachePort, ProviderCatalogScope,
|
||||
ProviderRuntimePolicyPort,
|
||||
@@ -39,6 +40,8 @@ const CATALOG_REFRESH_AFTER: Duration = Duration::from_hours(1);
|
||||
const MAX_ACCOUNT_CATALOG_MODELS: usize = 2_048;
|
||||
const MODEL_CATALOG_TIMEOUT: Duration = Duration::from_secs(15);
|
||||
|
||||
const CATALOG_FAILURE_BACKOFF_BASE: Duration = Duration::from_secs(60);
|
||||
const CATALOG_FAILURE_BACKOFF_MAX: Duration = Duration::from_hours(1);
|
||||
const REFRESH_CONCURRENCY: usize = 32;
|
||||
// 同时到期或导入大量账号时也限制起始速率,不能把连接并发上限当作请求速率上限
|
||||
const REFRESH_SPACING: Duration = Duration::from_millis(10);
|
||||
@@ -272,6 +275,8 @@ pub enum CodexCredentialCatalogError {
|
||||
Credential(#[from] CredentialRepositoryError),
|
||||
#[error("Codex model catalog upstream query failed: {detail}")]
|
||||
Upstream { detail: String },
|
||||
#[error("Codex model catalog storage is unavailable")]
|
||||
Store(#[from] StoreError),
|
||||
#[error("Codex model catalog cache is unavailable")]
|
||||
Cache,
|
||||
#[error("Codex model catalog ETag is invalid")]
|
||||
@@ -282,13 +287,40 @@ pub enum CodexCredentialCatalogError {
|
||||
Profile(#[source] gateway_core::error::ErrorSource),
|
||||
}
|
||||
|
||||
impl CodexCredentialCatalogError {
|
||||
fn is_account_failure(&self) -> bool {
|
||||
matches!(
|
||||
self,
|
||||
Self::Upstream { .. }
|
||||
| Self::Credential(CredentialRepositoryError::InvalidCredentialData(_))
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct AccountCatalogRefresh {
|
||||
etag: Option<String>,
|
||||
retry: Option<CatalogRetry>,
|
||||
}
|
||||
|
||||
struct CatalogRetry {
|
||||
at: tokio::time::Instant,
|
||||
delay: Duration,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum CatalogFetchMode {
|
||||
Discovery,
|
||||
Recovery,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct CatalogCacheState {
|
||||
restored: bool,
|
||||
revision: u64,
|
||||
generation: u64,
|
||||
snapshot: Option<Arc<CodexCredentialCatalogSnapshot>>,
|
||||
pending: BTreeMap<CodexCatalogScope, String>,
|
||||
refreshes: BTreeMap<CodexCatalogScope, AccountCatalogRefresh>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
@@ -301,6 +333,7 @@ pub struct CodexCredentialCatalogService {
|
||||
runtime_policy: Arc<dyn ProviderRuntimePolicyPort>,
|
||||
cache: Arc<RwLock<CatalogCacheState>>,
|
||||
refresh_notification: Arc<Notify>,
|
||||
retry_changed: Arc<Notify>,
|
||||
refresh_lock: Arc<tokio::sync::Mutex<()>>,
|
||||
publication: Arc<std::sync::Mutex<()>>,
|
||||
}
|
||||
@@ -323,6 +356,7 @@ impl CodexCredentialCatalogService {
|
||||
runtime_policy,
|
||||
cache: Arc::new(RwLock::new(CatalogCacheState::default())),
|
||||
refresh_notification: Arc::new(Notify::new()),
|
||||
retry_changed: Arc::new(Notify::new()),
|
||||
refresh_lock: Arc::new(tokio::sync::Mutex::new(())),
|
||||
publication: Default::default(),
|
||||
}
|
||||
@@ -469,6 +503,20 @@ impl CodexCredentialCatalogService {
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn should_replace_none_with_low(
|
||||
&self,
|
||||
account: &ProviderAccount,
|
||||
model: &UpstreamModelId,
|
||||
) -> bool {
|
||||
self.cached().ok().flatten().is_some_and(|snapshot| {
|
||||
snapshot.account_model(account, model).is_some_and(|entry| {
|
||||
let levels = entry.capabilities().reasoning_efforts();
|
||||
levels.iter().any(|level| level == "low")
|
||||
&& !levels.iter().any(|level| level == "none")
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn messages_model_capabilities(
|
||||
&self,
|
||||
account: &ProviderAccount,
|
||||
@@ -548,13 +596,23 @@ impl CodexCredentialCatalogService {
|
||||
if let Some(catalog) = self.read_account_catalog(account).await? {
|
||||
return Ok(catalog);
|
||||
}
|
||||
self.refresh_account_catalog(account.id()).await
|
||||
self.query_account_catalog(account.id(), CatalogFetchMode::Discovery)
|
||||
.await
|
||||
}
|
||||
|
||||
/// 实时刷新指定账号的模型集合,包括管理员显式查询的停用账号
|
||||
pub async fn refresh_account_catalog(
|
||||
&self,
|
||||
account_id: &ProviderAccountId,
|
||||
) -> Result<CodexAccountCatalog, CodexCredentialCatalogError> {
|
||||
self.query_account_catalog(account_id, CatalogFetchMode::Recovery)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn query_account_catalog(
|
||||
&self,
|
||||
account_id: &ProviderAccountId,
|
||||
mode: CatalogFetchMode,
|
||||
) -> Result<CodexAccountCatalog, CodexCredentialCatalogError> {
|
||||
let account = self
|
||||
.repository
|
||||
@@ -568,7 +626,7 @@ impl CodexCredentialCatalogService {
|
||||
let client = self.discovery_client().await?;
|
||||
let revision = self.state_revision()?;
|
||||
let (catalog, entry) = self
|
||||
.fetch_observation(&client, &account, &scope, None)
|
||||
.fetch_observation(&client, &account, &scope, None, mode)
|
||||
.await?;
|
||||
if eligible_catalog_account(&account, SystemTime::now())
|
||||
&& let Err(error) = self.merge_observations(revision, vec![(scope, entry)])
|
||||
@@ -587,9 +645,10 @@ impl CodexCredentialCatalogService {
|
||||
account: &ProviderAccount,
|
||||
scope: &CodexCatalogScope,
|
||||
etag: Option<String>,
|
||||
mode: CatalogFetchMode,
|
||||
) -> Result<(CodexAccountCatalog, AccountEntry), CodexCredentialCatalogError> {
|
||||
let observed_at = SystemTime::now();
|
||||
let mut fetched = self.fetch_account_models(client, account).await?;
|
||||
let mut fetched = self.fetch_account_models(client, account, mode).await?;
|
||||
let observed = AccountCatalogObservation {
|
||||
account_id: account.id().clone(),
|
||||
revision: account.revision(),
|
||||
@@ -601,8 +660,7 @@ impl CodexCredentialCatalogService {
|
||||
.repository
|
||||
.store()
|
||||
.save_account_catalog(&observed, &fetched.document)
|
||||
.await
|
||||
.map_err(|_| CodexCredentialCatalogError::Cache)?
|
||||
.await?
|
||||
{
|
||||
return Err(CodexCredentialCatalogError::ConcurrentUpdate);
|
||||
}
|
||||
@@ -637,7 +695,9 @@ impl CodexCredentialCatalogService {
|
||||
account: &ProviderAccount,
|
||||
) -> Result<(Vec<CodexCatalogModel>, SystemTime), CodexCredentialCatalogError> {
|
||||
let client = self.discovery_client().await?;
|
||||
let fetched = self.fetch_account_models(&client, account).await?;
|
||||
let fetched = self
|
||||
.fetch_account_models(&client, account, CatalogFetchMode::Discovery)
|
||||
.await?;
|
||||
if fetched.models.is_empty() {
|
||||
return Err(CodexCredentialCatalogError::NoEligibleCredential);
|
||||
}
|
||||
@@ -701,44 +761,56 @@ impl CodexCredentialCatalogService {
|
||||
&self,
|
||||
client: &CodexBackendClient,
|
||||
account: &ProviderAccount,
|
||||
mode: CatalogFetchMode,
|
||||
) -> Result<CodexModelCatalogSnapshot, CodexCredentialCatalogError> {
|
||||
tokio::time::timeout(MODEL_CATALOG_TIMEOUT, async {
|
||||
let credential = self.repository.load_runtime_credential(account).await?;
|
||||
let request_id = format!("catalog_{}", Uuid::now_v7().simple());
|
||||
let authorization = credential
|
||||
.authentication
|
||||
.authorization_header()
|
||||
.map_err(CredentialRepositoryError::from)?;
|
||||
let mut client = credential
|
||||
.authentication
|
||||
.model_client_for_account(client, account)
|
||||
.map_err(|error| CodexCredentialCatalogError::Upstream {
|
||||
detail: error.to_string(),
|
||||
})?;
|
||||
if let super::CodexRuntimeAuthentication::ApiKey(auth) = &credential.authentication
|
||||
&& auth.configuration.protocol == super::ApiKeyProtocol::Messages
|
||||
{
|
||||
client = client.with_messages_api_base_url(&auth.configuration.base_url);
|
||||
}
|
||||
let result = client
|
||||
.fetch_models_with_context(
|
||||
CodexRequestContext::auxiliary(
|
||||
authorization.expose_secret(),
|
||||
account.upstream_account_id(),
|
||||
&request_id,
|
||||
None,
|
||||
),
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
result.map_err(|error| CodexCredentialCatalogError::Upstream {
|
||||
let deadline = tokio::time::Instant::now() + MODEL_CATALOG_TIMEOUT;
|
||||
let credential =
|
||||
tokio::time::timeout_at(deadline, self.repository.load_runtime_credential(account))
|
||||
.await
|
||||
.map_err(|error| {
|
||||
CredentialRepositoryError::Store(StoreError::caused_by(
|
||||
StoreErrorKind::Unavailable,
|
||||
error,
|
||||
))
|
||||
})??;
|
||||
let request_id = format!("catalog_{}", Uuid::now_v7().simple());
|
||||
let authorization = credential
|
||||
.authentication
|
||||
.authorization_header()
|
||||
.map_err(CredentialRepositoryError::from)?;
|
||||
let mut client = credential
|
||||
.authentication
|
||||
.model_client_for_account(client, account)
|
||||
.map_err(|error| CodexCredentialCatalogError::Upstream {
|
||||
detail: error.to_string(),
|
||||
})
|
||||
})?;
|
||||
if let super::CodexRuntimeAuthentication::ApiKey(auth) = &credential.authentication
|
||||
&& auth.configuration.protocol == super::ApiKeyProtocol::Messages
|
||||
{
|
||||
client = client.with_messages_api_base_url(&auth.configuration.base_url);
|
||||
}
|
||||
let fetch = client.fetch_models_with_context(
|
||||
CodexRequestContext::auxiliary(
|
||||
authorization.expose_secret(),
|
||||
account.upstream_account_id(),
|
||||
&request_id,
|
||||
None,
|
||||
),
|
||||
None,
|
||||
);
|
||||
match mode {
|
||||
CatalogFetchMode::Discovery => {
|
||||
tokio::time::timeout_at(deadline, fetch)
|
||||
.await
|
||||
.map_err(|_| CodexCredentialCatalogError::Upstream {
|
||||
detail: "model catalog timed out".to_owned(),
|
||||
})?
|
||||
}
|
||||
CatalogFetchMode::Recovery => fetch.await,
|
||||
}
|
||||
.map_err(|error| CodexCredentialCatalogError::Upstream {
|
||||
detail: error.to_string(),
|
||||
})
|
||||
.await
|
||||
.map_err(|_| CodexCredentialCatalogError::Upstream {
|
||||
detail: "model catalog timed out".to_owned(),
|
||||
})?
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -12,8 +12,7 @@ impl CodexCredentialCatalogService {
|
||||
.repository
|
||||
.store()
|
||||
.load_account_catalogs(&provider)
|
||||
.await
|
||||
.map_err(|_| CodexCredentialCatalogError::Cache)?;
|
||||
.await?;
|
||||
let mut entries = Entries::new();
|
||||
for group in groups {
|
||||
let decoded =
|
||||
@@ -91,7 +90,7 @@ impl CodexCredentialCatalogService {
|
||||
.map_err(|_| CodexCredentialCatalogError::Cache)?;
|
||||
cache.revision = cache.revision.wrapping_add(1);
|
||||
cache
|
||||
.pending
|
||||
.refreshes
|
||||
.retain(|scope, _| !ids.contains(&scope.account_id) || current.contains(scope));
|
||||
cache.revision
|
||||
};
|
||||
@@ -120,8 +119,11 @@ impl CodexCredentialCatalogService {
|
||||
.cache
|
||||
.write()
|
||||
.map_err(|_| CodexCredentialCatalogError::Cache)?;
|
||||
let pending = state.pending.get(&scope);
|
||||
if pending.is_some_and(|tag| tag == etag) {
|
||||
let pending = state
|
||||
.refreshes
|
||||
.get(&scope)
|
||||
.and_then(|work| work.etag.as_deref());
|
||||
if pending == Some(etag) {
|
||||
return Ok(false);
|
||||
}
|
||||
if let Some(entry) = state.snapshot.as_ref().and_then(|s| s.entries.get(&scope))
|
||||
@@ -129,17 +131,22 @@ impl CodexCredentialCatalogService {
|
||||
{
|
||||
// 已收到变更时,迟到的旧标记不能覆盖待刷新版本
|
||||
if pending.is_none() && entry.etag.as_deref() == Some(etag) {
|
||||
let mut confirmed_at = entry
|
||||
*entry
|
||||
.etag_confirmed_at
|
||||
.lock()
|
||||
.map_err(|_| CodexCredentialCatalogError::Cache)?;
|
||||
*confirmed_at = Some(tokio::time::Instant::now());
|
||||
.map_err(|_| CodexCredentialCatalogError::Cache)? =
|
||||
Some(tokio::time::Instant::now());
|
||||
if state.refreshes.remove(&scope).is_some() {
|
||||
self.retry_changed.notify_one();
|
||||
}
|
||||
}
|
||||
return Ok(false);
|
||||
}
|
||||
state.pending.insert(scope, etag.to_owned());
|
||||
drop(state);
|
||||
self.refresh_notification.notify_one();
|
||||
let work = state.refreshes.entry(scope).or_default();
|
||||
work.etag = Some(etag.to_owned());
|
||||
if work.retry.is_none() {
|
||||
self.schedule_refresh();
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
@@ -148,7 +155,30 @@ impl CodexCredentialCatalogService {
|
||||
}
|
||||
|
||||
pub async fn wait_for_refresh(&self) {
|
||||
self.refresh_notification.notified().await;
|
||||
loop {
|
||||
// 周期任务可能正在批量登记失败,等本轮结束再读取最早期限
|
||||
let deadline = {
|
||||
let _scan = self.refresh_lock.lock().await;
|
||||
self.cache
|
||||
.read()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.refreshes
|
||||
.values()
|
||||
.filter_map(|work| work.retry.as_ref().map(|retry| retry.at))
|
||||
.min()
|
||||
};
|
||||
let timer = async {
|
||||
match deadline {
|
||||
Some(at) => tokio::time::sleep_until(at).await,
|
||||
None => std::future::pending().await,
|
||||
}
|
||||
};
|
||||
tokio::select! {
|
||||
() = self.refresh_notification.notified() => return,
|
||||
() = timer => return,
|
||||
() = self.retry_changed.notified() => {},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 只合并成功的账号;手动刷新和后台任务同时完成时,保留较新的观测
|
||||
@@ -176,15 +206,10 @@ impl CodexCredentialCatalogService {
|
||||
entries.insert(scope, Arc::new(entry));
|
||||
}
|
||||
}
|
||||
self.publish(revision, entries)?;
|
||||
Ok(())
|
||||
self.publish(revision, entries)
|
||||
}
|
||||
|
||||
fn publish(
|
||||
&self,
|
||||
revision: u64,
|
||||
entries: Entries,
|
||||
) -> Result<Option<Arc<CodexCredentialCatalogSnapshot>>, CodexCredentialCatalogError> {
|
||||
fn publish(&self, revision: u64, entries: Entries) -> Result<(), CodexCredentialCatalogError> {
|
||||
let next =
|
||||
(!entries.is_empty()).then(|| Arc::new(CodexCredentialCatalogSnapshot::new(entries)));
|
||||
let old = self.cached()?;
|
||||
@@ -207,29 +232,40 @@ impl CodexCredentialCatalogService {
|
||||
return Err(CodexCredentialCatalogError::ConcurrentUpdate);
|
||||
}
|
||||
if let Some(snapshot) = &next {
|
||||
cache.pending.retain(|scope, tag| {
|
||||
cache.refreshes.retain(|scope, work| {
|
||||
let Some(entry) = snapshot.entries.get(scope) else {
|
||||
return true;
|
||||
};
|
||||
// 发布其他账号时保留通知,只有该账号更新的观测才能确认 ETag
|
||||
!entry.recognizes_etag(tag)
|
||||
|| old
|
||||
.as_ref()
|
||||
.and_then(|s| s.entries.get(scope))
|
||||
.is_some_and(|previous| previous.observed_at >= entry.observed_at)
|
||||
if old
|
||||
.as_ref()
|
||||
.and_then(|s| s.entries.get(scope))
|
||||
.is_some_and(|previous| previous.observed_at >= entry.observed_at)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
// 只有该账号更新的观测能解除退避,期间到达的新 ETag 仍需对账
|
||||
let pending = work
|
||||
.etag
|
||||
.as_deref()
|
||||
.is_some_and(|tag| !entry.recognizes_etag(tag));
|
||||
if work.retry.take().is_some() {
|
||||
self.retry_changed.notify_one();
|
||||
}
|
||||
if pending {
|
||||
self.schedule_refresh();
|
||||
}
|
||||
pending
|
||||
});
|
||||
}
|
||||
cache.snapshot = next.clone();
|
||||
cache.snapshot = next;
|
||||
if changed {
|
||||
cache.generation = cache.generation.wrapping_add(1);
|
||||
}
|
||||
Ok(next)
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 一次对账只探测缺失、过期或有新 ETag 的账号;成功逐批发布,失败不更新观测时间
|
||||
pub async fn refresh_catalogs(
|
||||
&self,
|
||||
) -> Result<Arc<CodexCredentialCatalogSnapshot>, CodexCredentialCatalogError> {
|
||||
/// 对到期账号限速探测,逐批发布成功结果并按账号安排重试
|
||||
pub async fn refresh_catalogs(&self) -> Result<(), CodexCredentialCatalogError> {
|
||||
let _writer = self.refresh_lock.lock().await;
|
||||
// 启动时数据库暂不可用,应先重试恢复,不能把整池误判为没有历史
|
||||
if !self
|
||||
@@ -248,14 +284,6 @@ impl CodexCredentialCatalogService {
|
||||
.filter(|a| eligible_catalog_account(a, now))
|
||||
.map(|a| (CodexCatalogScope::for_account(&a), a))
|
||||
.collect();
|
||||
let pending = {
|
||||
let mut cache = self
|
||||
.cache
|
||||
.write()
|
||||
.map_err(|_| CodexCredentialCatalogError::Cache)?;
|
||||
cache.pending.retain(|scope, _| current.contains_key(scope));
|
||||
cache.pending.clone()
|
||||
};
|
||||
let previous = self.cached()?;
|
||||
let mut entries = previous
|
||||
.as_ref()
|
||||
@@ -281,17 +309,38 @@ impl CodexCredentialCatalogService {
|
||||
.values()
|
||||
.map(|e| (e.content.digest, e.content.clone()))
|
||||
.collect();
|
||||
let due = current
|
||||
.into_iter()
|
||||
.filter(|(scope, _)| {
|
||||
pending.contains_key(scope)
|
||||
|| !entries.get(scope).is_some_and(|entry| entry.is_fresh(now))
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let due = {
|
||||
let mut cache = self
|
||||
.cache
|
||||
.write()
|
||||
.map_err(|_| CodexCredentialCatalogError::Cache)?;
|
||||
if cache.revision != revision {
|
||||
return Err(CodexCredentialCatalogError::ConcurrentUpdate);
|
||||
}
|
||||
cache
|
||||
.refreshes
|
||||
.retain(|scope, _| current.contains_key(scope));
|
||||
let instant = tokio::time::Instant::now();
|
||||
current
|
||||
.into_iter()
|
||||
.filter_map(|(scope, account)| {
|
||||
let work = cache.refreshes.get(&scope);
|
||||
let mode = match work {
|
||||
Some(AccountCatalogRefresh {
|
||||
retry: Some(retry), ..
|
||||
}) => (retry.at <= instant).then_some(CatalogFetchMode::Recovery)?,
|
||||
None if entries.get(&scope).is_some_and(|entry| entry.is_fresh(now)) => {
|
||||
return None;
|
||||
}
|
||||
_ => CatalogFetchMode::Discovery,
|
||||
};
|
||||
let etag = work.and_then(|work| work.etag.clone());
|
||||
Some((scope, account, etag, mode))
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
if due.is_empty() {
|
||||
return self
|
||||
.cached()?
|
||||
.ok_or(CodexCredentialCatalogError::NoEligibleCredential);
|
||||
return Ok(());
|
||||
}
|
||||
let client = self.discovery_client().await?;
|
||||
let mut pace = tokio::time::interval(REFRESH_SPACING);
|
||||
@@ -302,25 +351,23 @@ impl CodexCredentialCatalogService {
|
||||
});
|
||||
let fetches = stream::iter(due)
|
||||
.zip(starts)
|
||||
.map(|((scope, account), ())| {
|
||||
.map(|((scope, account, etag, mode), ())| {
|
||||
let client = &client;
|
||||
let etag = pending.get(&scope).cloned();
|
||||
async move {
|
||||
let (_, entry) = self
|
||||
.fetch_observation(client, &account, &scope, etag.clone())
|
||||
.await?;
|
||||
Ok((scope, entry))
|
||||
let result = self
|
||||
.fetch_observation(client, &account, &scope, etag, mode)
|
||||
.await;
|
||||
(scope, result)
|
||||
}
|
||||
})
|
||||
.buffer_unordered(REFRESH_CONCURRENCY);
|
||||
tokio::pin!(fetches);
|
||||
let mut batch = Vec::with_capacity(PUBLICATION_BATCH);
|
||||
let mut completed = 0_usize;
|
||||
let mut failures = 0_usize;
|
||||
let mut last_error = None;
|
||||
while let Some(result) = fetches.next().await {
|
||||
let mut cycle_error = None;
|
||||
while let Some((scope, result)) = fetches.next().await {
|
||||
match result {
|
||||
Ok((scope, mut entry)) => {
|
||||
Ok((_, mut entry)) => {
|
||||
entry.content = contents
|
||||
.entry(entry.content.digest)
|
||||
.or_insert_with(|| entry.content.clone())
|
||||
@@ -331,27 +378,59 @@ impl CodexCredentialCatalogService {
|
||||
self.merge_observations(revision, std::mem::take(&mut batch))?;
|
||||
}
|
||||
}
|
||||
Err(error) if error.is_account_failure() => {
|
||||
self.defer_account(revision, &scope, &entries, &error)?;
|
||||
}
|
||||
Err(error) => {
|
||||
failures += 1;
|
||||
last_error = Some(error);
|
||||
cycle_error = Some(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
if !batch.is_empty() {
|
||||
self.merge_observations(revision, batch)?;
|
||||
}
|
||||
if let Some(error) = &last_error {
|
||||
tracing::warn!(successes=completed,failures,%error,"OpenAI account catalog refresh incomplete");
|
||||
cycle_error.map_or(Ok(()), Err)
|
||||
}
|
||||
|
||||
fn defer_account(
|
||||
&self,
|
||||
revision: u64,
|
||||
scope: &CodexCatalogScope,
|
||||
previous: &Entries,
|
||||
error: &CodexCredentialCatalogError,
|
||||
) -> Result<(), CodexCredentialCatalogError> {
|
||||
let mut cache = self
|
||||
.cache
|
||||
.write()
|
||||
.map_err(|_| CodexCredentialCatalogError::Cache)?;
|
||||
if cache.revision != revision {
|
||||
return Err(CodexCredentialCatalogError::ConcurrentUpdate);
|
||||
}
|
||||
if pending
|
||||
.keys()
|
||||
.any(|k| self.cache.read().is_ok_and(|c| c.pending.contains_key(k)))
|
||||
&& let Some(error) = last_error.clone()
|
||||
// 手动刷新可能在后台请求期间发布了新目录,迟到的失败不能恢复旧退避
|
||||
let latest = cache.snapshot.as_ref().and_then(|s| s.entries.get(scope));
|
||||
if latest.map(|e| e.observed_at) != previous.get(scope).map(|e| e.observed_at) {
|
||||
return Ok(());
|
||||
}
|
||||
// 普通响应也能在探测期间确认旧目录仍有效
|
||||
if !cache.refreshes.contains_key(scope)
|
||||
&& latest.is_some_and(|entry| entry.is_fresh(SystemTime::now()))
|
||||
{
|
||||
self.refresh_notification.notify_one();
|
||||
return Err(error);
|
||||
return Ok(());
|
||||
}
|
||||
self.cached()?
|
||||
.ok_or(last_error.unwrap_or(CodexCredentialCatalogError::NoEligibleCredential))
|
||||
let work = cache.refreshes.entry(scope.clone()).or_default();
|
||||
let delay = work
|
||||
.retry
|
||||
.as_ref()
|
||||
.map_or(CATALOG_FAILURE_BACKOFF_BASE, |retry| {
|
||||
(retry.delay * 2).min(CATALOG_FAILURE_BACKOFF_MAX)
|
||||
});
|
||||
work.retry = Some(CatalogRetry {
|
||||
at: tokio::time::Instant::now() + delay,
|
||||
delay,
|
||||
});
|
||||
drop(cache);
|
||||
self.retry_changed.notify_one();
|
||||
tracing::warn!(account_id = %scope.account_id, retry_after_secs = delay.as_secs(), %error, "OpenAI account catalog refresh deferred");
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -3,8 +3,30 @@
|
||||
use gateway_core::account::scope::FrozenAccountScope;
|
||||
use gateway_core::account::{ProviderAccount, ProviderAccountId};
|
||||
|
||||
use super::api_key::ApiKeyProtocol;
|
||||
use super::types::CODEX_AUTHENTICATION_KIND_OAUTH;
|
||||
|
||||
// 原生资格在账号边界检查,显式插件适配拥有自己的输入协议
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
pub(super) enum NativeProtocol {
|
||||
Fixed(ApiKeyProtocol),
|
||||
Chat,
|
||||
Unsupported,
|
||||
}
|
||||
|
||||
impl NativeProtocol {
|
||||
pub(super) fn for_source(protocol: &str) -> Self {
|
||||
match protocol {
|
||||
gateway_protocol::openai::OPENAI_PROTOCOL => Self::Fixed(ApiKeyProtocol::Responses),
|
||||
gateway_protocol::anthropic::ANTHROPIC_PROTOCOL | "token-count" => {
|
||||
Self::Fixed(ApiKeyProtocol::Messages)
|
||||
}
|
||||
gateway_protocol::chat_completions::CHAT_PROTOCOL => Self::Chat,
|
||||
_ => Self::Unsupported,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 选号使用的模型与端点类别,原生 Images 和 Search 允许模型未知
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) enum CodexSelectionModel<'a> {
|
||||
|
||||
@@ -10,6 +10,7 @@ mod eligibility;
|
||||
mod oauth;
|
||||
mod profile_statistics;
|
||||
mod quota;
|
||||
mod recovery_feedback;
|
||||
mod recovery_log;
|
||||
mod refresh;
|
||||
mod repository;
|
||||
@@ -24,6 +25,7 @@ pub(crate) use affinity::{
|
||||
derive_codex_transport_key, derive_endpoint_affinity_with_headers,
|
||||
derive_live_session_affinity, derive_messages_session_affinity,
|
||||
derive_previous_response_id_hash, derive_turn_alias, root_session_affinity,
|
||||
session_affinity_with_headers,
|
||||
};
|
||||
pub(crate) use eligibility::CodexSelectionModel;
|
||||
pub(crate) use oauth::oauth_owner_ref;
|
||||
@@ -59,13 +61,13 @@ pub use oauth::{
|
||||
pub use profile_statistics::{
|
||||
CodexCredentialProfileService, CodexProfileAvatarError, CodexProfileStatisticsError,
|
||||
};
|
||||
pub(crate) use quota::observed_quota_window;
|
||||
pub use quota::{
|
||||
CodexAccountQuotaSnapshot, CodexCredentialQuotaError, CodexCredentialQuotaService,
|
||||
CodexInitialSyncDelays, CodexQuotaFact, CodexQuotaRefreshPolicy, CodexQuotaSyncSummary,
|
||||
CodexQuotaWindow, CodexQuotaWindowKind, CodexQuotaWindowRole, CodexResetCreditsError,
|
||||
parse_codex_quota_usage,
|
||||
};
|
||||
pub(crate) use quota::{DEFAULT_RATE_LIMIT_COOLDOWN, observed_quota_window};
|
||||
pub use refresh::{
|
||||
CodexCredentialRefreshError, CodexCredentialRefreshOutcome, CodexCredentialRefreshService,
|
||||
DueCodexCredential,
|
||||
|
||||
@@ -75,7 +75,7 @@ use snapshot::{
|
||||
// 同一份上游观测只重做本地合并,高并发时不无限争抢写入
|
||||
const QUOTA_MERGE_ATTEMPTS: usize = 3;
|
||||
const LIMIT_EVIDENCE_FIELD: &str = "_cpr_quota_limit_evidence";
|
||||
const DEFAULT_RATE_LIMIT_COOLDOWN: Duration = Duration::from_secs(60);
|
||||
pub(crate) const DEFAULT_RATE_LIMIT_COOLDOWN: Duration = Duration::from_secs(60);
|
||||
pub(crate) const QUOTA_SCHEDULING_TTL: Duration = Duration::from_secs(10 * 60);
|
||||
const QUOTA_HYDRATION_FAILURE_TTL: Duration = Duration::from_secs(5);
|
||||
const PERIODIC_QUOTA_REFRESH_RETRY_INTERVAL: Duration = Duration::from_secs(30 * 60);
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
//! OpenAI 账号的 OAuth 拒绝记录与 Cloudflare 连续失败反馈
|
||||
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
use std::time::{Duration, SystemTime};
|
||||
|
||||
use gateway_core::account::{CredentialRevision, ProviderAccountId};
|
||||
|
||||
const STALE_AFTER: Duration = Duration::from_secs(60 * 60);
|
||||
const CHALLENGE_BACKOFF: [Duration; 4] = [
|
||||
Duration::from_secs(10),
|
||||
Duration::from_secs(30),
|
||||
Duration::from_secs(90),
|
||||
Duration::from_secs(120),
|
||||
];
|
||||
const PATH_BLOCK_THRESHOLD: usize = 3;
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct RecoveryFeedback {
|
||||
// 跨账号条目重建仍保持顺序,较早的成功不能清除后来创建的记录
|
||||
last_observation: u64,
|
||||
accounts: HashMap<ProviderAccountId, AccountFeedback>,
|
||||
}
|
||||
|
||||
struct AccountFeedback {
|
||||
observed_at: SystemTime,
|
||||
rejection: Option<TokenRejection>,
|
||||
challenges: VecDeque<u64>,
|
||||
path_blocks: VecDeque<u64>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct TokenRejection {
|
||||
/// 首次被拒并交给续期的版本;后续 401 不会再授予一次续期
|
||||
refresh_requested_at: CredentialRevision,
|
||||
last_observation: u64,
|
||||
}
|
||||
|
||||
impl AccountFeedback {
|
||||
fn is_active(&self, now: SystemTime) -> bool {
|
||||
!matches!(now.duration_since(self.observed_at), Ok(age) if age > STALE_AFTER)
|
||||
}
|
||||
}
|
||||
|
||||
// 超过最大退避或失效阈值的旧失败不会再影响决策
|
||||
fn record_failure(streak: &mut VecDeque<u64>, observation: u64, limit: usize) -> usize {
|
||||
if streak.len() == limit {
|
||||
streak.pop_front();
|
||||
}
|
||||
streak.push_back(observation);
|
||||
streak.len()
|
||||
}
|
||||
|
||||
impl RecoveryFeedback {
|
||||
fn active_account(
|
||||
&mut self,
|
||||
id: &ProviderAccountId,
|
||||
now: SystemTime,
|
||||
) -> Option<&AccountFeedback> {
|
||||
if !self.accounts.get(id)?.is_active(now) {
|
||||
self.accounts.remove(id);
|
||||
return None;
|
||||
}
|
||||
self.accounts.get(id)
|
||||
}
|
||||
|
||||
fn next_failure(
|
||||
&mut self,
|
||||
id: &ProviderAccountId,
|
||||
now: SystemTime,
|
||||
) -> (u64, &mut AccountFeedback) {
|
||||
self.accounts.retain(|_, state| state.is_active(now));
|
||||
self.last_observation += 1;
|
||||
let state = self
|
||||
.accounts
|
||||
.entry(id.clone())
|
||||
.or_insert_with(|| AccountFeedback {
|
||||
observed_at: now,
|
||||
rejection: None,
|
||||
challenges: VecDeque::new(),
|
||||
path_blocks: VecDeque::new(),
|
||||
});
|
||||
state.observed_at = now;
|
||||
(self.last_observation, state)
|
||||
}
|
||||
|
||||
pub(super) fn challenge_delay(
|
||||
&mut self,
|
||||
id: &ProviderAccountId,
|
||||
now: SystemTime,
|
||||
retry_after: Option<Duration>,
|
||||
) -> Duration {
|
||||
let (order, state) = self.next_failure(id, now);
|
||||
let count = record_failure(&mut state.challenges, order, CHALLENGE_BACKOFF.len());
|
||||
retry_after
|
||||
.unwrap_or_default()
|
||||
.max(CHALLENGE_BACKOFF[count - 1])
|
||||
}
|
||||
|
||||
pub(super) fn path_block_reached_limit(
|
||||
&mut self,
|
||||
id: &ProviderAccountId,
|
||||
now: SystemTime,
|
||||
) -> bool {
|
||||
let (order, state) = self.next_failure(id, now);
|
||||
record_failure(&mut state.path_blocks, order, PATH_BLOCK_THRESHOLD) == PATH_BLOCK_THRESHOLD
|
||||
}
|
||||
|
||||
pub(super) fn pending_refresh(
|
||||
&mut self,
|
||||
id: &ProviderAccountId,
|
||||
now: SystemTime,
|
||||
) -> Option<CredentialRevision> {
|
||||
self.active_account(id, now)?
|
||||
.rejection
|
||||
.map(|rejected| rejected.refresh_requested_at)
|
||||
}
|
||||
|
||||
pub(super) fn record_rejection(
|
||||
&mut self,
|
||||
id: &ProviderAccountId,
|
||||
refresh_requested_at: CredentialRevision,
|
||||
now: SystemTime,
|
||||
) {
|
||||
let (order, state) = self.next_failure(id, now);
|
||||
if state
|
||||
.rejection
|
||||
.is_none_or(|rejected| rejected.refresh_requested_at <= refresh_requested_at)
|
||||
{
|
||||
state.rejection = Some(TokenRejection {
|
||||
refresh_requested_at,
|
||||
last_observation: order,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// 在任何异步核对之前记下已观察到的失败范围
|
||||
pub(super) fn success_boundary(
|
||||
&mut self,
|
||||
id: &ProviderAccountId,
|
||||
now: SystemTime,
|
||||
) -> Option<u64> {
|
||||
self.active_account(id, now)?;
|
||||
Some(self.last_observation)
|
||||
}
|
||||
|
||||
pub(super) fn confirm_success(
|
||||
&mut self,
|
||||
id: &ProviderAccountId,
|
||||
through: u64,
|
||||
sent: CredentialRevision,
|
||||
) {
|
||||
let Some(state) = self.accounts.get_mut(id) else {
|
||||
return;
|
||||
};
|
||||
if state.rejection.is_some_and(|rejected| {
|
||||
rejected.refresh_requested_at < sent && rejected.last_observation <= through
|
||||
}) {
|
||||
state.rejection = None;
|
||||
}
|
||||
state.challenges.retain(|order| *order > through);
|
||||
state.path_blocks.retain(|order| *order > through);
|
||||
if state.challenges.is_empty() && state.path_blocks.is_empty() && state.rejection.is_none()
|
||||
{
|
||||
self.accounts.remove(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -330,6 +330,14 @@ impl CodexCredentialRefreshService {
|
||||
return Ok(CodexCredentialRefreshOutcome::LeaseUnavailable { account_id });
|
||||
}
|
||||
};
|
||||
// 候选快照在取锁前读取,其他刷新或 Cookie 写回可能已推进版本
|
||||
match self.repository.load_complete_data(&due.account).await {
|
||||
Ok(_) => {}
|
||||
Err(CredentialRepositoryError::RevisionConflict(_)) => {
|
||||
return Ok(CodexCredentialRefreshOutcome::Stale { account_id });
|
||||
}
|
||||
Err(error) => return Err(error.into()),
|
||||
}
|
||||
let refresh_token = due
|
||||
.secret
|
||||
.refresh_token
|
||||
|
||||
@@ -10,6 +10,8 @@ use gateway_core::policy::ClientApiKeyId;
|
||||
use gateway_core::provider_ports::ProviderConcurrencyPool;
|
||||
use tokio::sync::{Mutex as AsyncMutex, OwnedMutexGuard};
|
||||
|
||||
use super::eligibility::NativeProtocol;
|
||||
|
||||
const PROJECTION_TTL: Duration = Duration::from_millis(200);
|
||||
const MAX_PROJECTIONS: usize = 32;
|
||||
const MAX_CACHED_CANDIDATES: usize = 8192;
|
||||
@@ -19,6 +21,7 @@ pub(super) struct SchedulingProjectionKey {
|
||||
pub client_key: ClientApiKeyId,
|
||||
pub scope: Arc<FrozenAccountScope>,
|
||||
pub model: String,
|
||||
pub native_protocol: NativeProtocol,
|
||||
pub policy: AccountSelectionPolicy,
|
||||
pub requires_websocket: bool,
|
||||
pub concurrency_pool: ProviderConcurrencyPool,
|
||||
|
||||
@@ -27,9 +27,10 @@ use gateway_core::engine::{
|
||||
use gateway_core::provider_ports::{
|
||||
ProviderAccountAdmission, ProviderConcurrencyPool, ProviderCooldownPort, ProviderCooldownScope,
|
||||
ProviderLeaseAcquisition, ProviderLeaseGuard, ProviderLeasePort, ProviderLeaseRequest,
|
||||
ProviderSchedulingLeaseRequest, ProviderScopedCooldown, ProviderSessionAffinityKey,
|
||||
ProviderSessionAffinityPort, ProviderSessionBinding, ProviderSessionClaim,
|
||||
ProviderSessionExclusionPort, ProviderSessionExclusions, ProviderStoreError,
|
||||
ProviderRefreshLeaseRequest, ProviderSchedulingLeaseRequest, ProviderScopedCooldown,
|
||||
ProviderSessionAffinityKey, ProviderSessionAffinityPort, ProviderSessionBinding,
|
||||
ProviderSessionClaim, ProviderSessionExclusionPort, ProviderSessionExclusions,
|
||||
ProviderStoreError,
|
||||
};
|
||||
use gateway_core::routing::{ProviderKind, UpstreamModelId};
|
||||
use secrecy::ExposeSecret;
|
||||
@@ -40,8 +41,9 @@ use super::affinity::CodexSessionAffinity;
|
||||
use super::catalog::CodexCredentialCatalogService;
|
||||
use super::codec::CodexRuntimeAuthentication;
|
||||
use super::cookie::CodexCookiePolicy;
|
||||
use super::eligibility::CodexSelectionModel;
|
||||
use super::eligibility::{CodexSelectionModel, NativeProtocol};
|
||||
use super::quota::CodexCredentialQuotaService;
|
||||
use super::recovery_feedback::RecoveryFeedback;
|
||||
use super::refresh::refresh_recovery_deadline;
|
||||
use super::repository::{CodexCredentialRepository, CredentialRepositoryError};
|
||||
use super::scheduling_projection::{SchedulingProjectionCache, SchedulingProjectionKey};
|
||||
@@ -49,21 +51,11 @@ use super::types::{
|
||||
CODEX_AUTHENTICATION_KIND_OAUTH, CodexCookie, CodexCookieCaptureOutcome, RuntimeCodexCookie,
|
||||
};
|
||||
|
||||
const CLOUDFLARE_RECOVERY_STALE_AFTER: Duration = Duration::from_secs(60 * 60);
|
||||
const CLOUDFLARE_CHALLENGE_BACKOFF: [Duration; 4] = [
|
||||
Duration::from_secs(10),
|
||||
Duration::from_secs(30),
|
||||
Duration::from_secs(90),
|
||||
Duration::from_secs(120),
|
||||
];
|
||||
const CLOUDFLARE_PATH_BLOCK_THRESHOLD: u32 = 3;
|
||||
// 绑定失败会阻止发送,预算容纳短暂调度抖动;可丢失的策略排除记录保持独立预算
|
||||
const SESSION_AFFINITY_TIMEOUT: Duration = Duration::from_millis(500);
|
||||
const CYBER_POLICY_TIMEOUT: Duration = Duration::from_millis(100);
|
||||
const CYBER_POLICY_SESSION_TTL: Duration = Duration::from_secs(60 * 60);
|
||||
const MAX_ACCOUNT_SNAPSHOT_RETRIES: u32 = 3;
|
||||
// 套餐权限可能变化,明确拒绝只作有界的账号模型排除,不冻结整个账号
|
||||
const MODEL_UNSUPPORTED_COOLDOWN: Duration = Duration::from_secs(30 * 60);
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum CodexAccountFailure {
|
||||
@@ -98,13 +90,6 @@ pub enum CodexAccountFailure {
|
||||
CloudflarePathBlocked,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
struct RiskRecoveryState {
|
||||
challenge_count: u32,
|
||||
path_block_count: u32,
|
||||
observed_at: SystemTime,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
enum CookieRecovery {
|
||||
ExpireAt(SystemTime),
|
||||
@@ -157,7 +142,7 @@ pub struct CodexCredentialSelector {
|
||||
cooldowns: Arc<dyn ProviderCooldownPort>,
|
||||
upstream_info: Arc<dyn gateway_core::account::UpstreamInfoSource>,
|
||||
cookie_policy: CodexCookiePolicy,
|
||||
risk_recovery: Mutex<HashMap<String, RiskRecoveryState>>,
|
||||
recovery_feedback: Mutex<RecoveryFeedback>,
|
||||
account_feedback: Arc<AccountFeedbackStats>,
|
||||
scheduling_projection: SchedulingProjectionCache,
|
||||
endpoint_protocols:
|
||||
@@ -335,7 +320,7 @@ impl CodexCredentialSelector {
|
||||
cooldowns,
|
||||
upstream_info,
|
||||
cookie_policy,
|
||||
risk_recovery: Mutex::new(HashMap::new()),
|
||||
recovery_feedback: Mutex::default(),
|
||||
waiting: ConcurrencyWaitQueue::default(),
|
||||
reserved_waiting: ConcurrencyWaitQueue::default(),
|
||||
account_feedback,
|
||||
@@ -665,7 +650,10 @@ impl CodexCredentialSelector {
|
||||
account_ids: &[ProviderAccountId],
|
||||
native_accounts: &BTreeSet<ProviderAccountId>,
|
||||
model: CodexSelectionModel<'_>,
|
||||
) -> HashMap<ProviderAccountId, AccountCooldown> {
|
||||
) -> (
|
||||
HashMap<ProviderAccountId, AccountCooldown>,
|
||||
BTreeSet<ProviderAccountId>,
|
||||
) {
|
||||
let native = accounts
|
||||
.iter()
|
||||
.filter(|account| native_accounts.contains(account.id()));
|
||||
@@ -693,11 +681,15 @@ impl CodexCredentialSelector {
|
||||
.then(|| (id.clone(), state))
|
||||
})
|
||||
.collect();
|
||||
let mut model_rate_limited_accounts = BTreeSet::new();
|
||||
for (account, cooldown) in native.zip(model_cooldowns) {
|
||||
if let Some(cooldown) = cooldown.ok().flatten().filter(|cooldown| {
|
||||
cooldown.credential_revision() == account.revision()
|
||||
&& cooldown.until() > SystemTime::now()
|
||||
}) {
|
||||
if cooldown.rate_limited_until() == Some(cooldown.until()) {
|
||||
model_rate_limited_accounts.insert(account.id().clone());
|
||||
}
|
||||
// 两种冷却取较晚期限,保留账号级冷却的恢复探测语义
|
||||
active
|
||||
.entry(account.id().clone())
|
||||
@@ -708,7 +700,7 @@ impl CodexCredentialSelector {
|
||||
});
|
||||
}
|
||||
}
|
||||
active
|
||||
(active, model_rate_limited_accounts)
|
||||
}
|
||||
|
||||
async fn select_inner_loop(
|
||||
@@ -816,6 +808,7 @@ impl CodexCredentialSelector {
|
||||
client_key: request.attempt.client_api_key_ref().clone(),
|
||||
scope: Arc::clone(scope),
|
||||
model: model.to_owned(),
|
||||
native_protocol: request.native_protocol,
|
||||
policy: request.attempt.account_selection_policy(),
|
||||
requires_websocket: request.requires_websocket,
|
||||
concurrency_pool,
|
||||
@@ -1092,8 +1085,8 @@ impl CodexCredentialSelector {
|
||||
continue 'capacity;
|
||||
}
|
||||
let follow_only = follow_only && image_primary_to_keep.is_none();
|
||||
let rate_limits = if diagnostic {
|
||||
HashMap::new()
|
||||
let (rate_limits, model_rate_limited_accounts) = if diagnostic {
|
||||
Default::default()
|
||||
} else {
|
||||
self.load_candidate_cooldowns(&accounts, &account_ids, &native_accounts, model)
|
||||
.await
|
||||
@@ -1467,6 +1460,33 @@ impl CodexCredentialSelector {
|
||||
}
|
||||
// 只判断本次账号范围;空池、认证失效和租约失败不能伪装成额度耗尽
|
||||
// 策略排除与临时容量阻塞分开,保留繁忙账号的可恢复语义
|
||||
// 只有本轮可选账号的原生模型限流才提供等待提示
|
||||
let cooldown_retry = candidates
|
||||
.iter()
|
||||
.filter(|candidate| {
|
||||
model_rate_limited_accounts.contains(candidate.account.id())
|
||||
})
|
||||
.filter(|candidate| {
|
||||
!context.excluded_accounts.contains(candidate.account.id())
|
||||
})
|
||||
.filter(|candidate| {
|
||||
context
|
||||
.account_scope
|
||||
.as_ref()
|
||||
.is_none_or(|scope| scope.allows(candidate.account.id()))
|
||||
})
|
||||
.filter(|candidate| {
|
||||
candidate
|
||||
.account
|
||||
.status_projection(context.now, candidate.signals.cooldown)
|
||||
.status
|
||||
== AccountStatus::RateLimited
|
||||
})
|
||||
.filter_map(|candidate| candidate.signals.cooldown)
|
||||
.filter(|cooldown| cooldown.kind == AccountCooldownKind::RateLimit)
|
||||
.filter_map(|cooldown| cooldown.until.duration_since(context.now).ok())
|
||||
.min();
|
||||
shortest_retry = minimum_duration(shortest_retry, cooldown_retry);
|
||||
let mut statuses = candidates
|
||||
.iter()
|
||||
.filter(|candidate| {
|
||||
@@ -1689,20 +1709,11 @@ impl CodexCredentialSelector {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn record_model_unsupported(
|
||||
pub(crate) async fn record_model_cooldown(
|
||||
&self,
|
||||
account: &ProviderAccount,
|
||||
model: &gateway_core::routing::UpstreamModelId,
|
||||
cooldown: ProviderScopedCooldown,
|
||||
) -> Result<(), ProviderStoreError> {
|
||||
let now = SystemTime::now();
|
||||
self.cooldowns
|
||||
.put_scoped_if_later(ProviderScopedCooldown::new(
|
||||
account.id().clone(),
|
||||
account.revision(),
|
||||
ProviderCooldownScope::upstream_model(model.clone()),
|
||||
now.checked_add(MODEL_UNSUPPORTED_COOLDOWN).unwrap_or(now),
|
||||
))
|
||||
.await?;
|
||||
self.cooldowns.put_scoped_if_later(cooldown).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1974,6 +1985,7 @@ impl CodexCredentialSelector {
|
||||
pub async fn record_failure(
|
||||
&self,
|
||||
account: &ProviderAccount,
|
||||
authentication: &CodexRuntimeAuthentication,
|
||||
failure: CodexAccountFailure,
|
||||
message: Option<String>,
|
||||
) -> Result<(), CredentialSelectionError> {
|
||||
@@ -1981,40 +1993,8 @@ impl CodexCredentialSelector {
|
||||
let message = message.filter(|value| !value.trim().is_empty());
|
||||
match failure {
|
||||
CodexAccountFailure::CredentialExpired => {
|
||||
if account.authentication_kind() == CODEX_AUTHENTICATION_KIND_OAUTH
|
||||
&& account.has_refresh_token()
|
||||
&& account
|
||||
.access_token_expires_at()
|
||||
.is_some_and(|expires_at| expires_at <= now)
|
||||
&& refresh_recovery_deadline(account.access_token_expires_at())
|
||||
.is_some_and(|deadline| deadline > now)
|
||||
{
|
||||
tracing::info!(
|
||||
account_id = %account.id(),
|
||||
access_token_expires_at = ?account.access_token_expires_at()
|
||||
.map(chrono::DateTime::<chrono::Utc>::from),
|
||||
recovery_deadline = ?refresh_recovery_deadline(account.access_token_expires_at())
|
||||
.map(chrono::DateTime::<chrono::Utc>::from),
|
||||
"OpenAI access token expired; retaining account for bounded OAuth refresh recovery"
|
||||
);
|
||||
return self
|
||||
.apply_credential_state(
|
||||
account,
|
||||
CredentialState::Ready,
|
||||
AccountErrorReason::AccessTokenExpired,
|
||||
now,
|
||||
message,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
self.apply_credential_state(
|
||||
account,
|
||||
CredentialState::Expired,
|
||||
AccountErrorReason::AccessTokenExpired,
|
||||
now,
|
||||
message,
|
||||
)
|
||||
.await
|
||||
self.record_credential_expiry(account, authentication, now, message)
|
||||
.await
|
||||
}
|
||||
CodexAccountFailure::IdentityVerificationRequired => {
|
||||
self.apply_credential_state(
|
||||
@@ -2074,7 +2054,9 @@ impl CodexCredentialSelector {
|
||||
}
|
||||
// Cloudflare 挑战:内存退避表(记录风险计数),不写账号事实
|
||||
CodexAccountFailure::CloudflareChallenge { retry_after } => {
|
||||
let delay = self.cloudflare_challenge_delay(account.id(), now, retry_after);
|
||||
let delay = self
|
||||
.feedback()
|
||||
.challenge_delay(account.id(), now, retry_after);
|
||||
let recovery = now
|
||||
.checked_add(delay)
|
||||
.map_or(CookieRecovery::Clear, CookieRecovery::ExpireAt);
|
||||
@@ -2083,8 +2065,7 @@ impl CodexCredentialSelector {
|
||||
}
|
||||
// Cloudflare 路径被封:连续超阈值才置 Invalid;否则内存退避
|
||||
CodexAccountFailure::CloudflarePathBlocked => {
|
||||
let blocked = self.record_cloudflare_path_block(account.id(), now);
|
||||
if blocked >= CLOUDFLARE_PATH_BLOCK_THRESHOLD {
|
||||
if self.feedback().path_block_reached_limit(account.id(), now) {
|
||||
self.apply_credential_state(
|
||||
account,
|
||||
CredentialState::Invalid,
|
||||
@@ -2101,6 +2082,108 @@ impl CodexCredentialSelector {
|
||||
}
|
||||
}
|
||||
|
||||
async fn record_credential_expiry(
|
||||
&self,
|
||||
sent: &ProviderAccount,
|
||||
authentication: &CodexRuntimeAuthentication,
|
||||
now: SystemTime,
|
||||
message: Option<String>,
|
||||
) -> Result<(), CredentialSelectionError> {
|
||||
// 空闲时保持到期写入与恢复标记先于 RT exchange;租约忙也不能丢弃 401
|
||||
let _guard = if sent.has_refresh_token() && authentication.oauth().is_some() {
|
||||
self.credential_mutation_guard(sent).await?
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let mut account = std::borrow::Cow::Borrowed(sent);
|
||||
for _ in 0..=MAX_ACCOUNT_SNAPSHOT_RETRIES {
|
||||
match self
|
||||
.apply_credential_expiry(&account, now, message.clone())
|
||||
.await
|
||||
{
|
||||
Ok(true) => return Ok(()),
|
||||
Ok(false) | Err(CredentialSelectionError::RevisionConflict(_)) => (),
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
// Cookie CAS 保留到期时间;若它先推进版本,只对仍是出站 AT 的新快照重试
|
||||
let Some(latest) = self
|
||||
.current_account_for_token(sent.id(), authentication)
|
||||
.await?
|
||||
else {
|
||||
return Ok(());
|
||||
};
|
||||
if latest.revision() == account.revision() {
|
||||
return Ok(());
|
||||
}
|
||||
account = std::borrow::Cow::Owned(latest);
|
||||
}
|
||||
Err(CredentialRepositoryError::RevisionConflict(None).into())
|
||||
}
|
||||
|
||||
async fn apply_credential_expiry(
|
||||
&self,
|
||||
account: &ProviderAccount,
|
||||
now: SystemTime,
|
||||
message: Option<String>,
|
||||
) -> Result<bool, CredentialSelectionError> {
|
||||
let expires_at = account.access_token_expires_at().filter(|_| {
|
||||
account.authentication_kind() == CODEX_AUTHENTICATION_KIND_OAUTH
|
||||
&& account.has_refresh_token()
|
||||
});
|
||||
let pending_refresh =
|
||||
expires_at.and_then(|_| self.feedback().pending_refresh(account.id(), now));
|
||||
if expires_at.is_some_and(|expiry| expiry > now)
|
||||
&& pending_refresh.is_none_or(|rejected| rejected >= account.revision())
|
||||
{
|
||||
// 资源服务拒绝未到期的访问令牌不能证明 refresh token 失效
|
||||
// 让访问令牌到期并交给 OAuth 续期,条件写入不影响已轮换的凭据
|
||||
let expired = self
|
||||
.repository
|
||||
.store()
|
||||
.expire_access_token(account, now)
|
||||
.await
|
||||
.map_err(|source| CredentialSelectionError::Store(ErrorSource::new(source)))?;
|
||||
if !expired {
|
||||
return Ok(false);
|
||||
}
|
||||
self.feedback()
|
||||
.record_rejection(account.id(), account.revision(), now);
|
||||
tracing::info!(
|
||||
account_id = %account.id(),
|
||||
"OpenAI access token rejected before expiry; deferring to OAuth refresh"
|
||||
);
|
||||
return Ok(true);
|
||||
}
|
||||
let state = if expires_at.is_some_and(|expiry| expiry <= now)
|
||||
&& refresh_recovery_deadline(expires_at).is_some_and(|deadline| deadline > now)
|
||||
{
|
||||
tracing::info!(
|
||||
account_id = %account.id(),
|
||||
access_token_expires_at = ?expires_at
|
||||
.map(chrono::DateTime::<chrono::Utc>::from),
|
||||
recovery_deadline = ?refresh_recovery_deadline(expires_at)
|
||||
.map(chrono::DateTime::<chrono::Utc>::from),
|
||||
"OpenAI access token expired; retaining account for bounded OAuth refresh recovery"
|
||||
);
|
||||
CredentialState::Ready
|
||||
} else {
|
||||
CredentialState::Expired
|
||||
};
|
||||
self.apply_credential_state(
|
||||
account,
|
||||
state,
|
||||
AccountErrorReason::AccessTokenExpired,
|
||||
now,
|
||||
message,
|
||||
)
|
||||
.await?;
|
||||
if let Some(rejected) = pending_refresh {
|
||||
self.feedback()
|
||||
.record_rejection(account.id(), rejected, now);
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
async fn apply_credential_state(
|
||||
&self,
|
||||
account: &ProviderAccount,
|
||||
@@ -2121,45 +2204,85 @@ impl CodexCredentialSelector {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn record_success(&self, account: &ProviderAccount) {
|
||||
self.restore_recoverable_account_state(account).await;
|
||||
self.risk_recovery
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.remove(account.id().as_str());
|
||||
// 绑定只在发送前认领,迟到的响应不能迁移或复活已经过期的会话绑定
|
||||
}
|
||||
|
||||
async fn restore_recoverable_account_state(&self, account: &ProviderAccount) {
|
||||
pub async fn record_success(
|
||||
&self,
|
||||
account: &ProviderAccount,
|
||||
sent_revision: CredentialRevision,
|
||||
authentication: &CodexRuntimeAuthentication,
|
||||
) {
|
||||
let boundary = self
|
||||
.feedback()
|
||||
.success_boundary(account.id(), SystemTime::now());
|
||||
let Ok(current) = self.current_account(account.id()).await else {
|
||||
return;
|
||||
};
|
||||
if current.provider() != &self.provider_kind
|
||||
|| current.revision() != account.revision()
|
||||
|| !current.enabled()
|
||||
if current.provider() != &self.provider_kind || !current.enabled() {
|
||||
return;
|
||||
}
|
||||
let same_revision = current.revision() == account.revision();
|
||||
if same_revision {
|
||||
self.restore_recoverable_account_state(¤t).await;
|
||||
}
|
||||
let Some(through) = boundary else {
|
||||
return;
|
||||
};
|
||||
// Cookie 也会推进版本;版本不同时,只有出站 AT 仍在使用才承认这次成功
|
||||
if !same_revision
|
||||
&& !matches!(
|
||||
self.current_account_for_token(account.id(), authentication)
|
||||
.await,
|
||||
Ok(Some(_))
|
||||
)
|
||||
{
|
||||
return;
|
||||
}
|
||||
self.feedback()
|
||||
.confirm_success(account.id(), through, sent_revision);
|
||||
}
|
||||
|
||||
async fn current_account_for_token(
|
||||
&self,
|
||||
account_id: &ProviderAccountId,
|
||||
authentication: &CodexRuntimeAuthentication,
|
||||
) -> Result<Option<ProviderAccount>, CredentialSelectionError> {
|
||||
let Some(sent) = authentication.oauth() else {
|
||||
return Ok(None);
|
||||
};
|
||||
let loaded = self
|
||||
.repository
|
||||
.store()
|
||||
.load_current_credential(account_id)
|
||||
.await
|
||||
.map_err(|error| CredentialSelectionError::Store(ErrorSource::new(error)))?;
|
||||
let runtime = self.repository.decode_runtime_credential(&loaded)?;
|
||||
Ok((loaded.account.enabled()
|
||||
&& runtime.authentication.oauth().is_some_and(|oauth| {
|
||||
oauth.access_token.expose_secret() == sent.access_token.expose_secret()
|
||||
}))
|
||||
.then_some(loaded.account))
|
||||
}
|
||||
|
||||
async fn restore_recoverable_account_state(&self, current: &ProviderAccount) {
|
||||
let observed_at = SystemTime::now();
|
||||
if current.credential_state() != CredentialState::Ready
|
||||
&& let Err(error) = self
|
||||
.repository
|
||||
.apply_state(¤t, CredentialState::Ready, observed_at)
|
||||
.apply_state(current, CredentialState::Ready, observed_at)
|
||||
.await
|
||||
{
|
||||
tracing::warn!(
|
||||
account_id = %account.id(),
|
||||
account_id = %current.id(),
|
||||
error = %error,
|
||||
"OpenAI credential recovery after successful upstream response failed"
|
||||
);
|
||||
}
|
||||
if let Err(error) = self
|
||||
.quota
|
||||
.record_successful_inference(¤t, observed_at)
|
||||
.record_successful_inference(current, observed_at)
|
||||
.await
|
||||
{
|
||||
tracing::warn!(
|
||||
account_id = %account.id(),
|
||||
account_id = %current.id(),
|
||||
error = %error,
|
||||
"OpenAI quota recovery after successful upstream response failed"
|
||||
);
|
||||
@@ -2203,6 +2326,13 @@ impl CodexCredentialSelector {
|
||||
rejected: parsed.rejected,
|
||||
});
|
||||
}
|
||||
let Some(_guard) = self.credential_mutation_guard(account).await? else {
|
||||
// 刷新正在交换或提交 token,跳过可由后续响应再次捕获的 Cookie
|
||||
return Ok(CodexCookieCaptureOutcome {
|
||||
credential_revision: None,
|
||||
rejected: parsed.rejected,
|
||||
});
|
||||
};
|
||||
let mut data = self.repository.load_complete_data(account).await?;
|
||||
let Some(cookies) = data.cookies_mut() else {
|
||||
return Ok(CodexCookieCaptureOutcome {
|
||||
@@ -2241,36 +2371,28 @@ impl CodexCredentialSelector {
|
||||
})
|
||||
}
|
||||
|
||||
fn cloudflare_challenge_delay(
|
||||
&self,
|
||||
account_id: &ProviderAccountId,
|
||||
now: SystemTime,
|
||||
retry_after: Option<Duration>,
|
||||
) -> Duration {
|
||||
let mut recovery = self
|
||||
.risk_recovery
|
||||
fn feedback(&self) -> std::sync::MutexGuard<'_, RecoveryFeedback> {
|
||||
self.recovery_feedback
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let state = active_risk_recovery(&mut recovery, account_id.as_str(), now);
|
||||
state.challenge_count = state.challenge_count.saturating_add(1);
|
||||
state.observed_at = now;
|
||||
let index = usize::try_from(state.challenge_count.saturating_sub(1))
|
||||
.unwrap_or(usize::MAX)
|
||||
.min(CLOUDFLARE_CHALLENGE_BACKOFF.len() - 1);
|
||||
retry_after
|
||||
.unwrap_or_default()
|
||||
.max(CLOUDFLARE_CHALLENGE_BACKOFF[index])
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
}
|
||||
|
||||
fn record_cloudflare_path_block(&self, account_id: &ProviderAccountId, now: SystemTime) -> u32 {
|
||||
let mut recovery = self
|
||||
.risk_recovery
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let state = active_risk_recovery(&mut recovery, account_id.as_str(), now);
|
||||
state.path_block_count = state.path_block_count.saturating_add(1);
|
||||
state.observed_at = now;
|
||||
state.path_block_count
|
||||
/// Cookie 写回不能推进正在交换 RT 的凭据版本
|
||||
async fn credential_mutation_guard(
|
||||
&self,
|
||||
account: &ProviderAccount,
|
||||
) -> Result<Option<Box<dyn ProviderLeaseGuard>>, CredentialSelectionError> {
|
||||
match self
|
||||
.leases
|
||||
.try_acquire(ProviderLeaseRequest::Refresh(
|
||||
ProviderRefreshLeaseRequest::new(account.id().clone(), account.revision()),
|
||||
))
|
||||
.await
|
||||
.map_err(|source| CredentialSelectionError::Store(ErrorSource::new(source)))?
|
||||
{
|
||||
ProviderLeaseAcquisition::Acquired(guard) => Ok(Some(guard)),
|
||||
ProviderLeaseAcquisition::Busy { .. } => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
async fn apply_cookie_recovery(
|
||||
@@ -2278,6 +2400,9 @@ impl CodexCredentialSelector {
|
||||
account: &ProviderAccount,
|
||||
recovery: CookieRecovery,
|
||||
) -> Result<(), CredentialSelectionError> {
|
||||
let Some(_guard) = self.credential_mutation_guard(account).await? else {
|
||||
return Ok(());
|
||||
};
|
||||
let mut data = self.repository.load_complete_data(account).await?;
|
||||
if data.cookies().is_empty() {
|
||||
return Ok(());
|
||||
@@ -2311,24 +2436,6 @@ fn binding_store_error(
|
||||
)))
|
||||
}
|
||||
|
||||
fn active_risk_recovery<'a>(
|
||||
recovery: &'a mut HashMap<String, RiskRecoveryState>,
|
||||
account_id: &str,
|
||||
now: SystemTime,
|
||||
) -> &'a mut RiskRecoveryState {
|
||||
recovery.retain(|_, state| match now.duration_since(state.observed_at) {
|
||||
Ok(elapsed) => elapsed <= CLOUDFLARE_RECOVERY_STALE_AFTER,
|
||||
Err(_) => true,
|
||||
});
|
||||
recovery
|
||||
.entry(account_id.to_owned())
|
||||
.or_insert(RiskRecoveryState {
|
||||
challenge_count: 0,
|
||||
path_block_count: 0,
|
||||
observed_at: now,
|
||||
})
|
||||
}
|
||||
|
||||
impl fmt::Debug for CodexCredentialSelector {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
formatter
|
||||
@@ -2540,24 +2647,3 @@ fn minimum_duration(current: Option<Duration>, candidate: Option<Duration>) -> O
|
||||
(None, candidate) => candidate,
|
||||
}
|
||||
}
|
||||
|
||||
// 原生资格在账号边界检查,显式插件适配拥有自己的输入协议
|
||||
#[derive(Clone, Copy)]
|
||||
enum NativeProtocol {
|
||||
Fixed(ApiKeyProtocol),
|
||||
Chat,
|
||||
Unsupported,
|
||||
}
|
||||
|
||||
impl NativeProtocol {
|
||||
fn for_source(protocol: &str) -> Self {
|
||||
match protocol {
|
||||
gateway_protocol::openai::OPENAI_PROTOCOL => Self::Fixed(ApiKeyProtocol::Responses),
|
||||
gateway_protocol::anthropic::ANTHROPIC_PROTOCOL | "token-count" => {
|
||||
Self::Fixed(ApiKeyProtocol::Messages)
|
||||
}
|
||||
gateway_protocol::chat_completions::CHAT_PROTOCOL => Self::Chat,
|
||||
_ => Self::Unsupported,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -38,7 +38,7 @@ impl CodexProvider {
|
||||
};
|
||||
let mut source_context = generate.protocol_payload().context().clone();
|
||||
let target = selected.lease.authentication().api_protocol();
|
||||
let translator = response::ChatResponseTranslator::new(target, identity, original);
|
||||
let mut translator = response::ChatResponseTranslator::new(target, identity, original);
|
||||
match target {
|
||||
ApiKeyProtocol::Messages => {
|
||||
let capabilities = self
|
||||
@@ -82,6 +82,8 @@ impl CodexProvider {
|
||||
CodexRuntimeAuthentication::OAuth(_)
|
||||
) {
|
||||
crate::compat::normalize_translated_codex_service_tier(&mut body);
|
||||
translator.tool_names =
|
||||
crate::compat::normalize_translated_codex_tools(&mut body);
|
||||
}
|
||||
let body = serde_json::to_vec(&body).map_err(|_| request_error())?;
|
||||
let operation = operation
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
//! 单次响应直接映射为 Chat wire,原生观测与资源释放归现有执行链
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use super::*;
|
||||
use gateway_core::engine::provider::NativeResponseTranslator;
|
||||
use gateway_protocol::{
|
||||
@@ -20,6 +22,7 @@ pub(super) struct ChatResponseTranslator {
|
||||
complete_json: bool,
|
||||
streaming: bool,
|
||||
include_usage: bool,
|
||||
pub(super) tool_names: HashMap<String, String>,
|
||||
}
|
||||
|
||||
impl ChatResponseTranslator {
|
||||
@@ -54,6 +57,7 @@ impl ChatResponseTranslator {
|
||||
complete_json: false,
|
||||
streaming: request.get("stream").and_then(Value::as_bool) == Some(true),
|
||||
include_usage,
|
||||
tool_names: Default::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -79,7 +83,7 @@ impl NativeResponseTranslator for ChatResponseTranslator {
|
||||
}
|
||||
if let Some(raw) = event.raw_json_body() {
|
||||
let body = serde_json::from_slice(raw).map_err(|_| response_error())?;
|
||||
let response = match self.encoder {
|
||||
let mut response = match self.encoder {
|
||||
Encoder::Responses(_) => responses::project_response(&body, &self.identity),
|
||||
Encoder::Messages(_) => {
|
||||
messages::project_response_with_request(&body, &self.identity, &self.request)
|
||||
@@ -94,8 +98,10 @@ impl NativeResponseTranslator for ChatResponseTranslator {
|
||||
self.include_usage,
|
||||
)
|
||||
.map_err(map_error)?,
|
||||
&self.tool_names,
|
||||
);
|
||||
}
|
||||
restore_tool_names(&mut response, &self.tool_names);
|
||||
return ProtocolWireEvent::raw_json(
|
||||
CHAT_PROTOCOL,
|
||||
serde_json::to_vec(&response)
|
||||
@@ -113,7 +119,7 @@ impl NativeResponseTranslator for ChatResponseTranslator {
|
||||
Encoder::Messages(encoder) => encoder.push_event(event.event_type(), event.data()),
|
||||
}
|
||||
.map_err(map_error)?;
|
||||
wire_events(chunks)
|
||||
wire_events(chunks, &self.tool_names)
|
||||
}
|
||||
|
||||
fn finish(&mut self) -> Result<Vec<ProtocolWireEvent>, ProviderError> {
|
||||
@@ -125,19 +131,52 @@ impl NativeResponseTranslator for ChatResponseTranslator {
|
||||
Encoder::Messages(encoder) => encoder.finish(),
|
||||
}
|
||||
.map_err(map_error)?;
|
||||
wire_events(chunks)
|
||||
wire_events(chunks, &self.tool_names)
|
||||
}
|
||||
}
|
||||
|
||||
fn wire_events(chunks: Vec<Value>) -> Result<Vec<ProtocolWireEvent>, ProviderError> {
|
||||
fn wire_events(
|
||||
chunks: Vec<Value>,
|
||||
names: &HashMap<String, String>,
|
||||
) -> Result<Vec<ProtocolWireEvent>, ProviderError> {
|
||||
chunks
|
||||
.into_iter()
|
||||
.map(|chunk| {
|
||||
.map(|mut chunk| {
|
||||
restore_tool_names(&mut chunk, names);
|
||||
ProtocolWireEvent::json(CHAT_PROTOCOL, None, chunk).map_err(|_| response_error())
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn restore_tool_names(response: &mut Value, names: &HashMap<String, String>) {
|
||||
if names.is_empty() {
|
||||
return;
|
||||
}
|
||||
let Some(choices) = response.get_mut("choices").and_then(Value::as_array_mut) else {
|
||||
return;
|
||||
};
|
||||
for choice in choices {
|
||||
for field in ["message", "delta"] {
|
||||
let Some(calls) = choice
|
||||
.get_mut(field)
|
||||
.and_then(|message| message.get_mut("tool_calls"))
|
||||
.and_then(Value::as_array_mut)
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
for call in calls {
|
||||
for kind in ["function", "custom"] {
|
||||
if let Some(name) = call.get_mut(kind).and_then(|tool| tool.get_mut("name"))
|
||||
&& let Some(original) = name.as_str().and_then(|name| names.get(name))
|
||||
{
|
||||
*name = original.clone().into();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn map_error(error: ChatError) -> ProviderError {
|
||||
response_error().with_source(error)
|
||||
}
|
||||
@@ -658,6 +658,7 @@ pub(super) fn cold_json_response_stream(request: ColdJsonResponse) -> EventStrea
|
||||
let allows_account_state_mutation = request.lease.allows_account_state_mutation();
|
||||
let image_endpoint = matches!(request.endpoint_path, CODEX_IMAGE_GENERATIONS_PATH | CODEX_IMAGE_EDITS_PATH);
|
||||
let failure_context = OpenAiFailureContext {
|
||||
authentication: request.lease.authentication(),
|
||||
client: &request.client,
|
||||
selector: &request.selector,
|
||||
quota: &request.quota,
|
||||
@@ -726,6 +727,7 @@ pub(super) fn cold_json_response_stream(request: ColdJsonResponse) -> EventStrea
|
||||
yield ProviderEvent::observation(observation);
|
||||
}
|
||||
if allows_account_state_mutation {
|
||||
request.selector.record_success(&active_account, request.lease.account().revision(), request.lease.authentication()).await;
|
||||
synchronize_passive_quota_headers(
|
||||
&request.quota,
|
||||
&active_account,
|
||||
@@ -831,6 +833,7 @@ pub(super) fn cold_response_stream(response: ColdResponse) -> EventStream {
|
||||
let cyber_policy_scope = lease.cyber_policy_scope().cloned();
|
||||
let allows_account_state_mutation = lease.allows_account_state_mutation();
|
||||
let failure_context = OpenAiFailureContext {
|
||||
authentication: lease.authentication(),
|
||||
client: &client,
|
||||
image_endpoint: false,
|
||||
selector: &selector,
|
||||
@@ -1243,7 +1246,7 @@ pub(super) fn cold_response_stream(response: ColdResponse) -> EventStream {
|
||||
// 完成事实交给下游前更新账号健康,绑定已经在发送前完成
|
||||
let started = Instant::now();
|
||||
selector
|
||||
.record_success(&active_account)
|
||||
.record_success(&active_account, lease.account().revision(), lease.authentication())
|
||||
.await;
|
||||
trace.record("provider.account_success", json!({
|
||||
"durationMs": started.elapsed().as_millis(),
|
||||
@@ -1377,7 +1380,7 @@ pub(super) fn cold_response_stream(response: ColdResponse) -> EventStream {
|
||||
if allows_account_state_mutation && completed && terminal_failure.is_none() {
|
||||
// 尾部 finish() 也可能产出 completed,账号健康更新先于下游 yield
|
||||
selector
|
||||
.record_success(&active_account)
|
||||
.record_success(&active_account, lease.account().revision(), lease.authentication())
|
||||
.await;
|
||||
selector
|
||||
.observe_cyber_policy_success(cyber_policy_scope.as_ref())
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
use super::*;
|
||||
use crate::transport::protocol::responses::is_replaceable_response_prelude;
|
||||
use gateway_core::error::{ProxyConnectionHint, TransientRetryPolicy};
|
||||
use gateway_core::provider_ports::{ProviderCooldownScope, ProviderScopedCooldown};
|
||||
use gateway_protocol::http::preferred_response_request_id;
|
||||
|
||||
/// OpenAI 失败对 Smart 账号分数的结构化 reason 闭集
|
||||
@@ -41,6 +42,34 @@ pub fn openai_failure_affects_account_score(error: &ProviderError) -> bool {
|
||||
openai_account_score_failure_reason(error).is_some_and(is_openai_account_score_failure_reason)
|
||||
}
|
||||
|
||||
pub(super) enum ModelCooldown {
|
||||
Unsupported,
|
||||
RateLimited(std::time::SystemTime),
|
||||
}
|
||||
|
||||
impl ModelCooldown {
|
||||
fn for_account(
|
||||
&self,
|
||||
account: &ProviderAccount,
|
||||
model: &UpstreamModelId,
|
||||
) -> ProviderScopedCooldown {
|
||||
let (until, rate_limit) = match self {
|
||||
Self::Unsupported => (
|
||||
std::time::SystemTime::now() + Duration::from_secs(30 * 60),
|
||||
None,
|
||||
),
|
||||
Self::RateLimited(until) => (*until, Some(*until)),
|
||||
};
|
||||
ProviderScopedCooldown::new(
|
||||
account.id().clone(),
|
||||
account.revision(),
|
||||
ProviderCooldownScope::upstream_model(model.clone()),
|
||||
until,
|
||||
)
|
||||
.with_rate_limited_until(rate_limit)
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) struct MappedProviderFailure {
|
||||
pub(super) error: ProviderError,
|
||||
pub(super) websocket_transport_retryable: bool,
|
||||
@@ -48,7 +77,7 @@ pub(super) struct MappedProviderFailure {
|
||||
/// 原始上游错误描述,仅在凭据错误状态下持久化
|
||||
pub(super) error_message: Option<String>,
|
||||
pub(super) cyber_policy_failure: bool,
|
||||
pub(super) model_unsupported: bool,
|
||||
pub(super) model_cooldown: Option<ModelCooldown>,
|
||||
pub(super) set_cookie_headers: Vec<String>,
|
||||
pub(super) response_origin: Option<Url>,
|
||||
pub(super) rate_limit_headers: Vec<(String, String)>,
|
||||
@@ -65,7 +94,7 @@ impl MappedProviderFailure {
|
||||
account_failure: None,
|
||||
error_message: None,
|
||||
cyber_policy_failure: false,
|
||||
model_unsupported: false,
|
||||
model_cooldown: None,
|
||||
set_cookie_headers: Vec::new(),
|
||||
response_origin: None,
|
||||
rate_limit_headers: Vec::new(),
|
||||
@@ -185,6 +214,7 @@ impl ReplayBoundary {
|
||||
}
|
||||
|
||||
pub(super) struct OpenAiFailureContext<'a> {
|
||||
pub(super) authentication: &'a crate::credential::CodexRuntimeAuthentication,
|
||||
pub(super) client: &'a CodexBackendClient,
|
||||
pub(super) selector: &'a CodexCredentialSelector,
|
||||
pub(super) quota: &'a Arc<CodexCredentialQuotaService>,
|
||||
@@ -350,11 +380,11 @@ pub(super) async fn apply_failure(
|
||||
false,
|
||||
)
|
||||
.await;
|
||||
if failure.model_unsupported
|
||||
if let Some(model_cooldown) = &failure.model_cooldown
|
||||
&& let Some(model) = context.upstream_model
|
||||
&& let Err(error) = context
|
||||
.selector
|
||||
.record_model_unsupported(account, model)
|
||||
.record_model_cooldown(model_cooldown.for_account(account, model))
|
||||
.await
|
||||
{
|
||||
tracing::warn!(account_id = %account.id(), error = %error,
|
||||
@@ -381,7 +411,12 @@ pub(super) async fn apply_failure(
|
||||
.await;
|
||||
if let Err(error) = context
|
||||
.selector
|
||||
.record_failure(account, account_failure, failure.error_message.clone())
|
||||
.record_failure(
|
||||
account,
|
||||
context.authentication,
|
||||
account_failure,
|
||||
failure.error_message.clone(),
|
||||
)
|
||||
.await
|
||||
{
|
||||
tracing::warn!(
|
||||
@@ -554,7 +589,7 @@ pub(super) fn apply_websocket_recovery_policy(
|
||||
return;
|
||||
}
|
||||
// 明确账号拒绝走已有换号路径,业务瞬态失败走请求内退避,不消耗 WS 传输预算
|
||||
if failure.model_unsupported
|
||||
if matches!(failure.model_cooldown, Some(ModelCooldown::Unsupported))
|
||||
|| (failure.error.replay_is_safe()
|
||||
&& (failure.account_failure.is_some()
|
||||
|| matches!(
|
||||
@@ -1629,7 +1664,21 @@ pub(super) fn map_upstream_failure(
|
||||
account_failure: account_failure(&failure),
|
||||
error_message: failure.client_message,
|
||||
cyber_policy_failure,
|
||||
model_unsupported: category == CodexFailureCategory::ModelUnsupported,
|
||||
model_cooldown: match category {
|
||||
CodexFailureCategory::ModelUnsupported => Some(ModelCooldown::Unsupported),
|
||||
CodexFailureCategory::TurnRateLimited => {
|
||||
// 流内错误的 Retry-After 从错误发生时计时,不能使用早先的连接响应头时间
|
||||
let now = std::time::SystemTime::now();
|
||||
let duration = failure
|
||||
.retry_after_seconds
|
||||
.map(Duration::from_secs)
|
||||
.unwrap_or(crate::credential::DEFAULT_RATE_LIMIT_COOLDOWN);
|
||||
Some(ModelCooldown::RateLimited(
|
||||
now.checked_add(duration).unwrap_or(now),
|
||||
))
|
||||
}
|
||||
_ => None,
|
||||
},
|
||||
// 普通 5xx 与未知流内错误不足以证明容量拒绝,不能用于冻结账号
|
||||
set_cookie_headers: failure.set_cookie_headers,
|
||||
response_origin: failure.response_origin,
|
||||
@@ -1689,7 +1738,7 @@ fn upstream_failure_summary(
|
||||
}
|
||||
CodexFailureCategory::RateLimited => (ProviderErrorKind::RateLimited, "上游请求频率受限"),
|
||||
CodexFailureCategory::TurnRateLimited => {
|
||||
(ProviderErrorKind::RateLimited, "当前对话轮次受到限流")
|
||||
(ProviderErrorKind::RateLimited, "当前账号的模型请求频率受限")
|
||||
}
|
||||
CodexFailureCategory::CloudflareChallenge => {
|
||||
(ProviderErrorKind::Unavailable, "Cloudflare 要求验证请求")
|
||||
|
||||
@@ -419,6 +419,7 @@ fn cold_live_call_stream(request: ColdLiveCall) -> EventStream {
|
||||
let client = request.client.with_request_profile(profile.clone());
|
||||
let allows_account_state_mutation = request.lease.allows_account_state_mutation();
|
||||
let failure_context = OpenAiFailureContext {
|
||||
authentication: request.lease.authentication(),
|
||||
client: &client,
|
||||
image_endpoint: false,
|
||||
selector: &request.selector,
|
||||
@@ -526,6 +527,9 @@ fn cold_live_call_stream(request: ColdLiveCall) -> EventStream {
|
||||
);
|
||||
}
|
||||
|
||||
if allows_account_state_mutation {
|
||||
request.selector.record_success(&active_account, request.lease.account().revision(), request.lease.authentication()).await;
|
||||
}
|
||||
let response_meta = ResponseMeta::for_provider_endpoint(&request_id);
|
||||
yield ProviderEvent::canonical(GatewayEvent::Started(response_meta.clone()));
|
||||
let wire = ProtocolWireEvent::raw_http_body(OPENAI_PROTOCOL, response.body).map_err(|_| {
|
||||
|
||||
@@ -35,6 +35,7 @@ pub(super) struct ColdMessages {
|
||||
pub(super) fn cold_messages_stream(mut request: ColdMessages) -> EventStream {
|
||||
Box::pin(async_stream::try_stream! {
|
||||
let failure_context = OpenAiFailureContext {
|
||||
authentication: request.lease.authentication(),
|
||||
client: &request.client, selector: &request.selector, quota: &request.quota,
|
||||
response_origin: &request.response_origin, cyber_policy_scope: None,
|
||||
allows_account_state_mutation: request.lease.allows_account_state_mutation(),
|
||||
@@ -478,7 +479,12 @@ async fn record_message_failure(request: &ColdMessages, error: &ProviderError) {
|
||||
// 账号写回复用 selector 的凭据 revision 校验,流内错误不能污染已轮换的凭据
|
||||
if let Err(error) = request
|
||||
.selector
|
||||
.record_failure(request.lease.account(), failure, None)
|
||||
.record_failure(
|
||||
request.lease.account(),
|
||||
request.lease.authentication(),
|
||||
failure,
|
||||
None,
|
||||
)
|
||||
.await
|
||||
{
|
||||
tracing::warn!(account_id = %request.lease.account_id(), error = %error, "Failed to record Messages account failure");
|
||||
|
||||
@@ -57,15 +57,15 @@ use uuid::Uuid;
|
||||
|
||||
use crate::billing::normalize_service_tier;
|
||||
use crate::credential::{
|
||||
CodexAccountFailure, CodexCredentialCatalogError, CodexCredentialCatalogService,
|
||||
CodexCredentialLease, CodexCredentialQuotaService, CodexCredentialRefreshOutcome,
|
||||
CodexCredentialRefreshService, CodexCredentialRepository, CodexCredentialSelector,
|
||||
CodexCyberPolicyScope, CodexQuotaRefreshPolicy, CodexSessionAffinity, CredentialSelectionError,
|
||||
RuntimeCodexCookie, SelectCodexCredential, SelectCodexProviderEndpointCredential,
|
||||
derive_cache_preference, derive_codex_cyber_policy_session_key,
|
||||
derive_codex_endpoint_session_affinity, derive_codex_session_affinity,
|
||||
derive_codex_transport_key, derive_endpoint_affinity_with_headers,
|
||||
derive_live_session_affinity, derive_previous_response_id_hash, derive_turn_alias,
|
||||
CodexAccountFailure, CodexCredentialCatalogService, CodexCredentialLease,
|
||||
CodexCredentialQuotaService, CodexCredentialRefreshOutcome, CodexCredentialRefreshService,
|
||||
CodexCredentialRepository, CodexCredentialSelector, CodexCyberPolicyScope,
|
||||
CodexQuotaRefreshPolicy, CodexSessionAffinity, CredentialSelectionError, RuntimeCodexCookie,
|
||||
SelectCodexCredential, SelectCodexProviderEndpointCredential, derive_cache_preference,
|
||||
derive_codex_cyber_policy_session_key, derive_codex_endpoint_session_affinity,
|
||||
derive_codex_session_affinity, derive_codex_transport_key,
|
||||
derive_endpoint_affinity_with_headers, derive_live_session_affinity,
|
||||
derive_previous_response_id_hash, derive_turn_alias,
|
||||
};
|
||||
use crate::profile::{APPCAST_POLL_INTERVAL, CodexDesktopReleaseService, CodexWireProfileState};
|
||||
use crate::request_identity::{account_session_with_headers, turn_id_with_headers};
|
||||
@@ -553,7 +553,7 @@ impl Provider for CodexProvider {
|
||||
..Default::default()
|
||||
};
|
||||
};
|
||||
let Ok(encoded) = encode_generate_payload(request, "observability") else {
|
||||
let Ok(encoded) = encode_generate_payload(request, "observability", || false) else {
|
||||
return ProviderRequestObservation::default();
|
||||
};
|
||||
let previous_reasoning_effort_override = request
|
||||
@@ -694,7 +694,7 @@ impl Provider for CodexProvider {
|
||||
}
|
||||
// 跨协议转换必须在选号后执行;选号前只按各自协议读取明确会话身份
|
||||
let upstream = (generate.protocol_payload().protocol() == OPENAI_PROTOCOL)
|
||||
.then(|| encode_generate_payload(generate, upstream_model.as_str()))
|
||||
.then(|| encode_generate_payload(generate, upstream_model.as_str(), || false))
|
||||
.transpose()
|
||||
.map_err(map_request_error)?;
|
||||
// 固定调度约束:Guardian 分类先于选号,不能随原生/适配器发送路径改变
|
||||
@@ -745,11 +745,6 @@ impl Provider for CodexProvider {
|
||||
requires_websocket,
|
||||
)
|
||||
});
|
||||
let messages_affinity = crate::credential::derive_messages_session_affinity(
|
||||
generate.protocol_payload(),
|
||||
&[],
|
||||
context.client_api_key_ref(),
|
||||
);
|
||||
if let ContinuationAttempt::RotateForClientReplay(trigger) = context.continuation_attempt()
|
||||
&& (selection_session_affinity.is_none()
|
||||
|| (trigger == ClientReplayTrigger::UpstreamCapacity
|
||||
@@ -762,11 +757,28 @@ impl Provider for CodexProvider {
|
||||
UpstreamSendState::NotSent,
|
||||
));
|
||||
}
|
||||
// Messages 身份与内容亲和仅交给选号器,不建立 OpenAI 轮次或原生续接关联
|
||||
let payload = generate.protocol_payload();
|
||||
// Chat 转换保留入站会话头,正文中的 Responses 专用字段不会进入转换结果
|
||||
let protocol_affinity = if !adapted
|
||||
&& payload.protocol() == gateway_protocol::chat_completions::CHAT_PROTOCOL
|
||||
{
|
||||
crate::credential::session_affinity_with_headers(
|
||||
&Map::new(),
|
||||
payload.context(),
|
||||
&[],
|
||||
context.client_api_key_ref(),
|
||||
)
|
||||
} else {
|
||||
crate::credential::derive_messages_session_affinity(
|
||||
payload,
|
||||
&[],
|
||||
context.client_api_key_ref(),
|
||||
)
|
||||
};
|
||||
let account_affinity = selection_session_affinity
|
||||
.as_ref()
|
||||
.or(cache_preference.as_ref())
|
||||
.or(messages_affinity.as_ref());
|
||||
.or(protocol_affinity.as_ref());
|
||||
let selection_started_at = Instant::now();
|
||||
let selection = async {
|
||||
self.selector
|
||||
@@ -852,7 +864,6 @@ impl Provider for CodexProvider {
|
||||
.map_err(|_| provider_error(ProviderErrorKind::Protocol, UpstreamSendState::NotSent))?;
|
||||
let account_id = lease.account_id().clone();
|
||||
// 账号确定后再判断强制档位,避免借用其他账号的同名模型;attempt 可以继续改写正文
|
||||
let payload = generate.protocol_payload();
|
||||
let mut operation = Operation::Generate(generate.clone());
|
||||
if payload.protocol() == OPENAI_PROTOCOL
|
||||
&& !(adapter.is_none()
|
||||
@@ -965,8 +976,11 @@ impl CodexProvider {
|
||||
"provider_input",
|
||||
None,
|
||||
);
|
||||
let mut upstream = encode_generate_payload(&generate, upstream_model.as_str())
|
||||
.map_err(map_request_error)?;
|
||||
let mut upstream = encode_generate_payload(&generate, upstream_model.as_str(), || {
|
||||
self.catalog
|
||||
.should_replace_none_with_low(lease.account(), &upstream_model)
|
||||
})
|
||||
.map_err(map_request_error)?;
|
||||
upstream.client_account_follow_only = crate::request_identity::follows_session_with_headers(
|
||||
generate.protocol_payload().body(),
|
||||
generate.protocol_payload().context(),
|
||||
|
||||
@@ -77,7 +77,7 @@ impl CodexProvider {
|
||||
model,
|
||||
requested_service_tier,
|
||||
});
|
||||
let events = adapter.execute(UpstreamAdapterInvocation {
|
||||
let mut events = adapter.execute(UpstreamAdapterInvocation {
|
||||
operation,
|
||||
headers,
|
||||
context,
|
||||
@@ -85,6 +85,20 @@ impl CodexProvider {
|
||||
account,
|
||||
});
|
||||
let mutation = lease.allows_account_state_mutation();
|
||||
let selector = Arc::clone(&self.selector);
|
||||
let success_lease = Arc::clone(&lease);
|
||||
let events: EventStream = Box::pin(async_stream::try_stream! {
|
||||
while let Some(event) = events.next().await {
|
||||
let event = event?;
|
||||
// 适配器的完成事实由宿主在 RPC 成功结束后发布
|
||||
if mutation && event.canonical_facts().iter()
|
||||
.any(|fact| matches!(fact, GatewayEvent::Completed(_)))
|
||||
{
|
||||
selector.record_success(success_lease.account(), success_lease.account().revision(), success_lease.authentication()).await;
|
||||
}
|
||||
yield event;
|
||||
}
|
||||
});
|
||||
let stream = ProviderStream::new(metadata, events, lease);
|
||||
Ok(if mutation {
|
||||
stream.with_filtered_account_feedback(
|
||||
@@ -192,7 +206,12 @@ impl UpstreamAccountConnection for SelectedConnection {
|
||||
let _ = self
|
||||
.provider
|
||||
.selector
|
||||
.record_failure(self.lease.account(), failure, None)
|
||||
.record_failure(
|
||||
self.lease.account(),
|
||||
self.lease.authentication(),
|
||||
failure,
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
if error.kind() == ProviderErrorKind::QuotaExhausted {
|
||||
schedule_authoritative_quota_refresh_after_failure(
|
||||
|
||||
@@ -298,31 +298,22 @@ impl ScheduledTask for OpenAiQuotaTask {
|
||||
impl ScheduledTask for OpenAiCatalogTask {
|
||||
fn run_cycle(&self, context: WorkerCycleContext) -> BoxFuture<'_, Result<(), WorkerTaskError>> {
|
||||
Box::pin(async move {
|
||||
let Some(catalogs) = context
|
||||
let Some(result) = context
|
||||
.cancellation()
|
||||
.run_until_cancelled(self.catalog.refresh_catalogs())
|
||||
.await
|
||||
else {
|
||||
return Ok(());
|
||||
};
|
||||
let result = match catalogs {
|
||||
Ok(_) | Err(CodexCredentialCatalogError::NoEligibleCredential) => Ok(()),
|
||||
Err(error) => Err(WorkerTaskError::safe("模型目录同步失败").with_source(error)),
|
||||
};
|
||||
// 成功周期尾部追加 [0, 20%) 单侧随机抖动,打破固定周期轮询特征;
|
||||
// 放在周期尾部避免延迟冷启动首轮刷新,失败路径交给宿主退避不叠加。
|
||||
// 抖动期间 leader lease 由宿主监督循环并发续租,不会超时。
|
||||
if result.is_ok() {
|
||||
let jitter = crate::jitter::catalog_refresh_jitter(
|
||||
crate::jitter::random_u64(),
|
||||
self.interval,
|
||||
);
|
||||
tokio::select! {
|
||||
() = context.cancellation().cancelled() => {},
|
||||
() = tokio::time::sleep(jitter) => {},
|
||||
}
|
||||
}
|
||||
result
|
||||
result.map_err(|error| WorkerTaskError::safe("模型目录同步失败").with_source(error))?;
|
||||
// 成功周期尾部追加抖动,首轮刷新和失败重试不额外等待
|
||||
let jitter =
|
||||
crate::jitter::catalog_refresh_jitter(crate::jitter::random_u64(), self.interval);
|
||||
context
|
||||
.cancellation()
|
||||
.run_until_cancelled(tokio::time::sleep(jitter))
|
||||
.await;
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -340,12 +331,9 @@ impl DaemonTask for OpenAiCatalogEtagTask {
|
||||
()=cancellation.cancelled()=>return Ok(()),
|
||||
result=self.catalog.refresh_catalogs()=>result,
|
||||
};
|
||||
match result {
|
||||
Ok(_) | Err(CodexCredentialCatalogError::NoEligibleCredential) => {}
|
||||
Err(error) => {
|
||||
self.catalog.schedule_refresh();
|
||||
return Err(WorkerTaskError::safe("模型目录刷新失败").with_source(error));
|
||||
}
|
||||
if let Err(error) = result {
|
||||
self.catalog.schedule_refresh();
|
||||
return Err(WorkerTaskError::safe("模型目录刷新失败").with_source(error));
|
||||
}
|
||||
context.succeeded();
|
||||
}
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
//! 上游模型目录读取;Codex 版本协商与 Messages 分页各自遵循原生合同
|
||||
|
||||
use crate::profile::CodexWireProfile;
|
||||
use std::time::Duration;
|
||||
|
||||
use bytes::BytesMut;
|
||||
use gateway_protocol::openai::events::retry_after_seconds_from_body;
|
||||
use tokio::time::{Instant, timeout, timeout_at};
|
||||
|
||||
use crate::profile::CodexWireProfile;
|
||||
|
||||
use super::backend::{
|
||||
CodexBackendClient, CodexBackendTransport, CodexClientError, CodexClientResult,
|
||||
@@ -15,6 +20,8 @@ use super::super::{
|
||||
response_meta,
|
||||
};
|
||||
|
||||
const CATALOG_READ_IDLE: Duration = Duration::from_secs(30);
|
||||
|
||||
impl CodexBackendClient {
|
||||
/// 目录优先使用显式协商版本,否则沿用调用方冻结的画像版本
|
||||
pub async fn fetch_models_with_context(
|
||||
@@ -112,7 +119,12 @@ impl CodexBackendClient {
|
||||
.headers_mut()
|
||||
.insert(gateway_protocol::peer::ROUTE_HEADER, route.clone());
|
||||
}
|
||||
let response = self.client.execute(request).await?;
|
||||
let idle_timeout = |_| CodexClientError::StreamIdleTimeout {
|
||||
timeout: CATALOG_READ_IDLE,
|
||||
};
|
||||
let mut response = timeout(CATALOG_READ_IDLE, self.client.execute(request))
|
||||
.await
|
||||
.map_err(idle_timeout)??;
|
||||
let status = response.status();
|
||||
let diagnostics = response_meta::diagnostics(Some(status.as_u16()), response.headers())
|
||||
.with_response_origin(Some(response.url().clone()));
|
||||
@@ -123,7 +135,17 @@ impl CodexBackendClient {
|
||||
.then(|| catalog_etag(response.headers()))
|
||||
.transpose()?
|
||||
.flatten();
|
||||
let body = response.bytes().await?;
|
||||
let mut body = BytesMut::new();
|
||||
let mut deadline = Instant::now() + CATALOG_READ_IDLE;
|
||||
while let Some(chunk) = timeout_at(deadline, response.chunk())
|
||||
.await
|
||||
.map_err(idle_timeout)??
|
||||
{
|
||||
if !chunk.is_empty() {
|
||||
body.extend_from_slice(&chunk);
|
||||
deadline = Instant::now() + CATALOG_READ_IDLE;
|
||||
}
|
||||
}
|
||||
if !status.is_success() {
|
||||
let body = String::from_utf8_lossy(&body).into_owned();
|
||||
return Err(CodexClientError::Upstream {
|
||||
@@ -140,7 +162,7 @@ impl CodexBackendClient {
|
||||
send_phase: CodexUpstreamSendPhase::AfterPayload,
|
||||
});
|
||||
}
|
||||
Ok((body, etag))
|
||||
Ok((body.freeze(), etag))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -107,7 +107,7 @@ pub fn encode_generate_request(
|
||||
upstream_model: &str,
|
||||
location: Option<&CodexRequestLocation>,
|
||||
) -> Result<CodexResponsesRequest, CodexRequestEncodeError> {
|
||||
let mut encoded = encode_generate_payload(request, upstream_model)?;
|
||||
let mut encoded = encode_generate_payload(request, upstream_model, || false)?;
|
||||
apply_codex_request_country(
|
||||
encoded.body_mut(),
|
||||
location,
|
||||
@@ -121,6 +121,7 @@ pub fn encode_generate_request(
|
||||
pub(crate) fn encode_generate_payload(
|
||||
request: &GenerateRequest,
|
||||
upstream_model: &str,
|
||||
should_replace_none_with_low: impl FnOnce() -> bool,
|
||||
) -> Result<CodexResponsesRequest, CodexRequestEncodeError> {
|
||||
let payload = request.protocol_payload();
|
||||
if payload.protocol() != OPENAI_PROTOCOL {
|
||||
@@ -128,7 +129,7 @@ pub(crate) fn encode_generate_payload(
|
||||
}
|
||||
let mut body = payload.body().clone();
|
||||
body.insert("model".to_owned(), Value::String(upstream_model.to_owned()));
|
||||
normalize_codex_request_body(&mut body);
|
||||
normalize_codex_request_body(&mut body, should_replace_none_with_low);
|
||||
let mut encoded = CodexResponsesRequest::from_body(body);
|
||||
encoded.explicit_prompt_cache_key = encoded.prompt_cache_key().is_some();
|
||||
extract_request_context(&mut encoded);
|
||||
|
||||
@@ -1,17 +1,13 @@
|
||||
//! 物理 WS 的响应归属与 HTTP 全量输入的增量续接
|
||||
|
||||
use std::{
|
||||
collections::BTreeMap,
|
||||
hash::{Hash, Hasher},
|
||||
};
|
||||
|
||||
use serde_json::Value;
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
use crate::transport::protocol::{
|
||||
responses::CodexResponsesRequest, websocket::websocket_response_completed_id,
|
||||
};
|
||||
|
||||
use super::history::{HistoryItem, fingerprint};
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct WebSocketContinuationState {
|
||||
latest_response_id: Option<String>,
|
||||
@@ -31,11 +27,22 @@ impl WebSocketContinuationState {
|
||||
if request.store() || !request.generate() || body.contains_key("previous_response_id") {
|
||||
return Self::default();
|
||||
}
|
||||
// 每轮元数据随当前帧照常发送,模型、工具及未知正文属性均参与前缀校验
|
||||
let properties: BTreeMap<_, _> = body
|
||||
.iter()
|
||||
.filter(|(key, _)| !matches!(key.as_str(), "input" | "client_metadata"))
|
||||
.collect();
|
||||
// 对齐 Codex 的 responses_request_properties_mismatch,仅比较它用来判定续接的属性
|
||||
let properties = [
|
||||
"model",
|
||||
"tools",
|
||||
"tool_choice",
|
||||
"parallel_tool_calls",
|
||||
"reasoning",
|
||||
"store",
|
||||
"stream",
|
||||
"include",
|
||||
"service_tier",
|
||||
"prompt_cache_key",
|
||||
"prompt_cache_options",
|
||||
"text",
|
||||
]
|
||||
.map(|field| body.get(field).unwrap_or(&Value::Null));
|
||||
let mut input = Prefix {
|
||||
count: 0,
|
||||
digest: fingerprint((owner, properties)),
|
||||
@@ -47,9 +54,9 @@ impl WebSocketContinuationState {
|
||||
.history
|
||||
.as_ref()
|
||||
.map_or(0, |last| last.total.count.min(items.len()));
|
||||
input.extend(&items[..cut]);
|
||||
let reuse = self.history.is_some_and(|last| last.total == input) && cut < items.len();
|
||||
input.extend(&items[cut..]);
|
||||
input.extend(items[..cut].iter().map(HistoryItem::Input));
|
||||
let reuse = self.history.is_some_and(|last| last.total == input);
|
||||
input.extend(items[cut..].iter().map(HistoryItem::Input));
|
||||
if reuse && let Some(id) = self.latest_response_id.filter(|id| !id.is_empty()) {
|
||||
items.drain(..cut);
|
||||
request.set_previous_response_id(Some(id));
|
||||
@@ -73,7 +80,7 @@ impl WebSocketContinuationState {
|
||||
if let Some(item) = value.get("item").filter(|i| i.is_object())
|
||||
&& value["output_index"].as_u64() == Some(index as u64)
|
||||
{
|
||||
history.total.push(item);
|
||||
history.total.push(HistoryItem::Output(item));
|
||||
} else {
|
||||
self.history = None;
|
||||
}
|
||||
@@ -89,11 +96,9 @@ impl WebSocketContinuationState {
|
||||
self.history = None;
|
||||
} else {
|
||||
history.total = history.input;
|
||||
history.total.extend(output);
|
||||
history.total.extend(output.iter().map(HistoryItem::Output));
|
||||
}
|
||||
} else if history.total.count == history.input.count
|
||||
|| history.total.count - history.input.count < history.added
|
||||
{
|
||||
} else if history.total.count - history.input.count < history.added {
|
||||
self.history = None;
|
||||
}
|
||||
}
|
||||
@@ -120,33 +125,14 @@ struct Prefix {
|
||||
}
|
||||
|
||||
impl Prefix {
|
||||
fn extend(&mut self, items: &[Value]) {
|
||||
fn extend<'a>(&mut self, items: impl IntoIterator<Item = HistoryItem<'a>>) {
|
||||
for item in items {
|
||||
self.push(item);
|
||||
}
|
||||
}
|
||||
|
||||
fn push(&mut self, item: &Value) {
|
||||
fn push(&mut self, item: HistoryItem<'_>) {
|
||||
self.digest = fingerprint((self.digest, item));
|
||||
self.count += 1;
|
||||
}
|
||||
}
|
||||
|
||||
// Value 的 Hash 忽略对象键顺序、保留数组顺序;摘要只在当前进程的连接租约内比较
|
||||
fn fingerprint(value: impl Hash) -> [u8; 32] {
|
||||
struct DigestHasher(Sha256);
|
||||
|
||||
impl Hasher for DigestHasher {
|
||||
fn write(&mut self, bytes: &[u8]) {
|
||||
self.0.update(bytes);
|
||||
}
|
||||
|
||||
fn finish(&self) -> u64 {
|
||||
u64::from_be_bytes(self.0.clone().finalize().as_chunks::<8>().0[0])
|
||||
}
|
||||
}
|
||||
|
||||
let mut hasher = DigestHasher(Sha256::new());
|
||||
value.hash(&mut hasher);
|
||||
hasher.0.finalize().into()
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
//! Codex 历史项回传形状的只读摘要投影,不改写或留存业务正文
|
||||
|
||||
use std::hash::{Hash, Hasher};
|
||||
|
||||
use serde_json::Value;
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
// 基准:openai/codex rust-v0.174.0,models.rs 的 ResponseItem 及嵌套线协议
|
||||
// https://github.com/openai/codex/blob/2d42293d1d32079068f1e4ed8aa70fdbf146ec01/codex-rs/protocol/src/models.rs
|
||||
// 官方先解析类型再回传,不能直接比较上游 JSON 中未被客户端保留的字段
|
||||
#[derive(Clone, Copy)]
|
||||
enum Shape {
|
||||
Item,
|
||||
Content,
|
||||
AgentContent,
|
||||
ToolOutput,
|
||||
Summary,
|
||||
ReasoningContent,
|
||||
WebSearchAction,
|
||||
ShellAction,
|
||||
ConfigurationReasoning,
|
||||
}
|
||||
|
||||
pub(super) enum HistoryItem<'a> {
|
||||
Input(&'a Value),
|
||||
Output(&'a Value),
|
||||
}
|
||||
|
||||
impl Hash for HistoryItem<'_> {
|
||||
fn hash<H: Hasher>(&self, state: &mut H) {
|
||||
let (Self::Input(value) | Self::Output(value)) = self;
|
||||
hash_value(value, Shape::Item, state);
|
||||
let kind = value["type"].as_str().unwrap_or_default();
|
||||
if fields(Shape::Item, kind, value).is_some()
|
||||
&& !matches!(
|
||||
kind,
|
||||
"additional_tools" | "configuration_update" | "compaction_trigger"
|
||||
)
|
||||
{
|
||||
// 上游 JSON 的结果元数据被官方 skip_deserializing,客户端回传的宿主结果则必须比较
|
||||
if matches!(self, Self::Input(_)) {
|
||||
hash_tool_results(value, state);
|
||||
} else {
|
||||
false.hash(state);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn hash_value<H: Hasher>(value: &Value, shape: Shape, state: &mut H) {
|
||||
if let Some(items) = value.as_array()
|
||||
&& !matches!(shape, Shape::Item)
|
||||
{
|
||||
0_u8.hash(state);
|
||||
items.len().hash(state);
|
||||
for item in items {
|
||||
hash_value(item, shape, state);
|
||||
}
|
||||
return;
|
||||
}
|
||||
let kind = value
|
||||
.get("type")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or_default();
|
||||
let kind = match (shape, kind) {
|
||||
(Shape::Item, "compaction_summary") => "compaction",
|
||||
(Shape::ConfigurationReasoning, _) => "",
|
||||
_ => kind,
|
||||
};
|
||||
let Some(fields) = value.as_object().and_then(|_| fields(shape, kind, value)) else {
|
||||
// 未知类型和非对象值仍按原值比较,不能像客户端 Other 一样合并不同正文
|
||||
1_u8.hash(state);
|
||||
value.hash(state);
|
||||
return;
|
||||
};
|
||||
2_u8.hash(state);
|
||||
kind.hash(state);
|
||||
for field in fields {
|
||||
let child = &value[*field];
|
||||
match (shape, kind, *field) {
|
||||
// 空 reasoning.content 在官方序列化时省略,其他空数组仍是有意义的值
|
||||
(Shape::Item, "reasoning", "content") if child.is_null() => {
|
||||
hash_value(&Value::Array(Vec::new()), Shape::ReasoningContent, state);
|
||||
}
|
||||
(Shape::Item, "message", "content") => hash_value(child, Shape::Content, state),
|
||||
(Shape::Item, "agent_message", "content") => {
|
||||
hash_value(child, Shape::AgentContent, state);
|
||||
}
|
||||
(Shape::Item, "reasoning", "summary") => hash_value(child, Shape::Summary, state),
|
||||
(Shape::Item, "reasoning", "content") => {
|
||||
hash_value(child, Shape::ReasoningContent, state);
|
||||
}
|
||||
(Shape::Item, "function_call_output" | "custom_tool_call_output", "output") => {
|
||||
hash_value(child, Shape::ToolOutput, state);
|
||||
}
|
||||
(Shape::Item, "web_search_call", "action") => {
|
||||
hash_value(child, Shape::WebSearchAction, state);
|
||||
}
|
||||
(Shape::Item, "local_shell_call", "action") => {
|
||||
hash_value(child, Shape::ShellAction, state);
|
||||
}
|
||||
(Shape::Item, "configuration_update", "reasoning") => {
|
||||
hash_value(child, Shape::ConfigurationReasoning, state);
|
||||
}
|
||||
// arguments、工具定义、schema、annotations 和 logprobs 都保留完整 JSON
|
||||
_ => child.hash(state),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn fields(shape: Shape, kind: &str, value: &Value) -> Option<&'static [&'static str]> {
|
||||
Some(match (shape, kind) {
|
||||
(Shape::Item, "additional_tools") => &["id", "role", "tools"],
|
||||
(Shape::Item, "message") => &[
|
||||
"encrypted_content",
|
||||
"status",
|
||||
"id",
|
||||
"role",
|
||||
"content",
|
||||
"phase",
|
||||
],
|
||||
(Shape::Item, "agent_message") => &["id", "author", "recipient", "content"],
|
||||
(Shape::Item, "reasoning") => &["id", "summary", "content", "encrypted_content"],
|
||||
(Shape::Item, "local_shell_call") => {
|
||||
&["encrypted_content", "id", "call_id", "status", "action"]
|
||||
}
|
||||
(Shape::Item, "function_call") => &[
|
||||
"encrypted_content",
|
||||
"status",
|
||||
"id",
|
||||
"name",
|
||||
"namespace",
|
||||
"arguments",
|
||||
"encrypted_function_args",
|
||||
"call_id",
|
||||
],
|
||||
(Shape::Item, "tool_search_call") => &[
|
||||
"encrypted_content",
|
||||
"id",
|
||||
"call_id",
|
||||
"status",
|
||||
"execution",
|
||||
"arguments",
|
||||
],
|
||||
(Shape::Item, "function_call_output") => &["id", "call_id", "name", "namespace", "output"],
|
||||
(Shape::Item, "custom_tool_call") => &[
|
||||
"encrypted_content",
|
||||
"id",
|
||||
"status",
|
||||
"call_id",
|
||||
"name",
|
||||
"namespace",
|
||||
"input",
|
||||
],
|
||||
(Shape::Item, "custom_tool_call_output") => &["id", "call_id", "name", "output"],
|
||||
(Shape::Item, "tool_search_output") => &["id", "call_id", "status", "execution", "tools"],
|
||||
(Shape::Item, "web_search_call") => &["encrypted_content", "id", "status", "action"],
|
||||
(Shape::Item, "image_generation_call") => &[
|
||||
"encrypted_content",
|
||||
"id",
|
||||
"status",
|
||||
"revised_prompt",
|
||||
"result",
|
||||
],
|
||||
(Shape::Item, "compaction" | "compaction_summary" | "context_compaction") => {
|
||||
&["id", "encrypted_content"]
|
||||
}
|
||||
(Shape::Item, "configuration_update") => &["reasoning"],
|
||||
(Shape::Item, "compaction_trigger") => &[],
|
||||
(Shape::Content | Shape::AgentContent | Shape::ToolOutput, "input_text")
|
||||
| (Shape::Summary, "summary_text")
|
||||
| (Shape::ReasoningContent, "reasoning_text" | "text") => &["text"],
|
||||
(Shape::Content, "output_text") => &["text", "annotations", "logprobs"],
|
||||
(Shape::AgentContent | Shape::ToolOutput, "encrypted_content") => &["encrypted_content"],
|
||||
(Shape::Content | Shape::ToolOutput, "input_image") => {
|
||||
if value.get("image_url").is_some_and(Value::is_string) {
|
||||
&["image_url", "detail"]
|
||||
} else {
|
||||
&["file_id", "detail"]
|
||||
}
|
||||
}
|
||||
(Shape::Content | Shape::ToolOutput, "input_audio") => {
|
||||
if value.get("audio_url").is_some_and(Value::is_string) {
|
||||
&["audio_url"]
|
||||
} else {
|
||||
&["file_id"]
|
||||
}
|
||||
}
|
||||
(Shape::WebSearchAction, "search") => &["query", "queries"],
|
||||
(Shape::WebSearchAction, "open_page") => &["url"],
|
||||
(Shape::WebSearchAction, "find_in_page") => &["url", "pattern"],
|
||||
(Shape::ShellAction, "exec") => {
|
||||
&["command", "timeout_ms", "working_directory", "env", "user"]
|
||||
}
|
||||
(Shape::ConfigurationReasoning, "") => &["effort"],
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
fn hash_tool_results<H: Hasher>(item: &Value, state: &mut H) {
|
||||
// 官方比较宿主已记录的结果及调用绑定;反序列化会丢掉这些可信字段,不能借此忽略更新
|
||||
// result ID 只存在于客户端内存,线上可比较的事实是原始 metadata、调用位置、名称和参数
|
||||
for (index, call) in item["internal_chat_message_metadata_passthrough"]["executed_tool_calls"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.enumerate()
|
||||
{
|
||||
if let Some(result) = call.get("tool_result_metadata") {
|
||||
true.hash(state);
|
||||
(index, call.get("name"), call.get("arguments"), result).hash(state);
|
||||
}
|
||||
}
|
||||
false.hash(state);
|
||||
}
|
||||
|
||||
// Value 的 Hash 忽略对象键顺序、保留数组顺序;摘要只在当前进程的连接租约内比较
|
||||
pub(super) fn fingerprint(value: impl Hash) -> [u8; 32] {
|
||||
struct DigestHasher(Sha256);
|
||||
|
||||
impl Hasher for DigestHasher {
|
||||
fn write(&mut self, bytes: &[u8]) {
|
||||
self.0.update(bytes);
|
||||
}
|
||||
|
||||
fn finish(&self) -> u64 {
|
||||
u64::from_be_bytes(self.0.clone().finalize().as_chunks::<8>().0[0])
|
||||
}
|
||||
}
|
||||
|
||||
let mut hasher = DigestHasher(Sha256::new());
|
||||
value.hash(&mut hasher);
|
||||
hasher.0.finalize().into()
|
||||
}
|
||||
@@ -8,6 +8,7 @@ mod coordinator;
|
||||
mod error;
|
||||
mod exchange;
|
||||
mod handshake;
|
||||
mod history;
|
||||
mod live;
|
||||
mod model;
|
||||
mod pool;
|
||||
|
||||
@@ -988,7 +988,7 @@ mod errors {
|
||||
config.config.auth.oauth_token_endpoint = "http://127.0.0.1:0/oauth/token".to_owned();
|
||||
let bundle = provider_openai::initialize(
|
||||
config.config,
|
||||
refresh_ports(store.clone(), false),
|
||||
refresh_ports(store.clone(), false, false),
|
||||
Arc::new(gateway_core::account::UpstreamInfoReader::default()),
|
||||
)
|
||||
.await
|
||||
@@ -1025,6 +1025,39 @@ mod errors {
|
||||
assert!(prepared.facts().preserve_profile);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn manual_refresh_rechecks_revision_after_acquiring_the_lease() {
|
||||
let server = MockServer::start().await;
|
||||
let (_, store, config) = refresh_fixture(&server, false, true).await;
|
||||
let before = store.account("acct_refresh_error").unwrap();
|
||||
let bundle = provider_openai::initialize(
|
||||
config.config,
|
||||
refresh_ports(store.clone(), false, true),
|
||||
Arc::new(gateway_core::account::UpstreamInfoReader::default()),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let error = bundle
|
||||
.admin
|
||||
.prepare_refresh(PrepareCredentialRefresh {
|
||||
account: account_record(&before),
|
||||
})
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(error.kind(), Kind::Conflict);
|
||||
assert!(server.received_requests().await.unwrap().is_empty());
|
||||
let current = store.account("acct_refresh_error").unwrap();
|
||||
let data = store
|
||||
.repository()
|
||||
.load_complete_data(¤t)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
data.oauth().unwrap().refresh_token.as_deref(),
|
||||
Some("rt-concurrent-refresh")
|
||||
);
|
||||
}
|
||||
|
||||
async fn refresh_fixture(
|
||||
server: &MockServer,
|
||||
busy: bool,
|
||||
@@ -1053,7 +1086,7 @@ mod errors {
|
||||
config.config.auth.oauth_token_endpoint = format!("{}/oauth/token", server.uri());
|
||||
let bundle = provider_openai::initialize(
|
||||
config.config.clone(),
|
||||
refresh_ports(store.clone(), busy),
|
||||
refresh_ports(store.clone(), busy, false),
|
||||
Arc::new(gateway_core::account::UpstreamInfoReader::default()),
|
||||
)
|
||||
.await
|
||||
@@ -1061,10 +1094,18 @@ mod errors {
|
||||
(bundle, store, config)
|
||||
}
|
||||
|
||||
fn refresh_ports(store: Arc<MemoryAccountStore>, busy: bool) -> ProviderStorePorts {
|
||||
fn refresh_ports(
|
||||
store: Arc<MemoryAccountStore>,
|
||||
busy: bool,
|
||||
rotate: bool,
|
||||
) -> ProviderStorePorts {
|
||||
let rotate_before_acquire = rotate.then(|| store.clone());
|
||||
ProviderStorePorts::new(
|
||||
store,
|
||||
Arc::new(RefreshLeases { busy }),
|
||||
Arc::new(RefreshLeases {
|
||||
busy,
|
||||
rotate_before_acquire,
|
||||
}),
|
||||
Arc::new(MemorySessionAffinity::default()),
|
||||
Arc::new(MemorySessionExclusions::default()),
|
||||
Arc::new(TestCatalogCache::default()),
|
||||
@@ -1079,6 +1120,7 @@ mod errors {
|
||||
|
||||
struct RefreshLeases {
|
||||
busy: bool,
|
||||
rotate_before_acquire: Option<Arc<MemoryAccountStore>>,
|
||||
}
|
||||
|
||||
impl ProviderLeasePort for RefreshLeases {
|
||||
@@ -1101,6 +1143,21 @@ mod errors {
|
||||
ProviderLeaseRequest::Refresh(_) | ProviderLeaseRequest::RefreshCapacity(_)
|
||||
));
|
||||
Box::pin(async move {
|
||||
if let (ProviderLeaseRequest::Refresh(request), Some(store)) =
|
||||
(&request, &self.rotate_before_acquire)
|
||||
{
|
||||
let current = store.account(request.account_id().as_str()).unwrap();
|
||||
store
|
||||
.repository()
|
||||
.rotate_refreshed_oauth_secret(
|
||||
¤t,
|
||||
secret("concurrent-refresh"),
|
||||
current.access_token_expires_at(),
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
Ok(if self.busy {
|
||||
ProviderLeaseAcquisition::Busy { retry_after: None }
|
||||
} else {
|
||||
|
||||
@@ -603,7 +603,7 @@ async fn openai_admin_provider_exposes_live_wire_profile_and_validated_billing()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn openai_legacy_billing_should_not_infer_long_context_flag() {
|
||||
async fn openai_billing_reconstruction_does_not_infer_long_context_flag() {
|
||||
let config = valid_config();
|
||||
let bundle = provider_openai::initialize(
|
||||
config.config.clone(),
|
||||
@@ -626,7 +626,7 @@ async fn openai_legacy_billing_should_not_infer_long_context_flag() {
|
||||
amount: "1.5".parse().expect("stored total"),
|
||||
},
|
||||
})
|
||||
.expect("legacy billing")
|
||||
.expect("reconstructed billing")
|
||||
.expect("matching billing breakdown");
|
||||
|
||||
assert_eq!(billing.total_amount.amount.as_str(), "1.5");
|
||||
|
||||
@@ -266,7 +266,7 @@ async fn failed_client_catalog_never_falls_back_to_an_out_of_scope_account_or_ca
|
||||
.await;
|
||||
let service = service_with_catalog_cache(&store, server.uri(), catalog_cache());
|
||||
let scope = client_scope(&[allowed]);
|
||||
assert!(service.refresh_catalogs().await.is_err());
|
||||
service.refresh_catalogs().await.unwrap();
|
||||
for _ in 0..2 {
|
||||
assert!(
|
||||
service
|
||||
@@ -313,18 +313,11 @@ fn catalog_starts_without_a_snapshot_or_generation() {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn catalog_without_openai_accounts_fails_before_network_io() {
|
||||
async fn empty_account_pool_has_no_published_catalog() {
|
||||
let store = Arc::new(MemoryAccountStore::default());
|
||||
|
||||
let error = service(&store)
|
||||
.refresh_catalogs()
|
||||
.await
|
||||
.expect_err("empty account set");
|
||||
|
||||
assert!(matches!(
|
||||
error,
|
||||
CodexCredentialCatalogError::NoEligibleCredential
|
||||
));
|
||||
let service = service(&store);
|
||||
service.refresh_catalogs().await.unwrap();
|
||||
assert!(service.cached().unwrap().is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -437,9 +430,11 @@ async fn service_tier_changes_should_replace_cached_metadata_and_advance_generat
|
||||
.await;
|
||||
let service = service_with_catalog_cache(&store, server.uri(), catalog_cache());
|
||||
|
||||
let initial = service.refresh_catalogs().await.expect("initial catalog");
|
||||
service.refresh_catalogs().await.expect("initial catalog");
|
||||
let initial = service.cached().unwrap().unwrap();
|
||||
let generation = service.catalog_generation().get();
|
||||
let cached = service.refresh_catalogs().await.expect("cached catalog");
|
||||
service.refresh_catalogs().await.expect("cached catalog");
|
||||
let cached = service.cached().unwrap().unwrap();
|
||||
assert_eq!(cached.models(), initial.models());
|
||||
assert_eq!(
|
||||
cached.models()[0].metadata().service_tiers(),
|
||||
@@ -454,17 +449,10 @@ async fn service_tier_changes_should_replace_cached_metadata_and_advance_generat
|
||||
service
|
||||
.observe_response_etag(&store.account("acct_service_tiers").unwrap(), "new")
|
||||
.unwrap();
|
||||
let refreshed = service.refresh_catalogs().await.expect("updated catalog");
|
||||
service.refresh_catalogs().await.expect("updated catalog");
|
||||
let refreshed = service.cached().unwrap().unwrap();
|
||||
assert!(refreshed.models()[0].metadata().service_tiers().is_empty());
|
||||
assert_eq!(service.catalog_generation().get(), generation + 1);
|
||||
assert_eq!(
|
||||
service
|
||||
.cached()
|
||||
.expect("cache read")
|
||||
.expect("cached snapshot")
|
||||
.models(),
|
||||
refreshed.models()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -529,10 +517,11 @@ async fn cross_plan_presentation_drift_unions_on_the_first_seen_model() {
|
||||
}
|
||||
let service = service_with_catalog_cache(&store, server.uri(), catalog_cache());
|
||||
|
||||
let snapshot = service
|
||||
service
|
||||
.refresh_catalogs()
|
||||
.await
|
||||
.expect("presentation drift must not wedge the union");
|
||||
let snapshot = service.cached().unwrap().unwrap();
|
||||
|
||||
assert_eq!(snapshot.models().len(), 1);
|
||||
assert_eq!(snapshot.models()[0].display_name(), "GPT-5.4 Plus");
|
||||
@@ -559,10 +548,11 @@ async fn cross_plan_supported_in_api_drift_unions_on_the_first_seen_model() {
|
||||
.await;
|
||||
let service = service_with_catalog_cache(&store, server.uri(), catalog_cache());
|
||||
|
||||
let snapshot = service
|
||||
service
|
||||
.refresh_catalogs()
|
||||
.await
|
||||
.expect("supported_in_api drift must not block catalog publication");
|
||||
let snapshot = service.cached().unwrap().unwrap();
|
||||
|
||||
assert_eq!(snapshot.models().len(), 1);
|
||||
server.verify().await;
|
||||
@@ -595,10 +585,11 @@ async fn account_entitlements_keep_the_discovering_account_across_plans() {
|
||||
}
|
||||
let service = service_with_catalog_cache(&store, server.uri(), catalog_cache());
|
||||
|
||||
let snapshot = service
|
||||
service
|
||||
.refresh_catalogs()
|
||||
.await
|
||||
.expect("mixed-plan catalog");
|
||||
let snapshot = service.cached().unwrap().unwrap();
|
||||
|
||||
assert_eq!(snapshot.models().len(), 2);
|
||||
assert_eq!(
|
||||
@@ -623,7 +614,8 @@ async fn account_entitlements_keep_the_discovering_account_across_plans() {
|
||||
);
|
||||
let restarted = service_with_catalog_cache(&store, server.uri(), catalog_cache());
|
||||
restarted.restore().await.unwrap();
|
||||
let restored = restarted.refresh_catalogs().await.unwrap();
|
||||
restarted.refresh_catalogs().await.unwrap();
|
||||
let restored = restarted.cached().unwrap().unwrap();
|
||||
assert_eq!(
|
||||
restored.model_catalog_accounts(),
|
||||
snapshot.model_catalog_accounts()
|
||||
@@ -797,7 +789,7 @@ async fn api_key_client_catalog_distinguishes_filtered_empty_from_fetch_failure(
|
||||
.mount(&upstream)
|
||||
.await;
|
||||
let service = service_with_catalog_cache(&store, upstream.uri(), catalog_cache());
|
||||
assert_eq!(service.refresh_catalogs().await.is_ok(), status == 200);
|
||||
service.refresh_catalogs().await.unwrap();
|
||||
let result = service
|
||||
.client_model_catalog(
|
||||
&client_scope(&[store.account("acct_api").unwrap()]),
|
||||
@@ -1033,7 +1025,8 @@ async fn api_key_catalog_hides_only_known_specialized_models_in_codex_picker() {
|
||||
.mount(&upstream)
|
||||
.await;
|
||||
let service = service_with_catalog_cache(&store, upstream.uri(), catalog_cache());
|
||||
let snapshot = service.refresh_catalogs().await.expect("standard API IDs");
|
||||
service.refresh_catalogs().await.expect("standard API IDs");
|
||||
let snapshot = service.cached().unwrap().unwrap();
|
||||
assert_eq!(
|
||||
snapshot
|
||||
.models()
|
||||
@@ -1078,7 +1071,6 @@ async fn api_key_catalog_rejects_invalid_ids_and_duplicates() {
|
||||
store
|
||||
.seed_api_key("acct_api", upstream.uri(), ResponsesTransport::Http)
|
||||
.await;
|
||||
let service = service_with_catalog_cache(&store, upstream.uri(), catalog_cache());
|
||||
for invalid in [
|
||||
String::new(),
|
||||
"__reserved".to_owned(),
|
||||
@@ -1093,13 +1085,16 @@ async fn api_key_catalog_rejects_invalid_ids_and_duplicates() {
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
|
||||
"data": [{"id":"valid-model"}, {"id":invalid}]
|
||||
})))
|
||||
.expect(1)
|
||||
.mount(&upstream)
|
||||
.await;
|
||||
let service = service_with_catalog_cache(&store, upstream.uri(), catalog_cache());
|
||||
service.refresh_catalogs().await.unwrap();
|
||||
assert!(
|
||||
service.refresh_catalogs().await.is_err(),
|
||||
service.cached().unwrap().is_none(),
|
||||
"invalid entry accepted: {invalid:?}"
|
||||
);
|
||||
assert!(service.cached().expect("cache").is_none());
|
||||
upstream.verify().await;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1119,7 +1114,8 @@ async fn api_key_catalog_does_not_replace_native_metadata_for_shared_models() {
|
||||
}]})))
|
||||
.mount(&oauth).await;
|
||||
let service = service_with_catalog_cache(&store, oauth.uri(), catalog_cache());
|
||||
let before = service.refresh_catalogs().await.expect("OAuth directory");
|
||||
service.refresh_catalogs().await.expect("OAuth directory");
|
||||
let before = service.cached().unwrap().unwrap();
|
||||
store
|
||||
.seed_api_key("acct_api", upstream.uri(), ResponsesTransport::Http)
|
||||
.await;
|
||||
@@ -1132,7 +1128,8 @@ async fn api_key_catalog_does_not_replace_native_metadata_for_shared_models() {
|
||||
.mount(&upstream)
|
||||
.await;
|
||||
|
||||
let after = service.refresh_catalogs().await.expect("mixed directory");
|
||||
service.refresh_catalogs().await.expect("mixed directory");
|
||||
let after = service.cached().unwrap().unwrap();
|
||||
assert_eq!(
|
||||
after.models(),
|
||||
before.models(),
|
||||
@@ -1199,10 +1196,11 @@ async fn account_catalog_documents_keep_native_objects_of_the_account_plan() {
|
||||
.await;
|
||||
}
|
||||
let service = service_with_catalog_cache(&store, server.uri(), catalog_cache());
|
||||
let snapshot = service
|
||||
service
|
||||
.refresh_catalogs()
|
||||
.await
|
||||
.expect("shared union snapshot");
|
||||
let snapshot = service.cached().unwrap().unwrap();
|
||||
assert_eq!(snapshot.models().len(), 3);
|
||||
assert_eq!(snapshot.models()[1].display_name(), "Plus");
|
||||
|
||||
@@ -1284,10 +1282,12 @@ async fn catalog_account_membership_changes_advance_generation_without_model_cha
|
||||
.mount(&server)
|
||||
.await;
|
||||
let service = service_with_catalog_cache(&store, server.uri(), catalog_cache());
|
||||
let initial = service.refresh_catalogs().await.unwrap();
|
||||
service.refresh_catalogs().await.unwrap();
|
||||
let initial = service.cached().unwrap().unwrap();
|
||||
let generation = service.catalog_generation();
|
||||
let second = seed_account(&store, "acct_source_b").await;
|
||||
let refreshed = service.refresh_catalogs().await.unwrap();
|
||||
service.refresh_catalogs().await.unwrap();
|
||||
let refreshed = service.cached().unwrap().unwrap();
|
||||
assert_eq!(initial.models(), refreshed.models());
|
||||
assert!(service.catalog_generation() > generation);
|
||||
assert_eq!(
|
||||
|
||||
@@ -2,6 +2,9 @@
|
||||
|
||||
use super::*;
|
||||
use gateway_protocol::openai::OPENAI_PROTOCOL;
|
||||
use std::time::Duration;
|
||||
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
|
||||
use tokio::net::{TcpListener, TcpStream};
|
||||
|
||||
#[tokio::test]
|
||||
async fn invalidation_queues_background_refresh_without_an_upstream_etag() {
|
||||
@@ -152,14 +155,12 @@ async fn simultaneous_periodic_refreshes_share_the_completed_scan() {
|
||||
.mount(&server)
|
||||
.await;
|
||||
let service = service_with_catalog_cache(&store, server.uri(), catalog_cache());
|
||||
let (first, second, third) = tokio::join!(
|
||||
tokio::try_join!(
|
||||
service.refresh_catalogs(),
|
||||
service.refresh_catalogs(),
|
||||
service.refresh_catalogs(),
|
||||
);
|
||||
let first = first.expect("first refresh");
|
||||
assert_eq!(first.models(), second.expect("shared refresh").models());
|
||||
assert_eq!(first.models(), third.expect("shared refresh").models());
|
||||
)
|
||||
.unwrap();
|
||||
server.verify().await;
|
||||
}
|
||||
|
||||
@@ -199,10 +200,11 @@ async fn api_key_background_catalog_preserves_negotiated_reasoning_levels_and_en
|
||||
.mount(&upstream)
|
||||
.await;
|
||||
let service = service_with_catalog_cache(&store, upstream.uri(), catalog_cache());
|
||||
let snapshot = service
|
||||
service
|
||||
.refresh_catalogs()
|
||||
.await
|
||||
.expect("native background directory");
|
||||
let snapshot = service.cached().unwrap().unwrap();
|
||||
assert_eq!(
|
||||
snapshot.models()[0].capabilities().reasoning(),
|
||||
CodexCatalogCapabilityEvidence::Unknown
|
||||
@@ -234,3 +236,261 @@ async fn api_key_background_catalog_preserves_negotiated_reasoning_levels_and_en
|
||||
}
|
||||
upstream.verify().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn failed_catalog_write_keeps_the_snapshot_and_retries_without_account_backoff() {
|
||||
let store = Arc::new(MemoryAccountStore::default());
|
||||
let account = seed_account(&store, "acct_write").await;
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/codex/models"))
|
||||
.respond_with(SequencedCatalogResponder {
|
||||
calls: Arc::new(AtomicUsize::new(0)),
|
||||
bodies: [
|
||||
br#"{"models":[{"slug":"before","display_name":"Before"}]}"#,
|
||||
br#"{"models":[{"slug":"after","display_name":"After"}]}"#,
|
||||
],
|
||||
})
|
||||
.expect(3)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let service = service_with_catalog_cache(&store, server.uri(), catalog_cache());
|
||||
service.refresh_catalogs().await.unwrap();
|
||||
service.observe_response_etag(&account, "updated").unwrap();
|
||||
store.fail_catalog_write.store(true, Ordering::SeqCst);
|
||||
assert!(matches!(
|
||||
service.refresh_catalogs().await,
|
||||
Err(CodexCredentialCatalogError::Store(_))
|
||||
));
|
||||
assert_eq!(
|
||||
service.cached_account_models(&account).unwrap().unwrap(),
|
||||
["before"]
|
||||
);
|
||||
store.fail_catalog_write.store(false, Ordering::SeqCst);
|
||||
service.refresh_catalogs().await.unwrap();
|
||||
assert_eq!(
|
||||
service.cached_account_models(&account).unwrap().unwrap(),
|
||||
["after"]
|
||||
);
|
||||
server.verify().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn manual_catalog_recovery_releases_backoff_and_keeps_a_newer_etag() {
|
||||
let store = Arc::new(MemoryAccountStore::default());
|
||||
let account = seed_account(&store, "acct_manual").await;
|
||||
let healthy = seed_account(&store, "acct_healthy").await;
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/codex/models"))
|
||||
.and(header("chatgpt-account-id", "chatgpt-acct_manual"))
|
||||
.respond_with(ResponseTemplate::new(503))
|
||||
.up_to_n_times(1)
|
||||
.with_priority(1)
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/codex/models"))
|
||||
.respond_with(
|
||||
ResponseTemplate::new(200)
|
||||
.insert_header("etag", r#""v1""#)
|
||||
.set_body_raw(OFFICIAL_FIXTURE, "application/json"),
|
||||
)
|
||||
.expect(4)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let service = service_with_catalog_cache(&store, server.uri(), catalog_cache());
|
||||
service.refresh_catalogs().await.unwrap();
|
||||
assert!(service.observe_response_etag(&account, "v2").unwrap());
|
||||
assert!(
|
||||
service
|
||||
.observe_response_etag(&healthy, "healthy-change")
|
||||
.unwrap()
|
||||
);
|
||||
service.wait_for_refresh().await;
|
||||
service.refresh_catalogs().await.unwrap();
|
||||
assert_eq!(server.received_requests().await.unwrap().len(), 3);
|
||||
assert!(service.cached_account_models(&account).unwrap().is_none());
|
||||
service.refresh_account_catalog(account.id()).await.unwrap();
|
||||
tokio::time::timeout(
|
||||
std::time::Duration::from_secs(1),
|
||||
service.wait_for_refresh(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
service.refresh_catalogs().await.unwrap();
|
||||
assert!(!service.observe_response_etag(&account, "v2").unwrap());
|
||||
server.verify().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn periodic_failure_arms_an_idle_catalog_worker_without_an_etag() {
|
||||
use std::time::Duration;
|
||||
let store = Arc::new(MemoryAccountStore::default());
|
||||
let account = seed_account(&store, "acct_periodic").await;
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/codex/models"))
|
||||
.respond_with(ResponseTemplate::new(503))
|
||||
.up_to_n_times(1)
|
||||
.with_priority(1)
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/codex/models"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_raw(OFFICIAL_FIXTURE, "application/json"))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let service = service_with_catalog_cache(&store, server.uri(), catalog_cache());
|
||||
let wake = service.wait_for_refresh();
|
||||
tokio::pin!(wake);
|
||||
tokio::select! {
|
||||
biased;
|
||||
() = &mut wake => panic!("idle worker woke without a due account"),
|
||||
result = service.refresh_catalogs() => result.unwrap(),
|
||||
}
|
||||
tokio::time::pause();
|
||||
assert!(
|
||||
tokio::time::timeout(Duration::from_secs(59), &mut wake)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
tokio::time::timeout(Duration::from_secs(2), wake)
|
||||
.await
|
||||
.expect("periodic failure must arm the retry");
|
||||
tokio::time::resume();
|
||||
service.refresh_catalogs().await.unwrap();
|
||||
assert!(service.cached_account_models(&account).unwrap().is_some());
|
||||
server.verify().await;
|
||||
}
|
||||
|
||||
async fn accept_catalog_request(listener: &TcpListener) -> TcpStream {
|
||||
let (socket, _) = tokio::time::timeout(Duration::from_secs(5), listener.accept())
|
||||
.await
|
||||
.expect("expected an upstream catalog request")
|
||||
.unwrap();
|
||||
let mut reader = BufReader::new(socket);
|
||||
let mut line = String::new();
|
||||
reader.read_line(&mut line).await.unwrap();
|
||||
assert!(line.starts_with("GET /codex/models?"));
|
||||
loop {
|
||||
line.clear();
|
||||
assert_ne!(reader.read_line(&mut line).await.unwrap(), 0);
|
||||
if line == "\r\n" {
|
||||
return reader.into_inner();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const PARTIAL_CATALOG: &[u8] = b"HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n{";
|
||||
|
||||
async fn stalled_catalog<T>(
|
||||
listener: &TcpListener,
|
||||
request: impl Future<Output = T>,
|
||||
partial_body: bool,
|
||||
) -> (T, u64) {
|
||||
tokio::pin!(request);
|
||||
let mut socket = tokio::select! {
|
||||
_ = &mut request => panic!("catalog request ended before reaching the upstream"),
|
||||
socket = accept_catalog_request(listener) => socket,
|
||||
};
|
||||
if partial_body {
|
||||
socket.write_all(PARTIAL_CATALOG).await.unwrap();
|
||||
}
|
||||
tokio::time::pause();
|
||||
let start = tokio::time::Instant::now();
|
||||
let result = tokio::time::timeout(Duration::from_secs(35), request)
|
||||
.await
|
||||
.expect("stalled catalog request must release the connection");
|
||||
let elapsed = start.elapsed().as_secs();
|
||||
tokio::time::resume();
|
||||
(result, elapsed)
|
||||
}
|
||||
|
||||
async fn send_slow_catalog(listener: &TcpListener) {
|
||||
let mut socket = accept_catalog_request(listener).await;
|
||||
socket.write_all(PARTIAL_CATALOG).await.unwrap();
|
||||
for chunk in [
|
||||
br#""models":"#.as_slice(),
|
||||
b"[",
|
||||
br#"{"slug":"#,
|
||||
br#""slow","#,
|
||||
br#""display_name":"#,
|
||||
br#""Slow"}"#,
|
||||
b"]}",
|
||||
] {
|
||||
tokio::time::pause();
|
||||
tokio::time::sleep(Duration::from_secs(20)).await;
|
||||
tokio::time::resume();
|
||||
socket.write_all(chunk).await.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn discovery_times_out_but_a_due_retry_can_publish_a_slow_catalog() {
|
||||
let store = Arc::new(MemoryAccountStore::default());
|
||||
let account = seed_account(&store, "acct_slow_retry").await;
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let url = format!("http://{}", listener.local_addr().unwrap());
|
||||
let service = service_with_catalog_cache(&store, url, catalog_cache());
|
||||
|
||||
let (scan, elapsed) = stalled_catalog(&listener, service.refresh_catalogs(), true).await;
|
||||
scan.unwrap();
|
||||
assert!((14..=15).contains(&elapsed));
|
||||
assert!(service.cached_account_models(&account).unwrap().is_none());
|
||||
tokio::time::pause();
|
||||
tokio::time::advance(Duration::from_secs(61)).await;
|
||||
tokio::time::resume();
|
||||
let (retry, ()) = tokio::join!(service.refresh_catalogs(), send_slow_catalog(&listener));
|
||||
retry.unwrap();
|
||||
assert_eq!(
|
||||
service.cached_account_models(&account).unwrap().unwrap(),
|
||||
["slow"]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn manual_refresh_tracks_body_progress_and_keeps_the_catalog_on_stall() {
|
||||
let store = Arc::new(MemoryAccountStore::default());
|
||||
let account = seed_account(&store, "acct_slow_manual").await;
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let url = format!("http://{}", listener.local_addr().unwrap());
|
||||
let service = service_with_catalog_cache(&store, url, catalog_cache());
|
||||
let (miss, elapsed) = stalled_catalog(
|
||||
&listener,
|
||||
service.cached_or_refresh_account_catalog(&account),
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
assert!(matches!(
|
||||
miss,
|
||||
Err(CodexCredentialCatalogError::Upstream { .. })
|
||||
));
|
||||
assert!((14..=15).contains(&elapsed));
|
||||
|
||||
let (refresh, ()) = tokio::join!(
|
||||
service.refresh_account_catalog(account.id()),
|
||||
send_slow_catalog(&listener)
|
||||
);
|
||||
assert_eq!(refresh.unwrap().models(), ["slow"]);
|
||||
for partial_body in [false, true] {
|
||||
let (refresh, elapsed) = stalled_catalog(
|
||||
&listener,
|
||||
service.refresh_account_catalog(account.id()),
|
||||
partial_body,
|
||||
)
|
||||
.await;
|
||||
assert!(matches!(
|
||||
refresh,
|
||||
Err(CodexCredentialCatalogError::Upstream { .. })
|
||||
));
|
||||
assert!((29..=30).contains(&elapsed));
|
||||
assert_eq!(
|
||||
service.cached_account_models(&account).unwrap().unwrap(),
|
||||
["slow"]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -326,3 +326,133 @@ async fn shorter_account_cooldown_cannot_unmask_an_active_model_cooldown_during_
|
||||
assert!(cooldowns.cooldowns.lock().unwrap()[account.id()].until() < SystemTime::now());
|
||||
assert_eq!(selected.account_id().as_str(), "acct_second");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn model_cooldown_survives_success_and_only_blocks_the_matching_account_and_model() {
|
||||
let store = Arc::new(MemoryAccountStore::default());
|
||||
create_account(&store, "acct_first", "test-first");
|
||||
create_account(&store, "acct_second", "test-second");
|
||||
let account = store.account("acct_first").unwrap();
|
||||
let cooldowns = Arc::new(MemoryCooldownPort::new());
|
||||
let scope = ProviderCooldownScope::upstream_model(UpstreamModelId::new("gpt-5.4").unwrap());
|
||||
let until = SystemTime::now() + Duration::from_secs(60);
|
||||
cooldowns
|
||||
.put_scoped_if_later(
|
||||
ProviderScopedCooldown::new(
|
||||
account.id().clone(),
|
||||
account.revision(),
|
||||
scope.clone(),
|
||||
until,
|
||||
)
|
||||
.with_rate_limited_until(Some(until)),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let selector = selector_with_runtime(
|
||||
&store,
|
||||
Arc::new(TestLeaseCoordinator::default()),
|
||||
Arc::new(MemorySessionAffinity::default()),
|
||||
Arc::new(AccountFeedbackStats::default()),
|
||||
cooldowns.clone(),
|
||||
);
|
||||
selector
|
||||
.record_success(&account, account.revision(), &oauth_auth("test-first"))
|
||||
.await;
|
||||
let request_url = Url::parse(OFFICIAL_CODEX_BASE_URL).unwrap();
|
||||
let new_session = attempt(BTreeSet::new());
|
||||
let request = SelectCodexCredential {
|
||||
protocol: gateway_protocol::openai::OPENAI_PROTOCOL,
|
||||
upstream_model: "gpt-5.4",
|
||||
request_url: &request_url,
|
||||
attempt: &new_session,
|
||||
session_affinity_key: None,
|
||||
};
|
||||
let selected = selector.select(&request).await.unwrap();
|
||||
assert_eq!(selected.account_id().as_str(), "acct_second");
|
||||
drop(selected);
|
||||
let same_account = attempt_with_required(BTreeSet::new(), Some(account.id().clone()));
|
||||
let other_model = selector
|
||||
.select(&SelectCodexCredential {
|
||||
upstream_model: "gpt-5.5",
|
||||
attempt: &same_account,
|
||||
..request
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(other_model.account_id(), account.id());
|
||||
assert!(
|
||||
cooldowns
|
||||
.read_scoped(account.id(), &scope)
|
||||
.await
|
||||
.unwrap()
|
||||
.is_some()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn pinned_model_cooldown_returns_retry_after_without_rotating_or_entering_capacity_queue() {
|
||||
let store = Arc::new(MemoryAccountStore::default());
|
||||
create_account(&store, "acct_original", "test-original");
|
||||
create_account(&store, "acct_primary", "test-free");
|
||||
let account = store.account("acct_original").unwrap();
|
||||
let cooldowns = Arc::new(MemoryCooldownPort::new());
|
||||
let scope = ProviderCooldownScope::upstream_model(UpstreamModelId::new("gpt-5.4").unwrap());
|
||||
let until = SystemTime::now() + Duration::from_secs(60);
|
||||
cooldowns
|
||||
.put_scoped_if_later(
|
||||
ProviderScopedCooldown::new(
|
||||
account.id().clone(),
|
||||
account.revision(),
|
||||
scope.clone(),
|
||||
until,
|
||||
)
|
||||
.with_rate_limited_until(Some(until)),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let selector = selector_with_runtime(
|
||||
&store,
|
||||
Arc::new(TestLeaseCoordinator::default()),
|
||||
Arc::new(MemorySessionAffinity::default()),
|
||||
Arc::new(AccountFeedbackStats::default()),
|
||||
cooldowns.clone(),
|
||||
);
|
||||
let attempt = AttemptContext::new(
|
||||
RequestAttemptContext::new(
|
||||
ModelRequestId::new("req_model_wait").unwrap(),
|
||||
ClientApiKeyId::new("key_codex_contract").unwrap(),
|
||||
),
|
||||
NonZeroU32::new(1).unwrap(),
|
||||
SystemTime::now() + Duration::from_secs(5),
|
||||
account_policy().with_queue(gateway_core::concurrency::ConcurrencyQueuePolicy {
|
||||
max_waiting: 1,
|
||||
timeout: Duration::from_secs(2),
|
||||
}),
|
||||
AccountAttemptContext::new(BTreeSet::new(), Some(account.id().clone()), None)
|
||||
.with_account_scope(contract_account_scope()),
|
||||
None,
|
||||
CancellationToken::new(),
|
||||
);
|
||||
let request_url = Url::parse(OFFICIAL_CODEX_BASE_URL).unwrap();
|
||||
let request = SelectCodexCredential {
|
||||
protocol: gateway_protocol::openai::OPENAI_PROTOCOL,
|
||||
upstream_model: "gpt-5.4",
|
||||
request_url: &request_url,
|
||||
attempt: &attempt,
|
||||
session_affinity_key: None,
|
||||
};
|
||||
selector
|
||||
.record_success(&account, account.revision(), &oauth_auth("test-original"))
|
||||
.await;
|
||||
let error = selector.select(&request).await.unwrap_err();
|
||||
assert!(
|
||||
matches!(error, CredentialSelectionError::CapacityUnavailable { retry_after: Some(duration) } if duration > Duration::from_secs(55) && duration <= Duration::from_secs(60)),
|
||||
"{error:?}"
|
||||
);
|
||||
cooldowns
|
||||
.clear_scoped(account.id(), &scope, account.revision())
|
||||
.await
|
||||
.unwrap();
|
||||
let selected = selector.select(&request).await.unwrap();
|
||||
assert_eq!(selected.account_id(), account.id());
|
||||
}
|
||||
@@ -33,8 +33,8 @@ use gateway_core::routing::{
|
||||
use provider_openai::OFFICIAL_CODEX_BASE_URL;
|
||||
use provider_openai::credential::{
|
||||
CodexAccountFailure, CodexCookiePolicy, CodexCredentialCodec, CodexCredentialQuotaService,
|
||||
CodexCredentialSelector, CredentialSelectionError, ImportCodexOAuthCredential,
|
||||
SelectCodexCredential,
|
||||
CodexCredentialSelector, CodexRuntimeAuthentication, CredentialSelectionError,
|
||||
ImportCodexOAuthCredential, SelectCodexCredential,
|
||||
};
|
||||
use provider_openai::profile::{CodexWireProfile, CodexWireProfileState};
|
||||
use secrecy::ExposeSecret;
|
||||
@@ -46,6 +46,10 @@ use crate::support::{
|
||||
TestLeaseCoordinator, account_policy, profile, secret,
|
||||
};
|
||||
|
||||
fn oauth_auth(token: &str) -> CodexRuntimeAuthentication {
|
||||
CodexRuntimeAuthentication::OAuth(secret(token))
|
||||
}
|
||||
|
||||
fn create_account(store: &Arc<MemoryAccountStore>, id: &str, token: &str) {
|
||||
block_on(store.seed_oauth_credential(ImportCodexOAuthCredential {
|
||||
account_id: id.to_owned(),
|
||||
@@ -192,7 +196,7 @@ async fn smart_reselection_respects_native_and_required_account_boundaries() {
|
||||
}
|
||||
}
|
||||
|
||||
fn selector(
|
||||
pub(super) fn selector(
|
||||
store: &Arc<MemoryAccountStore>,
|
||||
leases: Arc<TestLeaseCoordinator>,
|
||||
) -> CodexCredentialSelector {
|
||||
@@ -975,7 +979,9 @@ async fn record_success_should_not_overwrite_a_newer_session_winner() {
|
||||
.await
|
||||
.expect("seed newer affinity");
|
||||
|
||||
selector.record_success(&first).await;
|
||||
selector
|
||||
.record_success(&first, first.revision(), &oauth_auth("at-first"))
|
||||
.await;
|
||||
|
||||
assert_eq!(
|
||||
affinity
|
||||
@@ -1011,7 +1017,13 @@ async fn selector_should_reuse_and_renew_the_account_bound_to_the_same_session()
|
||||
})
|
||||
.await
|
||||
.expect("select first account");
|
||||
selector.record_success(first.account()).await;
|
||||
selector
|
||||
.record_success(
|
||||
first.account(),
|
||||
first.account().revision(),
|
||||
first.authentication(),
|
||||
)
|
||||
.await;
|
||||
let first_account = first.account_id().clone();
|
||||
|
||||
let second_attempt = attempt(BTreeSet::new());
|
||||
@@ -1083,7 +1095,13 @@ async fn selector_should_replace_a_busy_affinity_binding_after_the_fallback_succ
|
||||
})
|
||||
.await
|
||||
.expect("select fallback account");
|
||||
selector.record_success(selected.account()).await;
|
||||
selector
|
||||
.record_success(
|
||||
selected.account(),
|
||||
selected.account().revision(),
|
||||
selected.authentication(),
|
||||
)
|
||||
.await;
|
||||
|
||||
assert_eq!(
|
||||
(
|
||||
@@ -1330,7 +1348,16 @@ fn selector_returns_capacity_error_when_every_redis_lease_is_busy() {
|
||||
#[test]
|
||||
fn credential_expired_failure_marks_unified_account_expired() {
|
||||
let store = Arc::new(MemoryAccountStore::default());
|
||||
create_account(&store, "acct_primary", "at-primary");
|
||||
let mut token_only = secret("at-primary");
|
||||
token_only.refresh_token = None;
|
||||
block_on(store.seed_oauth_credential(ImportCodexOAuthCredential {
|
||||
account_id: "acct_primary".to_owned(),
|
||||
name: "acct_primary".to_owned(),
|
||||
secret: token_only,
|
||||
verified_account: profile("chatgpt-acct_primary"),
|
||||
next_refresh_at: None,
|
||||
enabled: true,
|
||||
}));
|
||||
let selector = selector(&store, Arc::new(TestLeaseCoordinator::default()));
|
||||
let attempt = attempt(BTreeSet::new());
|
||||
let lease =
|
||||
@@ -1347,6 +1374,7 @@ fn credential_expired_failure_marks_unified_account_expired() {
|
||||
.expect("select account");
|
||||
block_on(selector.record_failure(
|
||||
lease.account(),
|
||||
lease.authentication(),
|
||||
CodexAccountFailure::CredentialExpired,
|
||||
None,
|
||||
))
|
||||
@@ -1366,6 +1394,211 @@ fn credential_expired_failure_marks_unified_account_expired() {
|
||||
assert_eq!(account.last_error_message(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn credential_expired_failure_refreshes_an_unexpired_oauth_token_once() {
|
||||
let store = Arc::new(MemoryAccountStore::default());
|
||||
create_account(&store, "acct_primary", "at-primary");
|
||||
let selector = selector(&store, Arc::new(TestLeaseCoordinator::default()));
|
||||
let reject = |account: &ProviderAccount, token: &str| {
|
||||
block_on(selector.record_failure(
|
||||
account,
|
||||
&oauth_auth(token),
|
||||
CodexAccountFailure::CredentialExpired,
|
||||
None,
|
||||
))
|
||||
.expect("record rejected access token");
|
||||
store.account("acct_primary").expect("account")
|
||||
};
|
||||
|
||||
// 未到期的访问令牌被拒后只提前到期,凭据版本与状态留给 OAuth 续期处理
|
||||
let before = store.account("acct_primary").expect("account");
|
||||
let deferred = reject(&before, "at-primary");
|
||||
assert_eq!(deferred.credential_state(), CredentialState::Ready);
|
||||
assert_eq!(deferred.revision(), before.revision());
|
||||
let status = deferred.status_projection(SystemTime::now(), None);
|
||||
assert_eq!(status.status, gateway_core::account::AccountStatus::Error);
|
||||
assert_eq!(
|
||||
status.error_reason,
|
||||
Some(AccountErrorReason::AccessTokenExpired)
|
||||
);
|
||||
|
||||
// 同一令牌的并发拒绝不消耗续期机会,续期后的令牌再被拒才写入过期
|
||||
assert_eq!(
|
||||
reject(&before, "at-primary").credential_state(),
|
||||
CredentialState::Ready
|
||||
);
|
||||
// 同版本成功须中断连续风控失败,但不能证明被拒的 AT 已经续期
|
||||
let path_block = || {
|
||||
block_on(selector.record_failure(
|
||||
&before,
|
||||
&oauth_auth("at-primary"),
|
||||
CodexAccountFailure::CloudflarePathBlocked,
|
||||
None,
|
||||
))
|
||||
.unwrap();
|
||||
};
|
||||
path_block();
|
||||
path_block();
|
||||
block_on(selector.record_success(&before, before.revision(), &oauth_auth("at-primary")));
|
||||
path_block();
|
||||
assert_eq!(
|
||||
store.account("acct_primary").unwrap().credential_state(),
|
||||
CredentialState::Ready
|
||||
);
|
||||
// 旧请求自己的 Cookie 写回推进了反馈版本,但它使用的仍是被拒的 AT
|
||||
block_on(selector.capture_response_cookies(
|
||||
&before,
|
||||
&Url::parse(OFFICIAL_CODEX_BASE_URL).unwrap(),
|
||||
&["__cf_bm=test; Path=/; Secure; HttpOnly; Max-Age=3600".to_owned()],
|
||||
))
|
||||
.unwrap();
|
||||
let with_cookie = store.account("acct_primary").unwrap();
|
||||
assert!(with_cookie.revision() > before.revision());
|
||||
block_on(selector.record_success(&with_cookie, before.revision(), &oauth_auth("at-primary")));
|
||||
block_on(store.repository().rotate_refreshed_oauth_secret(
|
||||
&with_cookie,
|
||||
secret("at-refreshed"),
|
||||
Some(SystemTime::now() + Duration::from_secs(3600)),
|
||||
None,
|
||||
))
|
||||
.expect("rotate access token");
|
||||
let refreshed = store.account("acct_primary").expect("refreshed account");
|
||||
// 旧令牌迟到的成功、401 均不能清掉新令牌的恢复限制
|
||||
block_on(selector.record_success(&before, before.revision(), &oauth_auth("at-primary")));
|
||||
reject(&before, "at-primary");
|
||||
for _ in 0..2 {
|
||||
assert_eq!(
|
||||
reject(&refreshed, "at-refreshed").credential_state(),
|
||||
CredentialState::Expired
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn successful_request_across_cookie_revision_only_rearms_the_same_access_token() {
|
||||
for token_changed in [false, true] {
|
||||
let store = Arc::new(MemoryAccountStore::default());
|
||||
create_account(&store, "acct_primary", "initial");
|
||||
let selector = selector(&store, Arc::new(TestLeaseCoordinator::default()));
|
||||
let current = || store.account("acct_primary").unwrap();
|
||||
let reject = |account: &ProviderAccount, token: &str| {
|
||||
block_on(selector.record_failure(
|
||||
account,
|
||||
&oauth_auth(token),
|
||||
CodexAccountFailure::CredentialExpired,
|
||||
None,
|
||||
))
|
||||
.unwrap();
|
||||
};
|
||||
let rotate = |access_token| {
|
||||
block_on(store.repository().rotate_refreshed_oauth_secret(
|
||||
¤t(),
|
||||
secret(access_token),
|
||||
Some(SystemTime::now() + Duration::from_secs(3600)),
|
||||
None,
|
||||
))
|
||||
.unwrap();
|
||||
};
|
||||
reject(¤t(), "initial");
|
||||
rotate("renewed");
|
||||
let block_path = |token: &str| {
|
||||
block_on(selector.record_failure(
|
||||
¤t(),
|
||||
&oauth_auth(token),
|
||||
CodexAccountFailure::CloudflarePathBlocked,
|
||||
None,
|
||||
))
|
||||
.unwrap();
|
||||
};
|
||||
block_path("renewed");
|
||||
let in_flight = current();
|
||||
// 一条并发响应更新 Cookie,另一条流随后用原请求快照报告成功
|
||||
let cookie = block_on(selector.capture_response_cookies(
|
||||
&in_flight,
|
||||
&Url::parse("https://chatgpt.com/backend-api/codex/responses").unwrap(),
|
||||
&["__cf_bm=test; Path=/; Secure; HttpOnly; Max-Age=3600".to_owned()],
|
||||
))
|
||||
.unwrap();
|
||||
assert!(cookie.credential_revision.is_some());
|
||||
if token_changed {
|
||||
rotate("replacement");
|
||||
}
|
||||
let current_token = if token_changed {
|
||||
"replacement"
|
||||
} else {
|
||||
"renewed"
|
||||
};
|
||||
let sent_auth = oauth_auth("renewed");
|
||||
let release = store.hold_next_current_credential_read();
|
||||
let mut success =
|
||||
std::pin::pin!(selector.record_success(&in_flight, in_flight.revision(), &sent_auth));
|
||||
assert!(futures::FutureExt::now_or_never(success.as_mut()).is_none());
|
||||
block_path(current_token);
|
||||
release.send(()).unwrap();
|
||||
block_on(success);
|
||||
reject(¤t(), current_token);
|
||||
let after = current();
|
||||
if token_changed {
|
||||
assert_eq!(after.credential_state(), CredentialState::Expired);
|
||||
} else {
|
||||
assert_eq!(after.credential_state(), CredentialState::Ready);
|
||||
assert!(after.access_token_expires_at().unwrap() <= SystemTime::now());
|
||||
}
|
||||
// 同一 AT 的成功只中断核对开始前的失败,真正旧 AT 的成功不打断任何失败
|
||||
block_path(current_token);
|
||||
if !token_changed {
|
||||
assert_eq!(current().credential_state(), CredentialState::Ready);
|
||||
block_path(current_token);
|
||||
}
|
||||
assert_eq!(current().credential_state(), CredentialState::Invalid);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn success_does_not_clear_a_rejection_recorded_while_verifying_the_token() {
|
||||
let store = Arc::new(MemoryAccountStore::default());
|
||||
create_account(&store, "acct_primary", "original");
|
||||
let selector = selector(&store, Arc::new(TestLeaseCoordinator::default()));
|
||||
let current = || store.account("acct_primary").unwrap();
|
||||
let reject = |token: &str| {
|
||||
block_on(selector.record_failure(
|
||||
¤t(),
|
||||
&oauth_auth(token),
|
||||
CodexAccountFailure::CredentialExpired,
|
||||
None,
|
||||
))
|
||||
.unwrap();
|
||||
};
|
||||
reject("original");
|
||||
block_on(store.repository().rotate_refreshed_oauth_secret(
|
||||
¤t(),
|
||||
secret("renewed"),
|
||||
Some(SystemTime::now() + Duration::from_secs(3600)),
|
||||
None,
|
||||
))
|
||||
.unwrap();
|
||||
let sent = current();
|
||||
let auth = oauth_auth("renewed");
|
||||
block_on(selector.capture_response_cookies(
|
||||
&sent,
|
||||
&Url::parse(OFFICIAL_CODEX_BASE_URL).unwrap(),
|
||||
&["__cf_bm=test; Path=/; Secure".to_owned()],
|
||||
))
|
||||
.unwrap();
|
||||
|
||||
let release = store.hold_next_current_credential_read();
|
||||
let mut success = std::pin::pin!(selector.record_success(&sent, sent.revision(), &auth));
|
||||
assert!(futures::FutureExt::now_or_never(success.as_mut()).is_none());
|
||||
reject("renewed");
|
||||
assert_eq!(current().credential_state(), CredentialState::Expired);
|
||||
release.send(()).unwrap();
|
||||
block_on(success);
|
||||
|
||||
// 早先的成功不能重新放开续期:同一 AT 再次被拒时,到期时间仍应在未来
|
||||
reject("renewed");
|
||||
assert!(current().access_token_expires_at().unwrap() > SystemTime::now());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn credential_expired_failure_keeps_expired_oauth_for_bounded_refresh_recovery() {
|
||||
let store = Arc::new(MemoryAccountStore::default());
|
||||
@@ -1385,6 +1618,7 @@ fn credential_expired_failure_keeps_expired_oauth_for_bounded_refresh_recovery()
|
||||
|
||||
block_on(selector.record_failure(
|
||||
&account,
|
||||
&oauth_auth("at-primary"),
|
||||
CodexAccountFailure::CredentialExpired,
|
||||
Some("token_expired".to_owned()),
|
||||
))
|
||||
@@ -1429,6 +1663,7 @@ fn rate_limited_failure_records_runtime_cooldown_without_changing_persisted_fact
|
||||
|
||||
block_on(selector.record_failure(
|
||||
lease.account(),
|
||||
lease.authentication(),
|
||||
CodexAccountFailure::RateLimited {
|
||||
retry_after: Some(Duration::from_secs(30)),
|
||||
},
|
||||
@@ -1460,6 +1695,7 @@ async fn usage_limit_exhaustion_marks_quota_exhausted_without_usage_probe() {
|
||||
selector
|
||||
.record_failure(
|
||||
&account,
|
||||
&oauth_auth("at-primary"),
|
||||
CodexAccountFailure::UsageLimitExhausted {
|
||||
reset_at: Some(SystemTime::now() + Duration::from_secs(30)),
|
||||
window_minutes: None,
|
||||
@@ -1488,6 +1724,7 @@ fn rate_limited_failure_does_not_downgrade_persisted_quota_exhaustion() {
|
||||
|
||||
block_on(selector.record_failure(
|
||||
&account,
|
||||
&oauth_auth("at-primary"),
|
||||
CodexAccountFailure::RateLimited {
|
||||
retry_after: Some(Duration::from_secs(30)),
|
||||
},
|
||||
@@ -1521,6 +1758,7 @@ fn rate_limited_failure_does_not_consult_stale_quota_snapshot() {
|
||||
|
||||
block_on(selector.record_failure(
|
||||
&account,
|
||||
&oauth_auth("at-primary"),
|
||||
CodexAccountFailure::RateLimited {
|
||||
retry_after: Some(Duration::from_secs(30)),
|
||||
},
|
||||
@@ -1555,6 +1793,7 @@ fn rate_limited_failure_does_not_overwrite_stale_authentication_state() {
|
||||
|
||||
block_on(selector.record_failure(
|
||||
¤t,
|
||||
&oauth_auth("at-primary"),
|
||||
CodexAccountFailure::RateLimited {
|
||||
retry_after: Some(Duration::from_secs(30)),
|
||||
},
|
||||
@@ -1585,7 +1824,7 @@ fn successful_upstream_response_recovers_non_quota_terminal_states() {
|
||||
let current = store.account("acct_primary").expect("stale account");
|
||||
let selector = selector(&store, Arc::new(TestLeaseCoordinator::default()));
|
||||
|
||||
block_on(selector.record_success(¤t));
|
||||
block_on(selector.record_success(¤t, current.revision(), &oauth_auth("at-primary")));
|
||||
|
||||
assert_eq!(
|
||||
store
|
||||
@@ -1629,9 +1868,12 @@ fn rate_limited_failures_for_distinct_accounts_do_not_conflict() {
|
||||
let selector = selector(&store, Arc::new(TestLeaseCoordinator::default()));
|
||||
|
||||
block_on(async {
|
||||
let first_auth = oauth_auth("at-first");
|
||||
let second_auth = oauth_auth("at-second");
|
||||
let (first_result, second_result) = futures::join!(
|
||||
selector.record_failure(
|
||||
&first,
|
||||
&first_auth,
|
||||
CodexAccountFailure::RateLimited {
|
||||
retry_after: Some(Duration::from_secs(30)),
|
||||
},
|
||||
@@ -1639,6 +1881,7 @@ fn rate_limited_failures_for_distinct_accounts_do_not_conflict() {
|
||||
),
|
||||
selector.record_failure(
|
||||
&second,
|
||||
&second_auth,
|
||||
CodexAccountFailure::RateLimited {
|
||||
retry_after: Some(Duration::from_secs(30)),
|
||||
},
|
||||
@@ -1671,8 +1914,13 @@ fn native_continuation_surfaces_the_original_accounts_quota_status_to_the_coordi
|
||||
create_account(&store, "acct_fallback", "at-fallback");
|
||||
let strict_selector = selector(&store, Arc::new(TestLeaseCoordinator::default()));
|
||||
let original = store.account("acct_original").expect("original account");
|
||||
block_on(strict_selector.record_failure(&original, CodexAccountFailure::QuotaExhausted, None))
|
||||
.expect("mark original account exhausted");
|
||||
block_on(strict_selector.record_failure(
|
||||
&original,
|
||||
&oauth_auth("at-original"),
|
||||
CodexAccountFailure::QuotaExhausted,
|
||||
None,
|
||||
))
|
||||
.expect("mark original account exhausted");
|
||||
|
||||
let selector = selector_with_runtime(
|
||||
&store,
|
||||
@@ -1811,6 +2059,7 @@ fn identity_verification_failure_isolates_only_selected_account() {
|
||||
|
||||
block_on(selector.record_failure(
|
||||
lease.account(),
|
||||
lease.authentication(),
|
||||
CodexAccountFailure::IdentityVerificationRequired,
|
||||
None,
|
||||
))
|
||||
@@ -1858,6 +2107,7 @@ fn cloudflare_challenge_does_not_change_persisted_account_facts() {
|
||||
|
||||
block_on(selector.record_failure(
|
||||
lease.account(),
|
||||
lease.authentication(),
|
||||
CodexAccountFailure::CloudflareChallenge { retry_after: None },
|
||||
None,
|
||||
))
|
||||
@@ -1870,7 +2120,105 @@ fn cloudflare_challenge_does_not_change_persisted_account_facts() {
|
||||
.credential_state(),
|
||||
CredentialState::Ready
|
||||
);
|
||||
block_on(selector.record_success(lease.account()));
|
||||
block_on(selector.record_success(
|
||||
lease.account(),
|
||||
lease.account().revision(),
|
||||
lease.authentication(),
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cookie_revision_success_breaks_consecutive_path_blocks_only_for_the_current_token() {
|
||||
for rotate in [false, true] {
|
||||
let store = Arc::new(MemoryAccountStore::default());
|
||||
create_account(&store, "acct_primary", "old-at");
|
||||
let selector = selector(&store, Arc::new(TestLeaseCoordinator::default()));
|
||||
let current = || store.account("acct_primary").unwrap();
|
||||
let block = |token| {
|
||||
block_on(selector.record_failure(
|
||||
¤t(),
|
||||
&oauth_auth(token),
|
||||
CodexAccountFailure::CloudflarePathBlocked,
|
||||
None,
|
||||
))
|
||||
.unwrap()
|
||||
};
|
||||
block("old-at");
|
||||
block("old-at");
|
||||
let sent = current();
|
||||
let cookie = block_on(selector.capture_response_cookies(
|
||||
&sent,
|
||||
&Url::parse(OFFICIAL_CODEX_BASE_URL).unwrap(),
|
||||
&["__cf_bm=test; Path=/; Secure".to_owned()],
|
||||
))
|
||||
.unwrap();
|
||||
assert!(cookie.credential_revision.is_some());
|
||||
if rotate {
|
||||
block_on(store.repository().rotate_refreshed_oauth_secret(
|
||||
¤t(),
|
||||
secret("new-at"),
|
||||
Some(SystemTime::now() + Duration::from_secs(3600)),
|
||||
None,
|
||||
))
|
||||
.unwrap();
|
||||
}
|
||||
block_on(selector.record_success(&sent, sent.revision(), &oauth_auth("old-at")));
|
||||
block(if rotate { "new-at" } else { "old-at" });
|
||||
assert_eq!(
|
||||
current().credential_state(),
|
||||
if rotate {
|
||||
CredentialState::Invalid
|
||||
} else {
|
||||
CredentialState::Ready
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cookie_lease_does_not_swallow_a_rejected_access_token() {
|
||||
for cookie_commits_first in [false, true] {
|
||||
let store = Arc::new(MemoryAccountStore::default());
|
||||
create_account(&store, "acct_primary", "old-at");
|
||||
let selector = Arc::new(selector(&store, Arc::new(TestLeaseCoordinator::default())));
|
||||
let sent = store.account("acct_primary").unwrap();
|
||||
let reject = |selector: Arc<CodexCredentialSelector>, sent: ProviderAccount| async move {
|
||||
selector
|
||||
.record_failure(
|
||||
&sent,
|
||||
&oauth_auth("old-at"),
|
||||
CodexAccountFailure::CredentialExpired,
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
};
|
||||
if !cookie_commits_first {
|
||||
// Cookie 写入已取锁但尚未提交,401 到期时间须保留到提交之后
|
||||
let selector = Arc::downgrade(&selector);
|
||||
let sent = sent.clone();
|
||||
store.on_credential_load(Arc::new(move |_, _, _| {
|
||||
let reject = reject(selector.upgrade().unwrap(), sent.clone());
|
||||
Box::pin(async move {
|
||||
reject.await;
|
||||
Ok(())
|
||||
})
|
||||
}));
|
||||
}
|
||||
let cookie = block_on(selector.capture_response_cookies(
|
||||
&sent,
|
||||
&Url::parse(OFFICIAL_CODEX_BASE_URL).unwrap(),
|
||||
&["__cf_bm=test; Path=/; Secure".to_owned()],
|
||||
))
|
||||
.unwrap();
|
||||
assert!(cookie.credential_revision.is_some());
|
||||
if cookie_commits_first {
|
||||
block_on(reject(selector.clone(), sent));
|
||||
}
|
||||
let current = store.account("acct_primary").unwrap();
|
||||
assert!(current.access_token_expires_at().unwrap() <= SystemTime::now());
|
||||
assert_eq!(current.credential_state(), CredentialState::Ready);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1899,6 +2247,7 @@ fn repeated_cloudflare_path_block_marks_only_the_affected_account_invalid() {
|
||||
for _ in 0..3 {
|
||||
block_on(selector.record_failure(
|
||||
lease.account(),
|
||||
lease.authentication(),
|
||||
CodexAccountFailure::CloudflarePathBlocked,
|
||||
None,
|
||||
))
|
||||
@@ -1956,6 +2305,7 @@ fn cloudflare_challenge_expires_provider_owned_cookies_at_cooldown_boundary() {
|
||||
.expect("select revised account");
|
||||
block_on(selector.record_failure(
|
||||
second.account(),
|
||||
second.authentication(),
|
||||
CodexAccountFailure::CloudflareChallenge { retry_after: None },
|
||||
None,
|
||||
))
|
||||
@@ -2005,6 +2355,7 @@ fn cloudflare_path_block_deletes_provider_owned_cookies() {
|
||||
.expect("select revised account");
|
||||
block_on(selector.record_failure(
|
||||
second.account(),
|
||||
second.authentication(),
|
||||
CodexAccountFailure::CloudflarePathBlocked,
|
||||
None,
|
||||
))
|
||||
@@ -2080,8 +2431,13 @@ fn response_cookie_rotation_returns_a_current_account_for_later_fenced_writes()
|
||||
|
||||
assert_eq!(outcome.credential_revision, Some(current.revision().get()));
|
||||
assert_ne!(current.revision(), lease.account().revision());
|
||||
block_on(selector.record_failure(¤t, CodexAccountFailure::QuotaExhausted, None))
|
||||
.expect("record failure with current revision");
|
||||
block_on(selector.record_failure(
|
||||
¤t,
|
||||
&oauth_auth("at-primary"),
|
||||
CodexAccountFailure::QuotaExhausted,
|
||||
None,
|
||||
))
|
||||
.expect("record failure with current revision");
|
||||
assert_eq!(
|
||||
store
|
||||
.account("acct_primary")
|
||||
|
||||
+20
-14
@@ -141,8 +141,8 @@ async fn changed_owner_and_lease_contention_refresh_the_complete_pool() {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn projection_is_isolated_by_client_scope_model_and_account_policy() {
|
||||
for changed in ["client", "scope", "model", "concurrency"] {
|
||||
async fn projection_is_isolated_by_client_scope_model_protocol_and_account_policy() {
|
||||
for changed in ["client", "scope", "model", "protocol", "concurrency"] {
|
||||
let store = Arc::new(MemoryAccountStore::default());
|
||||
create_account(&store, "acct_first", "test-first");
|
||||
create_account(&store, "acct_second", "test-second");
|
||||
@@ -173,18 +173,24 @@ async fn projection_is_isolated_by_client_scope_model_and_account_policy() {
|
||||
scope,
|
||||
policy,
|
||||
);
|
||||
let error = select(
|
||||
&selector,
|
||||
&attempt,
|
||||
&key,
|
||||
if changed == "model" {
|
||||
"gpt-5.5"
|
||||
} else {
|
||||
"gpt-5.4"
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
let error = selector
|
||||
.select(&SelectCodexCredential {
|
||||
protocol: if changed == "protocol" {
|
||||
gateway_protocol::chat_completions::CHAT_PROTOCOL
|
||||
} else {
|
||||
gateway_protocol::openai::OPENAI_PROTOCOL
|
||||
},
|
||||
upstream_model: if changed == "model" {
|
||||
"gpt-5.5"
|
||||
} else {
|
||||
"gpt-5.4"
|
||||
},
|
||||
request_url: &Url::parse(OFFICIAL_CODEX_BASE_URL).unwrap(),
|
||||
attempt: &attempt,
|
||||
session_affinity_key: Some(&key),
|
||||
})
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
matches!(error, CredentialSelectionError::Store(_)),
|
||||
"{changed}: {error:?}"
|
||||
|
||||
Loaded 100 of 160 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user