mirror of
https://github.com/zyycn/codex-proxy-rs.git
synced 2026-12-06 00:00:51 +00:00
Compare commits
62
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
177679a13c | ||
|
|
195c51c06c | ||
|
|
745bd15d3d | ||
|
|
3170b92d47 | ||
|
|
8b40e707fd | ||
|
|
15aabfc861 | ||
|
|
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 | ||
|
|
6eabda047c | ||
|
|
3c560b9276 | ||
|
|
77c42cea98 | ||
|
|
dd234c3619 | ||
|
|
b5e691c63d | ||
|
|
2d0a52096a | ||
|
|
47620e217a | ||
|
|
48aeccd0e0 | ||
|
|
bdc618701b | ||
|
|
acd76a09dc | ||
|
|
808387442b | ||
|
|
5bc4e3e5c8 | ||
|
|
7e98130cac | ||
|
|
2821a5e3bd | ||
|
|
6a6a167d41 | ||
|
|
cffb6b35d2 | ||
|
|
17e50df06f | ||
|
|
f2d95cc3fa | ||
|
|
e4f6e1d4e3 | ||
|
|
66f650f097 | ||
|
|
ca4d02068a | ||
|
|
d185a639a9 | ||
|
|
3078dd9993 |
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 演变与指定版本升级用例;需要验证迁移执行、数据保留或回滚时,在临时目录编写一次性验证并使用隔离数据库,测试通过即可,临时脚本不纳入维护测试集
|
||||
|
||||
@@ -30,6 +30,8 @@
|
||||
|
||||
验证前按[界面验证](../../../../CONTRIBUTING.md#界面验证)明确本次受影响的用户路径、状态和通过条件。局部修改围绕受影响区域及相关操作验收;主题、窗口尺寸和空/加载/错误状态仅在受影响时补充,共用主题或基础组件变更按主题规范扩大范围
|
||||
|
||||
沿实际操作验证待确认、执行中、完成、失败与取消等受影响阶段,同时检查当前弹层和背景区域,核对应该出现的反馈与不应出现的状态。必要时延迟模拟响应以观察过渡状态,不能仅凭请求成功或截图齐全判定交互通过
|
||||
|
||||
通过后按[验证停止条件](../../../../CONTRIBUTING.md#验证)收尾;只有新改动、失败或未解疑点时补验相关部分。补交截图或 PR 材料时复用仍有效的运行证据
|
||||
|
||||
## 交付前
|
||||
@@ -42,7 +44,7 @@
|
||||
- **样式与状态**:是否使用对应 Token 与 utility,局部样式是否符合适用边界,受影响的主题、窄屏及交互状态是否正确
|
||||
- **模块归属**从调用方核对公开入口。页面或多文件组件通过 `index.vue` 提供界面,其他页面复用整页时引用所属模块的布局入口,独立复用的业务组件按领域放置
|
||||
- **Provider 边界**涉及账号操作、身份配置或定价时,沿接口响应、控件和提交载荷追踪同一条规则。服务端决定的能力使用接口字段,Provider 专属表单解释自己的字段,多个页面共用的编辑流程只维护一份。按[前端职责](../../../../docs/architecture.md#34-前端模块职责)核对归属
|
||||
- **查询与动作**:区分首次加载、刷新、分页、单行与批量操作,核对 loading、禁用状态的影响范围;沿用请求层错误处理,不在页面叠加同一错误的提示
|
||||
- **查询与动作**:区分首次加载、刷新、分页、单行与批量操作,明确当前动作的反馈归属及其他控件的禁用范围,避免同一动作在前后景重复显示执行反馈。待确认不等于已提交,复用交互时重新核对 loading、进度与结果的显示条件是否适用于当前动作;沿用请求层错误处理,不在页面叠加同一错误的提示
|
||||
- **运行证据**:按界面验证核对截图与实际交互,证据对应当前实现;页面 PR 的可访问图片和 Draft 条件按该节执行
|
||||
|
||||
交付简述所复用的页面或组件、实际验证范围及缺口;环境不足时如实说明,不能仅凭构建、源码或截图推断未验证的行为
|
||||
@@ -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 中的手写说明,为常规版本追加安装入口、文档和 GitHub 变更列表。
|
||||
|
||||
只调整已发布页面的标题或正文时,编辑对应 GitHub Release 的 `name` 或 `body` 并回读核对;
|
||||
保持已有 tag、源码提交、附件和预发行状态,不重新执行发布入口。
|
||||
@@ -60,7 +60,8 @@ release/publish "$release_version"
|
||||
### 验收
|
||||
|
||||
- 发布完成后核对 GitHub Release 的版本、正式版/预发行状态和中文变更正文;对照平台清单与工作流确认归档、校验和及镜像产物。
|
||||
工作流附加的安装说明和自动提交列表按其当前配置处理,不用它们替代手写的中文变更说明。
|
||||
手写正文应与 tag 内的说明一致,核对安装入口和 `Full Changelog` 指向目标版本,正式版的比较范围从上一正式版开始
|
||||
- 核对 `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,20 @@
|
||||
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,正文使用中文
|
||||
- 常规版本按「新增功能」「优化改进」「问题修复」「升级须知」归类,省略空章节;单一改动可直接写一句。安装命令和文档入口由工作流附加
|
||||
- 常规版本的手写正文按「新增功能」「优化改进」「问题修复」「升级须知」归类,省略空章节;单一改动可直接写一句
|
||||
- 常规版本的安装入口、文档链接和 GitHub 变更列表由工作流在发版时追加
|
||||
- 每条用一句短语讲清一个用户可感知的结果,不加句号,例如「系统更新:确认当前平台有安装包后才提示升级」
|
||||
- 同一变化只写一次,保留会影响使用或升级的默认值和限制,不展开实现过程、逐条翻译提交或写未经验证的承诺
|
||||
- 剔除回退、重复及未进入发行范围的内容,升级事项须能追溯到实际迁移、配置或兼容变化
|
||||
@@ -31,7 +39,7 @@
|
||||
在上一发行基线到 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、发行物验证或实际发布授权
|
||||
预检不修改文件、Git 引用或远端状态;远端存在本地未知提交时,先同步再检查。它不替代 CI、发行物验证或实际发布授权
|
||||
|
||||
按[验证要求](../../../../CONTRIBUTING.md#验证)核对目标提交的证据,区分通过、失败、跳过与未执行
|
||||
数据库变更同时读取[迁移冻结规则](../../../../backend/migrations/README.md#冻结规则):
|
||||
|
||||
@@ -91,17 +91,36 @@ module ReleaseMetadata
|
||||
"#{APP_NAME}_#{version}_#{platform.fetch('os')}_#{platform.fetch('arch')}.#{platform.fetch('archive')}"
|
||||
end
|
||||
|
||||
# 正式版始终对比上一正式版,常规预发行优先对比同一目标版本的上一预发行
|
||||
def self.previous_tag(value)
|
||||
return if value.include?('-exp.')
|
||||
|
||||
endpoint = "repos/#{ENV.fetch('GITHUB_REPOSITORY')}/releases?per_page=100"
|
||||
output, status = Open3.capture2('gh', 'api', '--paginate', endpoint, '--jq',
|
||||
'.[] | select(.draft == false) | [.tag_name, .prerelease] | @tsv')
|
||||
raise 'Failed to read published releases' unless status.success?
|
||||
|
||||
reachable = git('tag', '--list', 'v*', '--merged', 'HEAD').lines.map(&:strip)
|
||||
candidates = output.each_line.each_with_object([]) do |line, tags|
|
||||
tag, prerelease = line.chomp.split("\t")
|
||||
next unless reachable.include?(tag) && tag.delete_prefix('v').match?(SEMVER) && !tag.include?('+')
|
||||
next unless prerelease?(tag) == (prerelease == 'true') && sort_key(tag) < sort_key(value)
|
||||
tags << tag
|
||||
end
|
||||
if prerelease?(value)
|
||||
prefix = "v#{value.split('-', 2).first}-"
|
||||
previous = candidates.select { |tag| tag.start_with?(prefix) && !tag.include?('-exp.') }.max_by { |tag| sort_key(tag) }
|
||||
return previous if previous
|
||||
end
|
||||
candidates.reject { |tag| prerelease?(tag) }.max_by { |tag| sort_key(tag) }
|
||||
end
|
||||
|
||||
def self.outputs(tag)
|
||||
value = release_version(YAML.load_file('release/version.yaml').fetch('version'))
|
||||
raise "Release tag #{tag} does not match v#{value}" unless tag == "v#{value}"
|
||||
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 +131,7 @@ 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,
|
||||
'previous_tag' => previous_tag(value),
|
||||
'prerelease' => prerelease?(value),
|
||||
'build_type' => value.split('+', 2).first.include?('-exp.') ? 'experimental' : 'release'
|
||||
}
|
||||
|
||||
@@ -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
|
||||
@@ -51,6 +51,8 @@ jobs:
|
||||
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
|
||||
@@ -68,6 +70,7 @@ jobs:
|
||||
- name: Read release metadata and seal plugin manifest
|
||||
id: version
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
RELEASE_TAG: ${{ inputs.tag }}
|
||||
run: ruby .github/scripts/release-metadata.rb outputs "$RELEASE_TAG" >> "$GITHUB_OUTPUT"
|
||||
|
||||
@@ -97,6 +100,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 +439,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,6 +550,8 @@ jobs:
|
||||
- name: Prepare release notes
|
||||
shell: bash
|
||||
env:
|
||||
PREVIOUS_TAG: ${{ needs.release-info.outputs.previous_tag }}
|
||||
RELEASE_TAG: ${{ needs.release-info.outputs.tag }}
|
||||
BUILD_TYPE: ${{ needs.release-info.outputs.build_type }}
|
||||
INSTALLATION_NOTES: |
|
||||
## Linux 一键安装(Docker Compose)
|
||||
@@ -537,7 +567,12 @@ jobs:
|
||||
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'
|
||||
unless ENV.fetch('BUILD_TYPE') == 'experimental'
|
||||
notes += "\n\n#{ENV.fetch('INSTALLATION_NOTES').strip}"
|
||||
if ENV.fetch('PREVIOUS_TAG').empty?
|
||||
notes += "\n\n**Full Changelog**: https://github.com/#{ENV.fetch('GITHUB_REPOSITORY')}/commits/#{ENV.fetch('RELEASE_TAG')}"
|
||||
end
|
||||
end
|
||||
output = File.join(ENV.fetch('RUNNER_TEMP'), 'release-notes.md')
|
||||
File.write(output, "#{notes}\n")
|
||||
RUBY
|
||||
@@ -552,7 +587,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' }}
|
||||
generate_release_notes: ${{ needs.release-info.outputs.build_type != 'experimental' && needs.release-info.outputs.previous_tag != '' }}
|
||||
previous_tag: ${{ needs.release-info.outputs.previous_tag }}
|
||||
prerelease: ${{ needs.release-info.outputs.prerelease == 'true' }}
|
||||
# action 保留已公开 Release 的状态,新 Release 上传完成后仍保持草稿
|
||||
|
||||
+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`,手写章节标题和正文使用中文;命令、配置键、协议名等保留原文。只说明本次版本的实际变化,按影响交代升级事项。常规版本由发布工作流追加安装入口、文档链接和 GitHub 变更列表,比较基线见[版本与说明准备](.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 帮助到你了,欢迎请我喝杯咖啡 ☕
|
||||
|
||||
Generated
+20
@@ -1887,6 +1887,7 @@ dependencies = [
|
||||
"tracing",
|
||||
"tracing-appender",
|
||||
"tracing-subscriber",
|
||||
"uuid",
|
||||
"wiremock",
|
||||
"yaml-rust2 0.13.2",
|
||||
]
|
||||
@@ -2707,6 +2708,12 @@ version = "0.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154"
|
||||
|
||||
[[package]]
|
||||
name = "lzma-rust2"
|
||||
version = "0.26.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4c7861572250348d13073a9035c6a83f3e583ec9a76a65ce92f338fe1107d8f5"
|
||||
|
||||
[[package]]
|
||||
name = "lzma-sys"
|
||||
version = "0.1.20"
|
||||
@@ -3404,6 +3411,7 @@ dependencies = [
|
||||
"reqwest",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sevenz-rust2",
|
||||
"sha2",
|
||||
"tar",
|
||||
"tempfile",
|
||||
@@ -4185,6 +4193,18 @@ dependencies = [
|
||||
"stable_deref_trait",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sevenz-rust2"
|
||||
version = "0.27.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2e668242e054ba8b7360918104c30c6685bdedf847909a784cf267d002f40a6a"
|
||||
dependencies = [
|
||||
"crc32fast",
|
||||
"js-sys",
|
||||
"lzma-rust2",
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sha1"
|
||||
version = "0.10.7"
|
||||
|
||||
@@ -135,6 +135,7 @@ async fn execute(
|
||||
store.admin_ports().settings(),
|
||||
timezone,
|
||||
providers.admin.clone(),
|
||||
core.snapshots(),
|
||||
core.snapshot_control(),
|
||||
core.account_probe(),
|
||||
Some(providers.peer.service()),
|
||||
|
||||
@@ -79,7 +79,11 @@ impl Providers {
|
||||
)
|
||||
.await?;
|
||||
environment.host.report_startup_ready("OpenAI Provider");
|
||||
let antigravity = provider_antigravity::initialize(ports.clone())?;
|
||||
let antigravity = provider_antigravity::initialize(
|
||||
ports.clone(),
|
||||
environment.host.runtime_data_dir().join("antigravity"),
|
||||
)
|
||||
.await?;
|
||||
environment
|
||||
.host
|
||||
.report_startup_ready("Antigravity Provider");
|
||||
|
||||
@@ -76,7 +76,9 @@ fn core_value_owners_do_not_depend_on_execution_or_routing() {
|
||||
let reexports = read_root_reexport_owners(&root);
|
||||
for relative in super::rust_files(&root) {
|
||||
let allowed: Option<&[&str]> = match relative.to_str().expect("source path") {
|
||||
"validation.rs" => Some(&[]),
|
||||
"validation.rs" | "time.rs" => Some(&[]),
|
||||
// 每日排班使用部署日历换算;时间值模块自身不得依赖路由、执行或其他业务
|
||||
"account/duty.rs" => Some(&["account", "time"]),
|
||||
"identity.rs" => Some(&["validation"]),
|
||||
"upstream.rs" => Some(&["validation"]),
|
||||
"event.rs" => Some(&["metering", "operation", "upstream", "validation"]),
|
||||
|
||||
@@ -99,6 +99,7 @@ async fn initialize_inner(
|
||||
store.settings(),
|
||||
timezone,
|
||||
providers.clone(),
|
||||
published_snapshot.clone(),
|
||||
snapshot.clone(),
|
||||
probe.clone(),
|
||||
upstream_info.clone(),
|
||||
@@ -194,6 +195,12 @@ async fn initialize_inner(
|
||||
)),
|
||||
auth,
|
||||
accounts: accounts.clone(),
|
||||
account_schedules: Arc::new(crate::AccountScheduleService {
|
||||
timezone,
|
||||
store: store.account_schedules(),
|
||||
providers: providers.clone(),
|
||||
snapshot: snapshot.clone(),
|
||||
}),
|
||||
account_groups: Arc::new(DefaultAccountGroupService::new(
|
||||
upstream_info.clone(),
|
||||
store.account_groups(),
|
||||
@@ -304,6 +311,7 @@ pub fn initialize_accounts(
|
||||
settings: Arc<dyn ports::store::SettingsStore>,
|
||||
timezone: gateway_core::time::DeploymentTimeZone,
|
||||
providers: ProviderAdminRegistry,
|
||||
published: gateway_core::runtime::RuntimeSnapshotHandle,
|
||||
snapshot: Arc<dyn SnapshotControl>,
|
||||
probe: Arc<dyn AccountProbe>,
|
||||
upstream_info: Option<Arc<dyn ports::peer::PeerUpstreamService>>,
|
||||
@@ -314,6 +322,7 @@ pub fn initialize_accounts(
|
||||
settings,
|
||||
timezone,
|
||||
providers,
|
||||
published,
|
||||
snapshot,
|
||||
probe,
|
||||
upstream_info,
|
||||
|
||||
@@ -263,10 +263,11 @@ impl ScheduledTask for FreezeRecoveryTask {
|
||||
context: WorkerCycleContext,
|
||||
) -> futures::future::BoxFuture<'_, Result<(), WorkerTaskError>> {
|
||||
Box::pin(async move {
|
||||
if context.cancellation().is_cancelled() {
|
||||
return Ok(());
|
||||
}
|
||||
self.run_cycle_inner().await;
|
||||
// 中止在途探测,避免把停机当成探测失败而延长冻结
|
||||
context
|
||||
.cancellation()
|
||||
.run_until_cancelled(self.run_cycle_inner())
|
||||
.await;
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
@@ -26,6 +26,7 @@ pub use use_case::peer_link::{PeerLinkError, PeerLinkService};
|
||||
|
||||
pub use use_case::{
|
||||
account_groups::AccountGroupService,
|
||||
account_schedules::AccountScheduleService,
|
||||
accounts::AccountsService,
|
||||
auth::AuthService,
|
||||
backup::BackupService,
|
||||
@@ -209,6 +210,7 @@ pub struct AdminServices {
|
||||
peer_link: Arc<dyn PeerLinkService>,
|
||||
accounts: Arc<dyn AccountsService>,
|
||||
account_groups: Arc<dyn AccountGroupService>,
|
||||
account_schedules: Arc<AccountScheduleService>,
|
||||
client_keys: Arc<dyn ClientKeyService>,
|
||||
client_distribution: Arc<dyn ClientDistributionService>,
|
||||
observability: Arc<dyn ObservabilityService>,
|
||||
@@ -272,6 +274,11 @@ impl AdminServices {
|
||||
self.accounts.as_ref()
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn account_schedules(&self) -> &AccountScheduleService {
|
||||
self.account_schedules.as_ref()
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn account_groups(&self) -> &dyn AccountGroupService {
|
||||
self.account_groups.as_ref()
|
||||
|
||||
@@ -0,0 +1,262 @@
|
||||
//! 账号排班的轻量目录与批量变更合同
|
||||
|
||||
use super::AdminError;
|
||||
use chrono::{DateTime, Offset, TimeDelta, Utc};
|
||||
use gateway_core::account::duty::{DailyShift, SchedulePolicy};
|
||||
use gateway_core::time::DeploymentTimeZone;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ScheduleAccount {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
#[serde(skip)]
|
||||
pub provider_kind: String,
|
||||
#[serde(skip)]
|
||||
pub has_cached_quota: bool,
|
||||
pub authentication_kind: String,
|
||||
pub plan_type: Option<String>,
|
||||
pub plan_type_display: Option<String>,
|
||||
pub group_ids: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct ScheduleGroup {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct ScheduleChange {
|
||||
#[serde(default)]
|
||||
pub clear: bool,
|
||||
pub revision: u64,
|
||||
pub policy: Option<SchedulePolicy>,
|
||||
pub targets: Vec<TargetChange>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum TargetKind {
|
||||
Account,
|
||||
Group,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct TargetChange {
|
||||
pub kind: TargetKind,
|
||||
pub id: String,
|
||||
pub action: ScheduleAction,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum ScheduleAction {
|
||||
Remove,
|
||||
Set(Vec<DailyShift>),
|
||||
}
|
||||
|
||||
impl ScheduleChange {
|
||||
pub fn validate(&self) -> Result<(), AdminError> {
|
||||
if self.revision == 0
|
||||
|| !self.clear && self.policy.is_none() && self.targets.is_empty()
|
||||
|| self
|
||||
.policy
|
||||
.is_some_and(|p| !(1..=100).contains(&p.limit_percent))
|
||||
{
|
||||
return Err(AdminError::invalid("排班策略或版本无效"));
|
||||
}
|
||||
validate_targets(&self.targets)
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_targets(changes: &[TargetChange]) -> Result<(), AdminError> {
|
||||
let mut targets = BTreeSet::new();
|
||||
for target in changes {
|
||||
if !targets.insert((target.kind, &target.id)) || target.id.is_empty() {
|
||||
return Err(AdminError::invalid("排班对象重复或无效"));
|
||||
}
|
||||
if let ScheduleAction::Set(shifts) = &target.action {
|
||||
let mut ids = BTreeSet::new();
|
||||
let mut spans = Vec::new();
|
||||
for shift in shifts {
|
||||
if shift.start >= 1440
|
||||
|| shift.end >= 1440
|
||||
|| uuid::Uuid::parse_str(&shift.id).is_err()
|
||||
|| !ids.insert(&shift.id)
|
||||
{
|
||||
return Err(AdminError::invalid("班次标识或时间无效"));
|
||||
}
|
||||
if shift.start < shift.end {
|
||||
spans.push((shift.start, shift.end));
|
||||
} else {
|
||||
spans.push((shift.start, 1440));
|
||||
if shift.end > 0 {
|
||||
spans.push((0, shift.end));
|
||||
}
|
||||
}
|
||||
}
|
||||
spans.sort_unstable();
|
||||
if spans.windows(2).any(|w| w[0].1 > w[1].0) {
|
||||
return Err(AdminError::invalid("同一排班对象的班次时间重叠"));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum ScheduleScope {
|
||||
Roster,
|
||||
Account,
|
||||
Group,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct ScheduleQuery {
|
||||
pub scope: ScheduleScope,
|
||||
pub page: u32,
|
||||
pub page_size: u32,
|
||||
pub revision: Option<u64>,
|
||||
#[serde(default)]
|
||||
pub search: String,
|
||||
#[serde(default)]
|
||||
pub group_id: String,
|
||||
#[serde(default)]
|
||||
pub targets: Vec<TargetChange>,
|
||||
#[serde(default)]
|
||||
pub clear: bool,
|
||||
pub summary_minute: Option<u16>,
|
||||
#[serde(default)]
|
||||
pub include_summary: bool,
|
||||
}
|
||||
|
||||
impl ScheduleQuery {
|
||||
pub fn validate(&self) -> Result<(), AdminError> {
|
||||
if self.page == 0
|
||||
|| !(1..=100).contains(&self.page_size)
|
||||
|| self.summary_minute.is_some_and(|minute| minute >= 1440)
|
||||
{
|
||||
return Err(AdminError::invalid("排班查询页码、每页数量或时间无效"));
|
||||
}
|
||||
validate_targets(&self.targets)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(tag = "kind", rename_all = "camelCase")]
|
||||
pub enum ScheduleItem {
|
||||
Account {
|
||||
#[serde(flatten)]
|
||||
account: ScheduleAccount,
|
||||
shifts: Option<Vec<DailyShift>>,
|
||||
},
|
||||
Group {
|
||||
#[serde(flatten)]
|
||||
group: ScheduleGroup,
|
||||
shifts: Option<Vec<DailyShift>>,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct ScheduleBand {
|
||||
pub start: u16,
|
||||
pub end: u16,
|
||||
pub count: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ScheduleSummary {
|
||||
pub target_count: u64,
|
||||
pub pool_count: u64,
|
||||
pub available: u64,
|
||||
pub off_duty: Option<String>,
|
||||
pub visible: u64,
|
||||
pub current: u64,
|
||||
pub bands: Vec<ScheduleBand>,
|
||||
pub editing: ScheduleEditingBasis,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ScheduleEditingBasis {
|
||||
pub bands: Vec<ScheduleBand>,
|
||||
pub available: u64,
|
||||
pub off_duty: Option<String>,
|
||||
pub cohorts: Vec<ScheduleCohort>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct ScheduleCohort {
|
||||
pub targets: Vec<String>,
|
||||
pub fixed: Vec<(u16, u16)>,
|
||||
pub count: u64,
|
||||
pub example: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct ScheduleList {
|
||||
pub revision: u64,
|
||||
pub policy: SchedulePolicy,
|
||||
pub items: Vec<ScheduleItem>,
|
||||
pub total: i64,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub groups: Option<Vec<ScheduleGroup>>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub summary: Option<ScheduleSummary>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct ScheduleQueryResult {
|
||||
#[serde(flatten)]
|
||||
pub page: ScheduleList,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub clock: Option<ScheduleClock>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ScheduleClock {
|
||||
pub valid_for_millis: i64,
|
||||
pub unix_millis: i64,
|
||||
pub minute: u16,
|
||||
}
|
||||
|
||||
impl ScheduleClock {
|
||||
#[must_use]
|
||||
pub fn at(now: DateTime<Utc>, timezone: DeploymentTimeZone) -> Self {
|
||||
let offset = |minutes| {
|
||||
timezone
|
||||
.local(now + TimeDelta::minutes(minutes))
|
||||
.offset()
|
||||
.fix()
|
||||
};
|
||||
let current = offset(0);
|
||||
let mut end = 24 * 60;
|
||||
// 同一偏移下可用经过的分钟推进本地时钟;遇到夏令时跳变就在边界重新采样
|
||||
if offset(end) != current {
|
||||
let mut start = 0;
|
||||
while end - start > 1 {
|
||||
let mid = (start + end) / 2;
|
||||
if offset(mid) == current {
|
||||
start = mid;
|
||||
} else {
|
||||
end = mid;
|
||||
}
|
||||
}
|
||||
}
|
||||
let unix_millis = now.timestamp_millis();
|
||||
Self {
|
||||
valid_for_millis: end * 60_000 - unix_millis.rem_euclid(60_000),
|
||||
unix_millis,
|
||||
minute: timezone.minute_of_day(now),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
@@ -13,6 +13,7 @@ pub enum MutationAuditOperation {
|
||||
AdminApiKeyChanged { exists: bool },
|
||||
AccountGroupCreate,
|
||||
AccountGroupUpdate,
|
||||
AccountScheduleUpdate,
|
||||
AccountGroupEnabled { enabled: bool },
|
||||
AccountGroupDelete,
|
||||
ClientApiKeyResetBudget,
|
||||
@@ -73,6 +74,7 @@ impl MutationAuditOperation {
|
||||
"runtime_settings",
|
||||
),
|
||||
Self::AccountGroupCreate => ("create", "account_group"),
|
||||
Self::AccountScheduleUpdate => ("update", "account_schedule"),
|
||||
Self::AccountGroupUpdate => ("update", "account_group"),
|
||||
Self::AccountGroupEnabled { enabled } => {
|
||||
(if enabled { "enable" } else { "disable" }, "account_group")
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
use std::num::{NonZeroU16, NonZeroU64};
|
||||
|
||||
pub mod account_groups;
|
||||
pub mod account_schedules;
|
||||
pub mod accounts;
|
||||
pub mod analytics;
|
||||
pub mod audit;
|
||||
|
||||
@@ -78,6 +78,8 @@ impl fmt::Debug for ImportCredentials {
|
||||
/// 批量导入提交结果
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct CredentialImportResult {
|
||||
/// 本次事务首次创建的账号,同身份重新导入沿用已有账号
|
||||
pub created_ids: std::collections::BTreeSet<ProviderAccountId>,
|
||||
pub config_revision: Revision,
|
||||
pub credential_ids: Vec<ProviderAccountId>,
|
||||
}
|
||||
@@ -540,10 +542,18 @@ impl fmt::Debug for AuthorizationReceiptKey {
|
||||
}
|
||||
}
|
||||
|
||||
/// 凭据事务对账号的实际影响,同身份授权可以更新既有账号
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum CredentialChange {
|
||||
Created,
|
||||
Updated,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct AuthorizationCommitResult {
|
||||
pub result: CredentialMutationResult,
|
||||
pub newly_committed: bool,
|
||||
/// 重放已提交回执时没有新的账号变更
|
||||
pub change: Option<CredentialChange>,
|
||||
}
|
||||
|
||||
/// OAuth 准备结果拆解后的 Store 命令与两个结算 guard
|
||||
@@ -698,7 +708,9 @@ pub struct PreparedCredentialRotationFacts {
|
||||
pub plan_type: Option<String>,
|
||||
/// Token 刷新保留提交时的资料,不以准备阶段的副本覆盖新套餐
|
||||
pub preserve_profile: bool,
|
||||
/// 连接配置变更保留当前凭据健康状态与错误事实
|
||||
/// 已核实同一身份续期时,允许把匹配此标识的目录续接至新凭据版本
|
||||
pub preserve_catalog_etag: Option<String>,
|
||||
/// 凭据或连接配置更新保留提交时的健康状态与错误事实
|
||||
pub preserve_credential_state: bool,
|
||||
pub preserve_access_token_expiry: bool,
|
||||
pub provider_material: ProviderDocument,
|
||||
@@ -722,13 +734,19 @@ impl PreparedCredentialRotation {
|
||||
Self { facts, guard }
|
||||
}
|
||||
|
||||
/// 仅修改连接配置时,不把配置更新视为凭据恢复成功
|
||||
/// 更新本身不能证明账号已恢复时,保留提交时的状态
|
||||
#[must_use]
|
||||
pub fn preserving_credential_state(mut self) -> Self {
|
||||
self.facts.preserve_credential_state = true;
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn preserving_catalog(mut self, etag: String) -> Self {
|
||||
self.facts.preserve_catalog_etag = Some(etag);
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn facts(&self) -> &PreparedCredentialRotationFacts {
|
||||
&self.facts
|
||||
@@ -890,6 +908,8 @@ pub struct ProviderQuotaReadRequest<'a> {
|
||||
/// Provider 已解析的 quota 结果及其不透明差异字段
|
||||
#[derive(Debug, Default, Clone, PartialEq)]
|
||||
pub struct ProviderQuota {
|
||||
/// 与 Provider 选号使用同一日额度观测,仅在其有效期内提供
|
||||
pub daily_used_percent: Option<u8>,
|
||||
pub paused_windows: Vec<String>,
|
||||
pub upstream: Option<super::upstream_info::ProviderUpstreamInfo>,
|
||||
/// 上游额度响应明确提供的套餐,可用于补全账号展示
|
||||
@@ -1319,6 +1339,8 @@ impl fmt::Debug for ProviderExport {
|
||||
/// 统一账号目录的一行完整结果
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct AccountDirectoryItem {
|
||||
pub schedule_duty: Option<gateway_core::account::duty::ScheduleDuty>,
|
||||
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,
|
||||
|
||||
@@ -45,6 +45,7 @@ pub use gateway_core::account::RotationStrategy;
|
||||
/// 运行设置的共同值;版本、Provider 画像更新和数据库秘密由外层类型拥有
|
||||
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct RuntimeSettingsValues {
|
||||
pub antigravity_background_refresh: bool,
|
||||
pub openai_websocket_pool: gateway_core::settings::OpenAiWebSocketPoolSettings,
|
||||
pub openai_request_settings: gateway_core::settings::OpenAiRequestSettings,
|
||||
pub codex_privacy_policy: gateway_core::settings::privacy::CodexPrivacyPolicy,
|
||||
|
||||
@@ -50,6 +50,8 @@ pub struct SystemUpdatePolicy {
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct SystemVersion {
|
||||
pub version: String,
|
||||
pub instance_id: String,
|
||||
pub restart_supported: bool,
|
||||
pub git_sha: String,
|
||||
pub build_time: String,
|
||||
pub deployment_mode: String,
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
//! 账号排班的事务存储边界
|
||||
|
||||
use super::store::AdminStoreResult;
|
||||
use crate::model::{
|
||||
MutationContext, Revision,
|
||||
account_schedules::{ScheduleChange, ScheduleList, ScheduleQuery},
|
||||
};
|
||||
use async_trait::async_trait;
|
||||
|
||||
#[async_trait]
|
||||
pub trait AccountScheduleStore: Send + Sync {
|
||||
async fn query(&self, query: &ScheduleQuery) -> AdminStoreResult<ScheduleList>;
|
||||
async fn save(
|
||||
&self,
|
||||
change: ScheduleChange,
|
||||
context: &MutationContext,
|
||||
) -> AdminStoreResult<Revision>;
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
//! 管理用例依赖的外部能力端口
|
||||
|
||||
pub mod account_schedules;
|
||||
pub mod backup;
|
||||
pub mod client_distribution;
|
||||
pub mod peer;
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
//! 原生 Provider 管理能力与启动时注册表
|
||||
|
||||
use std::{collections::BTreeMap, sync::Arc};
|
||||
use std::{
|
||||
collections::{BTreeMap, BTreeSet},
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
use async_trait::async_trait;
|
||||
use gateway_core::{
|
||||
@@ -145,6 +148,24 @@ struct ProviderAdminDiagnostic {
|
||||
source: Option<gateway_core::error::ErrorSource>,
|
||||
}
|
||||
|
||||
/// 区分新账号首查与既有账号变更后的后台观察
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct AccountFactsChange<'a> {
|
||||
pub ids: &'a [ProviderAccountId],
|
||||
pub created_ids: &'a BTreeSet<ProviderAccountId>,
|
||||
}
|
||||
|
||||
impl<'a> AccountFactsChange<'a> {
|
||||
#[must_use]
|
||||
pub const fn updated(ids: &'a [ProviderAccountId]) -> Self {
|
||||
static EMPTY: BTreeSet<ProviderAccountId> = BTreeSet::new();
|
||||
Self {
|
||||
ids,
|
||||
created_ids: &EMPTY,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 一个具体 Provider 对管理控制面提供的解析、验证、上游交互与运行时资源回收能力
|
||||
///
|
||||
/// 数据变更由 Provider 返回 prepared facts;config revision、审计与 PostgreSQL 事务
|
||||
@@ -297,7 +318,12 @@ pub trait ProviderAdmin: Send + Sync {
|
||||
/// 该通知发生在 Store 事务成功之后、下一份 RuntimeSnapshot 编译之前;通知
|
||||
/// 不参与已提交事务成败
|
||||
/// 没有账号派生状态的 Provider 可使用默认空实现
|
||||
async fn account_facts_changed(&self, _account_ids: &[ProviderAccountId]) {}
|
||||
async fn account_facts_changed(&self, _change: AccountFactsChange<'_>) {}
|
||||
|
||||
/// 既有账号变更后是否主动查额,手动刷新与新账号首查独立执行
|
||||
async fn background_quota_refresh_enabled(&self) -> Result<bool, ProviderAdminError> {
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// 生成一次连接测试所需的 Provider-owned operation;Core 负责实际执行与落账
|
||||
async fn connection_test_operation(
|
||||
|
||||
@@ -655,6 +655,7 @@ pub struct AdminAccountStorePorts {
|
||||
accounts: Arc<dyn AccountStore>,
|
||||
runtime: Arc<dyn AccountRuntimeStore>,
|
||||
groups: Arc<dyn AccountGroupStore>,
|
||||
schedules: Arc<dyn super::account_schedules::AccountScheduleStore>,
|
||||
proxies: Arc<dyn super::proxy::ProxyStore>,
|
||||
}
|
||||
|
||||
@@ -664,12 +665,14 @@ impl AdminAccountStorePorts {
|
||||
accounts: Arc<dyn AccountStore>,
|
||||
runtime: Arc<dyn AccountRuntimeStore>,
|
||||
groups: Arc<dyn AccountGroupStore>,
|
||||
schedules: Arc<dyn super::account_schedules::AccountScheduleStore>,
|
||||
proxies: Arc<dyn super::proxy::ProxyStore>,
|
||||
) -> Self {
|
||||
Self {
|
||||
accounts,
|
||||
runtime,
|
||||
groups,
|
||||
schedules,
|
||||
proxies,
|
||||
}
|
||||
}
|
||||
@@ -755,6 +758,11 @@ impl AdminStorePorts {
|
||||
self.accounts.runtime.clone()
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn account_schedules(&self) -> Arc<dyn super::account_schedules::AccountScheduleStore> {
|
||||
self.accounts.schedules.clone()
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn account_groups(&self) -> Arc<dyn AccountGroupStore> {
|
||||
self.accounts.groups.clone()
|
||||
|
||||
@@ -55,37 +55,44 @@ impl ScheduledTask for ResetCreditAutomationTask {
|
||||
context: WorkerCycleContext,
|
||||
) -> futures::future::BoxFuture<'_, Result<(), WorkerTaskError>> {
|
||||
Box::pin(async move {
|
||||
let settings = self
|
||||
.settings
|
||||
.load_runtime_settings()
|
||||
context
|
||||
.cancellation()
|
||||
.run_until_cancelled(self.run_due())
|
||||
.await
|
||||
.map_err(|_| WorkerTaskError::safe("重置卡设置读取失败"))?;
|
||||
// 单轮有界,积压沿到期顺序继续;并发复用已有账号刷新配置
|
||||
let due = self
|
||||
.store
|
||||
.due_reset_credit_automations(Utc::now(), 100)
|
||||
.await
|
||||
.map_err(|_| WorkerTaskError::safe("重置卡计划读取失败"))?;
|
||||
let work = futures::stream::iter(due)
|
||||
.map(|account_id| async move {
|
||||
let id = ProviderAccountId::new(account_id.clone())
|
||||
.map_err(|_| WorkerTaskError::safe("重置卡账号 ID 不合法"))?;
|
||||
if let Err(error) = self.accounts.reconcile_reset_credit_automation(id).await {
|
||||
tracing::warn!(
|
||||
account_id,
|
||||
error_kind = error.kind().as_str(),
|
||||
"自动重置卡任务失败"
|
||||
);
|
||||
}
|
||||
Ok::<_, WorkerTaskError>(())
|
||||
})
|
||||
.buffer_unordered(settings.values.refresh_concurrency.max(1) as usize)
|
||||
.collect::<Vec<_>>();
|
||||
tokio::select! {
|
||||
() = context.cancellation().cancelled() => {},
|
||||
_ = tokio::time::timeout(Duration::from_secs(30), work) => {},
|
||||
}
|
||||
Ok(())
|
||||
.unwrap_or(Ok(()))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl ResetCreditAutomationTask {
|
||||
async fn run_due(&self) -> Result<(), WorkerTaskError> {
|
||||
let settings = self
|
||||
.settings
|
||||
.load_runtime_settings()
|
||||
.await
|
||||
.map_err(|_| WorkerTaskError::safe("重置卡设置读取失败"))?;
|
||||
// 单轮有界,积压沿到期顺序继续;并发复用已有账号刷新配置
|
||||
let due = self
|
||||
.store
|
||||
.due_reset_credit_automations(Utc::now(), 100)
|
||||
.await
|
||||
.map_err(|_| WorkerTaskError::safe("重置卡计划读取失败"))?;
|
||||
let work = futures::stream::iter(due)
|
||||
.map(|account_id| async move {
|
||||
let id = ProviderAccountId::new(account_id.clone())
|
||||
.map_err(|_| WorkerTaskError::safe("重置卡账号 ID 不合法"))?;
|
||||
if let Err(error) = self.accounts.reconcile_reset_credit_automation(id).await {
|
||||
tracing::warn!(
|
||||
account_id,
|
||||
error_kind = error.kind().as_str(),
|
||||
"自动重置卡任务失败"
|
||||
);
|
||||
}
|
||||
Ok::<_, WorkerTaskError>(())
|
||||
})
|
||||
.buffer_unordered(settings.values.refresh_concurrency.max(1) as usize)
|
||||
.collect::<Vec<_>>();
|
||||
let _ = tokio::time::timeout(Duration::from_secs(30), work).await;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
//! 批量排班校验与已提交配置的发布
|
||||
|
||||
use super::{map_store_error, publish_committed};
|
||||
use crate::{
|
||||
model::{
|
||||
AdminError, MutationContext,
|
||||
account_schedules::{
|
||||
ScheduleAccount, ScheduleChange, ScheduleClock, ScheduleItem, ScheduleQuery,
|
||||
ScheduleQueryResult,
|
||||
},
|
||||
provider_credentials::ProviderQuotaRequest,
|
||||
},
|
||||
ports::{account_schedules::AccountScheduleStore, provider::ProviderAdminRegistry},
|
||||
};
|
||||
use futures::{StreamExt, stream};
|
||||
use gateway_core::{account::ProviderAccountId, routing::ProviderKind, runtime::SnapshotControl};
|
||||
use std::sync::Arc;
|
||||
|
||||
pub struct AccountScheduleService {
|
||||
pub(crate) timezone: gateway_core::time::DeploymentTimeZone,
|
||||
pub(crate) providers: ProviderAdminRegistry,
|
||||
pub(crate) store: Arc<dyn AccountScheduleStore>,
|
||||
pub(crate) snapshot: Arc<dyn SnapshotControl>,
|
||||
}
|
||||
|
||||
impl AccountScheduleService {
|
||||
pub async fn query(&self, mut query: ScheduleQuery) -> Result<ScheduleQueryResult, AdminError> {
|
||||
query.validate()?;
|
||||
let clock = query.include_summary.then(|| {
|
||||
let clock = ScheduleClock::at(chrono::Utc::now(), self.timezone);
|
||||
query.summary_minute.get_or_insert(clock.minute);
|
||||
clock
|
||||
});
|
||||
let mut page = self
|
||||
.store
|
||||
.query(&query)
|
||||
.await
|
||||
.map_err(|e| map_store_error(e, "账号排班"))?;
|
||||
stream::iter(page.items.iter_mut().filter_map(|item| match item {
|
||||
ScheduleItem::Account { account, .. } => Some(account),
|
||||
ScheduleItem::Group { .. } => None,
|
||||
}))
|
||||
.for_each_concurrent(8, |account| self.fill_plan(account))
|
||||
.await;
|
||||
Ok(ScheduleQueryResult { page, clock })
|
||||
}
|
||||
|
||||
async fn fill_plan(&self, account: &mut ScheduleAccount) {
|
||||
account.plan_type_display = self
|
||||
.providers
|
||||
.plan_type_display(&account.provider_kind, account.plan_type.as_deref());
|
||||
// 有些套餐名来自上游额度观测,只在目录缺少展示名时读取已保存的快照
|
||||
if account.plan_type_display.is_some()
|
||||
|| !account.has_cached_quota
|
||||
|| account.authentication_kind == "api_key"
|
||||
{
|
||||
return;
|
||||
}
|
||||
let (Ok(kind), Ok(account_id)) = (
|
||||
ProviderKind::new(account.provider_kind.clone()),
|
||||
ProviderAccountId::new(account.id.clone()),
|
||||
) else {
|
||||
return;
|
||||
};
|
||||
let Ok(provider) = self.providers.require(&kind) else {
|
||||
return;
|
||||
};
|
||||
if let Ok(quota) = provider
|
||||
.quota(ProviderQuotaRequest {
|
||||
account_id,
|
||||
refresh: false,
|
||||
rolling_usage: None,
|
||||
})
|
||||
.await
|
||||
{
|
||||
account.plan_type_display = self.providers.resolve_account_plan(
|
||||
&account.provider_kind,
|
||||
&mut account.plan_type,
|
||||
Some("a),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn save(
|
||||
&self,
|
||||
change: ScheduleChange,
|
||||
context: &MutationContext,
|
||||
) -> Result<u64, AdminError> {
|
||||
change.validate()?;
|
||||
let revision = self
|
||||
.store
|
||||
.save(change, context)
|
||||
.await
|
||||
.map_err(|e| map_store_error(e, "账号排班"))?;
|
||||
publish_committed(self.snapshot.as_ref(), revision).await?;
|
||||
Ok(revision.get())
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
mod reset_credit_automation;
|
||||
|
||||
use crate::ports::provider::AccountFactsChange;
|
||||
use std::{
|
||||
collections::{BTreeMap, BTreeSet},
|
||||
sync::Arc,
|
||||
@@ -197,6 +198,7 @@ pub(crate) struct DefaultAccountsService {
|
||||
settings: Arc<dyn crate::ports::store::SettingsStore>,
|
||||
timezone: gateway_core::time::DeploymentTimeZone,
|
||||
providers: ProviderAdminRegistry,
|
||||
published: gateway_core::runtime::RuntimeSnapshotHandle,
|
||||
snapshot: Arc<dyn SnapshotControl>,
|
||||
probe: Arc<dyn AccountProbe>,
|
||||
upstream_info: Option<Arc<dyn crate::ports::peer::PeerUpstreamService>>,
|
||||
@@ -216,6 +218,7 @@ impl DefaultAccountsService {
|
||||
settings: Arc<dyn crate::ports::store::SettingsStore>,
|
||||
timezone: gateway_core::time::DeploymentTimeZone,
|
||||
providers: ProviderAdminRegistry,
|
||||
published: gateway_core::runtime::RuntimeSnapshotHandle,
|
||||
snapshot: Arc<dyn SnapshotControl>,
|
||||
probe: Arc<dyn AccountProbe>,
|
||||
upstream_info: Option<Arc<dyn crate::ports::peer::PeerUpstreamService>>,
|
||||
@@ -226,6 +229,7 @@ impl DefaultAccountsService {
|
||||
settings,
|
||||
timezone,
|
||||
providers,
|
||||
published,
|
||||
snapshot,
|
||||
probe,
|
||||
upstream_info,
|
||||
@@ -513,6 +517,17 @@ impl DefaultAccountsService {
|
||||
lookback,
|
||||
);
|
||||
Ok(AccountDirectoryItem {
|
||||
schedule_duty: self
|
||||
.published
|
||||
.snapshot_for_diagnostics()
|
||||
.and_then(|snapshot| {
|
||||
snapshot.account_schedule_duty(
|
||||
account_id,
|
||||
std::time::SystemTime::now(),
|
||||
quota.daily_used_percent,
|
||||
)
|
||||
}),
|
||||
model_cooldowns: stored.model_cooldowns,
|
||||
platform_icon: stored.platform_icon,
|
||||
protection_rules: stored.protection_rules,
|
||||
capacity: super::peer_link::upstream::account_capacity(
|
||||
@@ -624,6 +639,7 @@ impl AccountsService for DefaultAccountsService {
|
||||
self.attach_quota_local_usage(&page.items, &mut quotas)
|
||||
.await?;
|
||||
let mut api_key_usage = self.load_api_key_usage(&page.items, "as).await?;
|
||||
let published = self.published.snapshot_for_diagnostics();
|
||||
let items = page
|
||||
.items
|
||||
.into_iter()
|
||||
@@ -648,6 +664,10 @@ impl AccountsService for DefaultAccountsService {
|
||||
lookback,
|
||||
);
|
||||
Ok(AccountDirectoryItem {
|
||||
schedule_duty: published.as_ref().and_then(|snapshot| {
|
||||
snapshot.account_schedule_duty(&id, now.into(), quota.daily_used_percent)
|
||||
}),
|
||||
model_cooldowns: item.model_cooldowns,
|
||||
platform_icon: item.platform_icon,
|
||||
protection_rules: item.protection_rules,
|
||||
capacity: crate::model::accounts::AccountCapacity {
|
||||
@@ -757,7 +777,7 @@ impl AccountsService for DefaultAccountsService {
|
||||
super::notify_account_facts_changed(
|
||||
self.upstream_info.as_deref(),
|
||||
provider.as_ref(),
|
||||
std::slice::from_ref(&result.account_id),
|
||||
AccountFactsChange::updated(std::slice::from_ref(&result.account_id)),
|
||||
)
|
||||
.await;
|
||||
publish_committed(self.snapshot.as_ref(), result.config_revision).await?;
|
||||
@@ -805,7 +825,7 @@ impl AccountsService for DefaultAccountsService {
|
||||
super::notify_account_facts_changed(
|
||||
self.upstream_info.as_deref(),
|
||||
provider.as_ref(),
|
||||
std::slice::from_ref(&account_id),
|
||||
AccountFactsChange::updated(std::slice::from_ref(&account_id)),
|
||||
)
|
||||
.await;
|
||||
publish_committed(self.snapshot.as_ref(), config_revision).await?;
|
||||
@@ -841,7 +861,7 @@ impl AccountsService for DefaultAccountsService {
|
||||
super::notify_account_facts_changed(
|
||||
self.upstream_info.as_deref(),
|
||||
provider.as_ref(),
|
||||
std::slice::from_ref(&account_id),
|
||||
AccountFactsChange::updated(std::slice::from_ref(&account_id)),
|
||||
)
|
||||
.await;
|
||||
publish_committed(self.snapshot.as_ref(), result.config_revision).await?;
|
||||
@@ -959,7 +979,7 @@ impl AccountsService for DefaultAccountsService {
|
||||
super::notify_account_facts_changed(
|
||||
self.upstream_info.as_deref(),
|
||||
provider.as_ref(),
|
||||
provider_ids,
|
||||
AccountFactsChange::updated(provider_ids),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
@@ -972,7 +992,7 @@ impl AccountsService for DefaultAccountsService {
|
||||
self.upstream_info.as_ref(),
|
||||
&provider,
|
||||
&self.accounts,
|
||||
&exhausted,
|
||||
AccountFactsChange::updated(&exhausted),
|
||||
context.request_id.as_str(),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -12,7 +12,10 @@ use crate::{
|
||||
ProviderQuotaRequest, StartAuthorization,
|
||||
},
|
||||
},
|
||||
ports::{provider::ProviderAdmin, store::AccountStore},
|
||||
ports::{
|
||||
provider::{AccountFactsChange, ProviderAdmin},
|
||||
store::AccountStore,
|
||||
},
|
||||
};
|
||||
use gateway_core::{account::ProviderAccountId, routing::ProviderKind, runtime::SnapshotControl};
|
||||
|
||||
@@ -24,13 +27,13 @@ pub(super) async fn publish_credentials_and_observe_quota(
|
||||
accounts: &std::sync::Arc<dyn AccountStore>,
|
||||
snapshot: &dyn SnapshotControl,
|
||||
revision: crate::model::Revision,
|
||||
account_ids: &[ProviderAccountId],
|
||||
change: AccountFactsChange<'_>,
|
||||
request_id: &str,
|
||||
) -> Result<(), AdminError> {
|
||||
notify_account_facts_changed(peer.map(AsRef::as_ref), provider.as_ref(), account_ids).await;
|
||||
notify_account_facts_changed(peer.map(AsRef::as_ref), provider.as_ref(), change).await;
|
||||
publish_committed(snapshot, revision).await?;
|
||||
|
||||
observe_account_quotas(peer, provider, accounts, account_ids, request_id);
|
||||
observe_account_quotas(peer, provider, accounts, change, request_id);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -38,16 +41,32 @@ pub(super) fn observe_account_quotas(
|
||||
peer: Option<&std::sync::Arc<dyn crate::ports::peer::PeerUpstreamService>>,
|
||||
provider: &std::sync::Arc<dyn ProviderAdmin>,
|
||||
accounts: &std::sync::Arc<dyn AccountStore>,
|
||||
account_ids: &[ProviderAccountId],
|
||||
change: AccountFactsChange<'_>,
|
||||
request_id: &str,
|
||||
) {
|
||||
// 配置已提交,额度查询失败不回滚配置
|
||||
let provider = provider.clone();
|
||||
let peer = peer.cloned();
|
||||
let accounts = accounts.clone();
|
||||
let account_ids = account_ids.to_vec();
|
||||
let mut seen = std::collections::BTreeSet::new();
|
||||
let (initial, updated): (Vec<_>, Vec<_>) = change
|
||||
.ids
|
||||
.iter()
|
||||
.filter(|id| seen.insert(*id))
|
||||
.cloned()
|
||||
.partition(|id| change.created_ids.contains(id));
|
||||
let request_id = request_id.to_owned();
|
||||
tokio::spawn(async move {
|
||||
let mut account_ids = initial;
|
||||
if !updated.is_empty() {
|
||||
match provider.background_quota_refresh_enabled().await {
|
||||
Ok(true) => account_ids.extend(updated),
|
||||
Ok(false) => {}
|
||||
Err(error) => {
|
||||
tracing::warn!(request_id, error = %error, "读取后台额度查询设置失败")
|
||||
}
|
||||
}
|
||||
}
|
||||
for account_id in account_ids {
|
||||
let request = ProviderQuotaRequest {
|
||||
account_id: account_id.clone(),
|
||||
@@ -292,7 +311,7 @@ pub(super) async fn commit_authorization(
|
||||
match accounts.commit_authorization(command, context).await {
|
||||
Ok(result) => {
|
||||
if let Some(guard) = credential_guard
|
||||
&& result.newly_committed
|
||||
&& result.change.is_some()
|
||||
{
|
||||
guard.finish();
|
||||
}
|
||||
@@ -405,7 +424,7 @@ pub(super) async fn delete_credentials(
|
||||
for account_id in &account_ids {
|
||||
notify_account_unavailable(peer, provider, account_id).await;
|
||||
}
|
||||
notify_account_facts_changed(peer, provider, &account_ids).await;
|
||||
notify_account_facts_changed(peer, provider, AccountFactsChange::updated(&account_ids)).await;
|
||||
Ok(CredentialDeletionResult {
|
||||
config_revision: revision,
|
||||
account_ids,
|
||||
@@ -415,11 +434,11 @@ pub(super) async fn delete_credentials(
|
||||
pub(super) async fn notify_account_facts_changed(
|
||||
peer: Option<&dyn crate::ports::peer::PeerUpstreamService>,
|
||||
provider: &dyn ProviderAdmin,
|
||||
ids: &[ProviderAccountId],
|
||||
change: AccountFactsChange<'_>,
|
||||
) {
|
||||
provider.account_facts_changed(ids).await;
|
||||
provider.account_facts_changed(change).await;
|
||||
if let Some(peer) = peer {
|
||||
for id in ids {
|
||||
for id in change.ids {
|
||||
if let Err(error) = peer.account_changed(id).await {
|
||||
tracing::warn!(account_id = %id, error = %error, "upstream information cache invalidation failed");
|
||||
}
|
||||
|
||||
@@ -9,13 +9,16 @@ use crate::{
|
||||
AdminError,
|
||||
provider_credentials::{
|
||||
AuthorizationCommitResult, AuthorizationReceiptKey, AuthorizationStarted,
|
||||
CompleteAuthorization, CredentialDeletion, CredentialDeletionResult,
|
||||
CompleteAuthorization, CredentialChange, CredentialDeletion, CredentialDeletionResult,
|
||||
CredentialImportCommit, CredentialImportResult, CredentialMutationResult,
|
||||
ImportCredentials, PrepareCredentialImport, PrepareCredentialRotation,
|
||||
RotateCredential, StartAuthorization,
|
||||
},
|
||||
},
|
||||
ports::{provider::ProviderAdmin, store::AccountStore},
|
||||
ports::{
|
||||
provider::{AccountFactsChange, ProviderAdmin},
|
||||
store::AccountStore,
|
||||
},
|
||||
};
|
||||
|
||||
use super::super::{
|
||||
@@ -97,7 +100,10 @@ impl ProviderCredentials {
|
||||
&self.accounts,
|
||||
self.snapshot.as_ref(),
|
||||
result.config_revision,
|
||||
&result.credential_ids,
|
||||
AccountFactsChange {
|
||||
ids: &result.credential_ids,
|
||||
created_ids: &result.created_ids,
|
||||
},
|
||||
&context.request_id,
|
||||
)
|
||||
.await?;
|
||||
@@ -175,7 +181,7 @@ impl ProviderCredentials {
|
||||
super::super::notify_account_facts_changed(
|
||||
self.upstream_info.as_deref(),
|
||||
self.provider.as_ref(),
|
||||
std::slice::from_ref(&result.account_id),
|
||||
AccountFactsChange::updated(std::slice::from_ref(&result.account_id)),
|
||||
)
|
||||
.await;
|
||||
publish_committed(self.snapshot.as_ref(), result.config_revision).await?;
|
||||
@@ -248,14 +254,23 @@ impl super::CredentialsService {
|
||||
request_id: &str,
|
||||
) -> Result<CredentialMutationResult, AdminError> {
|
||||
let result = outcome.result;
|
||||
if outcome.newly_committed {
|
||||
if let Some(change) = outcome.change {
|
||||
let ids = std::slice::from_ref(&result.account_id);
|
||||
let created_ids = (change == CredentialChange::Created)
|
||||
.then(|| result.account_id.clone())
|
||||
.into_iter()
|
||||
.collect();
|
||||
let change = AccountFactsChange {
|
||||
ids,
|
||||
created_ids: &created_ids,
|
||||
};
|
||||
publish_credentials_and_observe_quota(
|
||||
self.upstream_info.as_ref(),
|
||||
provider,
|
||||
&self.accounts,
|
||||
self.snapshot.as_ref(),
|
||||
result.config_revision,
|
||||
std::slice::from_ref(&result.account_id),
|
||||
change,
|
||||
request_id,
|
||||
)
|
||||
.await?;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! 管理控制面的用例实现
|
||||
|
||||
pub mod account_groups;
|
||||
pub mod account_schedules;
|
||||
pub mod accounts;
|
||||
pub mod auth;
|
||||
pub mod backup;
|
||||
|
||||
@@ -320,6 +320,13 @@ fn model_observation(
|
||||
reset.min(observed_at + TimeDelta::minutes(30))
|
||||
})
|
||||
.min(now + TimeDelta::minutes(5));
|
||||
let expires_at = if let Some(deadline) = account.quota.exhaustion_deadline()
|
||||
&& account.quota.is_exhausted()
|
||||
{
|
||||
expires_at.min(deadline.into())
|
||||
} else {
|
||||
expires_at
|
||||
};
|
||||
if observed_at > now || expires_at <= now {
|
||||
return None;
|
||||
}
|
||||
|
||||
@@ -214,6 +214,7 @@ impl PeerInfoService {
|
||||
}
|
||||
}
|
||||
ProviderQuota {
|
||||
daily_used_percent: None,
|
||||
paused_windows: Vec::new(),
|
||||
upstream: Some(info),
|
||||
plan_type: None,
|
||||
|
||||
@@ -172,6 +172,7 @@ impl PeerInfoService {
|
||||
.and_then(|peer| quota::observe(&peer, started_at, now))
|
||||
.unwrap_or(QuotaState::unknown());
|
||||
let observation = QuotaObservation {
|
||||
merge_base: None,
|
||||
quota_pause: None,
|
||||
expected_connection: Some(connection.clone()),
|
||||
account_id: id.clone(),
|
||||
|
||||
@@ -19,6 +19,8 @@ use crate::{
|
||||
},
|
||||
};
|
||||
|
||||
use crate::ports::provider::AccountFactsChange;
|
||||
|
||||
use super::{
|
||||
map_provider_error, map_store_error, publish_credentials_and_observe_quota,
|
||||
required_credential, required_plugin_credential, validate_prepared_import,
|
||||
@@ -218,7 +220,10 @@ impl PluginAccountAccess for DefaultPluginAccountAccess {
|
||||
&self.accounts,
|
||||
self.snapshot.as_ref(),
|
||||
result.config_revision,
|
||||
std::slice::from_ref(&account_id),
|
||||
AccountFactsChange {
|
||||
ids: &result.credential_ids,
|
||||
created_ids: &result.created_ids,
|
||||
},
|
||||
&context.request_id,
|
||||
)
|
||||
.await?;
|
||||
@@ -263,7 +268,7 @@ impl PluginAccountAccess for DefaultPluginAccountAccess {
|
||||
&self.accounts,
|
||||
self.snapshot.as_ref(),
|
||||
result.config_revision,
|
||||
std::slice::from_ref(&result.account_id),
|
||||
AccountFactsChange::updated(std::slice::from_ref(&result.account_id)),
|
||||
&context.request_id,
|
||||
)
|
||||
.await?;
|
||||
|
||||
@@ -106,6 +106,7 @@ fn provider_document_debug_should_not_expose_opaque_material() {
|
||||
#[test]
|
||||
fn representative_quota_should_prefer_short_window_and_highest_usage() {
|
||||
let quota = ProviderQuota {
|
||||
daily_used_percent: None,
|
||||
paused_windows: Vec::new(),
|
||||
upstream: None,
|
||||
credits: None,
|
||||
@@ -131,6 +132,7 @@ fn representative_quota_should_prefer_account_wide_window_over_model_specific_wi
|
||||
let mut model_specific = quota_window("shortTerm", Some(18_000), Some(64.0));
|
||||
model_specific.local_usage_attribution = QuotaLocalUsageAttribution::Unavailable;
|
||||
let quota = ProviderQuota {
|
||||
daily_used_percent: None,
|
||||
paused_windows: Vec::new(),
|
||||
upstream: None,
|
||||
credits: None,
|
||||
@@ -152,6 +154,7 @@ fn representative_quota_should_prefer_account_wide_window_over_model_specific_wi
|
||||
#[test]
|
||||
fn account_exhaustion_preserves_measured_and_unknown_window_usage() {
|
||||
let mut quota = ProviderQuota {
|
||||
daily_used_percent: None,
|
||||
paused_windows: Vec::new(),
|
||||
upstream: None,
|
||||
credits: None,
|
||||
@@ -183,6 +186,7 @@ fn exhausted_quota_should_preserve_the_provider_identified_reached_window() {
|
||||
let mut reached = quota_window("monthly", Some(2_592_000), Some(98.0));
|
||||
reached.limit_reached = true;
|
||||
let mut quota = ProviderQuota {
|
||||
daily_used_percent: None,
|
||||
paused_windows: Vec::new(),
|
||||
upstream: None,
|
||||
credits: None,
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
//! 排班分钟采样在部署时区的跳时和重复时刻重新对齐
|
||||
|
||||
use chrono::{DateTime, TimeDelta, Utc};
|
||||
use gateway_admin::model::account_schedules::ScheduleClock;
|
||||
|
||||
#[test]
|
||||
fn clock_expires_at_both_dst_boundaries() {
|
||||
let zone = "America/New_York".parse().unwrap();
|
||||
for (sample, before, after) in [
|
||||
("2026-03-08T06:59:44.500Z", 119, 180),
|
||||
("2026-11-01T05:59:44.500Z", 119, 60),
|
||||
] {
|
||||
let at: DateTime<Utc> = sample.parse().unwrap();
|
||||
let clock = ScheduleClock::at(at, zone);
|
||||
assert_eq!(clock.minute, before);
|
||||
assert_eq!(clock.valid_for_millis, 15_500);
|
||||
let next = ScheduleClock::at(at + TimeDelta::milliseconds(clock.valid_for_millis), zone);
|
||||
assert_eq!(next.minute, after);
|
||||
assert_eq!(next.valid_for_millis, 86_400_000);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
//! 模型模块测试:镜像 src/model/ 中带逻辑的模块
|
||||
|
||||
mod account_groups;
|
||||
mod account_schedules;
|
||||
mod audit;
|
||||
mod backup;
|
||||
mod client_keys;
|
||||
|
||||
@@ -116,6 +116,7 @@ fn selected_usage_window(quota: &ProviderQuota) -> Option<(&str, AccountUsagePer
|
||||
|
||||
fn usage_quota(windows: Vec<ProviderQuotaWindow>) -> ProviderQuota {
|
||||
ProviderQuota {
|
||||
daily_used_percent: None,
|
||||
paused_windows: Vec::new(),
|
||||
upstream: None,
|
||||
credits: None,
|
||||
@@ -170,6 +171,7 @@ fn usage_window(key: &str, group: &str, seconds: u64) -> ProviderQuotaWindow {
|
||||
#[test]
|
||||
fn dashboard_quota_should_preserve_unknown_and_actual_window_facts() {
|
||||
let mut quota = ProviderQuota {
|
||||
daily_used_percent: None,
|
||||
paused_windows: Vec::new(),
|
||||
upstream: None,
|
||||
credits: None,
|
||||
|
||||
@@ -59,6 +59,7 @@ fn window(key: &str, days: u64) -> ProviderQuotaWindow {
|
||||
|
||||
fn quota(windows: Vec<ProviderQuotaWindow>) -> ProviderQuota {
|
||||
ProviderQuota {
|
||||
daily_used_percent: None,
|
||||
paused_windows: Vec::new(),
|
||||
upstream: None,
|
||||
credits: None,
|
||||
|
||||
@@ -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(),
|
||||
|
||||
@@ -40,7 +40,7 @@ use gateway_admin::{
|
||||
provider_credentials::{
|
||||
AuthorizationCommit, AuthorizationCommitGuard, AuthorizationCredentialCommit,
|
||||
AuthorizationMutationTarget, AuthorizationStarted, CompleteAuthorization,
|
||||
ConsumeProviderResetCredit, CredentialCommitGuard, CredentialDetails,
|
||||
ConsumeProviderResetCredit, CredentialChange, CredentialCommitGuard, CredentialDetails,
|
||||
CredentialImportCommit, CredentialImportResult, CredentialMutationResult,
|
||||
CredentialRotationCommit, PendingAuthorizationMutation, PrepareCredentialImport,
|
||||
PrepareCredentialRefresh, PrepareCredentialRotation, PreparedAuthorizationCommit,
|
||||
@@ -267,6 +267,7 @@ impl FakeProviderAdmin {
|
||||
email: account.email.clone(),
|
||||
plan_type: account.plan_type.clone(),
|
||||
preserve_profile: false,
|
||||
preserve_catalog_etag: None,
|
||||
preserve_credential_state: false,
|
||||
preserve_access_token_expiry: false,
|
||||
provider_material: document(),
|
||||
@@ -346,7 +347,10 @@ impl ProviderAdmin for FakeProviderAdmin {
|
||||
self.record("provider.account_unavailable");
|
||||
}
|
||||
|
||||
async fn account_facts_changed(&self, _: &[ProviderAccountId]) {
|
||||
async fn account_facts_changed(
|
||||
&self,
|
||||
_: gateway_admin::ports::provider::AccountFactsChange<'_>,
|
||||
) {
|
||||
self.record("provider.account_facts_changed");
|
||||
}
|
||||
|
||||
@@ -740,6 +744,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 {
|
||||
@@ -993,6 +998,12 @@ impl AccountStore for FakeAccountStore {
|
||||
self.record_context(context);
|
||||
self.require_commit()?;
|
||||
Ok(CredentialImportResult {
|
||||
created_ids: command
|
||||
.prepared
|
||||
.credentials
|
||||
.iter()
|
||||
.map(|c| c.account_id.clone())
|
||||
.collect(),
|
||||
config_revision: revision(2),
|
||||
credential_ids: command
|
||||
.prepared
|
||||
@@ -1017,18 +1028,21 @@ impl AccountStore for FakeAccountStore {
|
||||
return Ok(
|
||||
gateway_admin::model::provider_credentials::AuthorizationCommitResult {
|
||||
result,
|
||||
newly_committed: false,
|
||||
change: None,
|
||||
},
|
||||
);
|
||||
}
|
||||
self.record("store.commit_authorization");
|
||||
self.record_context(context);
|
||||
self.require_commit()?;
|
||||
let (account_id, credential_revision) = match command.credential {
|
||||
AuthorizationCredentialCommit::Create(credential) => (credential.account_id, None),
|
||||
let (account_id, credential_revision, change) = match command.credential {
|
||||
AuthorizationCredentialCommit::Create(credential) => {
|
||||
(credential.account_id, None, CredentialChange::Created)
|
||||
}
|
||||
AuthorizationCredentialCommit::Reauthorize(credential) => (
|
||||
credential.account_id,
|
||||
Some(revision(credential.expected_credential_revision.get() + 1)),
|
||||
CredentialChange::Updated,
|
||||
),
|
||||
};
|
||||
let result = CredentialMutationResult {
|
||||
@@ -1043,7 +1057,7 @@ impl AccountStore for FakeAccountStore {
|
||||
Ok(
|
||||
gateway_admin::model::provider_credentials::AuthorizationCommitResult {
|
||||
result,
|
||||
newly_committed: true,
|
||||
change: Some(change),
|
||||
},
|
||||
)
|
||||
}
|
||||
@@ -1201,6 +1215,7 @@ impl SettingsStore for StaticSettingsStore {
|
||||
rotation_strategy: RotationStrategy::Smart,
|
||||
updated_at: Utc::now(),
|
||||
values: gateway_admin::model::settings::RuntimeSettingsValues {
|
||||
antigravity_background_refresh: true,
|
||||
openai_websocket_pool: Default::default(),
|
||||
openai_request_settings: gateway_core::settings::OpenAiRequestSettings {
|
||||
oauth_guardian_review_model: false,
|
||||
@@ -2148,6 +2163,7 @@ async fn accounts_list_should_degrade_quota_failure_to_empty_window_without_drop
|
||||
let events = events();
|
||||
let openai = FakeProviderAdmin::new("openai", events.clone());
|
||||
openai.set_quota(ProviderQuota {
|
||||
daily_used_percent: None,
|
||||
paused_windows: Vec::new(),
|
||||
upstream: None,
|
||||
credits: None,
|
||||
@@ -2310,6 +2326,7 @@ async fn accounts_list_should_map_unknown_credential_to_error_not_normal() {
|
||||
async fn accounts_list_should_not_derive_rate_limited_from_provider_quota_view() {
|
||||
let provider = FakeProviderAdmin::new("openai", events());
|
||||
provider.set_quota(ProviderQuota {
|
||||
daily_used_percent: None,
|
||||
paused_windows: Vec::new(),
|
||||
upstream: None,
|
||||
credits: None,
|
||||
@@ -2363,6 +2380,7 @@ async fn accounts_list_should_not_derive_rate_limited_from_provider_quota_view()
|
||||
async fn accounts_list_should_not_derive_exhaustion_from_provider_quota_view() {
|
||||
let provider = FakeProviderAdmin::new("openai", events());
|
||||
provider.set_quota(ProviderQuota {
|
||||
daily_used_percent: None,
|
||||
paused_windows: Vec::new(),
|
||||
upstream: None,
|
||||
credits: None,
|
||||
@@ -3129,6 +3147,7 @@ async fn accounts_list_should_attach_local_usage_to_quota_windows() {
|
||||
let provider = FakeProviderAdmin::new("openai", events());
|
||||
let reset_at = Utc::now() + TimeDelta::hours(1);
|
||||
provider.set_quota(ProviderQuota {
|
||||
daily_used_percent: None,
|
||||
paused_windows: Vec::new(),
|
||||
upstream: None,
|
||||
credits: None,
|
||||
@@ -3295,6 +3314,7 @@ async fn account_windows_attach_only_the_usage_allowed_by_the_provider() {
|
||||
let provider = FakeProviderAdmin::new("openai", events());
|
||||
let reset_at = Utc::now() + TimeDelta::days(7);
|
||||
let mut quota = ProviderQuota {
|
||||
daily_used_percent: None,
|
||||
paused_windows: Vec::new(),
|
||||
upstream: None,
|
||||
credits: None,
|
||||
@@ -3618,6 +3638,7 @@ pub(super) fn document() -> ProviderDocument {
|
||||
|
||||
fn empty_quota() -> ProviderQuota {
|
||||
ProviderQuota {
|
||||
daily_used_percent: None,
|
||||
paused_windows: Vec::new(),
|
||||
upstream: None,
|
||||
credits: None,
|
||||
@@ -3746,6 +3767,7 @@ fn plugin_rotation_facts(account: &AccountRecord) -> PreparedCredentialRotationF
|
||||
email: account.email.clone(),
|
||||
plan_type: account.plan_type.clone(),
|
||||
preserve_profile: true,
|
||||
preserve_catalog_etag: None,
|
||||
preserve_credential_state: false,
|
||||
preserve_access_token_expiry: false,
|
||||
provider_material: document(),
|
||||
|
||||
@@ -33,6 +33,7 @@ fn runtime_settings(enabled: bool, probe_enabled: bool) -> RuntimeSettings {
|
||||
rotation_strategy: gateway_admin::model::settings::RotationStrategy::Smart,
|
||||
updated_at: Utc::now(),
|
||||
values: gateway_admin::model::settings::RuntimeSettingsValues {
|
||||
antigravity_background_refresh: true,
|
||||
openai_websocket_pool: Default::default(),
|
||||
openai_request_settings: gateway_core::settings::OpenAiRequestSettings {
|
||||
oauth_guardian_review_model: false,
|
||||
|
||||
@@ -283,6 +283,7 @@ impl AdminHarness {
|
||||
self.accounts,
|
||||
self.account_runtime,
|
||||
self.account_groups,
|
||||
Arc::new(UnavailableStore),
|
||||
self.proxies,
|
||||
),
|
||||
self.auth,
|
||||
@@ -1381,3 +1382,20 @@ impl gateway_admin::ports::reset_credit_automation::ResetCreditAutomationStore
|
||||
Err(unavailable("reset-credit automation"))
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl gateway_admin::ports::account_schedules::AccountScheduleStore for UnavailableStore {
|
||||
async fn query(
|
||||
&self,
|
||||
_: &gateway_admin::model::account_schedules::ScheduleQuery,
|
||||
) -> AdminStoreResult<gateway_admin::model::account_schedules::ScheduleList> {
|
||||
unreachable!()
|
||||
}
|
||||
async fn save(
|
||||
&self,
|
||||
_: gateway_admin::model::account_schedules::ScheduleChange,
|
||||
_: &gateway_admin::model::MutationContext,
|
||||
) -> AdminStoreResult<gateway_admin::model::Revision> {
|
||||
unreachable!()
|
||||
}
|
||||
}
|
||||
@@ -337,6 +337,7 @@ impl SettingsStore for FixtureSettingsStore {
|
||||
rotation_strategy: RotationStrategy::Smart,
|
||||
updated_at: Utc::now(),
|
||||
values: gateway_admin::model::settings::RuntimeSettingsValues {
|
||||
antigravity_background_refresh: true,
|
||||
openai_websocket_pool: Default::default(),
|
||||
openai_request_settings: gateway_core::settings::OpenAiRequestSettings {
|
||||
oauth_guardian_review_model: false,
|
||||
|
||||
@@ -340,6 +340,7 @@ async fn linked_accounts_share_plan_resolution_and_only_read_cached_quota() {
|
||||
] {
|
||||
let provider = FakeProviderAdmin::new(kind, events());
|
||||
provider.set_quota(ProviderQuota {
|
||||
daily_used_percent: None,
|
||||
paused_windows: Vec::new(),
|
||||
upstream: None,
|
||||
credits: None,
|
||||
|
||||
@@ -349,6 +349,7 @@ async fn settings_should_reject_zero_refresh_margin_before_store_call() {
|
||||
model_mappings: Default::default(),
|
||||
rotation_strategy: RotationStrategy::Smart,
|
||||
values: gateway_admin::model::settings::RuntimeSettingsValues {
|
||||
antigravity_background_refresh: true,
|
||||
openai_websocket_pool: Default::default(),
|
||||
openai_request_settings: Default::default(),
|
||||
codex_privacy_policy: Default::default(),
|
||||
|
||||
@@ -27,6 +27,8 @@ impl SystemOperations for RecordingSystemOperations {
|
||||
}
|
||||
Ok(SystemVersion {
|
||||
version: "1.0.0".to_owned(),
|
||||
instance_id: "test-instance".to_owned(),
|
||||
restart_supported: false,
|
||||
git_sha: "unknown".to_owned(),
|
||||
build_time: "unknown".to_owned(),
|
||||
deployment_mode: "source".to_owned(),
|
||||
|
||||
@@ -12,6 +12,7 @@ where
|
||||
S: SessionState + Clone + Send + Sync + 'static,
|
||||
{
|
||||
Router::new()
|
||||
.merge(super::schedules::router::<S>())
|
||||
.merge(super::import_tasks::router::<S>())
|
||||
.route("/api/admin/accounts", get(list_accounts::<S>))
|
||||
.route(
|
||||
|
||||
@@ -68,6 +68,7 @@ mod credentials;
|
||||
mod handlers;
|
||||
mod import_tasks;
|
||||
mod presenter;
|
||||
mod schedules;
|
||||
mod upstream_info;
|
||||
mod wire;
|
||||
|
||||
|
||||
@@ -67,6 +67,8 @@ pub(super) fn account_view(
|
||||
time: crate::time::TimePresenter,
|
||||
) -> AccountView {
|
||||
let AccountDirectoryItem {
|
||||
schedule_duty,
|
||||
model_cooldowns,
|
||||
platform_icon,
|
||||
account,
|
||||
capacity,
|
||||
@@ -111,7 +113,19 @@ 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 {
|
||||
schedule_duty,
|
||||
platform_icon,
|
||||
quota_settings: account.quota_settings,
|
||||
auto_use_quota_credits: account.auto_use_quota_credits,
|
||||
@@ -271,6 +285,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
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
//! 管理端账号排班的读取与原子保存
|
||||
|
||||
use crate::SessionState;
|
||||
use crate::admin::{
|
||||
AdminAuth, AdminEnvelope, AdminError, AdminJson, AdminResponse, wire::map_admin_service_error,
|
||||
};
|
||||
use axum::{Router, extract::State, http::StatusCode, response::IntoResponse, routing::post};
|
||||
use gateway_admin::model::account_schedules::{ScheduleChange, ScheduleQuery};
|
||||
|
||||
pub fn router<S: SessionState + Clone + Send + Sync + 'static>() -> Router<S> {
|
||||
Router::new()
|
||||
.route("/api/admin/accounts/schedules/query", post(query::<S>))
|
||||
.route("/api/admin/accounts/schedules/update", post(save::<S>))
|
||||
}
|
||||
|
||||
async fn query<S: SessionState + Send + Sync>(
|
||||
_auth: AdminAuth,
|
||||
State(state): State<S>,
|
||||
AdminJson(query): AdminJson<ScheduleQuery>,
|
||||
) -> Result<impl IntoResponse, AdminError> {
|
||||
let page = state
|
||||
.admin_services()
|
||||
.account_schedules()
|
||||
.query(query)
|
||||
.await
|
||||
.map_err(map_admin_service_error)?;
|
||||
Ok(AdminResponse::new(StatusCode::OK, AdminEnvelope::ok(page)))
|
||||
}
|
||||
|
||||
async fn save<S: SessionState + Send + Sync>(
|
||||
auth: AdminAuth,
|
||||
State(state): State<S>,
|
||||
AdminJson(change): AdminJson<ScheduleChange>,
|
||||
) -> Result<impl IntoResponse, AdminError> {
|
||||
let revision = state
|
||||
.admin_services()
|
||||
.account_schedules()
|
||||
.save(change, &auth.context().mutation_context())
|
||||
.await
|
||||
.map_err(map_admin_service_error)?;
|
||||
Ok(AdminResponse::new(
|
||||
StatusCode::OK,
|
||||
AdminEnvelope::ok(revision),
|
||||
))
|
||||
}
|
||||
@@ -247,6 +247,8 @@ pub struct AccountSummaryView {
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AccountView {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub schedule_duty: Option<gateway_core::account::duty::ScheduleDuty>,
|
||||
pub platform_icon: Option<String>,
|
||||
pub quota_settings: gateway_core::account::AccountQuotaSettings,
|
||||
pub auto_use_quota_credits: bool,
|
||||
@@ -382,6 +384,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 +400,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(
|
||||
|
||||
@@ -36,6 +36,7 @@ pub type ProviderRequestProfileUpdates =
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct RuntimeSettingsFields {
|
||||
pub antigravity_background_refresh: bool,
|
||||
pub openai_websocket_pool: gateway_core::settings::OpenAiWebSocketPoolSettings,
|
||||
pub openai_request_settings: gateway_core::settings::OpenAiRequestSettings,
|
||||
pub codex_privacy_policy: gateway_core::settings::privacy::CodexPrivacyPolicy,
|
||||
@@ -715,6 +716,7 @@ impl RuntimeSettingsFields {
|
||||
self,
|
||||
) -> Result<gateway_admin::model::settings::RuntimeSettingsValues, WireValidationError> {
|
||||
let values = gateway_admin::model::settings::RuntimeSettingsValues {
|
||||
antigravity_background_refresh: self.antigravity_background_refresh,
|
||||
openai_websocket_pool: self.openai_websocket_pool,
|
||||
openai_request_settings: self.openai_request_settings,
|
||||
codex_privacy_policy: self.codex_privacy_policy,
|
||||
@@ -767,6 +769,7 @@ impl RuntimeSettingsFields {
|
||||
impl From<gateway_admin::model::settings::RuntimeSettingsValues> for RuntimeSettingsFields {
|
||||
fn from(settings: gateway_admin::model::settings::RuntimeSettingsValues) -> Self {
|
||||
crate::admin::settings::RuntimeSettingsFields {
|
||||
antigravity_background_refresh: settings.antigravity_background_refresh,
|
||||
openai_websocket_pool: settings.openai_websocket_pool,
|
||||
openai_request_settings: settings.openai_request_settings,
|
||||
codex_privacy_policy: settings.codex_privacy_policy,
|
||||
|
||||
@@ -81,6 +81,8 @@ impl UpdateRequest {
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct SystemVersionView {
|
||||
version: String,
|
||||
instance_id: String,
|
||||
restart_supported: bool,
|
||||
git_sha: String,
|
||||
build_time: String,
|
||||
deployment_mode: String,
|
||||
@@ -97,6 +99,8 @@ impl From<SystemVersion> for SystemVersionView {
|
||||
Self {
|
||||
deployment_mode_label: deployment_mode_label(&version.deployment_mode).to_owned(),
|
||||
version: version.version,
|
||||
instance_id: version.instance_id,
|
||||
restart_supported: version.restart_supported,
|
||||
git_sha: version.git_sha,
|
||||
build_time: version.build_time,
|
||||
deployment_mode: version.deployment_mode,
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -11,6 +11,7 @@ use gateway_core::{
|
||||
error::ProviderErrorKind,
|
||||
policy::{ClientVersionRejection, CodexClientKind},
|
||||
};
|
||||
use gateway_protocol::http::preferred_response_request_id;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
pub use gateway_core::engine::execution::gateway_error_from_engine;
|
||||
@@ -170,8 +171,8 @@ pub fn engine_error_response(error: &EngineError) -> Response {
|
||||
};
|
||||
response.headers_mut().append(name, value);
|
||||
}
|
||||
if !response.headers().contains_key("x-request-id")
|
||||
&& !response.headers().contains_key("x-oai-request-id")
|
||||
if preferred_response_request_id(|name| response.headers().get(name)?.to_str().ok())
|
||||
.is_none()
|
||||
&& let Some(request_id) = error.upstream_request_id()
|
||||
&& let Ok(value) = HeaderValue::from_str(request_id.as_str())
|
||||
{
|
||||
|
||||
@@ -665,7 +665,7 @@ fn engine_error_response_with_headers(
|
||||
response_headers: &[ProviderResponseHeader],
|
||||
) -> Response {
|
||||
let response = engine_error_response(error);
|
||||
let failure_request_ids = ["x-request-id", "x-oai-request-id"]
|
||||
let failure_request_ids = gateway_protocol::http::RESPONSE_REQUEST_ID_HEADERS
|
||||
.into_iter()
|
||||
.flat_map(|name| {
|
||||
response
|
||||
@@ -678,8 +678,9 @@ fn engine_error_response_with_headers(
|
||||
.collect::<Vec<_>>();
|
||||
// 失败后仍须交付已采集的 turn state;只隔离 opening 身份,不丢弃会话状态
|
||||
let mut response = apply_provider_response_headers(response, response_headers);
|
||||
response.headers_mut().remove("x-request-id");
|
||||
response.headers_mut().remove("x-oai-request-id");
|
||||
for name in gateway_protocol::http::RESPONSE_REQUEST_ID_HEADERS {
|
||||
response.headers_mut().remove(name);
|
||||
}
|
||||
for (name, value) in failure_request_ids {
|
||||
response.headers_mut().append(name, value);
|
||||
}
|
||||
|
||||
@@ -37,11 +37,11 @@ pub(crate) fn with_model_request_id(
|
||||
let usable = |value: &HeaderValue| value.to_str().is_ok_and(|id| !id.trim().is_empty());
|
||||
if !headers.get("x-request-id").is_some_and(usable) {
|
||||
// 只有别名时沿用同一个上游值,避免外层 middleware 再填入入口 ID
|
||||
let client_id = headers
|
||||
.get("x-oai-request-id")
|
||||
.filter(|value| usable(value))
|
||||
.unwrap_or(&gateway_id)
|
||||
.clone();
|
||||
let client_id = gateway_protocol::http::preferred_response_request_id(|name| {
|
||||
headers.get(name)?.to_str().ok()
|
||||
})
|
||||
.and_then(|value| HeaderValue::from_str(value).ok())
|
||||
.unwrap_or_else(|| gateway_id.clone());
|
||||
headers.insert("x-request-id", client_id);
|
||||
}
|
||||
headers.insert("x-gateway-request-id", gateway_id);
|
||||
|
||||
@@ -7,6 +7,7 @@ use crate::{
|
||||
auth::{ClientKeyHeaders, authenticate_client, client_access_error_response},
|
||||
error::gateway_error_response,
|
||||
generation::{GenerationEndpoint, GenerationHttpRequest, execute_prepared_generation},
|
||||
router::IngressStarted,
|
||||
},
|
||||
};
|
||||
use axum::{
|
||||
@@ -15,18 +16,43 @@ use axum::{
|
||||
http::{HeaderMap, StatusCode},
|
||||
response::Response,
|
||||
};
|
||||
use std::net::SocketAddr;
|
||||
use std::{net::SocketAddr, time::Instant};
|
||||
|
||||
/// `POST /v1/responses`
|
||||
pub(crate) async fn responses(
|
||||
State(state): State<ApiState>,
|
||||
connect_info: Option<Extension<ConnectInfo<SocketAddr>>>,
|
||||
ingress_id: Option<Extension<tower_http::request_id::RequestId>>,
|
||||
ingress_started: Option<Extension<IngressStarted>>,
|
||||
headers: HeaderMap,
|
||||
body: Bytes,
|
||||
) -> Response {
|
||||
// Bytes extractor 已读完传输正文;此时尚未认证、解压或解析 JSON
|
||||
let mut encodings = headers.get_all(axum::http::header::CONTENT_ENCODING).iter();
|
||||
let encoding = match (encodings.next(), encodings.next()) {
|
||||
(None, _) => "identity",
|
||||
(Some(value), None) => value
|
||||
.to_str()
|
||||
.ok()
|
||||
.and_then(|value| {
|
||||
["identity", "gzip", "deflate", "zstd"]
|
||||
.into_iter()
|
||||
.find(|known| known.eq_ignore_ascii_case(value.trim()))
|
||||
})
|
||||
.unwrap_or("other"),
|
||||
_ => "other",
|
||||
};
|
||||
tracing::info!(target: "request_trace", stage = "http.body.received",
|
||||
receive_ms = ingress_started.map(|Extension(start)| start.0.elapsed().as_millis()),
|
||||
encoded_bytes = body.len(), content_encoding = encoding,
|
||||
"HTTP request body received");
|
||||
let service = state.data_plane().clone();
|
||||
let client = match authenticate_client(&service, &headers, ClientKeyHeaders::Bearer).await {
|
||||
let started = Instant::now();
|
||||
let authentication = authenticate_client(&service, &headers, ClientKeyHeaders::Bearer).await;
|
||||
tracing::info!(target: "request_trace", stage = "http.auth.finished",
|
||||
auth_ms = started.elapsed().as_millis(), accepted = authentication.is_ok(),
|
||||
"HTTP request authentication finished");
|
||||
let client = match authentication {
|
||||
Ok(client) => client,
|
||||
Err(error) => return client_access_error_response(error),
|
||||
};
|
||||
@@ -42,7 +68,12 @@ pub(crate) async fn responses(
|
||||
}
|
||||
};
|
||||
let execution = service.execution();
|
||||
let prepared = match execution.prepare_execution(client).await {
|
||||
let started = Instant::now();
|
||||
let preparation = execution.prepare_execution(client).await;
|
||||
tracing::info!(target: "request_trace", stage = "http.execution.prepared",
|
||||
prepare_ms = started.elapsed().as_millis(), accepted = preparation.is_ok(),
|
||||
"HTTP execution preparation finished");
|
||||
let prepared = match preparation {
|
||||
Ok(prepared) => prepared,
|
||||
Err(error) => return gateway_error_response(&error),
|
||||
};
|
||||
|
||||
@@ -143,9 +143,20 @@ pub(crate) fn decode_request_with_body(
|
||||
headers: &HeaderMap,
|
||||
max_decompressed_bytes: usize,
|
||||
) -> Result<(DecodedGenerationRequest, Bytes), RequestDecodeError> {
|
||||
let body = decompress_request_body(body, headers, max_decompressed_bytes)?;
|
||||
let decoded = decode_request_inner(&body, &OpenAiRequestHeaders::from_headers(headers))?;
|
||||
Ok((decoded, Bytes::copy_from_slice(&body)))
|
||||
let started = std::time::Instant::now();
|
||||
let decompressed = decompress_request_body(body, headers, max_decompressed_bytes);
|
||||
tracing::info!(target: "request_trace", stage = "http.body.decompressed",
|
||||
decompress_ms = started.elapsed().as_millis(),
|
||||
decoded_bytes = decompressed.as_ref().ok().map(|body| body.len()),
|
||||
accepted = decompressed.is_ok(), "HTTP request body decompressed");
|
||||
let body = decompressed?;
|
||||
let started = std::time::Instant::now();
|
||||
let decoded = decode_request_inner(&body, &OpenAiRequestHeaders::from_headers(headers))
|
||||
.map(|decoded| (decoded, Bytes::copy_from_slice(&body)));
|
||||
tracing::info!(target: "request_trace", stage = "http.body.decoded",
|
||||
decode_ms = started.elapsed().as_millis(), accepted = decoded.is_ok(),
|
||||
"HTTP request body decoded");
|
||||
decoded
|
||||
}
|
||||
|
||||
pub(super) fn decode_request_inner(
|
||||
|
||||
@@ -8,6 +8,7 @@ use axum::http::{HeaderName, HeaderValue, StatusCode};
|
||||
use gateway_core::engine::EngineError;
|
||||
use gateway_core::error::ProviderErrorKind;
|
||||
use gateway_core::event::ProviderResponseHeader;
|
||||
use gateway_protocol::http::{RESPONSE_REQUEST_ID_HEADERS, preferred_response_request_id};
|
||||
use serde_json::{Map, Value, json};
|
||||
use thiserror::Error;
|
||||
|
||||
@@ -119,9 +120,12 @@ pub(super) fn response_metadata_event(
|
||||
response_headers: &[ProviderResponseHeader],
|
||||
) -> String {
|
||||
let mut headers = response_event_headers(response_headers);
|
||||
let client_request_id = preferred_response_request_id(|name| headers.get(name)?.as_str())
|
||||
.unwrap_or(request_id)
|
||||
.to_owned();
|
||||
headers
|
||||
.entry("x-request-id".to_owned())
|
||||
.or_insert_with(|| Value::String(request_id.to_owned()));
|
||||
.or_insert(Value::String(client_request_id));
|
||||
json!({
|
||||
"type": "response.metadata",
|
||||
"headers": headers,
|
||||
@@ -149,7 +153,7 @@ fn response_event_headers(response_headers: &[ProviderResponseHeader]) -> Map<St
|
||||
let Ok(value) = std::str::from_utf8(header.value()) else {
|
||||
continue;
|
||||
};
|
||||
if matches!(name.as_str(), "x-request-id" | "x-oai-request-id")
|
||||
if RESPONSE_REQUEST_ID_HEADERS.contains(&name.as_str())
|
||||
&& (value.trim().is_empty() || http_value.to_str().is_err())
|
||||
{
|
||||
continue;
|
||||
@@ -181,9 +185,13 @@ 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 身份不证明当前失败属于该请求;仅保留其他允许的会话头
|
||||
headers.remove("x-request-id");
|
||||
headers.remove("x-oai-request-id");
|
||||
for name in RESPONSE_REQUEST_ID_HEADERS {
|
||||
headers.remove(name);
|
||||
}
|
||||
}
|
||||
let status = if provider
|
||||
.is_some_and(|error| error.kind() == ProviderErrorKind::UpstreamCapacityUnavailable)
|
||||
@@ -221,7 +229,7 @@ pub(super) fn initial_engine_error_event(
|
||||
}
|
||||
|
||||
fn has_request_id(headers: &Map<String, Value>) -> bool {
|
||||
headers.contains_key("x-request-id") || headers.contains_key("x-oai-request-id")
|
||||
preferred_response_request_id(|name| headers.get(name)?.as_str()).is_some()
|
||||
}
|
||||
|
||||
pub(super) fn error_event(
|
||||
|
||||
@@ -46,6 +46,10 @@ pub(crate) fn router() -> Router<ApiState> {
|
||||
.merge(super::provider_endpoints::router())
|
||||
}
|
||||
|
||||
/// 在读取正文前保存入口时刻,交给端点区分接收与执行耗时
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) struct IngressStarted(pub(crate) std::time::Instant);
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) enum DataPlaneNamespace {
|
||||
V1,
|
||||
|
||||
@@ -19,7 +19,7 @@ use serde_json::json;
|
||||
use tower_http::request_id::RequestId;
|
||||
|
||||
use crate::client_error::{AccessRejection, ProtocolErrorBody};
|
||||
use crate::data_plane::router::DataPlaneNamespace;
|
||||
use crate::data_plane::router::{DataPlaneNamespace, IngressStarted};
|
||||
|
||||
pub(crate) async fn record_ingress(
|
||||
State(diagnostics): State<Arc<dyn OperationalDiagnostics>>,
|
||||
@@ -29,6 +29,9 @@ pub(crate) async fn record_ingress(
|
||||
let Some(namespace) = DataPlaneNamespace::for_path(request.uri().path()) else {
|
||||
return next.run(request).await;
|
||||
};
|
||||
request
|
||||
.extensions_mut()
|
||||
.insert(IngressStarted(std::time::Instant::now()));
|
||||
let correlation_id = request
|
||||
.extensions()
|
||||
.get::<RequestId>()
|
||||
|
||||
@@ -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!(
|
||||
@@ -361,6 +381,7 @@ async fn account_quota_refresh_time_uses_server_clock_and_deployment_timezone()
|
||||
),
|
||||
] {
|
||||
*fixture.provider_quota.lock().unwrap() = Some(ProviderQuota {
|
||||
daily_used_percent: None,
|
||||
paused_windows: Vec::new(),
|
||||
upstream: None,
|
||||
plan_type: None,
|
||||
@@ -411,6 +432,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 {
|
||||
|
||||
@@ -914,6 +914,7 @@ mod actions {
|
||||
#[test]
|
||||
fn account_import_response_should_emit_account_ids() {
|
||||
let response = AccountImportData::from_result(CredentialImportResult {
|
||||
created_ids: Default::default(),
|
||||
config_revision: Revision::new(8).expect("revision"),
|
||||
credential_ids: vec![ProviderAccountId::new("acct_imported").expect("account ID")],
|
||||
});
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -184,6 +184,7 @@ impl AdminTestFixture {
|
||||
unused.clone(),
|
||||
unused.clone(),
|
||||
account_groups.clone(),
|
||||
unused.clone(),
|
||||
Arc::new(proxies::MemoryProxies::default()),
|
||||
),
|
||||
auth.clone(),
|
||||
@@ -1484,6 +1485,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 +1494,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()),
|
||||
@@ -1994,6 +1997,7 @@ fn test_runtime_settings() -> RuntimeSettings {
|
||||
rotation_strategy: RotationStrategy::Smart,
|
||||
updated_at: Utc::now(),
|
||||
values: gateway_admin::model::settings::RuntimeSettingsValues {
|
||||
antigravity_background_refresh: true,
|
||||
openai_websocket_pool: Default::default(),
|
||||
openai_request_settings: Default::default(),
|
||||
codex_privacy_policy: Default::default(),
|
||||
@@ -2110,3 +2114,20 @@ impl gateway_admin::ports::reset_credit_automation::ResetCreditAutomationStore f
|
||||
Err(unavailable("reset-credit automation"))
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl gateway_admin::ports::account_schedules::AccountScheduleStore for UnusedStore {
|
||||
async fn query(
|
||||
&self,
|
||||
_: &gateway_admin::model::account_schedules::ScheduleQuery,
|
||||
) -> AdminStoreResult<gateway_admin::model::account_schedules::ScheduleList> {
|
||||
unreachable!()
|
||||
}
|
||||
async fn save(
|
||||
&self,
|
||||
_: gateway_admin::model::account_schedules::ScheduleChange,
|
||||
_: &gateway_admin::model::MutationContext,
|
||||
) -> AdminStoreResult<gateway_admin::model::Revision> {
|
||||
unreachable!()
|
||||
}
|
||||
}
|
||||
@@ -84,6 +84,7 @@ fn update_body() -> Value {
|
||||
"gpt-5.4": "gpt-5.5",
|
||||
"grok-latest": "grok-4.5"
|
||||
},
|
||||
"antigravityBackgroundRefresh": false,
|
||||
"refreshMarginSeconds": 1800,
|
||||
"refreshConcurrency": 4,
|
||||
"maxConcurrentPerAccount": 5,
|
||||
@@ -637,6 +638,7 @@ fn settings_service_contract_flattens_values_and_rejects_unknown_fields() {
|
||||
command
|
||||
);
|
||||
for field in [
|
||||
"antigravity_background_refresh",
|
||||
"openai_request_settings",
|
||||
"reset_credit_on_low_weekly_quota",
|
||||
] {
|
||||
@@ -993,22 +995,30 @@ fn decompression_setting_should_reject_invalid_values() {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn settings_update_rejects_unknown_fields_without_writing() {
|
||||
async fn settings_update_rejects_incomplete_and_unknown_fields_without_writing() {
|
||||
let fixture = AdminTestFixture::new().await;
|
||||
fixture.auth.insert_session("valid-session");
|
||||
let app = app(fixture.state());
|
||||
let initial = fixture.settings.settings.lock().unwrap().clone();
|
||||
let mut body = update_body();
|
||||
body["unknownSetting"] = json!(true);
|
||||
let response = app
|
||||
.oneshot(request(
|
||||
Method::POST,
|
||||
"/api/admin/settings/update",
|
||||
Some(body),
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
|
||||
let mut unknown = update_body();
|
||||
unknown["unknownSetting"] = json!(true);
|
||||
let mut incomplete = update_body();
|
||||
incomplete
|
||||
.as_object_mut()
|
||||
.unwrap()
|
||||
.remove("antigravityBackgroundRefresh");
|
||||
for body in [unknown, incomplete] {
|
||||
let response = app
|
||||
.clone()
|
||||
.oneshot(request(
|
||||
Method::POST,
|
||||
"/api/admin/settings/update",
|
||||
Some(body),
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
|
||||
}
|
||||
assert_eq!(*fixture.settings.settings.lock().unwrap(), initial);
|
||||
}
|
||||
|
||||
|
||||
@@ -24,6 +24,27 @@ use tower::ServiceExt as _;
|
||||
|
||||
use super::{AdminTestFixture, AdminTestState, unavailable_system};
|
||||
|
||||
#[tokio::test]
|
||||
async fn version_should_expose_runtime_identity_and_restart_capability() {
|
||||
let fixture = crate::support::key_fixture().await;
|
||||
fixture.auth.insert_session("valid-session");
|
||||
let response = app(fixture.state())
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.uri("/api/admin/system/version")
|
||||
.header(header::COOKIE, "cpr_session=valid-session")
|
||||
.header("x-request-id", "req_system_version")
|
||||
.body(Body::empty())
|
||||
.expect("version request"),
|
||||
)
|
||||
.await
|
||||
.expect("version response");
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
let body = crate::support::response_json(response).await;
|
||||
assert_eq!(body["data"]["instanceId"], "test-instance");
|
||||
assert_eq!(body["data"]["restartSupported"], true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn update_detail_query_should_default_to_no_refresh_and_reject_unknown_fields() {
|
||||
let query: UpdateDetailQuery = serde_json::from_str("{}").expect("empty query object");
|
||||
|
||||
@@ -256,12 +256,21 @@ async fn request_middleware_sees_original_chat_and_preserves_the_endpoint() {
|
||||
let mut execution = Execution::new(Session::new(vec![created(), completed("ok")]));
|
||||
execution.middleware = Some(middleware.frozen());
|
||||
let fixture = Fixture::with_execution(execution).await;
|
||||
let response = fixture.post(chat_request(false)).await;
|
||||
let mut request = chat_request(false);
|
||||
request["stream_options"] = json!({"include_usage":true});
|
||||
request["messages"] = json!([
|
||||
{"role":"developer","content":"brief"},
|
||||
{"role":"system","content":null},
|
||||
{"role":"assistant","tool_calls":[]},
|
||||
{"role":"user","content":[{"type":"text","text":null},{"type":"text","text":"hello"}]},
|
||||
{"role":"tool","name":"notifications","namespace":"agent","content":"notice"}
|
||||
]);
|
||||
let response = fixture.post(request.clone()).await;
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
let downstream = json_body(response).await;
|
||||
assert_eq!(downstream["object"], "chat.completion");
|
||||
let observed = middleware.requests.lock().unwrap();
|
||||
assert_eq!(observed.as_slice(), [chat_request(false)]);
|
||||
assert_eq!(observed.as_slice(), [request]);
|
||||
assert_eq!(
|
||||
middleware.inner.endpoints.lock().unwrap().as_slice(),
|
||||
[PATH]
|
||||
|
||||
@@ -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!(
|
||||
@@ -396,16 +400,16 @@ fn local_provider_capacity_exhaustion_should_map_to_service_unavailable() {
|
||||
);
|
||||
assert_eq!(
|
||||
projected.safe_message(),
|
||||
"The gateway account pool is busy."
|
||||
"No eligible account currently has capacity for this request."
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_eligible_provider_account_should_preserve_safe_provider_detail() {
|
||||
#[tokio::test]
|
||||
async fn no_eligible_provider_account_should_preserve_safe_provider_detail() {
|
||||
let detail = ClientVisibleUpstreamError::new(
|
||||
"no account is eligible for the requested model",
|
||||
Some("no_eligible_account".to_owned()),
|
||||
Some("account_unavailable_error".to_owned()),
|
||||
"This request requires an upstream WebSocket.",
|
||||
Some("websocket_account_unavailable".to_owned()),
|
||||
None,
|
||||
);
|
||||
let error = EngineError::Provider(
|
||||
ProviderError::new(
|
||||
@@ -419,17 +423,24 @@ fn no_eligible_provider_account_should_preserve_safe_provider_detail() {
|
||||
assert_eq!(gateway.kind(), GatewayErrorKind::NoAvailableProvider);
|
||||
assert_eq!(
|
||||
gateway.client_message(),
|
||||
"no account is eligible for the requested model"
|
||||
"This request requires an upstream WebSocket."
|
||||
);
|
||||
assert_eq!(gateway.client_error_code(), Some("no_eligible_account"));
|
||||
assert_eq!(
|
||||
gateway.client_error_type(),
|
||||
Some("account_unavailable_error")
|
||||
gateway.client_error_code(),
|
||||
Some("websocket_account_unavailable")
|
||||
);
|
||||
assert_eq!(gateway.client_error_type(), None);
|
||||
assert_eq!(
|
||||
gateway.safe_message(),
|
||||
"The gateway found no eligible account for this request."
|
||||
);
|
||||
let response = engine_error_response(&error);
|
||||
assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
|
||||
let body: serde_json::Value =
|
||||
serde_json::from_slice(&to_bytes(response.into_body(), usize::MAX).await.unwrap()).unwrap();
|
||||
assert_eq!(body["error"]["type"], "server_error");
|
||||
assert_eq!(body["error"]["code"], "websocket_account_unavailable");
|
||||
assert_eq!(body["error"]["message"], gateway.client_message());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -508,6 +519,7 @@ fn engine_provider_unsupported_capability_should_remain_unsupported() {
|
||||
|
||||
#[test]
|
||||
fn engine_provider_credential_failures_should_not_impersonate_client_auth_failures() {
|
||||
let mut messages = std::collections::HashSet::new();
|
||||
for kind in [
|
||||
ProviderErrorKind::Unauthorized,
|
||||
ProviderErrorKind::PermissionDenied,
|
||||
@@ -516,11 +528,19 @@ fn engine_provider_credential_failures_should_not_impersonate_client_auth_failur
|
||||
let mapped = gateway_error_from_engine(&error);
|
||||
|
||||
assert_eq!(mapped.kind(), GatewayErrorKind::UpstreamUnavailable);
|
||||
assert_eq!(
|
||||
mapped.safe_message(),
|
||||
"The upstream account cannot access the service."
|
||||
assert!(
|
||||
mapped
|
||||
.safe_message()
|
||||
.to_lowercase()
|
||||
.contains("upstream account")
|
||||
);
|
||||
messages.insert(mapped.safe_message().to_owned());
|
||||
}
|
||||
assert_eq!(
|
||||
messages.len(),
|
||||
2,
|
||||
"authentication and permission failures must be distinguishable"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -577,19 +597,29 @@ fn engine_provider_timeout_and_cancellation_should_remain_distinct() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn engine_provider_runtime_failures_should_collapse_to_safe_unavailability() {
|
||||
fn engine_provider_runtime_failures_preserve_the_cause_without_exposing_internal_details() {
|
||||
let mut messages = std::collections::HashSet::new();
|
||||
for kind in [
|
||||
ProviderErrorKind::Transport,
|
||||
ProviderErrorKind::Protocol,
|
||||
ProviderErrorKind::Unavailable,
|
||||
ProviderErrorKind::ProcessTerminated,
|
||||
] {
|
||||
let error = EngineError::Provider(ProviderError::new(kind, UpstreamSendState::Ambiguous));
|
||||
let error = EngineError::Provider(
|
||||
ProviderError::new(kind, UpstreamSendState::Ambiguous)
|
||||
.with_source(std::io::Error::other("PRIVATE_ENDPOINT_AND_CREDENTIAL")),
|
||||
);
|
||||
|
||||
let projected = gateway_error_from_engine(&error);
|
||||
assert_eq!(projected.kind(), GatewayErrorKind::UpstreamUnavailable);
|
||||
assert_eq!(projected.safe_message(), "Upstream service is unavailable.");
|
||||
assert!(!projected.client_message().contains("PRIVATE_"));
|
||||
messages.insert(projected.client_message().to_owned());
|
||||
}
|
||||
assert_eq!(
|
||||
messages.len(),
|
||||
4,
|
||||
"different failure causes must remain distinguishable"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -334,7 +334,7 @@ async fn request_settings_reach_query_terminal_without_mutating_authenticated_ba
|
||||
runtime["account_queue_timeout_seconds"] = serde_json::json!(30);
|
||||
runtime["switch_account_on_queue_failure"] = serde_json::json!(false);
|
||||
settings.runtime = serde_json::from_value(runtime).unwrap();
|
||||
settings.fast_mode = FastMode::Disabled;
|
||||
settings.fast_mode = Some(FastMode::Disabled);
|
||||
}),
|
||||
..Default::default()
|
||||
}));
|
||||
@@ -355,8 +355,12 @@ async fn request_settings_reach_query_terminal_without_mutating_authenticated_ba
|
||||
"model-a"
|
||||
);
|
||||
assert_ne!(
|
||||
execution.client.policy().account_scope().fast_mode(),
|
||||
FastMode::Disabled
|
||||
execution
|
||||
.client
|
||||
.policy()
|
||||
.account_scope()
|
||||
.fast_mode_override(),
|
||||
Some(FastMode::Disabled)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
@@ -133,6 +134,7 @@ async fn fixture(sharing: ClientPeerSharing, plaintext: &str) -> (AdminTestFixtu
|
||||
},
|
||||
});
|
||||
*fixture.provider_quota.lock().unwrap() = Some(ProviderQuota {
|
||||
daily_used_percent: None,
|
||||
paused_windows: Vec::new(),
|
||||
upstream: None,
|
||||
plan_type: Some("pro".into()),
|
||||
|
||||
@@ -3300,6 +3300,12 @@ async fn response_ids_are_provider_and_client_independent() {
|
||||
(&[], MODEL_REQUEST_ID),
|
||||
(&[("x-request-id", "upstream-primary")], "upstream-primary"),
|
||||
(&[("x-oai-request-id", "upstream-alias")], "upstream-alias"),
|
||||
(
|
||||
&[("x-openai-request-id", "upstream-openai")],
|
||||
"upstream-openai",
|
||||
),
|
||||
(&[("x-ms-request-id", "upstream-ms")], "upstream-ms"),
|
||||
(&[("cf-ray", "trace-only")], MODEL_REQUEST_ID),
|
||||
(
|
||||
&[
|
||||
("x-request-id", "upstream-primary"),
|
||||
@@ -3315,6 +3321,22 @@ async fn response_ids_are_provider_and_client_independent() {
|
||||
"upstream-alias",
|
||||
),
|
||||
(&[("x-request-id", "")], MODEL_REQUEST_ID),
|
||||
(
|
||||
&[
|
||||
("x-request-id", "é"),
|
||||
("x-oai-request-id", " "),
|
||||
("x-openai-request-id", ""),
|
||||
("x-ms-request-id", "upstream-ms"),
|
||||
],
|
||||
"upstream-ms",
|
||||
),
|
||||
(
|
||||
&[
|
||||
("x-openai-request-id", "upstream-openai"),
|
||||
("x-ms-request-id", "upstream-ms"),
|
||||
],
|
||||
"upstream-openai",
|
||||
),
|
||||
];
|
||||
for provider in ["openai", "xai"] {
|
||||
for streaming in [false, true] {
|
||||
@@ -3343,6 +3365,11 @@ async fn response_ids_are_provider_and_client_independent() {
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
assert_eq!(response.headers()["x-request-id"], *expected);
|
||||
assert_eq!(response.headers()["x-gateway-request-id"], MODEL_REQUEST_ID);
|
||||
for (name, value) in *upstream_headers {
|
||||
if *name != "x-request-id" {
|
||||
assert_eq!(response.headers()[*name].as_bytes(), value.as_bytes());
|
||||
}
|
||||
}
|
||||
assert!(
|
||||
!to_bytes(response.into_body(), 64 * 1024)
|
||||
.await
|
||||
@@ -3359,7 +3386,12 @@ async fn failure_ids_prefer_the_actual_error_over_session_headers() {
|
||||
let admin = crate::admin::AdminTestFixture::new().await.services;
|
||||
for provider in ["openai", "xai"] {
|
||||
for streaming in [false, true] {
|
||||
for upstream_headers in [vec![], headers(&[("x-oai-request-id", "actual-error")])] {
|
||||
for upstream_headers in [
|
||||
vec![],
|
||||
headers(&[("x-oai-request-id", "actual-error")]),
|
||||
headers(&[("x-openai-request-id", "actual-error")]),
|
||||
headers(&[("x-ms-request-id", "actual-error")]),
|
||||
] {
|
||||
let expected = if upstream_headers.is_empty() {
|
||||
MODEL_REQUEST_ID
|
||||
} else {
|
||||
@@ -3367,7 +3399,7 @@ async fn failure_ids_prefer_the_actual_error_over_session_headers() {
|
||||
};
|
||||
let raw =
|
||||
Bytes::from_static(br#"{"error":{"message":"synthetic upstream detail"}}"#);
|
||||
let error =
|
||||
let mut error =
|
||||
ProviderError::new(ProviderErrorKind::InvalidRequest, UpstreamSendState::Sent)
|
||||
.with_client_visible_upstream_response(
|
||||
ClientVisibleUpstreamResponse::new(
|
||||
@@ -3377,12 +3409,25 @@ async fn failure_ids_prefer_the_actual_error_over_session_headers() {
|
||||
)
|
||||
.with_headers(upstream_headers),
|
||||
);
|
||||
if expected == "actual-error" {
|
||||
// 最终响应头优先于错误对象中残留的旧观测 ID
|
||||
error = error.with_upstream_request_id(OpaqueUpstreamValue::new("stale-fact"));
|
||||
}
|
||||
let session = failed_session(streaming, EngineError::Provider(error))
|
||||
.with_response_headers(headers(&[("x-request-id", "earlier-session")]));
|
||||
.with_response_headers(headers(&[
|
||||
("x-request-id", "earlier-session"),
|
||||
("x-openai-request-id", "earlier-openai"),
|
||||
("x-ms-request-id", "earlier-ms"),
|
||||
]));
|
||||
let response = response(&admin, provider, session, streaming).await;
|
||||
assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
|
||||
assert_eq!(response.headers()["x-request-id"], expected);
|
||||
assert_eq!(response.headers()["x-gateway-request-id"], MODEL_REQUEST_ID);
|
||||
for name in ["x-openai-request-id", "x-ms-request-id"] {
|
||||
if let Some(value) = response.headers().get(name) {
|
||||
assert_eq!(value, "actual-error");
|
||||
}
|
||||
}
|
||||
assert_eq!(to_bytes(response.into_body(), 4096).await.unwrap(), raw);
|
||||
}
|
||||
|
||||
@@ -3394,12 +3439,16 @@ async fn failure_ids_prefer_the_actual_error_over_session_headers() {
|
||||
.with_response_headers(headers(&[
|
||||
("x-request-id", "earlier-session"),
|
||||
("x-oai-request-id", "earlier-alias"),
|
||||
("x-openai-request-id", "earlier-openai"),
|
||||
("x-ms-request-id", "earlier-ms"),
|
||||
]));
|
||||
let response = response(&admin, provider, session, streaming).await;
|
||||
assert_eq!(response.status(), StatusCode::BAD_GATEWAY);
|
||||
assert_eq!(response.headers()["x-request-id"], "body-read-error");
|
||||
assert_eq!(response.headers().get_all("x-request-id").iter().count(), 1);
|
||||
assert!(response.headers().get("x-oai-request-id").is_none());
|
||||
assert!(response.headers().get("x-openai-request-id").is_none());
|
||||
assert!(response.headers().get("x-ms-request-id").is_none());
|
||||
assert_eq!(response.headers()["x-gateway-request-id"], MODEL_REQUEST_ID);
|
||||
}
|
||||
}
|
||||
@@ -3414,12 +3463,16 @@ async fn local_execution_failure_uses_the_existing_model_id() {
|
||||
failed_session(streaming, EngineError::Deadline).with_response_headers(headers(&[
|
||||
("x-request-id", "opening-primary"),
|
||||
("x-oai-request-id", "opening-alias"),
|
||||
("x-openai-request-id", "opening-openai"),
|
||||
("x-ms-request-id", "opening-ms"),
|
||||
("x-codex-turn-state", "retained-turn-state"),
|
||||
]));
|
||||
let response = response(&admin, provider, session, streaming).await;
|
||||
assert_eq!(response.headers()["x-request-id"], MODEL_REQUEST_ID);
|
||||
assert_eq!(response.headers()["x-gateway-request-id"], MODEL_REQUEST_ID);
|
||||
assert!(response.headers().get("x-oai-request-id").is_none());
|
||||
assert!(response.headers().get("x-openai-request-id").is_none());
|
||||
assert!(response.headers().get("x-ms-request-id").is_none());
|
||||
assert_eq!(
|
||||
response.headers()["x-codex-turn-state"],
|
||||
"retained-turn-state"
|
||||
|
||||
@@ -369,23 +369,25 @@ async fn classified_capacity_error_without_special_code_returns_retryable_websoc
|
||||
|
||||
#[tokio::test]
|
||||
async fn final_failure_headers_take_precedence_over_observed_opening_headers() {
|
||||
let provider = upstream_failure(403, b"", vec![header("x-oai-request-id", b"req_final")])
|
||||
.with_status(502)
|
||||
.with_upstream_request_id(OpaqueUpstreamValue::new("req_stale_fact"));
|
||||
let error = initial_error(
|
||||
EngineError::Provider(provider),
|
||||
vec![
|
||||
header("x-request-id", b"req_old_opening"),
|
||||
header("x-codex-turn-state", b"old-turn-state"),
|
||||
],
|
||||
)
|
||||
.await;
|
||||
assert_eq!(error["status"], 403);
|
||||
assert_eq!(error["headers"]["x-oai-request-id"], "req_final");
|
||||
assert!(error["headers"].get("x-request-id").is_none());
|
||||
assert!(!error.to_string().contains("req_old_opening"));
|
||||
assert!(!error.to_string().contains("req_stale_fact"));
|
||||
assert!(!error.to_string().contains("old-turn-state"));
|
||||
for name in ["x-oai-request-id", "x-openai-request-id", "x-ms-request-id"] {
|
||||
let provider = upstream_failure(403, b"", vec![header(name, b"req_final")])
|
||||
.with_status(502)
|
||||
.with_upstream_request_id(OpaqueUpstreamValue::new("req_stale_fact"));
|
||||
let error = initial_error(
|
||||
EngineError::Provider(provider),
|
||||
vec![
|
||||
header("x-request-id", b"req_old_opening"),
|
||||
header("x-codex-turn-state", b"old-turn-state"),
|
||||
],
|
||||
)
|
||||
.await;
|
||||
assert_eq!(error["status"], 403);
|
||||
assert_eq!(error["headers"][name], "req_final");
|
||||
assert!(error["headers"].get("x-request-id").is_none());
|
||||
assert!(!error.to_string().contains("req_old_opening"));
|
||||
assert!(!error.to_string().contains("req_stale_fact"));
|
||||
assert!(!error.to_string().contains("old-turn-state"));
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -398,6 +400,8 @@ async fn provider_failure_facts_survive_without_a_complete_http_response() {
|
||||
vec![
|
||||
header("x-request-id", b"req_old"),
|
||||
header("x-oai-request-id", b"req_old_alias"),
|
||||
header("x-openai-request-id", b"req_old_openai"),
|
||||
header("x-ms-request-id", b"req_old_ms"),
|
||||
header("x-codex-turn-state", b"observed-turn-state"),
|
||||
],
|
||||
)
|
||||
@@ -409,9 +413,11 @@ async fn provider_failure_facts_survive_without_a_complete_http_response() {
|
||||
"observed-turn-state"
|
||||
);
|
||||
assert!(error["headers"].get("x-oai-request-id").is_none());
|
||||
assert!(error["headers"].get("x-openai-request-id").is_none());
|
||||
assert!(error["headers"].get("x-ms-request-id").is_none());
|
||||
assert_eq!(
|
||||
error["error"]["message"],
|
||||
"Upstream service is unavailable."
|
||||
"Communication with the upstream service failed."
|
||||
);
|
||||
}
|
||||
|
||||
@@ -511,6 +517,8 @@ async fn opening_ids_stay_in_metadata_but_do_not_identify_initial_failures() {
|
||||
vec![
|
||||
header("x-request-id", b"req_old_opening"),
|
||||
header("x-oai-request-id", b"req_observed"),
|
||||
header("x-openai-request-id", b"req_observed_openai"),
|
||||
header("x-ms-request-id", b"req_observed_ms"),
|
||||
header("x-codex-turn-state", b"observed-turn-state"),
|
||||
header("x-future-header", b"future-value"),
|
||||
],
|
||||
@@ -525,6 +533,8 @@ async fn opening_ids_stay_in_metadata_but_do_not_identify_initial_failures() {
|
||||
"headers": {
|
||||
"x-request-id": "req_old_opening",
|
||||
"x-oai-request-id": "req_observed",
|
||||
"x-openai-request-id": "req_observed_openai",
|
||||
"x-ms-request-id": "req_observed_ms",
|
||||
"x-codex-turn-state": "observed-turn-state",
|
||||
"x-future-header": "future-value",
|
||||
},
|
||||
@@ -548,6 +558,46 @@ async fn opening_ids_stay_in_metadata_but_do_not_identify_initial_failures() {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn metadata_prefers_readable_upstream_aliases_before_the_model_id() {
|
||||
let cases: &[(&str, &[u8], Option<&str>)] = &[
|
||||
("x-oai-request-id", b"req_oai", Some("req_oai")),
|
||||
("X-OpenAI-Request-ID", b"req_openai", Some("req_openai")),
|
||||
("x-ms-request-id", b"req_ms", Some("req_ms")),
|
||||
("x-ms-request-id", b" \t ", None),
|
||||
("x-ms-request-id", b"\xc3\xa9", None),
|
||||
];
|
||||
for (name, value, expected) in cases {
|
||||
let trace = Arc::new(AtomicFailureTrace {
|
||||
initial_errors: Mutex::new(VecDeque::from([EngineError::Deadline])),
|
||||
..AtomicFailureTrace::default()
|
||||
});
|
||||
let (mut socket, _server) = connect(
|
||||
Arc::clone(&trace),
|
||||
vec![header("x-request-id", b"\xff"), header(name, value)],
|
||||
)
|
||||
.await;
|
||||
send_request(&mut socket).await;
|
||||
let metadata = next_event(&mut socket).await;
|
||||
assert_eq!(metadata["type"], "response.metadata");
|
||||
let model_id = trace.prepared_request_id.lock().unwrap().clone().unwrap();
|
||||
assert_eq!(
|
||||
metadata["headers"]["x-request-id"],
|
||||
expected.unwrap_or(&model_id)
|
||||
);
|
||||
assert_eq!(
|
||||
metadata["headers"][name.to_ascii_lowercase()].as_str(),
|
||||
*expected
|
||||
);
|
||||
let error = next_event(&mut socket).await;
|
||||
assert_eq!(error["type"], "error");
|
||||
assert_eq!(error["headers"]["x-request-id"], "req_ws_atomic");
|
||||
assert_eq!(error["headers"]["x-gateway-request-id"], "req_ws_atomic");
|
||||
assert!(error["headers"].get(name.to_ascii_lowercase()).is_none());
|
||||
socket.close(None).await.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn header_only_request_middleware_updates_websocket_turn_context() {
|
||||
let middleware = Arc::new(crate::data_plane::middleware::RequestMiddleware {
|
||||
@@ -746,13 +796,38 @@ async fn initial_continuation_recovery_delivers_the_official_client_replay_signa
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn locally_exhausted_account_pool_sends_one_official_usage_limit_error() {
|
||||
let provider = ProviderError::new(
|
||||
async fn account_selection_errors_distinguish_quota_from_websocket_requirements() {
|
||||
let exhausted = ProviderError::new(
|
||||
ProviderErrorKind::AccountPoolQuotaExhausted,
|
||||
UpstreamSendState::NotSent,
|
||||
);
|
||||
let error = initial_error(EngineError::Provider(provider), Vec::new()).await;
|
||||
assert_eq!(error["status"], 429);
|
||||
assert_eq!(error["error"]["type"], "usage_limit_reached");
|
||||
assert_eq!(error["error"]["code"], "usage_limit_reached");
|
||||
let incompatible = ProviderError::new(
|
||||
ProviderErrorKind::NoEligibleAccount,
|
||||
UpstreamSendState::NotSent,
|
||||
)
|
||||
.with_client_visible_upstream_error(ClientVisibleUpstreamError::new(
|
||||
"This request requires an upstream WebSocket.",
|
||||
Some("websocket_account_unavailable".to_owned()),
|
||||
None,
|
||||
));
|
||||
for (provider, status, kind, code) in [
|
||||
(exhausted, 429, "usage_limit_reached", "usage_limit_reached"),
|
||||
(
|
||||
incompatible,
|
||||
503,
|
||||
"server_error",
|
||||
"websocket_account_unavailable",
|
||||
),
|
||||
] {
|
||||
let error = initial_error(EngineError::Provider(provider), Vec::new()).await;
|
||||
assert_eq!(error["status"], status);
|
||||
assert_eq!(error["error"]["type"], kind);
|
||||
assert_eq!(error["error"]["code"], code);
|
||||
if status == 503 {
|
||||
assert_eq!(
|
||||
error["error"]["message"],
|
||||
"This request requires an upstream WebSocket."
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -313,6 +313,7 @@ fn response_create_should_reject_non_boolean_stream_without_disclosing_body_valu
|
||||
|
||||
#[derive(Default)]
|
||||
struct AtomicFailureTrace {
|
||||
prepared_request_id: Mutex<Option<String>>,
|
||||
starts: AtomicUsize,
|
||||
next_calls: AtomicUsize,
|
||||
committed: AtomicBool,
|
||||
@@ -414,8 +415,9 @@ struct AtomicFailureExecution {
|
||||
impl ExecutionService for AtomicFailureExecution {
|
||||
fn middleware_plan(
|
||||
&self,
|
||||
_: &gateway_core::engine::execution::PreparedRootExecution,
|
||||
prepared: &gateway_core::engine::execution::PreparedRootExecution,
|
||||
) -> Option<gateway_core::engine::middleware::FrozenMiddlewarePlan> {
|
||||
*self.trace.prepared_request_id.lock().unwrap() = Some(prepared.request_id().to_string());
|
||||
self.trace.middleware.clone()
|
||||
}
|
||||
|
||||
|
||||
@@ -255,3 +255,71 @@ async fn original_rejected_request_is_dumped_only_when_explicitly_enabled() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn responses_ingress_separates_body_receipt_from_decompression_and_decoding() {
|
||||
use std::io::Write as _;
|
||||
use tracing::instrument::WithSubscriber as _;
|
||||
|
||||
let recorder = Recorder {
|
||||
dump_enabled: false,
|
||||
events: Arc::default(),
|
||||
};
|
||||
let events = recorder.events.clone();
|
||||
let decoded = json!({"model":42,"input":"SENSITIVE_CONTENT".repeat(1024)}).to_string();
|
||||
let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast());
|
||||
encoder.write_all(decoded.as_bytes()).unwrap();
|
||||
let encoded = encoder.finish().unwrap();
|
||||
let encoded_len = encoded.len();
|
||||
assert!(encoded_len < decoded.len());
|
||||
async {
|
||||
let (router, _) = fixture().await;
|
||||
let body = Body::from_stream(futures::stream::once(async move {
|
||||
tokio::time::sleep(std::time::Duration::from_millis(40)).await;
|
||||
Ok::<_, std::io::Error>(encoded)
|
||||
}));
|
||||
let response = router
|
||||
.oneshot(
|
||||
Request::post("/v1/responses")
|
||||
.header("authorization", "Bearer unused-client-route-key")
|
||||
.header("content-encoding", "gzip")
|
||||
.body(body)
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
|
||||
}
|
||||
.with_subscriber(recorder)
|
||||
.await;
|
||||
let events = events.lock().unwrap();
|
||||
let phases = events
|
||||
.iter()
|
||||
.filter(|event| {
|
||||
event.get("stage").is_some_and(|stage| {
|
||||
stage.starts_with("http.body.") || stage == "http.auth.finished"
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(
|
||||
phases
|
||||
.iter()
|
||||
.map(|event| event["stage"].as_str())
|
||||
.collect::<Vec<_>>(),
|
||||
[
|
||||
"http.body.received",
|
||||
"http.auth.finished",
|
||||
"http.body.decompressed",
|
||||
"http.body.decoded",
|
||||
]
|
||||
);
|
||||
assert!(phases[0]["receive_ms"].parse::<u64>().unwrap() >= 30);
|
||||
assert_eq!(phases[0]["encoded_bytes"], encoded_len.to_string());
|
||||
assert_eq!(phases[0]["content_encoding"], "gzip");
|
||||
assert_eq!(phases[2]["decoded_bytes"], decoded.len().to_string());
|
||||
assert_eq!(phases[2]["accepted"], "true");
|
||||
assert_eq!(phases[3]["accepted"], "false");
|
||||
assert!(events.iter().flat_map(|event| event.values()).all(|value| {
|
||||
!value.contains("SENSITIVE_CONTENT") && !value.contains("unused-client-route-key")
|
||||
}));
|
||||
}
|
||||
@@ -91,6 +91,8 @@ impl SystemOperations for VersionSystem {
|
||||
async fn version(&self) -> Result<SystemVersion, SystemOperationError> {
|
||||
Ok(SystemVersion {
|
||||
version: "3.7.0".to_owned(),
|
||||
instance_id: "test-instance".to_owned(),
|
||||
restart_supported: true,
|
||||
git_sha: "internal-revision".to_owned(),
|
||||
build_time: "internal-build-time".to_owned(),
|
||||
deployment_mode: "binary".to_owned(),
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
//! 每日重复的账号班次与接单资格,共享请求冻结的配置快照
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{collections::BTreeMap, time::SystemTime};
|
||||
|
||||
use super::{ProviderAccountId, scope::RuntimeAccount};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct DailyShift {
|
||||
pub id: String,
|
||||
pub start: u16,
|
||||
pub end: u16,
|
||||
}
|
||||
|
||||
impl DailyShift {
|
||||
pub fn contains(&self, minute: u16) -> bool {
|
||||
if self.start < self.end {
|
||||
(self.start..self.end).contains(&minute)
|
||||
} else {
|
||||
minute >= self.start || minute < self.end
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum OffShiftSession {
|
||||
Rebind,
|
||||
#[default]
|
||||
Keep,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct SchedulePolicy {
|
||||
pub enabled: bool,
|
||||
pub off_shift_session: OffShiftSession,
|
||||
pub early_finish: bool,
|
||||
pub limit_percent: u8,
|
||||
}
|
||||
|
||||
impl Default for SchedulePolicy {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
enabled: true,
|
||||
off_shift_session: OffShiftSession::default(),
|
||||
early_finish: false,
|
||||
limit_percent: 80,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum ScheduleDuty {
|
||||
OnDuty,
|
||||
OffDuty,
|
||||
QuotaReached,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct AccountSchedules {
|
||||
pub timezone: crate::time::DeploymentTimeZone,
|
||||
pub accounts: BTreeMap<String, Vec<DailyShift>>,
|
||||
pub groups: BTreeMap<String, Vec<DailyShift>>,
|
||||
pub policy: SchedulePolicy,
|
||||
}
|
||||
|
||||
impl AccountSchedules {
|
||||
/// 没有任何班表的账号沿用默认调度;个人和所在组有任一有效时段即可在班
|
||||
pub fn duty(
|
||||
&self,
|
||||
id: &ProviderAccountId,
|
||||
account: &RuntimeAccount,
|
||||
now: SystemTime,
|
||||
daily_used_percent: Option<u8>,
|
||||
) -> Option<ScheduleDuty> {
|
||||
if !self.policy.enabled || (self.accounts.is_empty() && self.groups.is_empty()) {
|
||||
return None;
|
||||
}
|
||||
let mut sources = self
|
||||
.accounts
|
||||
.get(id.as_str())
|
||||
.into_iter()
|
||||
.chain(
|
||||
account
|
||||
.group_ids()
|
||||
.iter()
|
||||
.filter_map(|id| self.groups.get(id.as_str())),
|
||||
)
|
||||
.peekable();
|
||||
sources.peek()?;
|
||||
let minute = self.timezone.minute_of_day(now.into());
|
||||
if !sources.any(|shifts| shifts.iter().any(|shift| shift.contains(minute))) {
|
||||
return Some(ScheduleDuty::OffDuty);
|
||||
}
|
||||
if self.policy.early_finish
|
||||
&& daily_used_percent.is_some_and(|used| used >= self.policy.limit_percent)
|
||||
{
|
||||
return Some(ScheduleDuty::QuotaReached);
|
||||
}
|
||||
Some(ScheduleDuty::OnDuty)
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Provider 账号领域、持久化端口与同一 target 内的账号选择
|
||||
|
||||
pub mod duty;
|
||||
mod error;
|
||||
mod error_protection;
|
||||
pub use error_protection::*;
|
||||
|
||||
@@ -407,6 +407,7 @@ pub struct QuotaState {
|
||||
evidence: Option<QuotaEvidence>,
|
||||
observed_at: Option<SystemTime>,
|
||||
reset_at: Option<SystemTime>,
|
||||
exhaustion_deadline: Option<SystemTime>,
|
||||
limit_window_minutes: Option<u16>,
|
||||
}
|
||||
|
||||
@@ -424,6 +425,7 @@ impl QuotaState {
|
||||
evidence: None,
|
||||
observed_at: None,
|
||||
reset_at: None,
|
||||
exhaustion_deadline: None,
|
||||
limit_window_minutes: None,
|
||||
}
|
||||
}
|
||||
@@ -435,6 +437,7 @@ impl QuotaState {
|
||||
evidence: None,
|
||||
observed_at: Some(observed_at),
|
||||
reset_at: None,
|
||||
exhaustion_deadline: None,
|
||||
limit_window_minutes: None,
|
||||
}
|
||||
}
|
||||
@@ -446,6 +449,7 @@ impl QuotaState {
|
||||
evidence: None,
|
||||
observed_at: Some(observed_at),
|
||||
reset_at: None,
|
||||
exhaustion_deadline: None,
|
||||
limit_window_minutes: None,
|
||||
}
|
||||
}
|
||||
@@ -461,6 +465,7 @@ impl QuotaState {
|
||||
evidence: Some(evidence),
|
||||
observed_at: Some(observed_at),
|
||||
reset_at,
|
||||
exhaustion_deadline: None,
|
||||
limit_window_minutes: None,
|
||||
}
|
||||
}
|
||||
@@ -473,6 +478,7 @@ impl QuotaState {
|
||||
evidence: Some(QuotaEvidence::CreditsAvailable),
|
||||
observed_at: Some(observed_at),
|
||||
reset_at,
|
||||
exhaustion_deadline: None,
|
||||
limit_window_minutes: None,
|
||||
}
|
||||
}
|
||||
@@ -501,6 +507,7 @@ impl QuotaState {
|
||||
evidence,
|
||||
observed_at,
|
||||
reset_at,
|
||||
exhaustion_deadline: None,
|
||||
limit_window_minutes: None,
|
||||
})
|
||||
} else {
|
||||
@@ -528,6 +535,28 @@ impl QuotaState {
|
||||
self.reset_at
|
||||
}
|
||||
|
||||
/// 耗尽观测阻止调度的截止时间;上游重置时间仍独立保留
|
||||
#[must_use]
|
||||
pub const fn exhaustion_deadline(self) -> Option<SystemTime> {
|
||||
self.exhaustion_deadline
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn with_exhaustion_deadline(mut self, deadline: Option<SystemTime>) -> Self {
|
||||
if self.is_exhausted() || self.evidence == Some(QuotaEvidence::CreditsAvailable) {
|
||||
self.exhaustion_deadline = deadline;
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn is_exhausted_at(self, now: SystemTime) -> bool {
|
||||
self.is_exhausted()
|
||||
&& self
|
||||
.exhaustion_deadline
|
||||
.is_none_or(|deadline| now < deadline)
|
||||
}
|
||||
|
||||
/// 本次上游用量拒绝明确指出的窗口时长
|
||||
#[must_use]
|
||||
pub const fn limit_window_minutes(self) -> Option<u16> {
|
||||
@@ -542,9 +571,7 @@ impl QuotaState {
|
||||
self
|
||||
}
|
||||
|
||||
/// 返回当前已确认的额度耗尽结论
|
||||
///
|
||||
/// `reset_at` 只表示何时应重新向 Provider 求证;时间到期本身不是额度恢复证据
|
||||
/// 返回最近观测的耗尽结论,选号使用带时间判断的有效状态
|
||||
#[must_use]
|
||||
pub fn is_exhausted(self) -> bool {
|
||||
self.access == QuotaAccessState::Exhausted
|
||||
@@ -552,13 +579,13 @@ impl QuotaState {
|
||||
|
||||
/// 判断已耗尽额度是否到达 Provider 的下一次复核时间
|
||||
///
|
||||
/// 有明确 `reset_at` 时严格等待该时刻;没有时由 Provider 传入自己的保守复核周期
|
||||
/// 优先使用耗尽截止时间,其次使用上游重置时间,缺省时按观测时间和复核周期计算
|
||||
#[must_use]
|
||||
pub fn exhaustion_refresh_due(self, now: SystemTime, fallback_interval: Duration) -> bool {
|
||||
if !self.is_exhausted() {
|
||||
return false;
|
||||
}
|
||||
let due_at = self.reset_at.or_else(|| {
|
||||
let due_at = self.exhaustion_deadline.or(self.reset_at).or_else(|| {
|
||||
self.observed_at
|
||||
.and_then(|observed_at| observed_at.checked_add(fallback_interval))
|
||||
});
|
||||
@@ -777,7 +804,7 @@ pub fn resolve_account_status(
|
||||
cooldown: None,
|
||||
};
|
||||
}
|
||||
if facts.quota.is_exhausted() {
|
||||
if facts.quota.is_exhausted_at(now) {
|
||||
return status_projection(AccountStatus::QuotaExhausted);
|
||||
}
|
||||
if facts
|
||||
@@ -1316,6 +1343,7 @@ pub struct CredentialCasUpdateParts {
|
||||
pub expected_revision: CredentialRevision,
|
||||
pub profile: ProviderAccountUpdate,
|
||||
pub preserve_profile: bool,
|
||||
pub preserve_catalog_etag: Option<String>,
|
||||
pub preserve_access_token_expiry: bool,
|
||||
pub credential: PlaintextCredential,
|
||||
pub has_refresh_token: bool,
|
||||
@@ -1331,6 +1359,7 @@ pub struct CredentialCasUpdate {
|
||||
expected_revision: CredentialRevision,
|
||||
profile: ProviderAccountUpdate,
|
||||
preserve_profile: bool,
|
||||
preserve_catalog_etag: Option<String>,
|
||||
preserve_access_token_expiry: bool,
|
||||
credential: PlaintextCredential,
|
||||
has_refresh_token: bool,
|
||||
@@ -1386,6 +1415,7 @@ impl CredentialCasUpdate {
|
||||
expected_revision,
|
||||
profile,
|
||||
preserve_profile: false,
|
||||
preserve_catalog_etag: None,
|
||||
preserve_access_token_expiry: false,
|
||||
credential,
|
||||
has_refresh_token,
|
||||
@@ -1402,6 +1432,13 @@ impl CredentialCasUpdate {
|
||||
self
|
||||
}
|
||||
|
||||
/// 同一身份续期只续接旧版本、当前套餐和指定标识均匹配的目录
|
||||
#[must_use]
|
||||
pub fn with_preserved_catalog_etag(mut self, etag: Option<String>) -> Self {
|
||||
self.preserve_catalog_etag = etag;
|
||||
self
|
||||
}
|
||||
|
||||
/// 沿用同一访问令牌时,保留提交时的有效期,避免覆盖在途收到的撤销事实
|
||||
#[must_use]
|
||||
pub const fn preserving_access_token_expiry(mut self) -> Self {
|
||||
@@ -1475,6 +1512,7 @@ impl CredentialCasUpdate {
|
||||
expected_revision: self.expected_revision,
|
||||
profile: self.profile,
|
||||
preserve_profile: self.preserve_profile,
|
||||
preserve_catalog_etag: self.preserve_catalog_etag,
|
||||
preserve_access_token_expiry: self.preserve_access_token_expiry,
|
||||
credential: self.credential,
|
||||
has_refresh_token: self.has_refresh_token,
|
||||
@@ -1503,6 +1541,8 @@ pub struct QuotaObservationVersion {
|
||||
/// Provider quota 的一次完整观察结果
|
||||
#[derive(Clone, PartialEq)]
|
||||
pub struct QuotaObservation {
|
||||
/// 合并旧快照时校验读取的版本,独立观测不需要基准版本
|
||||
pub merge_base: Option<super::QuotaMergeBase>,
|
||||
/// 本地阈值决策与观测一起写入,策略已变时拒绝旧结论
|
||||
pub quota_pause: Option<super::QuotaPauseDecision>,
|
||||
/// 网络查询可额外校验请求出口与启用状态,避免连接变化后的迟到写入
|
||||
|
||||
@@ -94,8 +94,6 @@ pub struct QuotaMergeBase {
|
||||
/// 此次判断依据的策略,以及是否有通用窗口触发暂停
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct QuotaPauseDecision {
|
||||
/// 独立观测无需合并,依赖旧快照的判断必须随写入校验版本
|
||||
pub merge_base: Option<QuotaMergeBase>,
|
||||
pub limits: AccountQuotaSettings,
|
||||
pub paused: bool,
|
||||
}
|
||||
@@ -104,10 +104,12 @@ impl RuntimeAccount {
|
||||
/// 全快照共享的账号、Provider 与分组反向索引
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct RuntimeAccountDirectory {
|
||||
pub schedules: super::duty::AccountSchedules,
|
||||
accounts: BTreeMap<ProviderAccountId, RuntimeAccount>,
|
||||
providers_with_accounts: BTreeSet<ProviderKind>,
|
||||
providers_by_group: BTreeMap<AccountGroupId, BTreeSet<ProviderKind>>,
|
||||
group_model_access: BTreeMap<AccountGroupId, AccountModelAccess>,
|
||||
group_fast_modes: BTreeMap<AccountGroupId, FastMode>,
|
||||
}
|
||||
|
||||
impl RuntimeAccountDirectory {
|
||||
@@ -125,10 +127,12 @@ impl RuntimeAccountDirectory {
|
||||
}
|
||||
}
|
||||
Self {
|
||||
schedules: Default::default(),
|
||||
accounts,
|
||||
providers_with_accounts,
|
||||
providers_by_group,
|
||||
group_model_access: BTreeMap::new(),
|
||||
group_fast_modes: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -141,6 +145,18 @@ impl RuntimeAccountDirectory {
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn with_schedules(mut self, schedules: super::duty::AccountSchedules) -> Self {
|
||||
self.schedules = schedules;
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn with_group_fast_modes(mut self, policies: BTreeMap<AccountGroupId, FastMode>) -> Self {
|
||||
self.group_fast_modes = policies;
|
||||
self
|
||||
}
|
||||
|
||||
pub(crate) fn accounts_in_group(
|
||||
&self,
|
||||
group: &AccountGroupId,
|
||||
@@ -288,7 +304,7 @@ impl ClientRoutingScope {
|
||||
pub struct FrozenAccountScope {
|
||||
allow_image_generation: bool,
|
||||
allow_subagents: bool,
|
||||
fast_mode: FastMode,
|
||||
fast_mode_override: Option<FastMode>,
|
||||
request_profiles: BTreeMap<ProviderKind, super::OpaqueProviderData>,
|
||||
directory: Arc<RuntimeAccountDirectory>,
|
||||
client_scope: ClientRoutingScope,
|
||||
@@ -355,16 +371,34 @@ impl FrozenAccountScope {
|
||||
self
|
||||
}
|
||||
|
||||
/// Key 绑定分组的冻结 Fast 策略,与账号成员资格无关
|
||||
/// 显式请求覆盖独立于分组策略;None 表示按选中账号的有效分组计算
|
||||
#[must_use]
|
||||
pub const fn with_fast_mode(mut self, fast_mode: FastMode) -> Self {
|
||||
self.fast_mode = fast_mode;
|
||||
pub const fn with_fast_mode_override(mut self, fast_mode: Option<FastMode>) -> Self {
|
||||
self.fast_mode_override = fast_mode;
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn fast_mode(&self) -> FastMode {
|
||||
self.fast_mode
|
||||
pub const fn fast_mode_override(&self) -> Option<FastMode> {
|
||||
self.fast_mode_override
|
||||
}
|
||||
|
||||
/// 只合并当前 Key 授权该账号与模型的启用分组,换号仍使用同一冻结目录
|
||||
#[must_use]
|
||||
pub fn fast_mode_for_account(
|
||||
&self,
|
||||
account_id: &ProviderAccountId,
|
||||
upstream_model: &str,
|
||||
) -> FastMode {
|
||||
if let Some(mode) = self.fast_mode_override {
|
||||
return mode;
|
||||
}
|
||||
let Some(account) = self.directory.account(account_id) else {
|
||||
return FastMode::Default;
|
||||
};
|
||||
self.matching_groups(account, |access| access.allows(upstream_model))
|
||||
.filter_map(|id| self.directory.group_fast_modes.get(id))
|
||||
.fold(FastMode::Default, |mode, other| mode.merge(*other))
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
@@ -376,7 +410,7 @@ impl FrozenAccountScope {
|
||||
Self {
|
||||
allow_image_generation: true,
|
||||
allow_subagents: true,
|
||||
fast_mode: FastMode::Default,
|
||||
fast_mode_override: None,
|
||||
request_profiles: BTreeMap::new(),
|
||||
directory,
|
||||
client_scope,
|
||||
@@ -460,18 +494,31 @@ impl FrozenAccountScope {
|
||||
}
|
||||
match &self.client_scope {
|
||||
ClientRoutingScope::AllAccounts => true,
|
||||
ClientRoutingScope::Restricted { .. } => {
|
||||
self.matching_groups(account, accepts).next().is_some()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn matching_groups<'a>(
|
||||
&'a self,
|
||||
account: &'a RuntimeAccount,
|
||||
accepts: impl Fn(&AccountModelAccess) -> bool + 'a,
|
||||
) -> impl Iterator<Item = &'a AccountGroupId> {
|
||||
let enabled = match &self.client_scope {
|
||||
ClientRoutingScope::AllAccounts => None,
|
||||
ClientRoutingScope::Restricted {
|
||||
enabled_group_ids, ..
|
||||
} => account
|
||||
.group_ids()
|
||||
.intersection(enabled_group_ids)
|
||||
.any(|id| {
|
||||
self.directory
|
||||
.group_model_access
|
||||
.get(id)
|
||||
.is_none_or(&accepts)
|
||||
}),
|
||||
}
|
||||
} => Some(enabled_group_ids),
|
||||
};
|
||||
account.group_ids().iter().filter(move |id| {
|
||||
enabled.is_some_and(|groups| groups.contains(*id))
|
||||
&& self
|
||||
.directory
|
||||
.group_model_access
|
||||
.get(*id)
|
||||
.is_none_or(&accepts)
|
||||
})
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
|
||||
@@ -261,6 +261,7 @@ pub struct AccountRuntimeSignals {
|
||||
pub recent_requests: u64,
|
||||
pub last_started_at: Option<SystemTime>,
|
||||
pub quota_reset_at: Option<SystemTime>,
|
||||
pub daily_used_percent: Option<u8>,
|
||||
pub quota_reset_windows: Option<Arc<[AccountQuotaResetWindow]>>,
|
||||
/// Provider 归一化的剩余额度基点:0 耗尽,10_000 全部可用
|
||||
pub quota_remaining_rank: Option<u64>,
|
||||
@@ -549,6 +550,7 @@ impl AccountRuntimeSignals {
|
||||
pub fn with_provider_quota(mut self, quota: Option<AccountQuotaSignals>) -> Self {
|
||||
if let Some(quota) = quota {
|
||||
self.quota_reset_at = quota.reset_at;
|
||||
self.daily_used_percent = quota.daily_used_percent();
|
||||
self.quota_reset_windows = quota.reset_windows;
|
||||
self.quota_remaining_rank = quota.remaining_rank;
|
||||
}
|
||||
@@ -583,6 +585,7 @@ pub struct AccountQuotaResetWindow {
|
||||
/// Provider 从私有 quota JSON 投影出的中立调度事实
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct AccountQuotaSignals {
|
||||
daily_used_percent: Option<u8>,
|
||||
reset_windows: Option<Arc<[AccountQuotaResetWindow]>>,
|
||||
reset_at: Option<SystemTime>,
|
||||
remaining_rank: Option<u64>,
|
||||
@@ -595,10 +598,22 @@ impl AccountQuotaSignals {
|
||||
Self {
|
||||
reset_at,
|
||||
remaining_rank,
|
||||
daily_used_percent: None,
|
||||
reset_windows: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn daily_used_percent(&self) -> Option<u8> {
|
||||
self.daily_used_percent
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn with_daily_used_percent(mut self, percent: Option<u8>) -> Self {
|
||||
self.daily_used_percent = percent;
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn with_reset_windows(mut self, windows: Vec<AccountQuotaResetWindow>) -> Self {
|
||||
self.reset_windows = (!windows.is_empty()).then(|| windows.into());
|
||||
@@ -664,6 +679,8 @@ pub struct AccountSelectionContext {
|
||||
/// 租约争用或队列让位只阻止立即选号,不排除等待资格
|
||||
pub busy_accounts: BTreeSet<ProviderAccountId>,
|
||||
pub preferred_account: Option<ProviderAccountId>,
|
||||
/// 经会话绑定或原生续接验证的账号,缓存偏好不能作为旧会话凭据
|
||||
pub bound_session_account: Option<ProviderAccountId>,
|
||||
/// 优先账号可调度时,是否优先于其它账号的持久权重
|
||||
pub preferred_account_overrides_weight: bool,
|
||||
pub round_robin_cursor: u64,
|
||||
@@ -674,6 +691,50 @@ pub struct AccountSelectionContext {
|
||||
}
|
||||
|
||||
impl AccountSelectionContext {
|
||||
fn off_shift_policy(
|
||||
&self,
|
||||
candidate: &AccountCandidate,
|
||||
) -> Option<super::duty::OffShiftSession> {
|
||||
let directory = self.account_scope.as_ref()?.directory();
|
||||
let id = candidate.account.id();
|
||||
let schedules = &directory.schedules;
|
||||
schedules
|
||||
.duty(
|
||||
id,
|
||||
directory.account(id)?,
|
||||
self.now,
|
||||
candidate.signals.daily_used_percent,
|
||||
)
|
||||
.filter(|duty| *duty != super::duty::ScheduleDuty::OnDuty)
|
||||
.map(|_| schedules.policy.off_shift_session)
|
||||
}
|
||||
|
||||
pub fn allows_shift(&self, candidate: &AccountCandidate) -> bool {
|
||||
match self.off_shift_policy(candidate) {
|
||||
None => true,
|
||||
Some(super::duty::OffShiftSession::Keep) => {
|
||||
self.bound_session_account.as_ref() == Some(candidate.account.id())
|
||||
}
|
||||
Some(super::duty::OffShiftSession::Rebind) => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// 下班后选择沿用原账号时,已有绑定优先于一般亲和与权重,健康和并发仍由共用资格判断约束
|
||||
pub fn prefer_retained_shift_owner(&mut self, candidates: &[AccountCandidate]) {
|
||||
if self.eligibility.bypasses_local_eligibility() {
|
||||
return;
|
||||
}
|
||||
let Some(id) = &self.bound_session_account else {
|
||||
return;
|
||||
};
|
||||
if let Some(candidate) = candidates.iter().find(|c| c.account.id() == id)
|
||||
&& self.off_shift_policy(candidate) == Some(super::duty::OffShiftSession::Keep)
|
||||
{
|
||||
self.preferred_account = Some(id.clone());
|
||||
self.preferred_account_overrides_weight = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// 本请求在该账号上可使用的并发上限;资格判断、租约与策略投影必须共用这一口径
|
||||
#[must_use]
|
||||
pub fn concurrency_limit(&self, candidate: &AccountCandidate) -> AccountConcurrency {
|
||||
@@ -1030,7 +1091,7 @@ impl AccountSelector {
|
||||
.account
|
||||
.status_projection(context.now, candidate.signals.cooldown)
|
||||
.status;
|
||||
if status != AccountStatus::Normal {
|
||||
if status != AccountStatus::Normal || !context.allows_shift(candidate) {
|
||||
return Some(AccountSchedulingBlocker::LocalAvailability);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1200,7 +1200,6 @@ where
|
||||
.with_lease_metadata(Arc::clone(&self.lease_metadata))
|
||||
.with_response_control(self.response_control.clone())
|
||||
.with_request_profile(self.request_profiles.get(candidate.provider()).cloned())
|
||||
.with_fast_mode(self.plan.fast_mode())
|
||||
.with_prompt_rewrite_rules(self.plan.prompt_rewrite_rules(candidate.provider()))
|
||||
.with_pricing(self.plan.pricing())
|
||||
.with_request_location(self.plan.request_location().cloned())
|
||||
|
||||
@@ -48,11 +48,17 @@ pub(super) fn map_routing_error(error: crate::validation::RoutingError) -> Gatew
|
||||
"Mapped model unavailable for this API key. Check the model mapping."
|
||||
},
|
||||
),
|
||||
crate::validation::RoutingError::NoCapableProvider { .. }
|
||||
| crate::validation::RoutingError::NoCapableProviderEndpoint { .. }
|
||||
| crate::validation::RoutingError::EmptyAccountScope => GatewayError::new(
|
||||
crate::validation::RoutingError::NoCapableProvider { .. } => GatewayError::new(
|
||||
GatewayErrorKind::NoAvailableProvider,
|
||||
"The gateway has no eligible provider for this request.",
|
||||
"The gateway cannot select a provider for this model and the requested capabilities.",
|
||||
),
|
||||
crate::validation::RoutingError::NoCapableProviderEndpoint { .. } => GatewayError::new(
|
||||
GatewayErrorKind::NoAvailableProvider,
|
||||
"No eligible provider is available for the requested API endpoint.",
|
||||
),
|
||||
crate::validation::RoutingError::EmptyAccountScope => GatewayError::new(
|
||||
GatewayErrorKind::NoAvailableProvider,
|
||||
"This API key has no accounts in its scope. Add accounts or check its enabled account groups.",
|
||||
),
|
||||
crate::validation::RoutingError::UnsupportedProviderEndpoint { .. } => GatewayError::new(
|
||||
GatewayErrorKind::Unsupported,
|
||||
|
||||
@@ -330,7 +330,6 @@ pub struct RequestAttemptContext {
|
||||
prompt_rewrite_rules: Option<Arc<crate::settings::prompt_rewrite::ProviderPromptRules>>,
|
||||
pricing: Arc<crate::metering::PricingOverrides>,
|
||||
request_profile: Option<crate::account::OpaqueProviderData>,
|
||||
fast_mode: FastMode,
|
||||
openai_websocket_pool: crate::settings::OpenAiWebSocketPoolSettings,
|
||||
openai_request_settings: crate::settings::OpenAiRequestSettings,
|
||||
request_location: Option<crate::account::RequestLocation>,
|
||||
@@ -424,12 +423,6 @@ impl RequestAttemptContext {
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn with_fast_mode(mut self, fast_mode: FastMode) -> Self {
|
||||
self.fast_mode = fast_mode;
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn with_privacy(
|
||||
mut self,
|
||||
@@ -478,7 +471,6 @@ impl RequestAttemptContext {
|
||||
request_profile: None,
|
||||
prompt_rewrite_rules: None,
|
||||
pricing: Arc::default(),
|
||||
fast_mode: FastMode::Default,
|
||||
openai_websocket_pool: Default::default(),
|
||||
openai_request_settings: Default::default(),
|
||||
request_location: None,
|
||||
@@ -743,8 +735,14 @@ impl AttemptContext {
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn fast_mode(&self) -> FastMode {
|
||||
self.request.fast_mode
|
||||
pub fn fast_mode_for_account(
|
||||
&self,
|
||||
account: &ProviderAccountId,
|
||||
upstream_model: &str,
|
||||
) -> FastMode {
|
||||
self.account_scope().map_or(FastMode::Default, |scope| {
|
||||
scope.fast_mode_for_account(account, upstream_model)
|
||||
})
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
|
||||
@@ -1436,14 +1436,14 @@ impl GatewayError {
|
||||
pub(crate) const fn concurrency_queue_full() -> Self {
|
||||
Self::new(
|
||||
GatewayErrorKind::ConcurrencyQueueFull,
|
||||
"The gateway request queue is full.",
|
||||
"The gateway concurrency queue is full.",
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) const fn concurrency_queue_timeout() -> Self {
|
||||
Self::new(
|
||||
GatewayErrorKind::ConcurrencyQueueTimeout,
|
||||
"The request timed out in the gateway queue.",
|
||||
"Timed out waiting for available concurrency in the gateway.",
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1516,20 +1516,25 @@ impl GatewayError {
|
||||
GatewayErrorKind::Unsupported,
|
||||
"Requested capability is unsupported.",
|
||||
),
|
||||
ProviderErrorKind::Unauthorized | ProviderErrorKind::PermissionDenied => Self::new(
|
||||
ProviderErrorKind::Unauthorized => Self::new(
|
||||
GatewayErrorKind::UpstreamUnavailable,
|
||||
"The upstream account cannot access the service.",
|
||||
"Upstream account authentication failed.",
|
||||
),
|
||||
ProviderErrorKind::PermissionDenied => Self::new(
|
||||
GatewayErrorKind::UpstreamUnavailable,
|
||||
"The upstream account does not have permission for this request.",
|
||||
),
|
||||
ProviderErrorKind::RequestPolicyDenied => error.denied_group_feature.map_or_else(
|
||||
|| Self::new(GatewayErrorKind::PolicyDenied, "Request blocked by policy."),
|
||||
Self::from,
|
||||
),
|
||||
ProviderErrorKind::RateLimited => {
|
||||
Self::new(GatewayErrorKind::RateLimited, "Request rate limit reached.")
|
||||
}
|
||||
ProviderErrorKind::RateLimited => Self::new(
|
||||
GatewayErrorKind::RateLimited,
|
||||
"Upstream request rate limit reached.",
|
||||
),
|
||||
ProviderErrorKind::QuotaExhausted => Self::new(
|
||||
GatewayErrorKind::QuotaExhausted,
|
||||
"Account quota is exhausted.",
|
||||
"Upstream account quota is exhausted.",
|
||||
),
|
||||
ProviderErrorKind::AccountPoolQuotaExhausted => Self::new(
|
||||
GatewayErrorKind::AccountPoolQuotaExhausted,
|
||||
@@ -1539,7 +1544,7 @@ impl GatewayError {
|
||||
ProviderErrorKind::ConcurrencyQueueTimeout => Self::concurrency_queue_timeout(),
|
||||
ProviderErrorKind::AccountCapacityUnavailable => Self::new(
|
||||
GatewayErrorKind::AccountCapacityUnavailable,
|
||||
"The gateway account pool is busy.",
|
||||
"No eligible account currently has capacity for this request.",
|
||||
),
|
||||
ProviderErrorKind::NoEligibleAccount => Self::new(
|
||||
GatewayErrorKind::NoAvailableProvider,
|
||||
@@ -1559,16 +1564,33 @@ impl GatewayError {
|
||||
ProviderErrorKind::Cancelled => {
|
||||
Self::new(GatewayErrorKind::Cancelled, "Request was cancelled.")
|
||||
}
|
||||
ProviderErrorKind::Transport
|
||||
| ProviderErrorKind::Protocol
|
||||
| ProviderErrorKind::Unavailable
|
||||
| ProviderErrorKind::UpstreamCapacityUnavailable
|
||||
| ProviderErrorKind::ProcessTerminated => Self::new(
|
||||
ProviderErrorKind::Transport => Self::new(
|
||||
GatewayErrorKind::UpstreamUnavailable,
|
||||
"Communication with the upstream service failed.",
|
||||
),
|
||||
ProviderErrorKind::Protocol => Self::new(
|
||||
GatewayErrorKind::UpstreamUnavailable,
|
||||
"Upstream protocol handling failed.",
|
||||
),
|
||||
ProviderErrorKind::ProcessTerminated => Self::new(
|
||||
GatewayErrorKind::UpstreamUnavailable,
|
||||
"The gateway stopped before the request completed.",
|
||||
),
|
||||
ProviderErrorKind::UpstreamCapacityUnavailable => Self::new(
|
||||
GatewayErrorKind::UpstreamUnavailable,
|
||||
"The upstream service has no capacity for this request.",
|
||||
),
|
||||
ProviderErrorKind::Unavailable => Self::new(
|
||||
GatewayErrorKind::UpstreamUnavailable,
|
||||
"Upstream service is unavailable.",
|
||||
),
|
||||
};
|
||||
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
|
||||
|
||||
@@ -5,6 +5,7 @@ use std::sync::{Arc, OnceLock};
|
||||
use std::time::{Duration, SystemTime};
|
||||
|
||||
use event_listener::Event;
|
||||
use futures::FutureExt as _;
|
||||
use futures::future::{BoxFuture, pending};
|
||||
use futures_timer::Delay;
|
||||
|
||||
@@ -142,6 +143,14 @@ impl CancellationToken {
|
||||
self.reason().is_some()
|
||||
}
|
||||
|
||||
/// 取消优先于同时就绪的工作,只用于可安全丢弃的 future
|
||||
pub async fn run_until_cancelled<T>(&self, work: impl Future<Output = T>) -> Option<T> {
|
||||
futures::select_biased! {
|
||||
() = self.cancelled().fuse() => None,
|
||||
result = work.fuse() => Some(result),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn cancelled(&self) {
|
||||
if self.is_cancelled() {
|
||||
return;
|
||||
|
||||
@@ -158,7 +158,7 @@ impl RateLimits {
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ClientSettings {
|
||||
pub request_profiles: BTreeMap<ProviderKind, OpaqueProviderData>,
|
||||
pub fast_mode: FastMode,
|
||||
pub fast_mode_override: Option<FastMode>,
|
||||
pub limits: RateLimits,
|
||||
}
|
||||
|
||||
@@ -185,18 +185,18 @@ impl ClientPolicy {
|
||||
pub(crate) fn with_settings(
|
||||
mut self,
|
||||
profiles: &BTreeMap<ProviderKind, OpaqueProviderData>,
|
||||
fast_mode: FastMode,
|
||||
fast_mode_override: Option<FastMode>,
|
||||
limits: RateLimits,
|
||||
) -> Self {
|
||||
if self.account_scope.request_profiles() != profiles
|
||||
|| self.account_scope.fast_mode() != fast_mode
|
||||
|| self.account_scope.fast_mode_override() != fast_mode_override
|
||||
{
|
||||
self.account_scope = Arc::new(
|
||||
self.account_scope
|
||||
.as_ref()
|
||||
.clone()
|
||||
.with_request_profiles(profiles.clone())
|
||||
.with_fast_mode(fast_mode),
|
||||
.with_fast_mode_override(fast_mode_override),
|
||||
);
|
||||
}
|
||||
self.limits = limits;
|
||||
@@ -217,7 +217,7 @@ impl ClientPolicy {
|
||||
name_snapshot: None,
|
||||
defaults: Arc::new(ClientSettings {
|
||||
request_profiles: account_scope.request_profiles().clone(),
|
||||
fast_mode: account_scope.fast_mode(),
|
||||
fast_mode_override: account_scope.fast_mode_override(),
|
||||
limits,
|
||||
}),
|
||||
key_id,
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -13,6 +13,11 @@ pub trait ProviderRuntimePolicyPort: Send + Sync {
|
||||
Box::pin(async { Ok(None) })
|
||||
}
|
||||
|
||||
/// 是否允许定时或缓存缺失时自动查询 Antigravity OAuth 账号
|
||||
fn antigravity_background_refresh(&self) -> BoxFuture<'_, Result<bool, ProviderStoreError>> {
|
||||
Box::pin(async { Ok(true) })
|
||||
}
|
||||
|
||||
/// 后台 OpenAI 操作读取当前全局请求设置
|
||||
fn load_openai_request_settings(
|
||||
&self,
|
||||
|
||||
@@ -36,6 +36,9 @@ impl<'a> ProviderSessionAffinityState<'a> {
|
||||
|
||||
/// 原生续接的固定账号由调用方优先设置,不以软亲和覆盖
|
||||
pub fn apply_preference(&self, context: &mut AccountSelectionContext) {
|
||||
if context.bound_session_account.is_none() {
|
||||
context.bound_session_account = self.bound_account().cloned();
|
||||
}
|
||||
if self.policy.account_affinity() != AccountAffinity::Relaxed
|
||||
&& context.preferred_account.is_none()
|
||||
{
|
||||
|
||||
@@ -23,7 +23,7 @@ use std::fmt;
|
||||
use std::num::{NonZeroU32, NonZeroU64};
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::account::{AccountSelectionPolicy, FastMode};
|
||||
use crate::account::AccountSelectionPolicy;
|
||||
use crate::operation::{CapabilityRequirements, Feature, OperationKind};
|
||||
use crate::validation::{IdentifierError, RoutingError, validate_text};
|
||||
|
||||
@@ -767,11 +767,6 @@ impl RoutingPlan {
|
||||
Arc::clone(&self.pricing)
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn fast_mode(&self) -> FastMode {
|
||||
self.account_scope.fast_mode()
|
||||
}
|
||||
|
||||
/// 本次请求冻结的已编译规则,重试不读取新的全局策略
|
||||
#[must_use]
|
||||
pub fn privacy(&self) -> Option<Arc<dyn crate::settings::privacy::CompiledPrivacyPolicy>> {
|
||||
|
||||
@@ -19,7 +19,8 @@ use crate::settings::{InvalidSettings, SettingsValues};
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct ExecutionSettings {
|
||||
pub runtime: SettingsValues,
|
||||
pub fast_mode: FastMode,
|
||||
/// None 按选中账号的有效分组解析;Some(Default) 显式跟随客户端
|
||||
pub fast_mode: Option<FastMode>,
|
||||
pub client_limits: RateLimits,
|
||||
/// null 表示不限制总时长;显式时限从请求开始计时,改写不重置计时原点
|
||||
pub timeout_ms: Option<u64>,
|
||||
@@ -38,7 +39,7 @@ struct ExecutionOverrides {
|
||||
defaults: Arc<ClientSettings>,
|
||||
client_key_id: String,
|
||||
input: Arc<ExecutionSettings>,
|
||||
fast_mode: Option<SettingOverride<FastMode>>,
|
||||
fast_mode: Option<SettingOverride<Option<FastMode>>>,
|
||||
client_limits: Option<SettingOverride<RateLimits>>,
|
||||
timeout_ms: Option<SettingOverride<Option<u64>>>,
|
||||
}
|
||||
@@ -186,9 +187,10 @@ impl RequestSettings {
|
||||
#[must_use]
|
||||
pub fn apply_policy(&self, policy: ClientPolicy) -> ClientPolicy {
|
||||
let values = self.resolve_execution(policy.key_id().as_str(), policy.defaults(), None);
|
||||
let fast_mode = self.fast_mode_override(policy.key_id().as_str(), policy.defaults());
|
||||
policy.with_settings(
|
||||
values.runtime.request_profiles(),
|
||||
values.fast_mode,
|
||||
fast_mode,
|
||||
values.client_limits,
|
||||
)
|
||||
}
|
||||
@@ -247,9 +249,7 @@ impl RequestSettings {
|
||||
}
|
||||
ExecutionSettings {
|
||||
runtime,
|
||||
fast_mode: overrides
|
||||
.and_then(|scope| scope.fast_mode.as_ref())
|
||||
.map_or(defaults.fast_mode, |change| change.value),
|
||||
fast_mode: self.fast_mode_override(key, defaults),
|
||||
client_limits: overrides
|
||||
.and_then(|scope| scope.client_limits.as_ref())
|
||||
.map_or(defaults.limits, |change| change.value),
|
||||
@@ -259,6 +259,15 @@ impl RequestSettings {
|
||||
}
|
||||
}
|
||||
|
||||
fn fast_mode_override(&self, key: &str, defaults: &ClientSettings) -> Option<FastMode> {
|
||||
self.execution
|
||||
.as_ref()
|
||||
.filter(|scope| scope.client_key_id == key)
|
||||
.and_then(|scope| scope.fast_mode.as_ref())
|
||||
.map(|change| change.value)
|
||||
.unwrap_or(defaults.fast_mode_override)
|
||||
}
|
||||
|
||||
pub(crate) fn execution_deadline(
|
||||
&self,
|
||||
key: &ClientApiKeyId,
|
||||
|
||||
Loaded 100 of 411 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user