mirror of
https://github.com/zyycn/codex-proxy-rs.git
synced 2026-12-03 08:01:10 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b5e691c63d | ||
|
|
2d0a52096a | ||
|
|
47620e217a | ||
|
|
48aeccd0e0 | ||
|
|
bdc618701b | ||
|
|
acd76a09dc | ||
|
|
808387442b | ||
|
|
5bc4e3e5c8 | ||
|
|
7e98130cac | ||
|
|
2821a5e3bd | ||
|
|
6a6a167d41 | ||
|
|
cffb6b35d2 | ||
|
|
17e50df06f | ||
|
|
f2d95cc3fa | ||
|
|
e4f6e1d4e3 | ||
|
|
66f650f097 | ||
|
|
ca4d02068a | ||
|
|
d185a639a9 | ||
|
|
3078dd9993 | ||
|
|
cad1a9245e | ||
|
|
d4d1114e73 | ||
|
|
9e8a5a9b61 | ||
|
|
9a5bf55bdf | ||
|
|
f57a375407 | ||
|
|
82cb91e1af | ||
|
|
441c012613 | ||
|
|
983eca5fe7 | ||
|
|
e0b0ab14da | ||
|
|
b4bb97d1dc | ||
|
|
9f979110d2 | ||
|
|
a5cddfe4a5 | ||
|
|
914c4c24d3 | ||
|
|
7251546c75 | ||
|
|
3c38925716 | ||
|
|
43ca35b027 | ||
|
|
95d545a7d8 | ||
|
|
db3324f90a | ||
|
|
30bcff3419 | ||
|
|
329503d967 | ||
|
|
eae19e211e | ||
|
|
294e9c8bd8 |
@@ -4,7 +4,9 @@
|
|||||||
|
|
||||||
## 领域必读
|
## 领域必读
|
||||||
|
|
||||||
确定页面方案或审查结论前,读取[前端职责](../../../../docs/architecture.md#34-前端模块职责)、[文案与信息层级](../../../../docs/theme.md#界面文案与信息层级)和[界面验证](../../../../CONTRIBUTING.md#界面验证)的完整章节,局部修改同样读取。明确本次用户操作、原页面、最接近的同类实现及可复用基础组件,沿用既有设计与请求层,按本轮验收分工留存所需截图
|
确定页面方案或审查结论前,读取[前端职责](../../../../docs/architecture.md#34-前端模块职责)、[文案与信息层级](../../../../docs/theme.md#界面文案与信息层级)和[界面验证](../../../../CONTRIBUTING.md#界面验证)的完整章节,局部修改同样读取。新增或移动文件时,页面与布局按同一套目录规则,根据调用范围和导出内容区分组件私有实现、共享常量和共享纯函数
|
||||||
|
|
||||||
|
明确本次用户操作、原页面、最接近的同类实现及可复用基础组件,沿用既有设计与请求层,按本轮验收分工留存所需截图
|
||||||
|
|
||||||
## 按改动补齐规范
|
## 按改动补齐规范
|
||||||
|
|
||||||
@@ -21,10 +23,15 @@
|
|||||||
|
|
||||||
普通维护和新增业务页面沿用现有设计;设计技能中的配色、字体、布局探索不覆盖项目规范,主题算法只在涉及时读取
|
普通维护和新增业务页面沿用现有设计;设计技能中的配色、字体、布局探索不覆盖项目规范,主题算法只在涉及时读取
|
||||||
|
|
||||||
|
- 页面和组件不添加浏览器原生提示的 `title` 属性。确需补充说明时,按内容复用已有的 Tooltip 或 Popover
|
||||||
|
- 列表行需要快速展示少量字段时,先核对列表接口已返回的字段和后端查询已读取的数据。能随当前页低成本返回的字段直接用于展示,完整详情在用户打开详情时加载
|
||||||
|
|
||||||
## 验收范围与收尾
|
## 验收范围与收尾
|
||||||
|
|
||||||
验证前按[界面验证](../../../../CONTRIBUTING.md#界面验证)明确本次受影响的用户路径、状态和通过条件。局部修改围绕受影响区域及相关操作验收;主题、窗口尺寸和空/加载/错误状态仅在受影响时补充,共用主题或基础组件变更按主题规范扩大范围
|
验证前按[界面验证](../../../../CONTRIBUTING.md#界面验证)明确本次受影响的用户路径、状态和通过条件。局部修改围绕受影响区域及相关操作验收;主题、窗口尺寸和空/加载/错误状态仅在受影响时补充,共用主题或基础组件变更按主题规范扩大范围
|
||||||
|
|
||||||
|
沿实际操作验证待确认、执行中、完成、失败与取消等受影响阶段,同时检查当前弹层和背景区域,核对应该出现的反馈与不应出现的状态。必要时延迟模拟响应以观察过渡状态,不能仅凭请求成功或截图齐全判定交互通过
|
||||||
|
|
||||||
通过后按[验证停止条件](../../../../CONTRIBUTING.md#验证)收尾;只有新改动、失败或未解疑点时补验相关部分。补交截图或 PR 材料时复用仍有效的运行证据
|
通过后按[验证停止条件](../../../../CONTRIBUTING.md#验证)收尾;只有新改动、失败或未解疑点时补验相关部分。补交截图或 PR 材料时复用仍有效的运行证据
|
||||||
|
|
||||||
## 交付前
|
## 交付前
|
||||||
@@ -37,7 +44,7 @@
|
|||||||
- **样式与状态**:是否使用对应 Token 与 utility,局部样式是否符合适用边界,受影响的主题、窄屏及交互状态是否正确
|
- **样式与状态**:是否使用对应 Token 与 utility,局部样式是否符合适用边界,受影响的主题、窄屏及交互状态是否正确
|
||||||
- **模块归属**从调用方核对公开入口。页面或多文件组件通过 `index.vue` 提供界面,其他页面复用整页时引用所属模块的布局入口,独立复用的业务组件按领域放置
|
- **模块归属**从调用方核对公开入口。页面或多文件组件通过 `index.vue` 提供界面,其他页面复用整页时引用所属模块的布局入口,独立复用的业务组件按领域放置
|
||||||
- **Provider 边界**涉及账号操作、身份配置或定价时,沿接口响应、控件和提交载荷追踪同一条规则。服务端决定的能力使用接口字段,Provider 专属表单解释自己的字段,多个页面共用的编辑流程只维护一份。按[前端职责](../../../../docs/architecture.md#34-前端模块职责)核对归属
|
- **Provider 边界**涉及账号操作、身份配置或定价时,沿接口响应、控件和提交载荷追踪同一条规则。服务端决定的能力使用接口字段,Provider 专属表单解释自己的字段,多个页面共用的编辑流程只维护一份。按[前端职责](../../../../docs/architecture.md#34-前端模块职责)核对归属
|
||||||
- **查询与动作**:区分首次加载、刷新、分页、单行与批量操作,核对 loading、禁用状态的影响范围;沿用请求层错误处理,不在页面叠加同一错误的提示
|
- **查询与动作**:区分首次加载、刷新、分页、单行与批量操作,明确当前动作的反馈归属及其他控件的禁用范围,避免同一动作在前后景重复显示执行反馈。待确认不等于已提交,复用交互时重新核对 loading、进度与结果的显示条件是否适用于当前动作;沿用请求层错误处理,不在页面叠加同一错误的提示
|
||||||
- **运行证据**:按界面验证核对截图与实际交互,证据对应当前实现;页面 PR 的可访问图片和 Draft 条件按该节执行
|
- **运行证据**:按界面验证核对截图与实际交互,证据对应当前实现;页面 PR 的可访问图片和 Draft 条件按该节执行
|
||||||
|
|
||||||
交付简述所复用的页面或组件、实际验证范围及缺口;环境不足时如实说明,不能仅凭构建、源码或截图推断未验证的行为
|
交付简述所复用的页面或组件、实际验证范围及缺口;环境不足时如实说明,不能仅凭构建、源码或截图推断未验证的行为
|
||||||
|
|||||||
@@ -46,7 +46,9 @@ release/publish "$release_version"
|
|||||||
|
|
||||||
- 尚未推送:补齐缺失的步骤,按入口原子推送分支和 tag
|
- 尚未推送:补齐缺失的步骤,按入口原子推送分支和 tag
|
||||||
- 已推送但未触发:使用入口提示的 dispatch 命令
|
- 已推送但未触发:使用入口提示的 dispatch 命令
|
||||||
- 已有 run:跟踪对应提交的任务,失败时重跑失败任务。构建产物保留 7 天,过期后从原 tag 重跑完整工作流
|
- Release 尚未公开时,跟踪原 run 并重跑失败任务。构建产物保留 7 天,过期后从原 tag 重跑工作流
|
||||||
|
- 正式版已公开,GitHub Latest 或镜像 `latest` 提升中断时,在已有恢复授权下执行 `gh workflow run release.yml --ref main -f tag="v$release_version" -f recover_latest=true`。任务核对公开附件、版本镜像与 tag 提交对应的镜像摘要,补齐稳定入口后同步通道表。若任一稳定入口已经指向更新版本,则保留现有入口
|
||||||
|
- 仅通道表写入失败时,确认工作流能写入 `main`,按已有授权执行 `gh workflow run release.yml --ref main -f tag="v$release_version" -f index_only=true`。各通道均可用此入口重新核对公开附件并合并通道表
|
||||||
|
|
||||||
### 修复源码后同版本重发
|
### 修复源码后同版本重发
|
||||||
|
|
||||||
@@ -60,7 +62,7 @@ release/publish "$release_version"
|
|||||||
- 发布完成后核对 GitHub Release 的版本、正式版/预发行状态和中文变更正文;对照平台清单与工作流确认归档、校验和及镜像产物。
|
- 发布完成后核对 GitHub Release 的版本、正式版/预发行状态和中文变更正文;对照平台清单与工作流确认归档、校验和及镜像产物。
|
||||||
工作流附加的安装说明和自动提交列表按其当前配置处理,不用它们替代手写的中文变更说明。
|
工作流附加的安装说明和自动提交列表按其当前配置处理,不用它们替代手写的中文变更说明。
|
||||||
- 回读 `main:release/version.yaml` 的 `published`。正式版参与同一大版本四个普通通道的比较;RC 参与 RC、Beta、Alpha,Beta 参与 Beta、Alpha,Alpha 只参与自身。实验版只推进 `exp["X.Y.Z"]`。有通道推进时应有 `chore(release): update release channels to <version>` 提交;重复执行或较旧版本未推进任何通道时无提交
|
- 回读 `main:release/version.yaml` 的 `published`。正式版参与同一大版本四个普通通道的比较;RC 参与 RC、Beta、Alpha,Beta 参与 Beta、Alpha,Alpha 只参与自身。实验版只推进 `exp["X.Y.Z"]`。有通道推进时应有 `chore(release): update release channels to <version>` 提交;重复执行或较旧版本未推进任何通道时无提交
|
||||||
- 通道表写入失败时,确认该版本已公开、工作流能写入 `main`,再按已有授权执行 `gh workflow run release.yml --ref main -f tag="v$release_version" -f index_only=true`。恢复任务重新校验公开附件、读取并合并当前清单,不重新打包或改 tag
|
- 正式版提升或恢复后,回读 GitHub Latest 的 tag 与镜像 `latest` 的摘要,核对两者均指向预期正式版
|
||||||
- 保留 v3.42.0 在线升级使用的 `update-index` 页面和 v3.42.1 的 `version.yaml` 附件
|
- 保留 v3.42.0 在线升级使用的 `update-index` 页面和 v3.42.1 的 `version.yaml` 附件
|
||||||
- 返回版本、tag 对应提交、Release/工作流链接及实际结果。失败、仍在构建或缺失产物时明确说明,不能称为发布成功;
|
- 返回版本、tag 对应提交、Release/工作流链接及实际结果。失败、仍在构建或缺失产物时明确说明,不能称为发布成功;
|
||||||
Release 和镜像已生成也不表示用户的运行实例已经升级。
|
Release 和镜像已生成也不表示用户的运行实例已经升级。
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
require_relative 'release-metadata'
|
require_relative 'published-channels'
|
||||||
|
|
||||||
# 构建和验证可以并行;调用方必须在仓库级发布锁内执行本脚本
|
# 构建和验证可以并行;调用方必须在仓库级发布锁内执行本脚本
|
||||||
module ReleasePublication
|
module ReleasePublication
|
||||||
@@ -39,44 +39,69 @@ module ReleasePublication
|
|||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def self.image_digest(ref)
|
||||||
|
digest = run('docker', 'buildx', 'imagetools', 'inspect', ref, '--format', '{{.Manifest.Digest}}')
|
||||||
|
raise "Invalid image digest for #{ref}" unless digest.match?(/\Asha256:[a-f0-9]{64}\z/)
|
||||||
|
digest
|
||||||
|
end
|
||||||
|
|
||||||
def self.tag(image, digest, name)
|
def self.tag(image, digest, name)
|
||||||
ref = "#{image}:#{name}"
|
ref = "#{image}:#{name}"
|
||||||
run('docker', 'buildx', 'imagetools', 'create', '-t', ref, "#{image}@#{digest}")
|
run('docker', 'buildx', 'imagetools', 'create', '-t', ref, "#{image}@#{digest}")
|
||||||
actual = run('docker', 'buildx', 'imagetools', 'inspect', ref, '--format', '{{.Manifest.Digest}}')
|
raise "Promoted image digest changed: #{ref}" unless image_digest(ref) == digest
|
||||||
raise "Promoted image digest changed: #{ref}" unless actual == digest
|
|
||||||
end
|
end
|
||||||
|
|
||||||
def self.publish(version:, image:, digest:, repository:, release_id:)
|
def self.publish(version:, image:, digest:, repository:, release_id:)
|
||||||
version = ReleaseMetadata.version(version)
|
version = ReleaseMetadata.release_version(version)
|
||||||
raise 'Invalid image digest' unless digest.match?(/\Asha256:[a-f0-9]{64}\z/)
|
raise 'Invalid image digest' unless digest.match?(/\Asha256:[a-f0-9]{64}\z/)
|
||||||
raise 'Invalid GitHub release ID' unless release_id.match?(/\A\d+\z/)
|
raise 'Invalid GitHub release ID' unless release_id.match?(/\A\d+\z/)
|
||||||
endpoint = "repos/#{repository}/releases/#{release_id}"
|
endpoint = "repos/#{repository}/releases/#{release_id}"
|
||||||
|
|
||||||
# 附件上传及镜像证明、签名已完成,再公开版本入口;失败可从本 job 重跑
|
# 附件、签名和证明就绪后才公开版本入口
|
||||||
tag(image, digest, version.tr('+', '-'))
|
tag(image, digest, version)
|
||||||
run('gh', 'api', '--method', 'PATCH', endpoint, '-F', 'draft=false', '-f', 'make_latest=false')
|
run('gh', 'api', '--method', 'PATCH', endpoint, '-F', 'draft=false', '-f', 'make_latest=false')
|
||||||
return if ReleaseMetadata.prerelease?(version)
|
promote_latest(version, image, digest, repository, endpoint) unless ReleaseMetadata.prerelease?(version)
|
||||||
|
end
|
||||||
|
|
||||||
current_versions = [latest_release(repository), latest_image(image)]
|
def self.recover_latest(tag:, image:, repository:, ref:)
|
||||||
|
version = ReleaseMetadata.release_version(tag)
|
||||||
|
raise 'Latest recovery requires a stable release' if ReleaseMetadata.prerelease?(version)
|
||||||
|
commit = ReleaseMetadata.tag_commit(tag, ref)
|
||||||
|
release = PublishedChannels::Publisher.new(repository).verify_assets(version)
|
||||||
|
digest = image_digest("#{image}:#{version}")
|
||||||
|
raise "Version image differs from the image built for #{commit}" unless image_digest("#{image}:sha-#{commit}") == digest
|
||||||
|
promote_latest(version, image, digest, repository, "repos/#{repository}/releases/#{release.fetch('id')}")
|
||||||
|
end
|
||||||
|
|
||||||
|
def self.promote_latest(version, image, digest, repository, endpoint)
|
||||||
|
github_latest = latest_release(repository)
|
||||||
|
docker_latest = latest_image(image)
|
||||||
|
current_versions = [github_latest, docker_latest]
|
||||||
unless can_promote?(version, current_versions)
|
unless can_promote?(version, current_versions)
|
||||||
puts "Published #{version}; latest remains at #{current_versions.compact.join(', ')}"
|
puts "Published #{version}; latest remains at #{current_versions.compact.join(', ')}"
|
||||||
return
|
return
|
||||||
end
|
end
|
||||||
|
|
||||||
# 两个服务不能原子更新;同时检查两侧版本,让失败重试可以补齐而旧版不能回退
|
# 两个服务不能原子更新;同时检查两侧版本,让失败重试可以补齐而旧版不能回退
|
||||||
tag(image, digest, 'latest')
|
tag(image, digest, 'latest') unless docker_latest == version && image_digest("#{image}:latest") == digest
|
||||||
run('gh', 'api', '--method', 'PATCH', endpoint, '-f', 'make_latest=true')
|
run('gh', 'api', '--method', 'PATCH', endpoint, '-f', 'make_latest=true') unless github_latest == "v#{version}"
|
||||||
puts "Published #{version} and promoted latest"
|
puts "Published #{version} and promoted latest"
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
if $PROGRAM_NAME == __FILE__
|
if $PROGRAM_NAME == __FILE__
|
||||||
begin
|
begin
|
||||||
ReleasePublication.publish(
|
image = "#{ENV.fetch('REGISTRY')}/#{ENV.fetch('IMAGE_NAME')}"
|
||||||
version: ENV.fetch('VERSION'), image: "#{ENV.fetch('REGISTRY')}/#{ENV.fetch('IMAGE_NAME')}",
|
repository = ENV.fetch('GITHUB_REPOSITORY')
|
||||||
digest: ENV.fetch('DIGEST'), repository: ENV.fetch('GITHUB_REPOSITORY'),
|
case ARGV
|
||||||
release_id: ENV.fetch('RELEASE_ID')
|
when []
|
||||||
)
|
ReleasePublication.publish(version: ENV.fetch('VERSION'), image: image, digest: ENV.fetch('DIGEST'),
|
||||||
|
repository: repository, release_id: ENV.fetch('RELEASE_ID'))
|
||||||
|
when ['recover-latest']
|
||||||
|
ReleasePublication.recover_latest(tag: ENV.fetch('TAG'), image: image, repository: repository, ref: ENV.fetch('GITHUB_REF'))
|
||||||
|
else
|
||||||
|
raise 'usage: publish-release.rb [recover-latest]'
|
||||||
|
end
|
||||||
rescue StandardError => error
|
rescue StandardError => error
|
||||||
warn "error: #{error.message}"
|
warn "error: #{error.message}"
|
||||||
exit 1
|
exit 1
|
||||||
|
|||||||
@@ -67,11 +67,12 @@ module PublishedChannels
|
|||||||
end
|
end
|
||||||
missing = expected - uploaded
|
missing = expected - uploaded
|
||||||
raise "Incomplete release #{tag}: #{missing.join(', ')}" unless missing.empty?
|
raise "Incomplete release #{tag}: #{missing.join(', ')}" unless missing.empty?
|
||||||
|
release
|
||||||
end
|
end
|
||||||
|
|
||||||
def check_unpublished(version)
|
def check_unpublished(version)
|
||||||
existing = find_release(version)
|
existing = find_release(version)
|
||||||
raise "Release v#{version} already public; use index-only recovery" if existing && !existing.fetch('draft')
|
raise "Release v#{version} already public; use recover_latest or index_only" if existing && !existing.fetch('draft')
|
||||||
end
|
end
|
||||||
|
|
||||||
def publish(version)
|
def publish(version)
|
||||||
|
|||||||
@@ -20,6 +20,31 @@ module ReleaseMetadata
|
|||||||
version(value).split('+', 2).first.include?('-')
|
version(value).split('+', 2).first.include?('-')
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def self.release_version(raw)
|
||||||
|
value = version(raw)
|
||||||
|
raise "Release versions cannot contain build metadata: #{raw}" if value.include?('+')
|
||||||
|
value
|
||||||
|
end
|
||||||
|
|
||||||
|
def self.validate_branch(raw, ref)
|
||||||
|
value = release_version(raw)
|
||||||
|
if value.include?('-exp.')
|
||||||
|
raise "Experimental releases require an experimental/<purpose> branch" unless ref.match?(%r{\Arefs/heads/experimental/.+\z})
|
||||||
|
elsif ref != 'refs/heads/main'
|
||||||
|
raise "Release #{value} requires the main branch"
|
||||||
|
end
|
||||||
|
value
|
||||||
|
end
|
||||||
|
|
||||||
|
# 从触发工作流的提交核对 tag,允许分支前进后重试同一发行
|
||||||
|
def self.tag_commit(tag, ref)
|
||||||
|
value = validate_branch(tag, ref)
|
||||||
|
raise "Expected release tag v#{value}" unless tag == "v#{value}"
|
||||||
|
commit = git('rev-parse', '--verify', "refs/tags/#{tag}^{commit}")
|
||||||
|
raise "#{tag} is outside #{ref}" unless git('merge-base', commit, 'HEAD') == commit
|
||||||
|
commit
|
||||||
|
end
|
||||||
|
|
||||||
def self.sort_key(value)
|
def self.sort_key(value)
|
||||||
Gem::Version.new(version(value).split('+', 2).first)
|
Gem::Version.new(version(value).split('+', 2).first)
|
||||||
end
|
end
|
||||||
@@ -67,7 +92,7 @@ module ReleaseMetadata
|
|||||||
end
|
end
|
||||||
|
|
||||||
def self.outputs(tag)
|
def self.outputs(tag)
|
||||||
value = version(YAML.load_file('release/version.yaml').fetch('version'))
|
value = release_version(YAML.load_file('release/version.yaml').fetch('version'))
|
||||||
raise "Release tag #{tag} does not match v#{value}" unless tag == "v#{value}"
|
raise "Release tag #{tag} does not match v#{value}" unless tag == "v#{value}"
|
||||||
validate_notes(value)
|
validate_notes(value)
|
||||||
entries = platforms
|
entries = platforms
|
||||||
@@ -80,7 +105,6 @@ module ReleaseMetadata
|
|||||||
{
|
{
|
||||||
'tag' => tag,
|
'tag' => tag,
|
||||||
'version' => value,
|
'version' => value,
|
||||||
'docker_version' => value.tr('+', '-'),
|
|
||||||
'build_time' => Time.now.utc.iso8601,
|
'build_time' => Time.now.utc.iso8601,
|
||||||
'git_sha' => git('rev-parse', 'HEAD'),
|
'git_sha' => git('rev-parse', 'HEAD'),
|
||||||
'platform_matrix' => JSON.generate('include' => entries),
|
'platform_matrix' => JSON.generate('include' => entries),
|
||||||
@@ -113,13 +137,16 @@ end
|
|||||||
|
|
||||||
if $PROGRAM_NAME == __FILE__
|
if $PROGRAM_NAME == __FILE__
|
||||||
begin
|
begin
|
||||||
command, value = ARGV
|
command, value, ref = ARGV
|
||||||
raise 'usage: release-metadata.rb validate VERSION | outputs TAG' unless ARGV.length == 2
|
arity = command == 'outputs' ? 2 : 3
|
||||||
|
raise 'usage: release-metadata.rb validate VERSION REF | tag-commit TAG REF | outputs TAG' unless ARGV.length == arity
|
||||||
case command
|
case command
|
||||||
when 'validate'
|
when 'validate'
|
||||||
value = ReleaseMetadata.version(value)
|
value = ReleaseMetadata.validate_branch(value, ref)
|
||||||
ReleaseMetadata.validate_notes(value)
|
ReleaseMetadata.validate_notes(value)
|
||||||
puts value
|
puts value
|
||||||
|
when 'tag-commit'
|
||||||
|
puts ReleaseMetadata.tag_commit(value, ref)
|
||||||
when 'outputs'
|
when 'outputs'
|
||||||
metadata = ReleaseMetadata.outputs(value)
|
metadata = ReleaseMetadata.outputs(value)
|
||||||
ReleaseMetadata.seal_manifest(metadata)
|
ReleaseMetadata.seal_manifest(metadata)
|
||||||
|
|||||||
@@ -11,6 +11,10 @@ on:
|
|||||||
description: 'Recover the index for an already public release without rebuilding'
|
description: 'Recover the index for an already public release without rebuilding'
|
||||||
type: boolean
|
type: boolean
|
||||||
default: false
|
default: false
|
||||||
|
recover_latest:
|
||||||
|
description: 'Recover latest and the channel index for an already public stable release'
|
||||||
|
type: boolean
|
||||||
|
default: false
|
||||||
|
|
||||||
permissions:
|
permissions:
|
||||||
contents: read
|
contents: read
|
||||||
@@ -25,7 +29,7 @@ env:
|
|||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
release-info:
|
release-info:
|
||||||
if: ${{ !inputs.index_only }}
|
if: ${{ !inputs.index_only && !inputs.recover_latest }}
|
||||||
runs-on: ubuntu-26.04
|
runs-on: ubuntu-26.04
|
||||||
timeout-minutes: 10
|
timeout-minutes: 10
|
||||||
permissions:
|
permissions:
|
||||||
@@ -34,7 +38,6 @@ jobs:
|
|||||||
outputs:
|
outputs:
|
||||||
tag: ${{ steps.version.outputs.tag }}
|
tag: ${{ steps.version.outputs.tag }}
|
||||||
version: ${{ steps.version.outputs.version }}
|
version: ${{ steps.version.outputs.version }}
|
||||||
docker_version: ${{ steps.version.outputs.docker_version }}
|
|
||||||
build_time: ${{ steps.version.outputs.build_time }}
|
build_time: ${{ steps.version.outputs.build_time }}
|
||||||
git_sha: ${{ steps.version.outputs.git_sha }}
|
git_sha: ${{ steps.version.outputs.git_sha }}
|
||||||
platform_matrix: ${{ steps.version.outputs.platform_matrix }}
|
platform_matrix: ${{ steps.version.outputs.platform_matrix }}
|
||||||
@@ -53,9 +56,15 @@ jobs:
|
|||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||||
with:
|
with:
|
||||||
ref: ${{ inputs.tag }}
|
|
||||||
fetch-depth: 0
|
fetch-depth: 0
|
||||||
|
|
||||||
|
- name: Verify release branch and check out the tagged commit
|
||||||
|
env:
|
||||||
|
RELEASE_TAG: ${{ inputs.tag }}
|
||||||
|
run: |
|
||||||
|
commit="$(ruby .github/scripts/release-metadata.rb tag-commit "$RELEASE_TAG" "$GITHUB_REF")"
|
||||||
|
git checkout --detach "$commit"
|
||||||
|
|
||||||
- name: Read release metadata and seal plugin manifest
|
- name: Read release metadata and seal plugin manifest
|
||||||
id: version
|
id: version
|
||||||
env:
|
env:
|
||||||
@@ -273,7 +282,7 @@ jobs:
|
|||||||
shell: bash
|
shell: bash
|
||||||
env:
|
env:
|
||||||
VERSION: ${{ needs.release-info.outputs.version }}
|
VERSION: ${{ needs.release-info.outputs.version }}
|
||||||
DOCKER_VERSION: ${{ needs.release-info.outputs.docker_version }}
|
DOCKER_VERSION: ${{ needs.release-info.outputs.version }}
|
||||||
PLATFORM_MATRIX: ${{ needs.release-info.outputs.platform_matrix }}
|
PLATFORM_MATRIX: ${{ needs.release-info.outputs.platform_matrix }}
|
||||||
run: ruby .github/scripts/package-release.rb archives
|
run: ruby .github/scripts/package-release.rb archives
|
||||||
|
|
||||||
@@ -443,6 +452,12 @@ jobs:
|
|||||||
username: ${{ github.actor }}
|
username: ${{ github.actor }}
|
||||||
password: ${{ secrets.GITHUB_TOKEN }}
|
password: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
|
||||||
|
- name: Check that the release is unpublished
|
||||||
|
env:
|
||||||
|
GH_TOKEN: ${{ github.token }}
|
||||||
|
VERSION: ${{ needs.release-info.outputs.version }}
|
||||||
|
run: ruby .github/scripts/published-channels.rb check "$VERSION"
|
||||||
|
|
||||||
- name: Assemble candidate image manifest
|
- name: Assemble candidate image manifest
|
||||||
id: manifest
|
id: manifest
|
||||||
shell: bash
|
shell: bash
|
||||||
@@ -507,6 +522,7 @@ jobs:
|
|||||||
- name: Prepare release notes
|
- name: Prepare release notes
|
||||||
shell: bash
|
shell: bash
|
||||||
env:
|
env:
|
||||||
|
BUILD_TYPE: ${{ needs.release-info.outputs.build_type }}
|
||||||
INSTALLATION_NOTES: |
|
INSTALLATION_NOTES: |
|
||||||
## Linux 一键安装(Docker Compose)
|
## Linux 一键安装(Docker Compose)
|
||||||
|
|
||||||
@@ -521,17 +537,11 @@ jobs:
|
|||||||
run: |
|
run: |
|
||||||
ruby <<'RUBY'
|
ruby <<'RUBY'
|
||||||
notes = File.readlines('release/notes.md').drop(1).join.strip
|
notes = File.readlines('release/notes.md').drop(1).join.strip
|
||||||
installation = ENV.fetch('INSTALLATION_NOTES').strip
|
notes += "\n\n#{ENV.fetch('INSTALLATION_NOTES').strip}" unless ENV.fetch('BUILD_TYPE') == 'experimental'
|
||||||
output = File.join(ENV.fetch('RUNNER_TEMP'), 'release-notes.md')
|
output = File.join(ENV.fetch('RUNNER_TEMP'), 'release-notes.md')
|
||||||
File.write(output, "#{notes}\n\n#{installation}\n")
|
File.write(output, "#{notes}\n")
|
||||||
RUBY
|
RUBY
|
||||||
|
|
||||||
- name: Check that the release is unpublished
|
|
||||||
env:
|
|
||||||
GH_TOKEN: ${{ github.token }}
|
|
||||||
VERSION: ${{ needs.release-info.outputs.version }}
|
|
||||||
run: ruby .github/scripts/published-channels.rb check "$VERSION"
|
|
||||||
|
|
||||||
- name: Generate release asset provenance
|
- name: Generate release asset provenance
|
||||||
uses: actions/attest@1e69f48acb82d1966a394da916b4c1698aa569d6 # v4.2.2
|
uses: actions/attest@1e69f48acb82d1966a394da916b4c1698aa569d6 # v4.2.2
|
||||||
with:
|
with:
|
||||||
@@ -542,7 +552,7 @@ jobs:
|
|||||||
uses: softprops/action-gh-release@8a0cd651e5b2365bd640854a3fa5dfc70e4875f3 # v3.0.4
|
uses: softprops/action-gh-release@8a0cd651e5b2365bd640854a3fa5dfc70e4875f3 # v3.0.4
|
||||||
with:
|
with:
|
||||||
tag_name: ${{ needs.release-info.outputs.tag }}
|
tag_name: ${{ needs.release-info.outputs.tag }}
|
||||||
generate_release_notes: true
|
generate_release_notes: ${{ needs.release-info.outputs.build_type != 'experimental' }}
|
||||||
previous_tag: ${{ needs.release-info.outputs.previous_tag }}
|
previous_tag: ${{ needs.release-info.outputs.previous_tag }}
|
||||||
prerelease: ${{ needs.release-info.outputs.prerelease == 'true' }}
|
prerelease: ${{ needs.release-info.outputs.prerelease == 'true' }}
|
||||||
# action 保留已公开 Release 的状态,新 Release 上传完成后仍保持草稿
|
# action 保留已公开 Release 的状态,新 Release 上传完成后仍保持草稿
|
||||||
@@ -567,8 +577,34 @@ jobs:
|
|||||||
VERSION: ${{ needs.release-info.outputs.version }}
|
VERSION: ${{ needs.release-info.outputs.version }}
|
||||||
run: ruby .github/scripts/published-channels.rb publish "$VERSION"
|
run: ruby .github/scripts/published-channels.rb publish "$VERSION"
|
||||||
|
|
||||||
|
recover-latest:
|
||||||
|
if: inputs.recover_latest
|
||||||
|
runs-on: ubuntu-26.04
|
||||||
|
concurrency:
|
||||||
|
group: release-publication
|
||||||
|
queue: max
|
||||||
|
permissions:
|
||||||
|
contents: write
|
||||||
|
packages: write
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
- uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1
|
||||||
|
- uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0
|
||||||
|
with:
|
||||||
|
registry: ${{ env.REGISTRY }}
|
||||||
|
username: ${{ github.actor }}
|
||||||
|
password: ${{ github.token }}
|
||||||
|
- name: Restore latest from the verified version image
|
||||||
|
env:
|
||||||
|
GH_TOKEN: ${{ github.token }}
|
||||||
|
TAG: ${{ inputs.tag }}
|
||||||
|
run: ruby .github/scripts/publish-release.rb recover-latest
|
||||||
|
|
||||||
recover-index:
|
recover-index:
|
||||||
if: inputs.index_only
|
needs: recover-latest
|
||||||
|
if: ${{ !cancelled() && (needs.recover-latest.result == 'success' || (inputs.index_only && !inputs.recover_latest)) }}
|
||||||
runs-on: ubuntu-26.04
|
runs-on: ubuntu-26.04
|
||||||
concurrency:
|
concurrency:
|
||||||
group: release-publication
|
group: release-publication
|
||||||
|
|||||||
Generated
+1
@@ -1887,6 +1887,7 @@ dependencies = [
|
|||||||
"tracing",
|
"tracing",
|
||||||
"tracing-appender",
|
"tracing-appender",
|
||||||
"tracing-subscriber",
|
"tracing-subscriber",
|
||||||
|
"uuid",
|
||||||
"wiremock",
|
"wiremock",
|
||||||
"yaml-rust2 0.13.2",
|
"yaml-rust2 0.13.2",
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -263,10 +263,11 @@ impl ScheduledTask for FreezeRecoveryTask {
|
|||||||
context: WorkerCycleContext,
|
context: WorkerCycleContext,
|
||||||
) -> futures::future::BoxFuture<'_, Result<(), WorkerTaskError>> {
|
) -> futures::future::BoxFuture<'_, Result<(), WorkerTaskError>> {
|
||||||
Box::pin(async move {
|
Box::pin(async move {
|
||||||
if context.cancellation().is_cancelled() {
|
// 中止在途探测,避免把停机当成探测失败而延长冻结
|
||||||
return Ok(());
|
context
|
||||||
}
|
.cancellation()
|
||||||
self.run_cycle_inner().await;
|
.run_until_cancelled(self.run_cycle_inner())
|
||||||
|
.await;
|
||||||
Ok(())
|
Ok(())
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -55,7 +55,7 @@ pub struct AccountImportSettings {
|
|||||||
/// 账号列表排序字段
|
/// 账号列表排序字段
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
pub enum AccountSortField {
|
pub enum AccountSortField {
|
||||||
Email,
|
Name,
|
||||||
Status,
|
Status,
|
||||||
PlanType,
|
PlanType,
|
||||||
Usage,
|
Usage,
|
||||||
|
|||||||
@@ -889,12 +889,14 @@ impl UsageErrorOrigin {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// 使用记录表格的窄读模型
|
/// 使用记录表格的窄读模型
|
||||||
#[derive(Debug, Clone, PartialEq)]
|
#[derive(Clone, PartialEq)]
|
||||||
pub struct UsageListRecord {
|
pub struct UsageListRecord {
|
||||||
pub platform_icon: Option<String>,
|
pub platform_icon: Option<String>,
|
||||||
pub outcome: RequestOutcome,
|
pub outcome: RequestOutcome,
|
||||||
/// 已保存的上游错误对象含非空字符串 code、type 或 message
|
/// 已保存的上游错误对象含非空字符串 code、type 或 message
|
||||||
pub has_upstream_error: bool,
|
pub has_upstream_error: bool,
|
||||||
|
pub upstream_error_message: Option<String>,
|
||||||
|
pub retry_after_ms: Option<u64>,
|
||||||
pub error_code: Option<String>,
|
pub error_code: Option<String>,
|
||||||
pub error_message: Option<String>,
|
pub error_message: Option<String>,
|
||||||
pub error_kind: Option<String>,
|
pub error_kind: Option<String>,
|
||||||
@@ -961,6 +963,17 @@ pub struct UsageListRecord {
|
|||||||
pub started_at: DateTime<Utc>,
|
pub started_at: DateTime<Utc>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 上游错误原文只交付给管理端,避免整行调试输出带出正文
|
||||||
|
impl std::fmt::Debug for UsageListRecord {
|
||||||
|
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
formatter
|
||||||
|
.debug_struct("UsageListRecord")
|
||||||
|
.field("id", &self.id)
|
||||||
|
.field("outcome", &self.outcome)
|
||||||
|
.finish_non_exhaustive()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// 受控请求详情中的上游错误字段,不参与错误分类或普通日志输出
|
/// 受控请求详情中的上游错误字段,不参与错误分类或普通日志输出
|
||||||
#[derive(Clone, PartialEq)]
|
#[derive(Clone, PartialEq)]
|
||||||
pub struct UsageUpstreamError {
|
pub struct UsageUpstreamError {
|
||||||
@@ -1169,6 +1182,7 @@ pub struct DiagnosticsObservation {
|
|||||||
pub struct DiagnosticObservation {
|
pub struct DiagnosticObservation {
|
||||||
pub key: String,
|
pub key: String,
|
||||||
pub name: String,
|
pub name: String,
|
||||||
|
pub account_email: Option<String>,
|
||||||
pub providers: Vec<String>,
|
pub providers: Vec<String>,
|
||||||
pub platform_icon: Option<String>,
|
pub platform_icon: Option<String>,
|
||||||
pub account_authentication_kind: Option<String>,
|
pub account_authentication_kind: Option<String>,
|
||||||
@@ -1647,6 +1661,7 @@ pub struct DiagnosticsItem {
|
|||||||
pub platform_icon: Option<String>,
|
pub platform_icon: Option<String>,
|
||||||
pub key: String,
|
pub key: String,
|
||||||
pub name: String,
|
pub name: String,
|
||||||
|
pub account_email: Option<String>,
|
||||||
pub account_authentication_kind: Option<String>,
|
pub account_authentication_kind: Option<String>,
|
||||||
pub account_plan_type: Option<String>,
|
pub account_plan_type: Option<String>,
|
||||||
/// 仅账号维度补充当前互联识别结果
|
/// 仅账号维度补充当前互联识别结果
|
||||||
|
|||||||
@@ -50,11 +50,13 @@ pub struct SystemUpdatePolicy {
|
|||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub struct SystemVersion {
|
pub struct SystemVersion {
|
||||||
pub version: String,
|
pub version: String,
|
||||||
|
pub instance_id: String,
|
||||||
|
pub restart_supported: bool,
|
||||||
pub git_sha: String,
|
pub git_sha: String,
|
||||||
pub build_time: String,
|
pub build_time: String,
|
||||||
pub deployment_mode: String,
|
pub deployment_mode: String,
|
||||||
pub update_channel: String,
|
pub update_channel: String,
|
||||||
pub latest_version: String,
|
pub latest_version: Option<String>,
|
||||||
pub has_update: bool,
|
pub has_update: bool,
|
||||||
pub update_cached: bool,
|
pub update_cached: bool,
|
||||||
pub update_warning: Option<String>,
|
pub update_warning: Option<String>,
|
||||||
@@ -67,7 +69,7 @@ pub struct SystemVersion {
|
|||||||
pub struct SystemUpdateDetail {
|
pub struct SystemUpdateDetail {
|
||||||
pub policy: SystemUpdatePolicy,
|
pub policy: SystemUpdatePolicy,
|
||||||
pub current_version: String,
|
pub current_version: String,
|
||||||
pub latest_version: String,
|
pub latest_version: Option<String>,
|
||||||
pub has_update: bool,
|
pub has_update: bool,
|
||||||
pub deployment_mode: String,
|
pub deployment_mode: String,
|
||||||
pub build_type: String,
|
pub build_type: String,
|
||||||
|
|||||||
@@ -55,37 +55,44 @@ impl ScheduledTask for ResetCreditAutomationTask {
|
|||||||
context: WorkerCycleContext,
|
context: WorkerCycleContext,
|
||||||
) -> futures::future::BoxFuture<'_, Result<(), WorkerTaskError>> {
|
) -> futures::future::BoxFuture<'_, Result<(), WorkerTaskError>> {
|
||||||
Box::pin(async move {
|
Box::pin(async move {
|
||||||
let settings = self
|
context
|
||||||
.settings
|
.cancellation()
|
||||||
.load_runtime_settings()
|
.run_until_cancelled(self.run_due())
|
||||||
.await
|
.await
|
||||||
.map_err(|_| WorkerTaskError::safe("重置卡设置读取失败"))?;
|
.unwrap_or(Ok(()))
|
||||||
// 单轮有界,积压沿到期顺序继续;并发复用已有账号刷新配置
|
|
||||||
let due = self
|
|
||||||
.store
|
|
||||||
.due_reset_credit_automations(Utc::now(), 100)
|
|
||||||
.await
|
|
||||||
.map_err(|_| WorkerTaskError::safe("重置卡计划读取失败"))?;
|
|
||||||
let work = futures::stream::iter(due)
|
|
||||||
.map(|account_id| async move {
|
|
||||||
let id = ProviderAccountId::new(account_id.clone())
|
|
||||||
.map_err(|_| WorkerTaskError::safe("重置卡账号 ID 不合法"))?;
|
|
||||||
if let Err(error) = self.accounts.reconcile_reset_credit_automation(id).await {
|
|
||||||
tracing::warn!(
|
|
||||||
account_id,
|
|
||||||
error_kind = error.kind().as_str(),
|
|
||||||
"自动重置卡任务失败"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
Ok::<_, WorkerTaskError>(())
|
|
||||||
})
|
|
||||||
.buffer_unordered(settings.values.refresh_concurrency.max(1) as usize)
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
tokio::select! {
|
|
||||||
() = context.cancellation().cancelled() => {},
|
|
||||||
_ = tokio::time::timeout(Duration::from_secs(30), work) => {},
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl ResetCreditAutomationTask {
|
||||||
|
async fn run_due(&self) -> Result<(), WorkerTaskError> {
|
||||||
|
let settings = self
|
||||||
|
.settings
|
||||||
|
.load_runtime_settings()
|
||||||
|
.await
|
||||||
|
.map_err(|_| WorkerTaskError::safe("重置卡设置读取失败"))?;
|
||||||
|
// 单轮有界,积压沿到期顺序继续;并发复用已有账号刷新配置
|
||||||
|
let due = self
|
||||||
|
.store
|
||||||
|
.due_reset_credit_automations(Utc::now(), 100)
|
||||||
|
.await
|
||||||
|
.map_err(|_| WorkerTaskError::safe("重置卡计划读取失败"))?;
|
||||||
|
let work = futures::stream::iter(due)
|
||||||
|
.map(|account_id| async move {
|
||||||
|
let id = ProviderAccountId::new(account_id.clone())
|
||||||
|
.map_err(|_| WorkerTaskError::safe("重置卡账号 ID 不合法"))?;
|
||||||
|
if let Err(error) = self.accounts.reconcile_reset_credit_automation(id).await {
|
||||||
|
tracing::warn!(
|
||||||
|
account_id,
|
||||||
|
error_kind = error.kind().as_str(),
|
||||||
|
"自动重置卡任务失败"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
Ok::<_, WorkerTaskError>(())
|
||||||
|
})
|
||||||
|
.buffer_unordered(settings.values.refresh_concurrency.max(1) as usize)
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
let _ = tokio::time::timeout(Duration::from_secs(30), work).await;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -1342,7 +1342,8 @@ impl AccountsService for DefaultAccountsService {
|
|||||||
.map(ToOwned::to_owned);
|
.map(ToOwned::to_owned);
|
||||||
let upstream_body = error
|
let upstream_body = error
|
||||||
.upstream_response()
|
.upstream_response()
|
||||||
.map(|response| String::from_utf8_lossy(response.body()).into_owned());
|
.and_then(gateway_core::engine::probe::AccountProbeUpstreamResponse::body)
|
||||||
|
.map(|body| String::from_utf8_lossy(body).into_owned());
|
||||||
let message = error.client_message().to_owned();
|
let message = error.client_message().to_owned();
|
||||||
vec![AccountConnectionTestEvent::Failed {
|
vec![AccountConnectionTestEvent::Failed {
|
||||||
source: error.source(),
|
source: error.source(),
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ mod flow;
|
|||||||
|
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
use gateway_core::{routing::ProviderKind, runtime::SnapshotControl};
|
use gateway_core::{account::ProviderAccountId, routing::ProviderKind, runtime::SnapshotControl};
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
model::AdminError,
|
model::AdminError,
|
||||||
@@ -40,6 +40,20 @@ impl CredentialsService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 已有账号的凭据操作按已保存的归属选择 Provider
|
||||||
|
pub async fn for_account(
|
||||||
|
&self,
|
||||||
|
account_id: &ProviderAccountId,
|
||||||
|
) -> Result<ProviderCredentials, AdminError> {
|
||||||
|
let account = self
|
||||||
|
.accounts
|
||||||
|
.load_account_record(account_id)
|
||||||
|
.await
|
||||||
|
.map_err(|error| super::map_store_error(error, "provider credentials"))?
|
||||||
|
.ok_or_else(|| AdminError::not_found("账号不存在"))?;
|
||||||
|
self.for_provider(&account.provider_kind)
|
||||||
|
}
|
||||||
|
|
||||||
pub fn for_provider(&self, kind: &ProviderKind) -> Result<ProviderCredentials, AdminError> {
|
pub fn for_provider(&self, kind: &ProviderKind) -> Result<ProviderCredentials, AdminError> {
|
||||||
let provider = self
|
let provider = self
|
||||||
.providers
|
.providers
|
||||||
|
|||||||
@@ -379,6 +379,7 @@ impl ObservabilityService for DefaultObservabilityService {
|
|||||||
account_upstream_peer: peers.get(&item.key).copied(),
|
account_upstream_peer: peers.get(&item.key).copied(),
|
||||||
key: item.key,
|
key: item.key,
|
||||||
name: item.name,
|
name: item.name,
|
||||||
|
account_email: item.account_email,
|
||||||
account_authentication_kind: item.account_authentication_kind,
|
account_authentication_kind: item.account_authentication_kind,
|
||||||
account_plan_type_display: self.historical_plan_display(
|
account_plan_type_display: self.historical_plan_display(
|
||||||
item.account_plan_type_display,
|
item.account_plan_type_display,
|
||||||
|
|||||||
@@ -1,5 +1,108 @@
|
|||||||
//! 按 Provider 组织凭据导入、授权与提交边界测试
|
//! 验证账号归属分派,并组织凭据导入、授权与提交边界测试
|
||||||
|
|
||||||
mod openai;
|
mod openai;
|
||||||
mod peer;
|
mod peer;
|
||||||
mod xai;
|
mod xai;
|
||||||
|
|
||||||
|
use gateway_admin::model::{
|
||||||
|
AdminErrorKind,
|
||||||
|
provider_credentials::{CredentialMutation, RotateCredential},
|
||||||
|
};
|
||||||
|
use gateway_core::account::ProviderAccountId;
|
||||||
|
|
||||||
|
use super::{
|
||||||
|
AdminHarness,
|
||||||
|
accounts::{
|
||||||
|
FakeAccountStore, FakeProviderAdmin, account_record, context, document, events, recorded,
|
||||||
|
revision,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn account_rotation_should_dispatch_by_saved_provider_for_each_authentication_kind() {
|
||||||
|
for kind in ["openai", "xai", "antigravity"] {
|
||||||
|
for authentication in ["oauth", "api_key"] {
|
||||||
|
let store_events = events();
|
||||||
|
let mut account = account_record(kind);
|
||||||
|
account.authentication_kind = authentication.to_owned();
|
||||||
|
if authentication == "api_key" {
|
||||||
|
account.upstream_user_id = None;
|
||||||
|
account.has_refresh_token = false;
|
||||||
|
account.access_token_expires_at = None;
|
||||||
|
account.next_refresh_at = None;
|
||||||
|
}
|
||||||
|
let account_id = ProviderAccountId::new(account.id.clone()).unwrap();
|
||||||
|
let store = FakeAccountStore::with_account(account, store_events.clone());
|
||||||
|
let mut harness = AdminHarness::new().accounts(store.clone());
|
||||||
|
let mut provider_events = Vec::new();
|
||||||
|
for registered_kind in ["openai", "xai", "antigravity"] {
|
||||||
|
let calls = events();
|
||||||
|
harness = harness.provider(FakeProviderAdmin::new(registered_kind, calls.clone()));
|
||||||
|
provider_events.push((registered_kind, calls));
|
||||||
|
}
|
||||||
|
let services = harness.build().await;
|
||||||
|
let result = services
|
||||||
|
.credentials()
|
||||||
|
.for_account(&account_id)
|
||||||
|
.await
|
||||||
|
.expect("select saved provider")
|
||||||
|
.rotate(RotateCredential {
|
||||||
|
mutation: CredentialMutation {
|
||||||
|
context: context("rotate-account-connection"),
|
||||||
|
account_id: account_id.clone(),
|
||||||
|
},
|
||||||
|
settings: None,
|
||||||
|
provider_material: document(),
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.expect("rotate selected account");
|
||||||
|
|
||||||
|
assert_eq!(result.account_id, account_id);
|
||||||
|
assert_eq!(result.credential_revision, Some(revision(2)));
|
||||||
|
assert_eq!(store.audit_requests(), ["rotate-account-connection"]);
|
||||||
|
assert_eq!(
|
||||||
|
recorded(&store_events),
|
||||||
|
[
|
||||||
|
"store.load_account_record",
|
||||||
|
"store.credential_details",
|
||||||
|
"store.commit_rotation",
|
||||||
|
]
|
||||||
|
);
|
||||||
|
for (registered_kind, calls) in provider_events {
|
||||||
|
let expected: &[&str] = if registered_kind == kind {
|
||||||
|
&[
|
||||||
|
"provider.prepare_rotation",
|
||||||
|
"guard.finish",
|
||||||
|
"provider.account_facts_changed",
|
||||||
|
]
|
||||||
|
} else {
|
||||||
|
&[]
|
||||||
|
};
|
||||||
|
assert_eq!(recorded(&calls), expected, "{kind}/{authentication}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn missing_account_should_stop_credential_dispatch_before_provider_or_store_mutation() {
|
||||||
|
let store_events = events();
|
||||||
|
let provider_events = events();
|
||||||
|
let store = FakeAccountStore::new("openai", store_events.clone());
|
||||||
|
let mut harness = AdminHarness::new().accounts(store.clone());
|
||||||
|
for kind in ["openai", "xai", "antigravity"] {
|
||||||
|
harness = harness.provider(FakeProviderAdmin::new(kind, provider_events.clone()));
|
||||||
|
}
|
||||||
|
let services = harness.build().await;
|
||||||
|
let error = services
|
||||||
|
.credentials()
|
||||||
|
.for_account(&ProviderAccountId::new("acct_missing").unwrap())
|
||||||
|
.await
|
||||||
|
.err()
|
||||||
|
.expect("missing account must fail before selecting a provider");
|
||||||
|
|
||||||
|
assert_eq!(error.kind(), AdminErrorKind::NotFound);
|
||||||
|
assert_eq!(recorded(&store_events), ["store.load_account_record"]);
|
||||||
|
assert!(recorded(&provider_events).is_empty());
|
||||||
|
assert!(store.audit_requests().is_empty());
|
||||||
|
}
|
||||||
|
|||||||
@@ -454,6 +454,8 @@ fn total_record(
|
|||||||
platform_icon: None,
|
platform_icon: None,
|
||||||
provider_account_upstream_peer: None,
|
provider_account_upstream_peer: None,
|
||||||
has_upstream_error: false,
|
has_upstream_error: false,
|
||||||
|
upstream_error_message: None,
|
||||||
|
retry_after_ms: None,
|
||||||
error_code: None,
|
error_code: None,
|
||||||
error_message: None,
|
error_message: None,
|
||||||
error_kind: None,
|
error_kind: None,
|
||||||
@@ -550,6 +552,7 @@ fn diagnostic(name: &str, request_count: u64) -> DiagnosticObservation {
|
|||||||
account_plan_type_display: None,
|
account_plan_type_display: None,
|
||||||
key: name.to_owned(),
|
key: name.to_owned(),
|
||||||
name: name.to_owned(),
|
name: name.to_owned(),
|
||||||
|
account_email: None,
|
||||||
request_count,
|
request_count,
|
||||||
success_count: request_count,
|
success_count: request_count,
|
||||||
failure_count: 0,
|
failure_count: 0,
|
||||||
|
|||||||
@@ -27,12 +27,14 @@ impl SystemOperations for RecordingSystemOperations {
|
|||||||
}
|
}
|
||||||
Ok(SystemVersion {
|
Ok(SystemVersion {
|
||||||
version: "1.0.0".to_owned(),
|
version: "1.0.0".to_owned(),
|
||||||
|
instance_id: "test-instance".to_owned(),
|
||||||
|
restart_supported: false,
|
||||||
git_sha: "unknown".to_owned(),
|
git_sha: "unknown".to_owned(),
|
||||||
build_time: "unknown".to_owned(),
|
build_time: "unknown".to_owned(),
|
||||||
deployment_mode: "source".to_owned(),
|
deployment_mode: "source".to_owned(),
|
||||||
update_channel: "stable".to_owned(),
|
update_channel: "stable".to_owned(),
|
||||||
|
|
||||||
latest_version: "1.0.0".to_owned(),
|
latest_version: None,
|
||||||
has_update: false,
|
has_update: false,
|
||||||
update_cached: false,
|
update_cached: false,
|
||||||
update_warning: None,
|
update_warning: None,
|
||||||
@@ -50,7 +52,7 @@ impl SystemOperations for RecordingSystemOperations {
|
|||||||
available_channels: vec![gateway_admin::model::system::SystemUpdateChannel::Stable],
|
available_channels: vec![gateway_admin::model::system::SystemUpdateChannel::Stable],
|
||||||
},
|
},
|
||||||
current_version: "1.0.0".to_owned(),
|
current_version: "1.0.0".to_owned(),
|
||||||
latest_version: "1.0.0".to_owned(),
|
latest_version: None,
|
||||||
has_update: false,
|
has_update: false,
|
||||||
deployment_mode: "source".to_owned(),
|
deployment_mode: "source".to_owned(),
|
||||||
build_type: "source".to_owned(),
|
build_type: "source".to_owned(),
|
||||||
|
|||||||
@@ -288,13 +288,13 @@ impl UpdateAccountRequest {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 编辑 OpenAI 账号的连接设置;OAuth 仅接受传输方式
|
/// 连接字段由 Provider 按账号类型校验,未提供的选项不注入凭据文档
|
||||||
#[derive(Clone, Deserialize)]
|
#[derive(Clone, Deserialize)]
|
||||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||||
pub struct AccountConnectionUpdateRequest {
|
pub struct AccountConnectionUpdateRequest {
|
||||||
pub protocol: Option<String>,
|
pub protocol: Option<String>,
|
||||||
pub base_url: Option<String>,
|
pub base_url: Option<String>,
|
||||||
pub transport: String,
|
pub transport: Option<String>,
|
||||||
pub api_key: Option<String>,
|
pub api_key: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -310,7 +310,11 @@ impl AccountConnectionUpdateRequest {
|
|||||||
if let Some(base_url) = &self.base_url {
|
if let Some(base_url) = &self.base_url {
|
||||||
require_text(base_url, 2048, "connection.baseUrl")?;
|
require_text(base_url, 2048, "connection.baseUrl")?;
|
||||||
}
|
}
|
||||||
if !matches!(self.transport.as_str(), "http" | "prefer_websocket") {
|
if self
|
||||||
|
.transport
|
||||||
|
.as_deref()
|
||||||
|
.is_some_and(|transport| !matches!(transport, "http" | "prefer_websocket"))
|
||||||
|
{
|
||||||
return Err(WireValidationError::new("connection.transport"));
|
return Err(WireValidationError::new("connection.transport"));
|
||||||
}
|
}
|
||||||
if self.api_key.as_ref().is_some_and(|key| {
|
if self.api_key.as_ref().is_some_and(|key| {
|
||||||
@@ -324,8 +328,10 @@ impl AccountConnectionUpdateRequest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn into_document(self) -> ProviderDocument {
|
fn into_document(self) -> ProviderDocument {
|
||||||
let mut material =
|
let mut material = Map::new();
|
||||||
Map::from_iter([("transport".to_owned(), Value::String(self.transport))]);
|
if let Some(transport) = self.transport {
|
||||||
|
material.insert("transport".to_owned(), Value::String(transport));
|
||||||
|
}
|
||||||
if let Some(protocol) = self.protocol {
|
if let Some(protocol) = self.protocol {
|
||||||
material.insert("protocol".to_owned(), Value::String(protocol));
|
material.insert("protocol".to_owned(), Value::String(protocol));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -281,13 +281,13 @@ where
|
|||||||
let (command, connection) = request.into_command().map_err(map_wire_error)?;
|
let (command, connection) = request.into_command().map_err(map_wire_error)?;
|
||||||
let context = auth.context().mutation_context();
|
let context = auth.context().mutation_context();
|
||||||
let result = if let Some(provider_material) = connection {
|
let result = if let Some(provider_material) = connection {
|
||||||
let provider = ProviderKind::new("openai").map_err(|_| AdminError::internal())?;
|
|
||||||
let account_id = ProviderAccountId::new(command.account_id.clone())
|
let account_id = ProviderAccountId::new(command.account_id.clone())
|
||||||
.map_err(|_| AdminError::internal())?;
|
.map_err(|_| AdminError::internal())?;
|
||||||
let result = state
|
let result = state
|
||||||
.admin_services()
|
.admin_services()
|
||||||
.credentials()
|
.credentials()
|
||||||
.for_provider(&provider)
|
.for_account(&account_id)
|
||||||
|
.await
|
||||||
.map_err(map_service_error)?
|
.map_err(map_service_error)?
|
||||||
.rotate(RotateCredential {
|
.rotate(RotateCredential {
|
||||||
mutation: CredentialMutation {
|
mutation: CredentialMutation {
|
||||||
|
|||||||
@@ -203,7 +203,7 @@ fn parse_provider(value: &str) -> Result<Option<ProviderKind>, WireValidationErr
|
|||||||
|
|
||||||
fn parse_sort_field(value: &str) -> Option<AccountSortField> {
|
fn parse_sort_field(value: &str) -> Option<AccountSortField> {
|
||||||
match value.trim() {
|
match value.trim() {
|
||||||
"email" => Some(AccountSortField::Email),
|
"name" => Some(AccountSortField::Name),
|
||||||
"status" => Some(AccountSortField::Status),
|
"status" => Some(AccountSortField::Status),
|
||||||
"planType" => Some(AccountSortField::PlanType),
|
"planType" => Some(AccountSortField::PlanType),
|
||||||
"usage" => Some(AccountSortField::Usage),
|
"usage" => Some(AccountSortField::Usage),
|
||||||
|
|||||||
@@ -263,6 +263,8 @@ pub(crate) fn usage_list_record_view(
|
|||||||
upstream_status_code: record.upstream_status_code,
|
upstream_status_code: record.upstream_status_code,
|
||||||
error_code: record.error_code,
|
error_code: record.error_code,
|
||||||
error_message: record.error_message,
|
error_message: record.error_message,
|
||||||
|
upstream_error_message: record.upstream_error_message,
|
||||||
|
retry_after_ms: record.retry_after_ms,
|
||||||
error_kind: record.error_kind,
|
error_kind: record.error_kind,
|
||||||
websocket_close_code: record.websocket_close_code,
|
websocket_close_code: record.websocket_close_code,
|
||||||
continuation_unavailable_reason: record.continuation_unavailable_reason,
|
continuation_unavailable_reason: record.continuation_unavailable_reason,
|
||||||
@@ -1354,13 +1356,14 @@ pub(crate) fn diagnostics_view(
|
|||||||
.map(|item| DiagnosticItemView {
|
.map(|item| DiagnosticItemView {
|
||||||
providers: item.providers,
|
providers: item.providers,
|
||||||
platform_icon: item.platform_icon,
|
platform_icon: item.platform_icon,
|
||||||
key: item.key,
|
account_email: item.account_email,
|
||||||
authentication_kind: item.account_authentication_kind,
|
authentication_kind: item.account_authentication_kind,
|
||||||
name: if item.name == "__none__" {
|
name: if item.key == "__none__" {
|
||||||
"未知".to_owned()
|
"未知".to_owned()
|
||||||
} else {
|
} else {
|
||||||
item.name
|
item.name
|
||||||
},
|
},
|
||||||
|
key: item.key,
|
||||||
request_count: item.request_count,
|
request_count: item.request_count,
|
||||||
account_plan_type: item.account_plan_type,
|
account_plan_type: item.account_plan_type,
|
||||||
account_plan_type_display: item.account_plan_type_display,
|
account_plan_type_display: item.account_plan_type_display,
|
||||||
|
|||||||
@@ -92,6 +92,8 @@ pub struct UsageListRecordView {
|
|||||||
pub upstream_status_code: Option<u16>,
|
pub upstream_status_code: Option<u16>,
|
||||||
pub error_code: Option<String>,
|
pub error_code: Option<String>,
|
||||||
pub error_message: Option<String>,
|
pub error_message: Option<String>,
|
||||||
|
pub upstream_error_message: Option<String>,
|
||||||
|
pub retry_after_ms: Option<u64>,
|
||||||
pub error_kind: Option<String>,
|
pub error_kind: Option<String>,
|
||||||
pub websocket_close_code: Option<u16>,
|
pub websocket_close_code: Option<u16>,
|
||||||
pub continuation_unavailable_reason: Option<String>,
|
pub continuation_unavailable_reason: Option<String>,
|
||||||
@@ -878,6 +880,7 @@ pub struct DiagnosticItemView {
|
|||||||
pub platform_icon: Option<String>,
|
pub platform_icon: Option<String>,
|
||||||
pub key: String,
|
pub key: String,
|
||||||
pub name: String,
|
pub name: String,
|
||||||
|
pub account_email: Option<String>,
|
||||||
pub authentication_kind: Option<String>,
|
pub authentication_kind: Option<String>,
|
||||||
pub account_plan_type: Option<String>,
|
pub account_plan_type: Option<String>,
|
||||||
pub account_plan_type_display: Option<String>,
|
pub account_plan_type_display: Option<String>,
|
||||||
|
|||||||
@@ -81,12 +81,14 @@ impl UpdateRequest {
|
|||||||
#[serde(rename_all = "camelCase")]
|
#[serde(rename_all = "camelCase")]
|
||||||
struct SystemVersionView {
|
struct SystemVersionView {
|
||||||
version: String,
|
version: String,
|
||||||
|
instance_id: String,
|
||||||
|
restart_supported: bool,
|
||||||
git_sha: String,
|
git_sha: String,
|
||||||
build_time: String,
|
build_time: String,
|
||||||
deployment_mode: String,
|
deployment_mode: String,
|
||||||
deployment_mode_label: String,
|
deployment_mode_label: String,
|
||||||
update_channel: String,
|
update_channel: String,
|
||||||
latest_version: String,
|
latest_version: Option<String>,
|
||||||
has_update: bool,
|
has_update: bool,
|
||||||
update_cached: bool,
|
update_cached: bool,
|
||||||
update_warning: Option<String>,
|
update_warning: Option<String>,
|
||||||
@@ -97,6 +99,8 @@ impl From<SystemVersion> for SystemVersionView {
|
|||||||
Self {
|
Self {
|
||||||
deployment_mode_label: deployment_mode_label(&version.deployment_mode).to_owned(),
|
deployment_mode_label: deployment_mode_label(&version.deployment_mode).to_owned(),
|
||||||
version: version.version,
|
version: version.version,
|
||||||
|
instance_id: version.instance_id,
|
||||||
|
restart_supported: version.restart_supported,
|
||||||
git_sha: version.git_sha,
|
git_sha: version.git_sha,
|
||||||
build_time: version.build_time,
|
build_time: version.build_time,
|
||||||
deployment_mode: version.deployment_mode,
|
deployment_mode: version.deployment_mode,
|
||||||
@@ -114,7 +118,7 @@ impl From<SystemVersion> for SystemVersionView {
|
|||||||
struct SystemUpdateDetailView {
|
struct SystemUpdateDetailView {
|
||||||
policy: SystemUpdatePolicy,
|
policy: SystemUpdatePolicy,
|
||||||
current_version: String,
|
current_version: String,
|
||||||
latest_version: String,
|
latest_version: Option<String>,
|
||||||
has_update: bool,
|
has_update: bool,
|
||||||
deployment_mode: String,
|
deployment_mode: String,
|
||||||
deployment_mode_label: String,
|
deployment_mode_label: String,
|
||||||
|
|||||||
@@ -72,10 +72,6 @@ pub(crate) fn client_error_code(code: &str) -> &str {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn is_retry_after_header(name: &str) -> bool {
|
|
||||||
name.eq_ignore_ascii_case("retry-after") || name.eq_ignore_ascii_case("retry-after-ms")
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 为 HTTP 错误或流内失败保留原有字段,仅投影客户端需要的重试信号
|
/// 为 HTTP 错误或流内失败保留原有字段,仅投影客户端需要的重试信号
|
||||||
pub(crate) fn capacity_error_for_client(data: &Value) -> Option<Value> {
|
pub(crate) fn capacity_error_for_client(data: &Value) -> Option<Value> {
|
||||||
const CODE_PATHS: [&str; 2] = ["/error/code", "/response/error/code"];
|
const CODE_PATHS: [&str; 2] = ["/error/code", "/response/error/code"];
|
||||||
@@ -91,12 +87,6 @@ pub(crate) fn capacity_error_for_client(data: &Value) -> Option<Value> {
|
|||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
let mut projected = data.clone();
|
let mut projected = data.clone();
|
||||||
// 容量等待与换号已由网关执行;旧账号的等待提示不能再次阻塞客户端的新一轮路由
|
|
||||||
for path in ["/headers", "/error/headers", "/response/error/headers"] {
|
|
||||||
if let Some(Value::Object(headers)) = projected.pointer_mut(path) {
|
|
||||||
headers.retain(|name, _| !is_retry_after_header(name));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for path in CODE_PATHS {
|
for path in CODE_PATHS {
|
||||||
if let Some(code) = projected.pointer_mut(path)
|
if let Some(code) = projected.pointer_mut(path)
|
||||||
&& capacity_code(code)
|
&& capacity_code(code)
|
||||||
|
|||||||
@@ -11,11 +11,12 @@ use gateway_core::{
|
|||||||
error::ProviderErrorKind,
|
error::ProviderErrorKind,
|
||||||
policy::{ClientVersionRejection, CodexClientKind},
|
policy::{ClientVersionRejection, CodexClientKind},
|
||||||
};
|
};
|
||||||
|
use gateway_protocol::http::preferred_response_request_id;
|
||||||
use serde_json::{Value, json};
|
use serde_json::{Value, json};
|
||||||
|
|
||||||
pub use gateway_core::engine::execution::gateway_error_from_engine;
|
pub use gateway_core::engine::execution::gateway_error_from_engine;
|
||||||
|
|
||||||
use crate::client_error::{ProtocolErrorBody, capacity_error_for_client, is_retry_after_header};
|
use crate::client_error::{ProtocolErrorBody, capacity_error_for_client};
|
||||||
|
|
||||||
pub use crate::client_error::{
|
pub use crate::client_error::{
|
||||||
gateway_error_contract, gateway_error_response, openai_error_response,
|
gateway_error_contract, gateway_error_response, openai_error_response,
|
||||||
@@ -109,6 +110,24 @@ pub fn model_not_found_response() -> (StatusCode, Json<Value>) {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 将上游实际给出的等待头交给客户端错误事件
|
||||||
|
pub(crate) fn upstream_retry_headers(error: &EngineError) -> serde_json::Map<String, Value> {
|
||||||
|
let mut headers = Vec::new();
|
||||||
|
if let EngineError::Provider(provider) = error {
|
||||||
|
provider.extend_client_retry_headers(&mut headers, &[]);
|
||||||
|
}
|
||||||
|
headers
|
||||||
|
.into_iter()
|
||||||
|
.filter_map(|header| {
|
||||||
|
let value = HeaderValue::from_bytes(header.value()).ok()?;
|
||||||
|
Some((
|
||||||
|
header.name().to_ascii_lowercase(),
|
||||||
|
Value::String(value.to_str().ok()?.to_owned()),
|
||||||
|
))
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
/// 在下游尚未提交时交付 Provider 的 HTTP 失败响应,并应用客户端容量恢复合同
|
/// 在下游尚未提交时交付 Provider 的 HTTP 失败响应,并应用客户端容量恢复合同
|
||||||
pub fn engine_error_response(error: &EngineError) -> Response {
|
pub fn engine_error_response(error: &EngineError) -> Response {
|
||||||
let capacity_unavailable = matches!(error, EngineError::Provider(error)
|
let capacity_unavailable = matches!(error, EngineError::Provider(error)
|
||||||
@@ -122,7 +141,6 @@ pub fn engine_error_response(error: &EngineError) -> Response {
|
|||||||
let projected = serde_json::from_slice::<Value>(upstream.body())
|
let projected = serde_json::from_slice::<Value>(upstream.body())
|
||||||
.ok()
|
.ok()
|
||||||
.and_then(|body| capacity_error_for_client(&body));
|
.and_then(|body| capacity_error_for_client(&body));
|
||||||
let suppress_retry_after = capacity_unavailable || projected.is_some();
|
|
||||||
let mut response = match projected {
|
let mut response = match projected {
|
||||||
Some(body) => {
|
Some(body) => {
|
||||||
let mut response = Response::new(Body::from(body.to_string()));
|
let mut response = Response::new(Body::from(body.to_string()));
|
||||||
@@ -145,9 +163,6 @@ pub fn engine_error_response(error: &EngineError) -> Response {
|
|||||||
response.headers_mut().insert(CONTENT_TYPE, content_type);
|
response.headers_mut().insert(CONTENT_TYPE, content_type);
|
||||||
}
|
}
|
||||||
for header in upstream.headers() {
|
for header in upstream.headers() {
|
||||||
if suppress_retry_after && is_retry_after_header(header.name()) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
let Ok(name) = HeaderName::from_bytes(header.name().as_bytes()) else {
|
let Ok(name) = HeaderName::from_bytes(header.name().as_bytes()) else {
|
||||||
continue;
|
continue;
|
||||||
};
|
};
|
||||||
@@ -156,8 +171,8 @@ pub fn engine_error_response(error: &EngineError) -> Response {
|
|||||||
};
|
};
|
||||||
response.headers_mut().append(name, value);
|
response.headers_mut().append(name, value);
|
||||||
}
|
}
|
||||||
if !response.headers().contains_key("x-request-id")
|
if preferred_response_request_id(|name| response.headers().get(name)?.to_str().ok())
|
||||||
&& !response.headers().contains_key("x-oai-request-id")
|
.is_none()
|
||||||
&& let Some(request_id) = error.upstream_request_id()
|
&& let Some(request_id) = error.upstream_request_id()
|
||||||
&& let Ok(value) = HeaderValue::from_str(request_id.as_str())
|
&& let Ok(value) = HeaderValue::from_str(request_id.as_str())
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -665,7 +665,7 @@ fn engine_error_response_with_headers(
|
|||||||
response_headers: &[ProviderResponseHeader],
|
response_headers: &[ProviderResponseHeader],
|
||||||
) -> Response {
|
) -> Response {
|
||||||
let response = engine_error_response(error);
|
let response = engine_error_response(error);
|
||||||
let failure_request_ids = ["x-request-id", "x-oai-request-id"]
|
let failure_request_ids = gateway_protocol::http::RESPONSE_REQUEST_ID_HEADERS
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.flat_map(|name| {
|
.flat_map(|name| {
|
||||||
response
|
response
|
||||||
@@ -678,8 +678,9 @@ fn engine_error_response_with_headers(
|
|||||||
.collect::<Vec<_>>();
|
.collect::<Vec<_>>();
|
||||||
// 失败后仍须交付已采集的 turn state;只隔离 opening 身份,不丢弃会话状态
|
// 失败后仍须交付已采集的 turn state;只隔离 opening 身份,不丢弃会话状态
|
||||||
let mut response = apply_provider_response_headers(response, response_headers);
|
let mut response = apply_provider_response_headers(response, response_headers);
|
||||||
response.headers_mut().remove("x-request-id");
|
for name in gateway_protocol::http::RESPONSE_REQUEST_ID_HEADERS {
|
||||||
response.headers_mut().remove("x-oai-request-id");
|
response.headers_mut().remove(name);
|
||||||
|
}
|
||||||
for (name, value) in failure_request_ids {
|
for (name, value) in failure_request_ids {
|
||||||
response.headers_mut().append(name, value);
|
response.headers_mut().append(name, value);
|
||||||
}
|
}
|
||||||
@@ -830,7 +831,10 @@ impl StreamingExecutionBody {
|
|||||||
}
|
}
|
||||||
Ok(None) => return Err(invalid_execution_stream()),
|
Ok(None) => return Err(invalid_execution_stream()),
|
||||||
Err(error) if self.committed => {
|
Err(error) if self.committed => {
|
||||||
self.push_stream_error(gateway_error_from_engine(&error));
|
self.push_stream_error(
|
||||||
|
gateway_error_from_engine(&error),
|
||||||
|
crate::data_plane::error::upstream_retry_headers(&error),
|
||||||
|
);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
Err(error) => return Err(MiddlewareError::Engine(error)),
|
Err(error) => return Err(MiddlewareError::Engine(error)),
|
||||||
@@ -893,9 +897,13 @@ impl StreamingExecutionBody {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn push_stream_error(&mut self, error: GatewayError) {
|
fn push_stream_error(
|
||||||
|
&mut self,
|
||||||
|
error: GatewayError,
|
||||||
|
headers: serde_json::Map<String, serde_json::Value>,
|
||||||
|
) {
|
||||||
self.pending.push_back(MiddlewareFrame::new(
|
self.pending.push_back(MiddlewareFrame::new(
|
||||||
self.encoder.error_frame(&error),
|
self.encoder.error_frame(&error, headers),
|
||||||
MiddlewareFraming::SseEvent,
|
MiddlewareFraming::SseEvent,
|
||||||
false,
|
false,
|
||||||
));
|
));
|
||||||
@@ -935,7 +943,7 @@ impl MiddlewareBody for StreamingExecutionBody {
|
|||||||
"Gateway response stream could not be delivered.",
|
"Gateway response stream could not be delivered.",
|
||||||
),
|
),
|
||||||
};
|
};
|
||||||
self.push_stream_error(error);
|
self.push_stream_error(error, Default::default());
|
||||||
}
|
}
|
||||||
Ok(self.pending.pop_front())
|
Ok(self.pending.pop_front())
|
||||||
})
|
})
|
||||||
@@ -972,7 +980,7 @@ impl MiddlewareBody for StreamingExecutionBody {
|
|||||||
"The Chat response could not be finalized.",
|
"The Chat response could not be finalized.",
|
||||||
),
|
),
|
||||||
};
|
};
|
||||||
self.push_stream_error(error);
|
self.push_stream_error(error, Default::default());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -113,15 +113,9 @@ async fn stream_failure(
|
|||||||
error_encoder: Option<fn(&Value) -> Bytes>,
|
error_encoder: Option<fn(&Value) -> Bytes>,
|
||||||
append_done: bool,
|
append_done: bool,
|
||||||
) -> Body {
|
) -> Body {
|
||||||
let status = response.status();
|
let (parts, body) = response.into_parts();
|
||||||
let retry_after = response
|
let status = parts.status;
|
||||||
.headers()
|
let bytes = to_bytes(body, usize::MAX).await.unwrap_or_default();
|
||||||
.get(header::RETRY_AFTER)
|
|
||||||
.and_then(|value| value.to_str().ok())
|
|
||||||
.map(ToOwned::to_owned);
|
|
||||||
let bytes = to_bytes(response.into_body(), usize::MAX)
|
|
||||||
.await
|
|
||||||
.unwrap_or_default();
|
|
||||||
let json = serde_json::from_slice::<Value>(&bytes).ok();
|
let json = serde_json::from_slice::<Value>(&bytes).ok();
|
||||||
let raw_message = std::str::from_utf8(&bytes)
|
let raw_message = std::str::from_utf8(&bytes)
|
||||||
.ok()
|
.ok()
|
||||||
@@ -144,16 +138,20 @@ async fn stream_failure(
|
|||||||
)
|
)
|
||||||
});
|
});
|
||||||
// HTTP 头已提交,按官方 SSE 错误合同保留允许下发的重试建议
|
// HTTP 头已提交,按官方 SSE 错误合同保留允许下发的重试建议
|
||||||
if let Some(retry_after) = retry_after
|
for name in gateway_protocol::http::RETRY_AFTER_HEADERS {
|
||||||
&& let Some(error) = data["response"]["error"].as_object_mut()
|
if let Some(value) = parts
|
||||||
&& let Some(headers) = error
|
.headers
|
||||||
.entry("headers")
|
.get(name)
|
||||||
.or_insert_with(|| serde_json::json!({}))
|
.and_then(|value| value.to_str().ok())
|
||||||
.as_object_mut()
|
&& let Some(error) = data["response"]["error"].as_object_mut()
|
||||||
{
|
&& let Some(headers) = error
|
||||||
headers
|
.entry("headers")
|
||||||
.entry("retry-after")
|
.or_insert_with(|| serde_json::json!({}))
|
||||||
.or_insert(Value::String(retry_after));
|
.as_object_mut()
|
||||||
|
&& !headers.keys().any(|key| key.eq_ignore_ascii_case(name))
|
||||||
|
{
|
||||||
|
headers.insert(name.to_owned(), Value::String(value.to_owned()));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
let mut event = match error_encoder {
|
let mut event = match error_encoder {
|
||||||
Some(encode) => encode(&data).to_vec(),
|
Some(encode) => encode(&data).to_vec(),
|
||||||
|
|||||||
@@ -6,7 +6,8 @@ use gateway_protocol::anthropic::ANTHROPIC_PROTOCOL;
|
|||||||
use gateway_protocol::{
|
use gateway_protocol::{
|
||||||
anthropic::MessagesAccumulator,
|
anthropic::MessagesAccumulator,
|
||||||
openai::sse::{
|
openai::sse::{
|
||||||
DONE_SSE_FRAME, encode_sse_event_with_metadata, response_failed_sse_event_with_id,
|
DONE_SSE_FRAME, encode_sse_event, encode_sse_event_with_metadata,
|
||||||
|
response_failed_sse_data_with_id,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
use serde_json::{Value, json};
|
use serde_json::{Value, json};
|
||||||
@@ -159,7 +160,11 @@ impl GenerationEncoder {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(super) fn error_frame(&self, error: &GatewayError) -> Bytes {
|
pub(super) fn error_frame(
|
||||||
|
&self,
|
||||||
|
error: &GatewayError,
|
||||||
|
headers: serde_json::Map<String, Value>,
|
||||||
|
) -> Bytes {
|
||||||
let (status, error_type, code) = gateway_error_contract(error.kind());
|
let (status, error_type, code) = gateway_error_contract(error.kind());
|
||||||
match self {
|
match self {
|
||||||
Self::Chat(_) => {
|
Self::Chat(_) => {
|
||||||
@@ -169,12 +174,21 @@ impl GenerationEncoder {
|
|||||||
"message": error.client_message(),
|
"message": error.client_message(),
|
||||||
}}))
|
}}))
|
||||||
}
|
}
|
||||||
Self::Responses(encoder) => Bytes::from(response_failed_sse_event_with_id(
|
Self::Responses(encoder) => {
|
||||||
encoder.response_id(),
|
let mut data = response_failed_sse_data_with_id(
|
||||||
error.client_error_type().unwrap_or(error_type),
|
encoder.response_id(),
|
||||||
crate::client_error::client_error_code(error.client_error_code().unwrap_or(code)),
|
error.client_error_type().unwrap_or(error_type),
|
||||||
error.client_message(),
|
crate::client_error::client_error_code(
|
||||||
)),
|
error.client_error_code().unwrap_or(code),
|
||||||
|
),
|
||||||
|
error.client_message(),
|
||||||
|
);
|
||||||
|
if !headers.is_empty() {
|
||||||
|
data["response"]["error"]["headers"] = json!(headers);
|
||||||
|
data["error"]["headers"] = Value::Object(headers);
|
||||||
|
}
|
||||||
|
Bytes::from(encode_sse_event("response.failed", &data.to_string()))
|
||||||
|
}
|
||||||
Self::GenAi { .. } => {
|
Self::GenAi { .. } => {
|
||||||
crate::data_plane::genai::error_frame(status, error.client_message())
|
crate::data_plane::genai::error_frame(status, error.client_message())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -37,11 +37,11 @@ pub(crate) fn with_model_request_id(
|
|||||||
let usable = |value: &HeaderValue| value.to_str().is_ok_and(|id| !id.trim().is_empty());
|
let usable = |value: &HeaderValue| value.to_str().is_ok_and(|id| !id.trim().is_empty());
|
||||||
if !headers.get("x-request-id").is_some_and(usable) {
|
if !headers.get("x-request-id").is_some_and(usable) {
|
||||||
// 只有别名时沿用同一个上游值,避免外层 middleware 再填入入口 ID
|
// 只有别名时沿用同一个上游值,避免外层 middleware 再填入入口 ID
|
||||||
let client_id = headers
|
let client_id = gateway_protocol::http::preferred_response_request_id(|name| {
|
||||||
.get("x-oai-request-id")
|
headers.get(name)?.to_str().ok()
|
||||||
.filter(|value| usable(value))
|
})
|
||||||
.unwrap_or(&gateway_id)
|
.and_then(|value| HeaderValue::from_str(value).ok())
|
||||||
.clone();
|
.unwrap_or_else(|| gateway_id.clone());
|
||||||
headers.insert("x-request-id", client_id);
|
headers.insert("x-request-id", client_id);
|
||||||
}
|
}
|
||||||
headers.insert("x-gateway-request-id", gateway_id);
|
headers.insert("x-gateway-request-id", gateway_id);
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ use crate::{
|
|||||||
auth::{ClientKeyHeaders, authenticate_client, client_access_error_response},
|
auth::{ClientKeyHeaders, authenticate_client, client_access_error_response},
|
||||||
error::gateway_error_response,
|
error::gateway_error_response,
|
||||||
generation::{GenerationEndpoint, GenerationHttpRequest, execute_prepared_generation},
|
generation::{GenerationEndpoint, GenerationHttpRequest, execute_prepared_generation},
|
||||||
|
router::IngressStarted,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
use axum::{
|
use axum::{
|
||||||
@@ -15,18 +16,43 @@ use axum::{
|
|||||||
http::{HeaderMap, StatusCode},
|
http::{HeaderMap, StatusCode},
|
||||||
response::Response,
|
response::Response,
|
||||||
};
|
};
|
||||||
use std::net::SocketAddr;
|
use std::{net::SocketAddr, time::Instant};
|
||||||
|
|
||||||
/// `POST /v1/responses`
|
/// `POST /v1/responses`
|
||||||
pub(crate) async fn responses(
|
pub(crate) async fn responses(
|
||||||
State(state): State<ApiState>,
|
State(state): State<ApiState>,
|
||||||
connect_info: Option<Extension<ConnectInfo<SocketAddr>>>,
|
connect_info: Option<Extension<ConnectInfo<SocketAddr>>>,
|
||||||
ingress_id: Option<Extension<tower_http::request_id::RequestId>>,
|
ingress_id: Option<Extension<tower_http::request_id::RequestId>>,
|
||||||
|
ingress_started: Option<Extension<IngressStarted>>,
|
||||||
headers: HeaderMap,
|
headers: HeaderMap,
|
||||||
body: Bytes,
|
body: Bytes,
|
||||||
) -> Response {
|
) -> Response {
|
||||||
|
// Bytes extractor 已读完传输正文;此时尚未认证、解压或解析 JSON
|
||||||
|
let mut encodings = headers.get_all(axum::http::header::CONTENT_ENCODING).iter();
|
||||||
|
let encoding = match (encodings.next(), encodings.next()) {
|
||||||
|
(None, _) => "identity",
|
||||||
|
(Some(value), None) => value
|
||||||
|
.to_str()
|
||||||
|
.ok()
|
||||||
|
.and_then(|value| {
|
||||||
|
["identity", "gzip", "deflate", "zstd"]
|
||||||
|
.into_iter()
|
||||||
|
.find(|known| known.eq_ignore_ascii_case(value.trim()))
|
||||||
|
})
|
||||||
|
.unwrap_or("other"),
|
||||||
|
_ => "other",
|
||||||
|
};
|
||||||
|
tracing::info!(target: "request_trace", stage = "http.body.received",
|
||||||
|
receive_ms = ingress_started.map(|Extension(start)| start.0.elapsed().as_millis()),
|
||||||
|
encoded_bytes = body.len(), content_encoding = encoding,
|
||||||
|
"HTTP request body received");
|
||||||
let service = state.data_plane().clone();
|
let service = state.data_plane().clone();
|
||||||
let client = match authenticate_client(&service, &headers, ClientKeyHeaders::Bearer).await {
|
let started = Instant::now();
|
||||||
|
let authentication = authenticate_client(&service, &headers, ClientKeyHeaders::Bearer).await;
|
||||||
|
tracing::info!(target: "request_trace", stage = "http.auth.finished",
|
||||||
|
auth_ms = started.elapsed().as_millis(), accepted = authentication.is_ok(),
|
||||||
|
"HTTP request authentication finished");
|
||||||
|
let client = match authentication {
|
||||||
Ok(client) => client,
|
Ok(client) => client,
|
||||||
Err(error) => return client_access_error_response(error),
|
Err(error) => return client_access_error_response(error),
|
||||||
};
|
};
|
||||||
@@ -42,7 +68,12 @@ pub(crate) async fn responses(
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
let execution = service.execution();
|
let execution = service.execution();
|
||||||
let prepared = match execution.prepare_execution(client).await {
|
let started = Instant::now();
|
||||||
|
let preparation = execution.prepare_execution(client).await;
|
||||||
|
tracing::info!(target: "request_trace", stage = "http.execution.prepared",
|
||||||
|
prepare_ms = started.elapsed().as_millis(), accepted = preparation.is_ok(),
|
||||||
|
"HTTP execution preparation finished");
|
||||||
|
let prepared = match preparation {
|
||||||
Ok(prepared) => prepared,
|
Ok(prepared) => prepared,
|
||||||
Err(error) => return gateway_error_response(&error),
|
Err(error) => return gateway_error_response(&error),
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -143,9 +143,20 @@ pub(crate) fn decode_request_with_body(
|
|||||||
headers: &HeaderMap,
|
headers: &HeaderMap,
|
||||||
max_decompressed_bytes: usize,
|
max_decompressed_bytes: usize,
|
||||||
) -> Result<(DecodedGenerationRequest, Bytes), RequestDecodeError> {
|
) -> Result<(DecodedGenerationRequest, Bytes), RequestDecodeError> {
|
||||||
let body = decompress_request_body(body, headers, max_decompressed_bytes)?;
|
let started = std::time::Instant::now();
|
||||||
let decoded = decode_request_inner(&body, &OpenAiRequestHeaders::from_headers(headers))?;
|
let decompressed = decompress_request_body(body, headers, max_decompressed_bytes);
|
||||||
Ok((decoded, Bytes::copy_from_slice(&body)))
|
tracing::info!(target: "request_trace", stage = "http.body.decompressed",
|
||||||
|
decompress_ms = started.elapsed().as_millis(),
|
||||||
|
decoded_bytes = decompressed.as_ref().ok().map(|body| body.len()),
|
||||||
|
accepted = decompressed.is_ok(), "HTTP request body decompressed");
|
||||||
|
let body = decompressed?;
|
||||||
|
let started = std::time::Instant::now();
|
||||||
|
let decoded = decode_request_inner(&body, &OpenAiRequestHeaders::from_headers(headers))
|
||||||
|
.map(|decoded| (decoded, Bytes::copy_from_slice(&body)));
|
||||||
|
tracing::info!(target: "request_trace", stage = "http.body.decoded",
|
||||||
|
decode_ms = started.elapsed().as_millis(), accepted = decoded.is_ok(),
|
||||||
|
"HTTP request body decoded");
|
||||||
|
decoded
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(super) fn decode_request_inner(
|
pub(super) fn decode_request_inner(
|
||||||
|
|||||||
@@ -575,7 +575,10 @@ impl WebSocketExecutionBody {
|
|||||||
Ok(Some(delivery)) => delivery,
|
Ok(Some(delivery)) => delivery,
|
||||||
Ok(None) => return Err(MiddlewareError::InvalidState),
|
Ok(None) => return Err(MiddlewareError::InvalidState),
|
||||||
Err(error) if self.committed => {
|
Err(error) if self.committed => {
|
||||||
self.push_gateway_error(gateway_error_from_engine(&error));
|
self.push_gateway_error(
|
||||||
|
gateway_error_from_engine(&error),
|
||||||
|
crate::data_plane::error::upstream_retry_headers(&error),
|
||||||
|
);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
Err(error) => return Err(MiddlewareError::Engine(error)),
|
Err(error) => return Err(MiddlewareError::Engine(error)),
|
||||||
@@ -635,7 +638,11 @@ impl WebSocketExecutionBody {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn push_gateway_error(&mut self, error: GatewayError) {
|
fn push_gateway_error(
|
||||||
|
&mut self,
|
||||||
|
error: GatewayError,
|
||||||
|
headers: serde_json::Map<String, serde_json::Value>,
|
||||||
|
) {
|
||||||
let (status, default_type, default_code) = gateway_error_contract(error.kind());
|
let (status, default_type, default_code) = gateway_error_contract(error.kind());
|
||||||
self.pending.push_back(MiddlewareFrame::new(
|
self.pending.push_back(MiddlewareFrame::new(
|
||||||
Bytes::from(
|
Bytes::from(
|
||||||
@@ -646,7 +653,7 @@ impl WebSocketExecutionBody {
|
|||||||
error.client_message(),
|
error.client_message(),
|
||||||
None,
|
None,
|
||||||
Some(&self.request_id),
|
Some(&self.request_id),
|
||||||
serde_json::Map::new(),
|
headers,
|
||||||
)
|
)
|
||||||
.to_string(),
|
.to_string(),
|
||||||
),
|
),
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ use axum::http::{HeaderName, HeaderValue, StatusCode};
|
|||||||
use gateway_core::engine::EngineError;
|
use gateway_core::engine::EngineError;
|
||||||
use gateway_core::error::ProviderErrorKind;
|
use gateway_core::error::ProviderErrorKind;
|
||||||
use gateway_core::event::ProviderResponseHeader;
|
use gateway_core::event::ProviderResponseHeader;
|
||||||
|
use gateway_protocol::http::{RESPONSE_REQUEST_ID_HEADERS, preferred_response_request_id};
|
||||||
use serde_json::{Map, Value, json};
|
use serde_json::{Map, Value, json};
|
||||||
use thiserror::Error;
|
use thiserror::Error;
|
||||||
|
|
||||||
@@ -119,9 +120,12 @@ pub(super) fn response_metadata_event(
|
|||||||
response_headers: &[ProviderResponseHeader],
|
response_headers: &[ProviderResponseHeader],
|
||||||
) -> String {
|
) -> String {
|
||||||
let mut headers = response_event_headers(response_headers);
|
let mut headers = response_event_headers(response_headers);
|
||||||
|
let client_request_id = preferred_response_request_id(|name| headers.get(name)?.as_str())
|
||||||
|
.unwrap_or(request_id)
|
||||||
|
.to_owned();
|
||||||
headers
|
headers
|
||||||
.entry("x-request-id".to_owned())
|
.entry("x-request-id".to_owned())
|
||||||
.or_insert_with(|| Value::String(request_id.to_owned()));
|
.or_insert(Value::String(client_request_id));
|
||||||
json!({
|
json!({
|
||||||
"type": "response.metadata",
|
"type": "response.metadata",
|
||||||
"headers": headers,
|
"headers": headers,
|
||||||
@@ -149,7 +153,7 @@ fn response_event_headers(response_headers: &[ProviderResponseHeader]) -> Map<St
|
|||||||
let Ok(value) = std::str::from_utf8(header.value()) else {
|
let Ok(value) = std::str::from_utf8(header.value()) else {
|
||||||
continue;
|
continue;
|
||||||
};
|
};
|
||||||
if matches!(name.as_str(), "x-request-id" | "x-oai-request-id")
|
if RESPONSE_REQUEST_ID_HEADERS.contains(&name.as_str())
|
||||||
&& (value.trim().is_empty() || http_value.to_str().is_err())
|
&& (value.trim().is_empty() || http_value.to_str().is_err())
|
||||||
{
|
{
|
||||||
continue;
|
continue;
|
||||||
@@ -173,12 +177,18 @@ pub(super) fn initial_engine_error_event(
|
|||||||
};
|
};
|
||||||
let upstream = provider.and_then(|error| error.client_visible_upstream_response());
|
let upstream = provider.and_then(|error| error.client_visible_upstream_response());
|
||||||
// 最终失败响应优先于会话快照,避免混入先前 attempt 或 opening 的关联头
|
// 最终失败响应优先于会话快照,避免混入先前 attempt 或 opening 的关联头
|
||||||
let mut headers =
|
let mut headers = if let Some((provider, response)) = provider.zip(upstream) {
|
||||||
response_event_headers(upstream.map_or(response_headers, |response| response.headers()));
|
let mut headers = response.headers().to_vec();
|
||||||
|
provider.extend_client_retry_headers(&mut headers, &[]);
|
||||||
|
response_event_headers(&headers)
|
||||||
|
} else {
|
||||||
|
response_event_headers(response_headers)
|
||||||
|
};
|
||||||
if upstream.is_none() {
|
if upstream.is_none() {
|
||||||
// 会话 opening 身份不证明当前失败属于该请求;仅保留其他允许的会话头
|
// 会话 opening 身份不证明当前失败属于该请求;仅保留其他允许的会话头
|
||||||
headers.remove("x-request-id");
|
for name in RESPONSE_REQUEST_ID_HEADERS {
|
||||||
headers.remove("x-oai-request-id");
|
headers.remove(name);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
let status = if provider
|
let status = if provider
|
||||||
.is_some_and(|error| error.kind() == ProviderErrorKind::UpstreamCapacityUnavailable)
|
.is_some_and(|error| error.kind() == ProviderErrorKind::UpstreamCapacityUnavailable)
|
||||||
@@ -216,7 +226,7 @@ pub(super) fn initial_engine_error_event(
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn has_request_id(headers: &Map<String, Value>) -> bool {
|
fn has_request_id(headers: &Map<String, Value>) -> bool {
|
||||||
headers.contains_key("x-request-id") || headers.contains_key("x-oai-request-id")
|
preferred_response_request_id(|name| headers.get(name)?.as_str()).is_some()
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(super) fn error_event(
|
pub(super) fn error_event(
|
||||||
|
|||||||
@@ -46,6 +46,10 @@ pub(crate) fn router() -> Router<ApiState> {
|
|||||||
.merge(super::provider_endpoints::router())
|
.merge(super::provider_endpoints::router())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 在读取正文前保存入口时刻,交给端点区分接收与执行耗时
|
||||||
|
#[derive(Clone, Copy)]
|
||||||
|
pub(crate) struct IngressStarted(pub(crate) std::time::Instant);
|
||||||
|
|
||||||
#[derive(Clone, Copy)]
|
#[derive(Clone, Copy)]
|
||||||
pub(crate) enum DataPlaneNamespace {
|
pub(crate) enum DataPlaneNamespace {
|
||||||
V1,
|
V1,
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ use serde_json::json;
|
|||||||
use tower_http::request_id::RequestId;
|
use tower_http::request_id::RequestId;
|
||||||
|
|
||||||
use crate::client_error::{AccessRejection, ProtocolErrorBody};
|
use crate::client_error::{AccessRejection, ProtocolErrorBody};
|
||||||
use crate::data_plane::router::DataPlaneNamespace;
|
use crate::data_plane::router::{DataPlaneNamespace, IngressStarted};
|
||||||
|
|
||||||
pub(crate) async fn record_ingress(
|
pub(crate) async fn record_ingress(
|
||||||
State(diagnostics): State<Arc<dyn OperationalDiagnostics>>,
|
State(diagnostics): State<Arc<dyn OperationalDiagnostics>>,
|
||||||
@@ -29,6 +29,9 @@ pub(crate) async fn record_ingress(
|
|||||||
let Some(namespace) = DataPlaneNamespace::for_path(request.uri().path()) else {
|
let Some(namespace) = DataPlaneNamespace::for_path(request.uri().path()) else {
|
||||||
return next.run(request).await;
|
return next.run(request).await;
|
||||||
};
|
};
|
||||||
|
request
|
||||||
|
.extensions_mut()
|
||||||
|
.insert(IngressStarted(std::time::Instant::now()));
|
||||||
let correlation_id = request
|
let correlation_id = request
|
||||||
.extensions()
|
.extensions()
|
||||||
.get::<RequestId>()
|
.get::<RequestId>()
|
||||||
|
|||||||
@@ -639,14 +639,22 @@ async fn connection_update_requires_admin_and_validates_before_calling_the_servi
|
|||||||
"connection":{"baseUrl":"https://api.example.invalid/v1", "transport":"http"}
|
"connection":{"baseUrl":"https://api.example.invalid/v1", "transport":"http"}
|
||||||
});
|
});
|
||||||
for (authenticated, transport, oauth, expected) in [
|
for (authenticated, transport, oauth, expected) in [
|
||||||
(false, "http", false, StatusCode::UNAUTHORIZED),
|
(false, Some("http"), false, StatusCode::UNAUTHORIZED),
|
||||||
(true, "invalid", false, StatusCode::BAD_REQUEST),
|
(true, Some("invalid"), false, StatusCode::BAD_REQUEST),
|
||||||
// 夹具没有凭据 Store,合法输入必须进入服务,不能按普通设置静默保存
|
// 夹具没有凭据 Store,合法输入必须进入服务,不能按普通设置静默保存
|
||||||
(true, "http", false, StatusCode::SERVICE_UNAVAILABLE),
|
(true, Some("http"), false, StatusCode::SERVICE_UNAVAILABLE),
|
||||||
(true, "http", true, StatusCode::SERVICE_UNAVAILABLE),
|
(true, Some("http"), true, StatusCode::SERVICE_UNAVAILABLE),
|
||||||
|
(true, None, false, StatusCode::SERVICE_UNAVAILABLE),
|
||||||
] {
|
] {
|
||||||
let mut input = input.clone();
|
let mut input = input.clone();
|
||||||
input["connection"]["transport"] = serde_json::json!(transport);
|
if let Some(transport) = transport {
|
||||||
|
input["connection"]["transport"] = serde_json::json!(transport);
|
||||||
|
} else {
|
||||||
|
input["connection"]
|
||||||
|
.as_object_mut()
|
||||||
|
.unwrap()
|
||||||
|
.remove("transport");
|
||||||
|
}
|
||||||
if oauth {
|
if oauth {
|
||||||
input["connection"]
|
input["connection"]
|
||||||
.as_object_mut()
|
.as_object_mut()
|
||||||
|
|||||||
@@ -126,7 +126,7 @@ mod query {
|
|||||||
"provider": "xai",
|
"provider": "xai",
|
||||||
"search": " operator ",
|
"search": " operator ",
|
||||||
"status": "normal",
|
"status": "normal",
|
||||||
"sortBy": "lastUsedAt",
|
"sortBy": "name",
|
||||||
"sortDirection": "desc"
|
"sortDirection": "desc"
|
||||||
}))
|
}))
|
||||||
.expect("deserialize account query");
|
.expect("deserialize account query");
|
||||||
@@ -139,10 +139,7 @@ mod query {
|
|||||||
));
|
));
|
||||||
assert_eq!(query.search.as_deref(), Some("operator"));
|
assert_eq!(query.search.as_deref(), Some("operator"));
|
||||||
assert_eq!(query.status, Some(AccountStatus::Normal));
|
assert_eq!(query.status, Some(AccountStatus::Normal));
|
||||||
assert_eq!(
|
assert_eq!(query.sort.expect("sort").field, AccountSortField::Name);
|
||||||
query.sort.expect("sort").field,
|
|
||||||
AccountSortField::LastUsedAt
|
|
||||||
);
|
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
query.sort.expect("copy sort").direction,
|
query.sort.expect("copy sort").direction,
|
||||||
SortDirection::Desc
|
SortDirection::Desc
|
||||||
@@ -727,6 +724,20 @@ mod actions {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn native_api_key_connection_accepts_address_and_key_without_transport() {
|
||||||
|
let request: UpdateAccountRequest = serde_json::from_value(json!({
|
||||||
|
"accountId":"acct_api", "enabled":true, "concurrencyLimit":null,
|
||||||
|
"weight":1, "groupIds":[],
|
||||||
|
"connection":{"baseUrl":"https://relay.example/antigravity/v1beta","apiKey":"fixture-key"}
|
||||||
|
})).unwrap();
|
||||||
|
request.validate().unwrap();
|
||||||
|
let connection = request.connection.unwrap();
|
||||||
|
assert!(connection.protocol.is_none());
|
||||||
|
assert!(connection.transport.is_none());
|
||||||
|
assert_eq!(connection.api_key.as_deref(), Some("fixture-key"));
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn account_connection_update_rejects_invalid_fields_and_generic_credentials() {
|
fn account_connection_update_rejects_invalid_fields_and_generic_credentials() {
|
||||||
let request = json!({
|
let request = json!({
|
||||||
|
|||||||
@@ -753,7 +753,8 @@ async fn diagnostics_should_keep_stable_key_and_display_name_contract() {
|
|||||||
account_authentication_kind: authentication_kind.map(str::to_owned),
|
account_authentication_kind: authentication_kind.map(str::to_owned),
|
||||||
account_plan_type: plan_type.map(str::to_owned),
|
account_plan_type: plan_type.map(str::to_owned),
|
||||||
account_plan_type_display: None,
|
account_plan_type_display: None,
|
||||||
name: "diag@example.invalid".to_owned(),
|
account_email: Some("diag@example.invalid".to_owned()),
|
||||||
|
name: "__none__".to_owned(),
|
||||||
request_count: 2,
|
request_count: 2,
|
||||||
success_count: 2,
|
success_count: 2,
|
||||||
failure_count: 0,
|
failure_count: 0,
|
||||||
@@ -813,11 +814,13 @@ async fn diagnostics_should_keep_stable_key_and_display_name_contract() {
|
|||||||
(
|
(
|
||||||
&value["data"]["items"][0]["key"],
|
&value["data"]["items"][0]["key"],
|
||||||
&value["data"]["items"][0]["name"],
|
&value["data"]["items"][0]["name"],
|
||||||
|
&value["data"]["items"][0]["accountEmail"],
|
||||||
&value["data"]["items"][0]["latencyP95Ms"],
|
&value["data"]["items"][0]["latencyP95Ms"],
|
||||||
&value["data"]["dimension"],
|
&value["data"]["dimension"],
|
||||||
),
|
),
|
||||||
(
|
(
|
||||||
&serde_json::json!("acct_diag"),
|
&serde_json::json!("acct_diag"),
|
||||||
|
&serde_json::json!("__none__"),
|
||||||
&serde_json::json!("diag@example.invalid"),
|
&serde_json::json!("diag@example.invalid"),
|
||||||
&serde_json::json!(3800),
|
&serde_json::json!(3800),
|
||||||
&serde_json::json!("account"),
|
&serde_json::json!("account"),
|
||||||
@@ -987,6 +990,8 @@ async fn usage_route_projects_request_facts_and_billing() {
|
|||||||
platform_icon: None,
|
platform_icon: None,
|
||||||
provider_account_upstream_peer: None,
|
provider_account_upstream_peer: None,
|
||||||
has_upstream_error: false,
|
has_upstream_error: false,
|
||||||
|
upstream_error_message: None,
|
||||||
|
retry_after_ms: None,
|
||||||
error_code: None,
|
error_code: None,
|
||||||
error_message: None,
|
error_message: None,
|
||||||
error_kind: None,
|
error_kind: None,
|
||||||
@@ -1089,6 +1094,8 @@ async fn usage_route_projects_request_facts_and_billing() {
|
|||||||
failed.upstream_status_code = Some(429);
|
failed.upstream_status_code = Some(429);
|
||||||
failed.error_code = Some("server_error".to_owned());
|
failed.error_code = Some("server_error".to_owned());
|
||||||
failed.error_message = Some("The upstream service is temporarily unavailable.".to_owned());
|
failed.error_message = Some("The upstream service is temporarily unavailable.".to_owned());
|
||||||
|
failed.upstream_error_message = Some("Retry once capacity is available.".to_owned());
|
||||||
|
failed.retry_after_ms = Some(30_000);
|
||||||
records.push(failed);
|
records.push(failed);
|
||||||
let mut closed = records[0].clone();
|
let mut closed = records[0].clone();
|
||||||
closed.id = "request_ws_closed".to_owned();
|
closed.id = "request_ws_closed".to_owned();
|
||||||
@@ -1131,6 +1138,11 @@ async fn usage_route_projects_request_facts_and_billing() {
|
|||||||
assert!(value["data"]["items"][0]["errorCode"].is_null());
|
assert!(value["data"]["items"][0]["errorCode"].is_null());
|
||||||
assert!(value["data"]["items"][0]["errorMessage"].is_null());
|
assert!(value["data"]["items"][0]["errorMessage"].is_null());
|
||||||
assert_eq!(value["data"]["items"][3]["errorCode"], "server_error");
|
assert_eq!(value["data"]["items"][3]["errorCode"], "server_error");
|
||||||
|
assert_eq!(
|
||||||
|
value["data"]["items"][3]["upstreamErrorMessage"],
|
||||||
|
"Retry once capacity is available."
|
||||||
|
);
|
||||||
|
assert_eq!(value["data"]["items"][3]["retryAfterMs"], 30_000);
|
||||||
assert_eq!(value["data"]["items"][3]["clientStatusCode"], 503);
|
assert_eq!(value["data"]["items"][3]["clientStatusCode"], 503);
|
||||||
assert_eq!(value["data"]["items"][3]["upstreamStatusCode"], 429);
|
assert_eq!(value["data"]["items"][3]["upstreamStatusCode"], 429);
|
||||||
assert_eq!(value["data"]["items"][3]["errorOrigin"], "upstream");
|
assert_eq!(value["data"]["items"][3]["errorOrigin"], "upstream");
|
||||||
|
|||||||
@@ -24,6 +24,27 @@ use tower::ServiceExt as _;
|
|||||||
|
|
||||||
use super::{AdminTestFixture, AdminTestState, unavailable_system};
|
use super::{AdminTestFixture, AdminTestState, unavailable_system};
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn version_should_expose_runtime_identity_and_restart_capability() {
|
||||||
|
let fixture = crate::support::key_fixture().await;
|
||||||
|
fixture.auth.insert_session("valid-session");
|
||||||
|
let response = app(fixture.state())
|
||||||
|
.oneshot(
|
||||||
|
Request::builder()
|
||||||
|
.uri("/api/admin/system/version")
|
||||||
|
.header(header::COOKIE, "cpr_session=valid-session")
|
||||||
|
.header("x-request-id", "req_system_version")
|
||||||
|
.body(Body::empty())
|
||||||
|
.expect("version request"),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.expect("version response");
|
||||||
|
assert_eq!(response.status(), StatusCode::OK);
|
||||||
|
let body = crate::support::response_json(response).await;
|
||||||
|
assert_eq!(body["data"]["instanceId"], "test-instance");
|
||||||
|
assert_eq!(body["data"]["restartSupported"], true);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn update_detail_query_should_default_to_no_refresh_and_reject_unknown_fields() {
|
fn update_detail_query_should_default_to_no_refresh_and_reject_unknown_fields() {
|
||||||
let query: UpdateDetailQuery = serde_json::from_str("{}").expect("empty query object");
|
let query: UpdateDetailQuery = serde_json::from_str("{}").expect("empty query object");
|
||||||
@@ -216,7 +237,7 @@ impl SystemOperations for ProgressSystem {
|
|||||||
available_channels: vec![SystemUpdateChannel::Stable, SystemUpdateChannel::Beta],
|
available_channels: vec![SystemUpdateChannel::Stable, SystemUpdateChannel::Beta],
|
||||||
},
|
},
|
||||||
current_version: "0.1.0".into(),
|
current_version: "0.1.0".into(),
|
||||||
latest_version: "0.2.0".into(),
|
latest_version: Some("0.2.0".into()),
|
||||||
has_update: true,
|
has_update: true,
|
||||||
deployment_mode: "docker".into(),
|
deployment_mode: "docker".into(),
|
||||||
build_type: "release".into(),
|
build_type: "release".into(),
|
||||||
|
|||||||
@@ -256,12 +256,20 @@ async fn request_middleware_sees_original_chat_and_preserves_the_endpoint() {
|
|||||||
let mut execution = Execution::new(Session::new(vec![created(), completed("ok")]));
|
let mut execution = Execution::new(Session::new(vec![created(), completed("ok")]));
|
||||||
execution.middleware = Some(middleware.frozen());
|
execution.middleware = Some(middleware.frozen());
|
||||||
let fixture = Fixture::with_execution(execution).await;
|
let fixture = Fixture::with_execution(execution).await;
|
||||||
let response = fixture.post(chat_request(false)).await;
|
let mut request = chat_request(false);
|
||||||
|
request["stream_options"] = json!({"include_usage":true});
|
||||||
|
request["messages"] = json!([
|
||||||
|
{"role":"developer","content":"brief"},
|
||||||
|
{"role":"system","content":null},
|
||||||
|
{"role":"assistant","tool_calls":[]},
|
||||||
|
{"role":"user","content":[{"type":"text","text":null},{"type":"text","text":"hello"}]}
|
||||||
|
]);
|
||||||
|
let response = fixture.post(request.clone()).await;
|
||||||
assert_eq!(response.status(), StatusCode::OK);
|
assert_eq!(response.status(), StatusCode::OK);
|
||||||
let downstream = json_body(response).await;
|
let downstream = json_body(response).await;
|
||||||
assert_eq!(downstream["object"], "chat.completion");
|
assert_eq!(downstream["object"], "chat.completion");
|
||||||
let observed = middleware.requests.lock().unwrap();
|
let observed = middleware.requests.lock().unwrap();
|
||||||
assert_eq!(observed.as_slice(), [chat_request(false)]);
|
assert_eq!(observed.as_slice(), [request]);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
middleware.inner.endpoints.lock().unwrap().as_slice(),
|
middleware.inner.endpoints.lock().unwrap().as_slice(),
|
||||||
[PATH]
|
[PATH]
|
||||||
|
|||||||
@@ -101,8 +101,8 @@ async fn capacity_errors_offer_client_retry_without_changing_upstream_facts() {
|
|||||||
assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
|
assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
|
||||||
if raw_response {
|
if raw_response {
|
||||||
assert_eq!(response.headers()["x-request-id"], "req_capacity");
|
assert_eq!(response.headers()["x-request-id"], "req_capacity");
|
||||||
assert!(!response.headers().contains_key("retry-after"));
|
assert_eq!(response.headers()["retry-after"], "7");
|
||||||
assert!(!response.headers().contains_key("retry-after-ms"));
|
assert_eq!(response.headers()["retry-after-ms"], "7000");
|
||||||
}
|
}
|
||||||
let body: Value = serde_json::from_slice(
|
let body: Value = serde_json::from_slice(
|
||||||
&to_bytes(response.into_body(), 4096)
|
&to_bytes(response.into_body(), 4096)
|
||||||
@@ -116,7 +116,6 @@ async fn capacity_errors_offer_client_retry_without_changing_upstream_facts() {
|
|||||||
if raw_response {
|
if raw_response {
|
||||||
let mut expected = original.clone();
|
let mut expected = original.clone();
|
||||||
expected["error"]["code"] = json!("server_error");
|
expected["error"]["code"] = json!("server_error");
|
||||||
expected["error"]["headers"] = json!({"x-request-id":"req_capacity"});
|
|
||||||
assert_eq!(body, expected);
|
assert_eq!(body, expected);
|
||||||
}
|
}
|
||||||
let EngineError::Provider(provider) = error else {
|
let EngineError::Provider(provider) = error else {
|
||||||
@@ -397,16 +396,16 @@ fn local_provider_capacity_exhaustion_should_map_to_service_unavailable() {
|
|||||||
);
|
);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
projected.safe_message(),
|
projected.safe_message(),
|
||||||
"The gateway account pool is busy."
|
"No eligible account currently has capacity for this request."
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[tokio::test]
|
||||||
fn no_eligible_provider_account_should_preserve_safe_provider_detail() {
|
async fn no_eligible_provider_account_should_preserve_safe_provider_detail() {
|
||||||
let detail = ClientVisibleUpstreamError::new(
|
let detail = ClientVisibleUpstreamError::new(
|
||||||
"no account is eligible for the requested model",
|
"This request requires an upstream WebSocket.",
|
||||||
Some("no_eligible_account".to_owned()),
|
Some("websocket_account_unavailable".to_owned()),
|
||||||
Some("account_unavailable_error".to_owned()),
|
None,
|
||||||
);
|
);
|
||||||
let error = EngineError::Provider(
|
let error = EngineError::Provider(
|
||||||
ProviderError::new(
|
ProviderError::new(
|
||||||
@@ -420,17 +419,24 @@ fn no_eligible_provider_account_should_preserve_safe_provider_detail() {
|
|||||||
assert_eq!(gateway.kind(), GatewayErrorKind::NoAvailableProvider);
|
assert_eq!(gateway.kind(), GatewayErrorKind::NoAvailableProvider);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
gateway.client_message(),
|
gateway.client_message(),
|
||||||
"no account is eligible for the requested model"
|
"This request requires an upstream WebSocket."
|
||||||
);
|
);
|
||||||
assert_eq!(gateway.client_error_code(), Some("no_eligible_account"));
|
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
gateway.client_error_type(),
|
gateway.client_error_code(),
|
||||||
Some("account_unavailable_error")
|
Some("websocket_account_unavailable")
|
||||||
);
|
);
|
||||||
|
assert_eq!(gateway.client_error_type(), None);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
gateway.safe_message(),
|
gateway.safe_message(),
|
||||||
"The gateway found no eligible account for this request."
|
"The gateway found no eligible account for this request."
|
||||||
);
|
);
|
||||||
|
let response = engine_error_response(&error);
|
||||||
|
assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
|
||||||
|
let body: serde_json::Value =
|
||||||
|
serde_json::from_slice(&to_bytes(response.into_body(), usize::MAX).await.unwrap()).unwrap();
|
||||||
|
assert_eq!(body["error"]["type"], "server_error");
|
||||||
|
assert_eq!(body["error"]["code"], "websocket_account_unavailable");
|
||||||
|
assert_eq!(body["error"]["message"], gateway.client_message());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -509,6 +515,7 @@ fn engine_provider_unsupported_capability_should_remain_unsupported() {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn engine_provider_credential_failures_should_not_impersonate_client_auth_failures() {
|
fn engine_provider_credential_failures_should_not_impersonate_client_auth_failures() {
|
||||||
|
let mut messages = std::collections::HashSet::new();
|
||||||
for kind in [
|
for kind in [
|
||||||
ProviderErrorKind::Unauthorized,
|
ProviderErrorKind::Unauthorized,
|
||||||
ProviderErrorKind::PermissionDenied,
|
ProviderErrorKind::PermissionDenied,
|
||||||
@@ -517,11 +524,19 @@ fn engine_provider_credential_failures_should_not_impersonate_client_auth_failur
|
|||||||
let mapped = gateway_error_from_engine(&error);
|
let mapped = gateway_error_from_engine(&error);
|
||||||
|
|
||||||
assert_eq!(mapped.kind(), GatewayErrorKind::UpstreamUnavailable);
|
assert_eq!(mapped.kind(), GatewayErrorKind::UpstreamUnavailable);
|
||||||
assert_eq!(
|
assert!(
|
||||||
mapped.safe_message(),
|
mapped
|
||||||
"The upstream account cannot access the service."
|
.safe_message()
|
||||||
|
.to_lowercase()
|
||||||
|
.contains("upstream account")
|
||||||
);
|
);
|
||||||
|
messages.insert(mapped.safe_message().to_owned());
|
||||||
}
|
}
|
||||||
|
assert_eq!(
|
||||||
|
messages.len(),
|
||||||
|
2,
|
||||||
|
"authentication and permission failures must be distinguishable"
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -578,19 +593,29 @@ fn engine_provider_timeout_and_cancellation_should_remain_distinct() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn engine_provider_runtime_failures_should_collapse_to_safe_unavailability() {
|
fn engine_provider_runtime_failures_preserve_the_cause_without_exposing_internal_details() {
|
||||||
|
let mut messages = std::collections::HashSet::new();
|
||||||
for kind in [
|
for kind in [
|
||||||
ProviderErrorKind::Transport,
|
ProviderErrorKind::Transport,
|
||||||
ProviderErrorKind::Protocol,
|
ProviderErrorKind::Protocol,
|
||||||
ProviderErrorKind::Unavailable,
|
ProviderErrorKind::Unavailable,
|
||||||
ProviderErrorKind::ProcessTerminated,
|
ProviderErrorKind::ProcessTerminated,
|
||||||
] {
|
] {
|
||||||
let error = EngineError::Provider(ProviderError::new(kind, UpstreamSendState::Ambiguous));
|
let error = EngineError::Provider(
|
||||||
|
ProviderError::new(kind, UpstreamSendState::Ambiguous)
|
||||||
|
.with_source(std::io::Error::other("PRIVATE_ENDPOINT_AND_CREDENTIAL")),
|
||||||
|
);
|
||||||
|
|
||||||
let projected = gateway_error_from_engine(&error);
|
let projected = gateway_error_from_engine(&error);
|
||||||
assert_eq!(projected.kind(), GatewayErrorKind::UpstreamUnavailable);
|
assert_eq!(projected.kind(), GatewayErrorKind::UpstreamUnavailable);
|
||||||
assert_eq!(projected.safe_message(), "Upstream service is unavailable.");
|
assert!(!projected.client_message().contains("PRIVATE_"));
|
||||||
|
messages.insert(projected.client_message().to_owned());
|
||||||
}
|
}
|
||||||
|
assert_eq!(
|
||||||
|
messages.len(),
|
||||||
|
4,
|
||||||
|
"different failure causes must remain distinguishable"
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|||||||
@@ -334,7 +334,7 @@ async fn request_settings_reach_query_terminal_without_mutating_authenticated_ba
|
|||||||
runtime["account_queue_timeout_seconds"] = serde_json::json!(30);
|
runtime["account_queue_timeout_seconds"] = serde_json::json!(30);
|
||||||
runtime["switch_account_on_queue_failure"] = serde_json::json!(false);
|
runtime["switch_account_on_queue_failure"] = serde_json::json!(false);
|
||||||
settings.runtime = serde_json::from_value(runtime).unwrap();
|
settings.runtime = serde_json::from_value(runtime).unwrap();
|
||||||
settings.fast_mode = FastMode::Disabled;
|
settings.fast_mode = Some(FastMode::Disabled);
|
||||||
}),
|
}),
|
||||||
..Default::default()
|
..Default::default()
|
||||||
}));
|
}));
|
||||||
@@ -355,8 +355,12 @@ async fn request_settings_reach_query_terminal_without_mutating_authenticated_ba
|
|||||||
"model-a"
|
"model-a"
|
||||||
);
|
);
|
||||||
assert_ne!(
|
assert_ne!(
|
||||||
execution.client.policy().account_scope().fast_mode(),
|
execution
|
||||||
FastMode::Disabled
|
.client
|
||||||
|
.policy()
|
||||||
|
.account_scope()
|
||||||
|
.fast_mode_override(),
|
||||||
|
Some(FastMode::Disabled)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1416,7 +1416,7 @@ async fn streaming_bad_request_preserves_extended_error_fields_before_and_after_
|
|||||||
Some(b"application/json".to_vec()),
|
Some(b"application/json".to_vec()),
|
||||||
Bytes::from(json!({"error": error}).to_string()),
|
Bytes::from(json!({"error": error}).to_string()),
|
||||||
)
|
)
|
||||||
.with_headers(headers(&[("retry-after", "7")])),
|
.with_headers(headers(&[("retry-after", "7"), ("retry-after-ms", "7012")])),
|
||||||
)
|
)
|
||||||
};
|
};
|
||||||
let immediate = FakeSession::streaming(
|
let immediate = FakeSession::streaming(
|
||||||
@@ -1447,7 +1447,7 @@ async fn streaming_bad_request_preserves_extended_error_fields_before_and_after_
|
|||||||
.find(|event| event.event.as_deref() == Some("response.failed"))
|
.find(|event| event.event.as_deref() == Some("response.failed"))
|
||||||
.unwrap();
|
.unwrap();
|
||||||
let payload: Value = serde_json::from_str(&failed.data).unwrap();
|
let payload: Value = serde_json::from_str(&failed.data).unwrap();
|
||||||
error["headers"] = json!({"retry-after": "7"});
|
error["headers"] = json!({"retry-after": "7", "retry-after-ms":"7012"});
|
||||||
assert_eq!(payload["response"]["error"], error);
|
assert_eq!(payload["response"]["error"], error);
|
||||||
assert!(bytes.ends_with(b"data: [DONE]\n\n"));
|
assert!(bytes.ends_with(b"data: [DONE]\n\n"));
|
||||||
}
|
}
|
||||||
@@ -2214,14 +2214,13 @@ async fn streaming_upstream_wire_failure_should_not_be_rewritten_as_a_gateway_er
|
|||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn streaming_upstream_error_event_should_be_translated_to_response_failed_for_sse() {
|
async fn streaming_upstream_error_event_should_be_translated_to_response_failed_for_sse() {
|
||||||
for (error_type, code, client_code, kind, client_status, keeps_retry_after) in [
|
for (error_type, code, client_code, kind, client_status) in [
|
||||||
(
|
(
|
||||||
"service_unavailable_error",
|
"service_unavailable_error",
|
||||||
"server_is_overloaded",
|
"server_is_overloaded",
|
||||||
"server_error",
|
"server_error",
|
||||||
ProviderErrorKind::UpstreamCapacityUnavailable,
|
ProviderErrorKind::UpstreamCapacityUnavailable,
|
||||||
503,
|
503,
|
||||||
false,
|
|
||||||
),
|
),
|
||||||
(
|
(
|
||||||
"rate_limit_error",
|
"rate_limit_error",
|
||||||
@@ -2229,7 +2228,6 @@ async fn streaming_upstream_error_event_should_be_translated_to_response_failed_
|
|||||||
"turn_rate_limit_exceeded",
|
"turn_rate_limit_exceeded",
|
||||||
ProviderErrorKind::RateLimited,
|
ProviderErrorKind::RateLimited,
|
||||||
429,
|
429,
|
||||||
true,
|
|
||||||
),
|
),
|
||||||
] {
|
] {
|
||||||
let trace = Arc::new(Trace::default());
|
let trace = Arc::new(Trace::default());
|
||||||
@@ -2306,16 +2304,17 @@ async fn streaming_upstream_error_event_should_be_translated_to_response_failed_
|
|||||||
.find(|event| event.event.as_deref() == Some("response.failed"))
|
.find(|event| event.event.as_deref() == Some("response.failed"))
|
||||||
.expect("translated response.failed event");
|
.expect("translated response.failed event");
|
||||||
let failed: Value = serde_json::from_str(&failed.data).expect("response.failed JSON");
|
let failed: Value = serde_json::from_str(&failed.data).expect("response.failed JSON");
|
||||||
let mut expected = json!({
|
let expected = json!({
|
||||||
"type": "response.failed",
|
"type": "response.failed",
|
||||||
"status": client_status,
|
"status": client_status,
|
||||||
"headers": {"x-request-id": "req_test"},
|
"headers": {"Retry-After": "24", "retry-after-ms": "24000", "x-request-id": "req_test"},
|
||||||
"response": {
|
"response": {
|
||||||
"id": "resp_test",
|
"id": "resp_test",
|
||||||
"model": "public-model",
|
"model": "public-model",
|
||||||
"status": "failed",
|
"status": "failed",
|
||||||
"error": {
|
"error": {
|
||||||
"type": error_type,
|
"type": error_type,
|
||||||
|
"headers": {"retry-after": "24", "retry-after-ms": "24000"},
|
||||||
"code": client_code,
|
"code": client_code,
|
||||||
"message": "Our servers are currently overloaded. Please try again later.",
|
"message": "Our servers are currently overloaded. Please try again later.",
|
||||||
"param": null,
|
"param": null,
|
||||||
@@ -2326,11 +2325,6 @@ async fn streaming_upstream_error_event_should_be_translated_to_response_failed_
|
|||||||
"sequence_number": 2,
|
"sequence_number": 2,
|
||||||
"future_event_field": {"keep": true}
|
"future_event_field": {"keep": true}
|
||||||
});
|
});
|
||||||
if keeps_retry_after {
|
|
||||||
expected["headers"]["Retry-After"] = json!("24");
|
|
||||||
expected["headers"]["retry-after-ms"] = json!("24000");
|
|
||||||
expected["response"]["error"]["headers"] = json!({"retry-after": "24"});
|
|
||||||
}
|
|
||||||
|
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
(
|
(
|
||||||
@@ -2346,18 +2340,38 @@ async fn streaming_upstream_error_event_should_be_translated_to_response_failed_
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn streaming_capacity_error_after_commit_offers_client_retry() {
|
async fn streaming_errors_after_commit_preserve_upstream_retry_headers() {
|
||||||
for code in ["server_is_overloaded", "slow_down"] {
|
for (kind, code, expected) in [
|
||||||
let trace = Arc::new(Trace::default());
|
(
|
||||||
let error = ProviderError::new(
|
|
||||||
ProviderErrorKind::UpstreamCapacityUnavailable,
|
ProviderErrorKind::UpstreamCapacityUnavailable,
|
||||||
UpstreamSendState::Sent,
|
"server_is_overloaded",
|
||||||
)
|
"server_error",
|
||||||
.with_client_visible_upstream_error(ClientVisibleUpstreamError::new(
|
),
|
||||||
"busy",
|
(
|
||||||
Some(code.to_owned()),
|
ProviderErrorKind::UpstreamCapacityUnavailable,
|
||||||
Some("service_unavailable_error".to_owned()),
|
"slow_down",
|
||||||
));
|
"server_error",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
ProviderErrorKind::QuotaExhausted,
|
||||||
|
"previous_response_not_found",
|
||||||
|
"previous_response_not_found",
|
||||||
|
),
|
||||||
|
] {
|
||||||
|
let trace = Arc::new(Trace::default());
|
||||||
|
let error = ProviderError::new(kind, UpstreamSendState::Sent)
|
||||||
|
.with_client_visible_upstream_response(
|
||||||
|
ClientVisibleUpstreamResponse::new(400, None, Bytes::new()).with_headers(vec![
|
||||||
|
ProviderResponseHeader::new("Retry-After", Bytes::from_static(b"309")),
|
||||||
|
ProviderResponseHeader::new("retry-after-ms", Bytes::from_static(b"309001")),
|
||||||
|
ProviderResponseHeader::new("x-unrelated", Bytes::from_static(b"omit")),
|
||||||
|
]),
|
||||||
|
)
|
||||||
|
.with_client_visible_upstream_error(ClientVisibleUpstreamError::new(
|
||||||
|
"busy",
|
||||||
|
Some(code.to_owned()),
|
||||||
|
Some("service_unavailable_error".to_owned()),
|
||||||
|
));
|
||||||
let session = FakeSession::streaming(
|
let session = FakeSession::streaming(
|
||||||
Arc::clone(&trace),
|
Arc::clone(&trace),
|
||||||
vec![
|
vec![
|
||||||
@@ -2377,7 +2391,11 @@ async fn streaming_capacity_error_after_commit_offers_client_retry() {
|
|||||||
.find(|event| event.event.as_deref() == Some("response.failed"))
|
.find(|event| event.event.as_deref() == Some("response.failed"))
|
||||||
.expect("failed event");
|
.expect("failed event");
|
||||||
let failed: Value = serde_json::from_str(&failed.data).expect("JSON");
|
let failed: Value = serde_json::from_str(&failed.data).expect("JSON");
|
||||||
assert_eq!(failed["response"]["error"]["code"], "server_error");
|
assert_eq!(failed["response"]["error"]["code"], expected);
|
||||||
|
assert_eq!(
|
||||||
|
failed["response"]["error"]["headers"],
|
||||||
|
json!({"retry-after": "309", "retry-after-ms": "309001"})
|
||||||
|
);
|
||||||
assert_eq!(failed["response"]["error"]["message"], "busy");
|
assert_eq!(failed["response"]["error"]["message"], "busy");
|
||||||
assert_eq!(text.matches("event: response.failed").count(), 1);
|
assert_eq!(text.matches("event: response.failed").count(), 1);
|
||||||
assert!(text.ends_with("data: [DONE]\n\n"));
|
assert!(text.ends_with("data: [DONE]\n\n"));
|
||||||
@@ -3282,6 +3300,12 @@ async fn response_ids_are_provider_and_client_independent() {
|
|||||||
(&[], MODEL_REQUEST_ID),
|
(&[], MODEL_REQUEST_ID),
|
||||||
(&[("x-request-id", "upstream-primary")], "upstream-primary"),
|
(&[("x-request-id", "upstream-primary")], "upstream-primary"),
|
||||||
(&[("x-oai-request-id", "upstream-alias")], "upstream-alias"),
|
(&[("x-oai-request-id", "upstream-alias")], "upstream-alias"),
|
||||||
|
(
|
||||||
|
&[("x-openai-request-id", "upstream-openai")],
|
||||||
|
"upstream-openai",
|
||||||
|
),
|
||||||
|
(&[("x-ms-request-id", "upstream-ms")], "upstream-ms"),
|
||||||
|
(&[("cf-ray", "trace-only")], MODEL_REQUEST_ID),
|
||||||
(
|
(
|
||||||
&[
|
&[
|
||||||
("x-request-id", "upstream-primary"),
|
("x-request-id", "upstream-primary"),
|
||||||
@@ -3297,6 +3321,22 @@ async fn response_ids_are_provider_and_client_independent() {
|
|||||||
"upstream-alias",
|
"upstream-alias",
|
||||||
),
|
),
|
||||||
(&[("x-request-id", "")], MODEL_REQUEST_ID),
|
(&[("x-request-id", "")], MODEL_REQUEST_ID),
|
||||||
|
(
|
||||||
|
&[
|
||||||
|
("x-request-id", "é"),
|
||||||
|
("x-oai-request-id", " "),
|
||||||
|
("x-openai-request-id", ""),
|
||||||
|
("x-ms-request-id", "upstream-ms"),
|
||||||
|
],
|
||||||
|
"upstream-ms",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
&[
|
||||||
|
("x-openai-request-id", "upstream-openai"),
|
||||||
|
("x-ms-request-id", "upstream-ms"),
|
||||||
|
],
|
||||||
|
"upstream-openai",
|
||||||
|
),
|
||||||
];
|
];
|
||||||
for provider in ["openai", "xai"] {
|
for provider in ["openai", "xai"] {
|
||||||
for streaming in [false, true] {
|
for streaming in [false, true] {
|
||||||
@@ -3325,6 +3365,11 @@ async fn response_ids_are_provider_and_client_independent() {
|
|||||||
assert_eq!(response.status(), StatusCode::OK);
|
assert_eq!(response.status(), StatusCode::OK);
|
||||||
assert_eq!(response.headers()["x-request-id"], *expected);
|
assert_eq!(response.headers()["x-request-id"], *expected);
|
||||||
assert_eq!(response.headers()["x-gateway-request-id"], MODEL_REQUEST_ID);
|
assert_eq!(response.headers()["x-gateway-request-id"], MODEL_REQUEST_ID);
|
||||||
|
for (name, value) in *upstream_headers {
|
||||||
|
if *name != "x-request-id" {
|
||||||
|
assert_eq!(response.headers()[*name].as_bytes(), value.as_bytes());
|
||||||
|
}
|
||||||
|
}
|
||||||
assert!(
|
assert!(
|
||||||
!to_bytes(response.into_body(), 64 * 1024)
|
!to_bytes(response.into_body(), 64 * 1024)
|
||||||
.await
|
.await
|
||||||
@@ -3341,7 +3386,12 @@ async fn failure_ids_prefer_the_actual_error_over_session_headers() {
|
|||||||
let admin = crate::admin::AdminTestFixture::new().await.services;
|
let admin = crate::admin::AdminTestFixture::new().await.services;
|
||||||
for provider in ["openai", "xai"] {
|
for provider in ["openai", "xai"] {
|
||||||
for streaming in [false, true] {
|
for streaming in [false, true] {
|
||||||
for upstream_headers in [vec![], headers(&[("x-oai-request-id", "actual-error")])] {
|
for upstream_headers in [
|
||||||
|
vec![],
|
||||||
|
headers(&[("x-oai-request-id", "actual-error")]),
|
||||||
|
headers(&[("x-openai-request-id", "actual-error")]),
|
||||||
|
headers(&[("x-ms-request-id", "actual-error")]),
|
||||||
|
] {
|
||||||
let expected = if upstream_headers.is_empty() {
|
let expected = if upstream_headers.is_empty() {
|
||||||
MODEL_REQUEST_ID
|
MODEL_REQUEST_ID
|
||||||
} else {
|
} else {
|
||||||
@@ -3349,7 +3399,7 @@ async fn failure_ids_prefer_the_actual_error_over_session_headers() {
|
|||||||
};
|
};
|
||||||
let raw =
|
let raw =
|
||||||
Bytes::from_static(br#"{"error":{"message":"synthetic upstream detail"}}"#);
|
Bytes::from_static(br#"{"error":{"message":"synthetic upstream detail"}}"#);
|
||||||
let error =
|
let mut error =
|
||||||
ProviderError::new(ProviderErrorKind::InvalidRequest, UpstreamSendState::Sent)
|
ProviderError::new(ProviderErrorKind::InvalidRequest, UpstreamSendState::Sent)
|
||||||
.with_client_visible_upstream_response(
|
.with_client_visible_upstream_response(
|
||||||
ClientVisibleUpstreamResponse::new(
|
ClientVisibleUpstreamResponse::new(
|
||||||
@@ -3359,12 +3409,25 @@ async fn failure_ids_prefer_the_actual_error_over_session_headers() {
|
|||||||
)
|
)
|
||||||
.with_headers(upstream_headers),
|
.with_headers(upstream_headers),
|
||||||
);
|
);
|
||||||
|
if expected == "actual-error" {
|
||||||
|
// 最终响应头优先于错误对象中残留的旧观测 ID
|
||||||
|
error = error.with_upstream_request_id(OpaqueUpstreamValue::new("stale-fact"));
|
||||||
|
}
|
||||||
let session = failed_session(streaming, EngineError::Provider(error))
|
let session = failed_session(streaming, EngineError::Provider(error))
|
||||||
.with_response_headers(headers(&[("x-request-id", "earlier-session")]));
|
.with_response_headers(headers(&[
|
||||||
|
("x-request-id", "earlier-session"),
|
||||||
|
("x-openai-request-id", "earlier-openai"),
|
||||||
|
("x-ms-request-id", "earlier-ms"),
|
||||||
|
]));
|
||||||
let response = response(&admin, provider, session, streaming).await;
|
let response = response(&admin, provider, session, streaming).await;
|
||||||
assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
|
assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
|
||||||
assert_eq!(response.headers()["x-request-id"], expected);
|
assert_eq!(response.headers()["x-request-id"], expected);
|
||||||
assert_eq!(response.headers()["x-gateway-request-id"], MODEL_REQUEST_ID);
|
assert_eq!(response.headers()["x-gateway-request-id"], MODEL_REQUEST_ID);
|
||||||
|
for name in ["x-openai-request-id", "x-ms-request-id"] {
|
||||||
|
if let Some(value) = response.headers().get(name) {
|
||||||
|
assert_eq!(value, "actual-error");
|
||||||
|
}
|
||||||
|
}
|
||||||
assert_eq!(to_bytes(response.into_body(), 4096).await.unwrap(), raw);
|
assert_eq!(to_bytes(response.into_body(), 4096).await.unwrap(), raw);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -3376,12 +3439,16 @@ async fn failure_ids_prefer_the_actual_error_over_session_headers() {
|
|||||||
.with_response_headers(headers(&[
|
.with_response_headers(headers(&[
|
||||||
("x-request-id", "earlier-session"),
|
("x-request-id", "earlier-session"),
|
||||||
("x-oai-request-id", "earlier-alias"),
|
("x-oai-request-id", "earlier-alias"),
|
||||||
|
("x-openai-request-id", "earlier-openai"),
|
||||||
|
("x-ms-request-id", "earlier-ms"),
|
||||||
]));
|
]));
|
||||||
let response = response(&admin, provider, session, streaming).await;
|
let response = response(&admin, provider, session, streaming).await;
|
||||||
assert_eq!(response.status(), StatusCode::BAD_GATEWAY);
|
assert_eq!(response.status(), StatusCode::BAD_GATEWAY);
|
||||||
assert_eq!(response.headers()["x-request-id"], "body-read-error");
|
assert_eq!(response.headers()["x-request-id"], "body-read-error");
|
||||||
assert_eq!(response.headers().get_all("x-request-id").iter().count(), 1);
|
assert_eq!(response.headers().get_all("x-request-id").iter().count(), 1);
|
||||||
assert!(response.headers().get("x-oai-request-id").is_none());
|
assert!(response.headers().get("x-oai-request-id").is_none());
|
||||||
|
assert!(response.headers().get("x-openai-request-id").is_none());
|
||||||
|
assert!(response.headers().get("x-ms-request-id").is_none());
|
||||||
assert_eq!(response.headers()["x-gateway-request-id"], MODEL_REQUEST_ID);
|
assert_eq!(response.headers()["x-gateway-request-id"], MODEL_REQUEST_ID);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -3396,12 +3463,16 @@ async fn local_execution_failure_uses_the_existing_model_id() {
|
|||||||
failed_session(streaming, EngineError::Deadline).with_response_headers(headers(&[
|
failed_session(streaming, EngineError::Deadline).with_response_headers(headers(&[
|
||||||
("x-request-id", "opening-primary"),
|
("x-request-id", "opening-primary"),
|
||||||
("x-oai-request-id", "opening-alias"),
|
("x-oai-request-id", "opening-alias"),
|
||||||
|
("x-openai-request-id", "opening-openai"),
|
||||||
|
("x-ms-request-id", "opening-ms"),
|
||||||
("x-codex-turn-state", "retained-turn-state"),
|
("x-codex-turn-state", "retained-turn-state"),
|
||||||
]));
|
]));
|
||||||
let response = response(&admin, provider, session, streaming).await;
|
let response = response(&admin, provider, session, streaming).await;
|
||||||
assert_eq!(response.headers()["x-request-id"], MODEL_REQUEST_ID);
|
assert_eq!(response.headers()["x-request-id"], MODEL_REQUEST_ID);
|
||||||
assert_eq!(response.headers()["x-gateway-request-id"], MODEL_REQUEST_ID);
|
assert_eq!(response.headers()["x-gateway-request-id"], MODEL_REQUEST_ID);
|
||||||
assert!(response.headers().get("x-oai-request-id").is_none());
|
assert!(response.headers().get("x-oai-request-id").is_none());
|
||||||
|
assert!(response.headers().get("x-openai-request-id").is_none());
|
||||||
|
assert!(response.headers().get("x-ms-request-id").is_none());
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
response.headers()["x-codex-turn-state"],
|
response.headers()["x-codex-turn-state"],
|
||||||
"retained-turn-state"
|
"retained-turn-state"
|
||||||
|
|||||||
@@ -1256,16 +1256,12 @@ fn capacity_failure_projection_preserves_wire_metadata_and_original_events() {
|
|||||||
assert_eq!(sse_data["response"]["error"]["code"], "server_error");
|
assert_eq!(sse_data["response"]["error"]["code"], "server_error");
|
||||||
assert_eq!(sse_data["response"]["error"]["message"], "busy");
|
assert_eq!(sse_data["response"]["error"]["message"], "busy");
|
||||||
assert_eq!(sse_data["response"]["error"]["future"], 42);
|
assert_eq!(sse_data["response"]["error"]["future"], 42);
|
||||||
assert_eq!(
|
assert_eq!(sse_data["response"]["error"]["headers"], error["headers"]);
|
||||||
sse_data["response"]["error"]["headers"],
|
|
||||||
json!({"x-request-id":"req_capacity"})
|
|
||||||
);
|
|
||||||
let messages = ws.push_websocket(&event);
|
let messages = ws.push_websocket(&event);
|
||||||
let ws_data: Value = serde_json::from_str(&messages[0]).expect("JSON");
|
let ws_data: Value = serde_json::from_str(&messages[0]).expect("JSON");
|
||||||
if event_type == "error" && status.is_some() {
|
if event_type == "error" && status.is_some() {
|
||||||
let mut expected = original.clone();
|
let mut expected = original.clone();
|
||||||
expected["error"]["code"] = json!("server_error");
|
expected["error"]["code"] = json!("server_error");
|
||||||
expected["error"]["headers"] = json!({"x-request-id":"req_capacity"});
|
|
||||||
expected["status_code"] = json!(503);
|
expected["status_code"] = json!(503);
|
||||||
assert_eq!(ws_data, expected);
|
assert_eq!(ws_data, expected);
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -340,8 +340,8 @@ async fn initial_capacity_failure_offers_client_retry_with_upstream_correlation(
|
|||||||
assert_eq!(error["error"]["code"], "server_error");
|
assert_eq!(error["error"]["code"], "server_error");
|
||||||
assert_eq!(error["error"]["message"], "busy");
|
assert_eq!(error["error"]["message"], "busy");
|
||||||
assert_eq!(error["headers"]["x-request-id"], "req_capacity");
|
assert_eq!(error["headers"]["x-request-id"], "req_capacity");
|
||||||
assert!(error["headers"].get("retry-after").is_none());
|
assert_eq!(error["headers"]["retry-after"], "7");
|
||||||
assert!(error["headers"].get("retry-after-ms").is_none());
|
assert_eq!(error["headers"]["retry-after-ms"], "7000");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -369,23 +369,25 @@ async fn classified_capacity_error_without_special_code_returns_retryable_websoc
|
|||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn final_failure_headers_take_precedence_over_observed_opening_headers() {
|
async fn final_failure_headers_take_precedence_over_observed_opening_headers() {
|
||||||
let provider = upstream_failure(403, b"", vec![header("x-oai-request-id", b"req_final")])
|
for name in ["x-oai-request-id", "x-openai-request-id", "x-ms-request-id"] {
|
||||||
.with_status(502)
|
let provider = upstream_failure(403, b"", vec![header(name, b"req_final")])
|
||||||
.with_upstream_request_id(OpaqueUpstreamValue::new("req_stale_fact"));
|
.with_status(502)
|
||||||
let error = initial_error(
|
.with_upstream_request_id(OpaqueUpstreamValue::new("req_stale_fact"));
|
||||||
EngineError::Provider(provider),
|
let error = initial_error(
|
||||||
vec![
|
EngineError::Provider(provider),
|
||||||
header("x-request-id", b"req_old_opening"),
|
vec![
|
||||||
header("x-codex-turn-state", b"old-turn-state"),
|
header("x-request-id", b"req_old_opening"),
|
||||||
],
|
header("x-codex-turn-state", b"old-turn-state"),
|
||||||
)
|
],
|
||||||
.await;
|
)
|
||||||
assert_eq!(error["status"], 403);
|
.await;
|
||||||
assert_eq!(error["headers"]["x-oai-request-id"], "req_final");
|
assert_eq!(error["status"], 403);
|
||||||
assert!(error["headers"].get("x-request-id").is_none());
|
assert_eq!(error["headers"][name], "req_final");
|
||||||
assert!(!error.to_string().contains("req_old_opening"));
|
assert!(error["headers"].get("x-request-id").is_none());
|
||||||
assert!(!error.to_string().contains("req_stale_fact"));
|
assert!(!error.to_string().contains("req_old_opening"));
|
||||||
assert!(!error.to_string().contains("old-turn-state"));
|
assert!(!error.to_string().contains("req_stale_fact"));
|
||||||
|
assert!(!error.to_string().contains("old-turn-state"));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
@@ -398,6 +400,8 @@ async fn provider_failure_facts_survive_without_a_complete_http_response() {
|
|||||||
vec![
|
vec![
|
||||||
header("x-request-id", b"req_old"),
|
header("x-request-id", b"req_old"),
|
||||||
header("x-oai-request-id", b"req_old_alias"),
|
header("x-oai-request-id", b"req_old_alias"),
|
||||||
|
header("x-openai-request-id", b"req_old_openai"),
|
||||||
|
header("x-ms-request-id", b"req_old_ms"),
|
||||||
header("x-codex-turn-state", b"observed-turn-state"),
|
header("x-codex-turn-state", b"observed-turn-state"),
|
||||||
],
|
],
|
||||||
)
|
)
|
||||||
@@ -409,9 +413,11 @@ async fn provider_failure_facts_survive_without_a_complete_http_response() {
|
|||||||
"observed-turn-state"
|
"observed-turn-state"
|
||||||
);
|
);
|
||||||
assert!(error["headers"].get("x-oai-request-id").is_none());
|
assert!(error["headers"].get("x-oai-request-id").is_none());
|
||||||
|
assert!(error["headers"].get("x-openai-request-id").is_none());
|
||||||
|
assert!(error["headers"].get("x-ms-request-id").is_none());
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
error["error"]["message"],
|
error["error"]["message"],
|
||||||
"Upstream service is unavailable."
|
"Communication with the upstream service failed."
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -511,6 +517,8 @@ async fn opening_ids_stay_in_metadata_but_do_not_identify_initial_failures() {
|
|||||||
vec![
|
vec![
|
||||||
header("x-request-id", b"req_old_opening"),
|
header("x-request-id", b"req_old_opening"),
|
||||||
header("x-oai-request-id", b"req_observed"),
|
header("x-oai-request-id", b"req_observed"),
|
||||||
|
header("x-openai-request-id", b"req_observed_openai"),
|
||||||
|
header("x-ms-request-id", b"req_observed_ms"),
|
||||||
header("x-codex-turn-state", b"observed-turn-state"),
|
header("x-codex-turn-state", b"observed-turn-state"),
|
||||||
header("x-future-header", b"future-value"),
|
header("x-future-header", b"future-value"),
|
||||||
],
|
],
|
||||||
@@ -525,6 +533,8 @@ async fn opening_ids_stay_in_metadata_but_do_not_identify_initial_failures() {
|
|||||||
"headers": {
|
"headers": {
|
||||||
"x-request-id": "req_old_opening",
|
"x-request-id": "req_old_opening",
|
||||||
"x-oai-request-id": "req_observed",
|
"x-oai-request-id": "req_observed",
|
||||||
|
"x-openai-request-id": "req_observed_openai",
|
||||||
|
"x-ms-request-id": "req_observed_ms",
|
||||||
"x-codex-turn-state": "observed-turn-state",
|
"x-codex-turn-state": "observed-turn-state",
|
||||||
"x-future-header": "future-value",
|
"x-future-header": "future-value",
|
||||||
},
|
},
|
||||||
@@ -548,6 +558,46 @@ async fn opening_ids_stay_in_metadata_but_do_not_identify_initial_failures() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn metadata_prefers_readable_upstream_aliases_before_the_model_id() {
|
||||||
|
let cases: &[(&str, &[u8], Option<&str>)] = &[
|
||||||
|
("x-oai-request-id", b"req_oai", Some("req_oai")),
|
||||||
|
("X-OpenAI-Request-ID", b"req_openai", Some("req_openai")),
|
||||||
|
("x-ms-request-id", b"req_ms", Some("req_ms")),
|
||||||
|
("x-ms-request-id", b" \t ", None),
|
||||||
|
("x-ms-request-id", b"\xc3\xa9", None),
|
||||||
|
];
|
||||||
|
for (name, value, expected) in cases {
|
||||||
|
let trace = Arc::new(AtomicFailureTrace {
|
||||||
|
initial_errors: Mutex::new(VecDeque::from([EngineError::Deadline])),
|
||||||
|
..AtomicFailureTrace::default()
|
||||||
|
});
|
||||||
|
let (mut socket, _server) = connect(
|
||||||
|
Arc::clone(&trace),
|
||||||
|
vec![header("x-request-id", b"\xff"), header(name, value)],
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
send_request(&mut socket).await;
|
||||||
|
let metadata = next_event(&mut socket).await;
|
||||||
|
assert_eq!(metadata["type"], "response.metadata");
|
||||||
|
let model_id = trace.prepared_request_id.lock().unwrap().clone().unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
metadata["headers"]["x-request-id"],
|
||||||
|
expected.unwrap_or(&model_id)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
metadata["headers"][name.to_ascii_lowercase()].as_str(),
|
||||||
|
*expected
|
||||||
|
);
|
||||||
|
let error = next_event(&mut socket).await;
|
||||||
|
assert_eq!(error["type"], "error");
|
||||||
|
assert_eq!(error["headers"]["x-request-id"], "req_ws_atomic");
|
||||||
|
assert_eq!(error["headers"]["x-gateway-request-id"], "req_ws_atomic");
|
||||||
|
assert!(error["headers"].get(name.to_ascii_lowercase()).is_none());
|
||||||
|
socket.close(None).await.unwrap();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn header_only_request_middleware_updates_websocket_turn_context() {
|
async fn header_only_request_middleware_updates_websocket_turn_context() {
|
||||||
let middleware = Arc::new(crate::data_plane::middleware::RequestMiddleware {
|
let middleware = Arc::new(crate::data_plane::middleware::RequestMiddleware {
|
||||||
@@ -720,7 +770,9 @@ async fn initial_quota_recovery_delivers_client_projection_instead_of_upstream_s
|
|||||||
ClientVisibleUpstreamResponse::new(
|
ClientVisibleUpstreamResponse::new(
|
||||||
400,
|
400,
|
||||||
Some(b"application/json".to_vec()),
|
Some(b"application/json".to_vec()),
|
||||||
Bytes::from(json!({"error":detail}).to_string()),
|
Bytes::from(
|
||||||
|
json!({"error":detail, "headers":{"Retry-After-Ms":"777"}}).to_string(),
|
||||||
|
),
|
||||||
)
|
)
|
||||||
.with_headers(vec![header("x-request-id", b"req-quota-rejected")]),
|
.with_headers(vec![header("x-request-id", b"req-quota-rejected")]),
|
||||||
);
|
);
|
||||||
@@ -729,6 +781,7 @@ async fn initial_quota_recovery_delivers_client_projection_instead_of_upstream_s
|
|||||||
assert_eq!(error["error"], detail);
|
assert_eq!(error["error"], detail);
|
||||||
assert_eq!(error["headers"]["x-request-id"], "req-quota-rejected");
|
assert_eq!(error["headers"]["x-request-id"], "req-quota-rejected");
|
||||||
assert!(error["headers"].get("retry-after").is_none());
|
assert!(error["headers"].get("retry-after").is_none());
|
||||||
|
assert_eq!(error["headers"]["retry-after-ms"], "777");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
@@ -743,13 +796,38 @@ async fn initial_continuation_recovery_delivers_the_official_client_replay_signa
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn locally_exhausted_account_pool_sends_one_official_usage_limit_error() {
|
async fn account_selection_errors_distinguish_quota_from_websocket_requirements() {
|
||||||
let provider = ProviderError::new(
|
let exhausted = ProviderError::new(
|
||||||
ProviderErrorKind::AccountPoolQuotaExhausted,
|
ProviderErrorKind::AccountPoolQuotaExhausted,
|
||||||
UpstreamSendState::NotSent,
|
UpstreamSendState::NotSent,
|
||||||
);
|
);
|
||||||
let error = initial_error(EngineError::Provider(provider), Vec::new()).await;
|
let incompatible = ProviderError::new(
|
||||||
assert_eq!(error["status"], 429);
|
ProviderErrorKind::NoEligibleAccount,
|
||||||
assert_eq!(error["error"]["type"], "usage_limit_reached");
|
UpstreamSendState::NotSent,
|
||||||
assert_eq!(error["error"]["code"], "usage_limit_reached");
|
)
|
||||||
|
.with_client_visible_upstream_error(ClientVisibleUpstreamError::new(
|
||||||
|
"This request requires an upstream WebSocket.",
|
||||||
|
Some("websocket_account_unavailable".to_owned()),
|
||||||
|
None,
|
||||||
|
));
|
||||||
|
for (provider, status, kind, code) in [
|
||||||
|
(exhausted, 429, "usage_limit_reached", "usage_limit_reached"),
|
||||||
|
(
|
||||||
|
incompatible,
|
||||||
|
503,
|
||||||
|
"server_error",
|
||||||
|
"websocket_account_unavailable",
|
||||||
|
),
|
||||||
|
] {
|
||||||
|
let error = initial_error(EngineError::Provider(provider), Vec::new()).await;
|
||||||
|
assert_eq!(error["status"], status);
|
||||||
|
assert_eq!(error["error"]["type"], kind);
|
||||||
|
assert_eq!(error["error"]["code"], code);
|
||||||
|
if status == 503 {
|
||||||
|
assert_eq!(
|
||||||
|
error["error"]["message"],
|
||||||
|
"This request requires an upstream WebSocket."
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -313,6 +313,7 @@ fn response_create_should_reject_non_boolean_stream_without_disclosing_body_valu
|
|||||||
|
|
||||||
#[derive(Default)]
|
#[derive(Default)]
|
||||||
struct AtomicFailureTrace {
|
struct AtomicFailureTrace {
|
||||||
|
prepared_request_id: Mutex<Option<String>>,
|
||||||
starts: AtomicUsize,
|
starts: AtomicUsize,
|
||||||
next_calls: AtomicUsize,
|
next_calls: AtomicUsize,
|
||||||
committed: AtomicBool,
|
committed: AtomicBool,
|
||||||
@@ -414,8 +415,9 @@ struct AtomicFailureExecution {
|
|||||||
impl ExecutionService for AtomicFailureExecution {
|
impl ExecutionService for AtomicFailureExecution {
|
||||||
fn middleware_plan(
|
fn middleware_plan(
|
||||||
&self,
|
&self,
|
||||||
_: &gateway_core::engine::execution::PreparedRootExecution,
|
prepared: &gateway_core::engine::execution::PreparedRootExecution,
|
||||||
) -> Option<gateway_core::engine::middleware::FrozenMiddlewarePlan> {
|
) -> Option<gateway_core::engine::middleware::FrozenMiddlewarePlan> {
|
||||||
|
*self.trace.prepared_request_id.lock().unwrap() = Some(prepared.request_id().to_string());
|
||||||
self.trace.middleware.clone()
|
self.trace.middleware.clone()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -255,3 +255,71 @@ async fn original_rejected_request_is_dumped_only_when_explicitly_enabled() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn responses_ingress_separates_body_receipt_from_decompression_and_decoding() {
|
||||||
|
use std::io::Write as _;
|
||||||
|
use tracing::instrument::WithSubscriber as _;
|
||||||
|
|
||||||
|
let recorder = Recorder {
|
||||||
|
dump_enabled: false,
|
||||||
|
events: Arc::default(),
|
||||||
|
};
|
||||||
|
let events = recorder.events.clone();
|
||||||
|
let decoded = json!({"model":42,"input":"SENSITIVE_CONTENT".repeat(1024)}).to_string();
|
||||||
|
let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast());
|
||||||
|
encoder.write_all(decoded.as_bytes()).unwrap();
|
||||||
|
let encoded = encoder.finish().unwrap();
|
||||||
|
let encoded_len = encoded.len();
|
||||||
|
assert!(encoded_len < decoded.len());
|
||||||
|
async {
|
||||||
|
let (router, _) = fixture().await;
|
||||||
|
let body = Body::from_stream(futures::stream::once(async move {
|
||||||
|
tokio::time::sleep(std::time::Duration::from_millis(40)).await;
|
||||||
|
Ok::<_, std::io::Error>(encoded)
|
||||||
|
}));
|
||||||
|
let response = router
|
||||||
|
.oneshot(
|
||||||
|
Request::post("/v1/responses")
|
||||||
|
.header("authorization", "Bearer unused-client-route-key")
|
||||||
|
.header("content-encoding", "gzip")
|
||||||
|
.body(body)
|
||||||
|
.unwrap(),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
|
||||||
|
}
|
||||||
|
.with_subscriber(recorder)
|
||||||
|
.await;
|
||||||
|
let events = events.lock().unwrap();
|
||||||
|
let phases = events
|
||||||
|
.iter()
|
||||||
|
.filter(|event| {
|
||||||
|
event.get("stage").is_some_and(|stage| {
|
||||||
|
stage.starts_with("http.body.") || stage == "http.auth.finished"
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
assert_eq!(
|
||||||
|
phases
|
||||||
|
.iter()
|
||||||
|
.map(|event| event["stage"].as_str())
|
||||||
|
.collect::<Vec<_>>(),
|
||||||
|
[
|
||||||
|
"http.body.received",
|
||||||
|
"http.auth.finished",
|
||||||
|
"http.body.decompressed",
|
||||||
|
"http.body.decoded",
|
||||||
|
]
|
||||||
|
);
|
||||||
|
assert!(phases[0]["receive_ms"].parse::<u64>().unwrap() >= 30);
|
||||||
|
assert_eq!(phases[0]["encoded_bytes"], encoded_len.to_string());
|
||||||
|
assert_eq!(phases[0]["content_encoding"], "gzip");
|
||||||
|
assert_eq!(phases[2]["decoded_bytes"], decoded.len().to_string());
|
||||||
|
assert_eq!(phases[2]["accepted"], "true");
|
||||||
|
assert_eq!(phases[3]["accepted"], "false");
|
||||||
|
assert!(events.iter().flat_map(|event| event.values()).all(|value| {
|
||||||
|
!value.contains("SENSITIVE_CONTENT") && !value.contains("unused-client-route-key")
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|||||||
@@ -104,6 +104,8 @@ fn usage_record() -> UsageListRecord {
|
|||||||
platform_icon: None,
|
platform_icon: None,
|
||||||
provider_account_upstream_peer: None,
|
provider_account_upstream_peer: None,
|
||||||
has_upstream_error: false,
|
has_upstream_error: false,
|
||||||
|
upstream_error_message: Some("private-sentinel-upstream".into()),
|
||||||
|
retry_after_ms: Some(30_000),
|
||||||
error_code: None,
|
error_code: None,
|
||||||
error_message: None,
|
error_message: None,
|
||||||
error_kind: None,
|
error_kind: None,
|
||||||
|
|||||||
@@ -91,12 +91,14 @@ impl SystemOperations for VersionSystem {
|
|||||||
async fn version(&self) -> Result<SystemVersion, SystemOperationError> {
|
async fn version(&self) -> Result<SystemVersion, SystemOperationError> {
|
||||||
Ok(SystemVersion {
|
Ok(SystemVersion {
|
||||||
version: "3.7.0".to_owned(),
|
version: "3.7.0".to_owned(),
|
||||||
|
instance_id: "test-instance".to_owned(),
|
||||||
|
restart_supported: true,
|
||||||
git_sha: "internal-revision".to_owned(),
|
git_sha: "internal-revision".to_owned(),
|
||||||
build_time: "internal-build-time".to_owned(),
|
build_time: "internal-build-time".to_owned(),
|
||||||
deployment_mode: "binary".to_owned(),
|
deployment_mode: "binary".to_owned(),
|
||||||
update_channel: "release".to_owned(),
|
update_channel: "release".to_owned(),
|
||||||
|
|
||||||
latest_version: "3.8.0".to_owned(),
|
latest_version: Some("3.8.0".to_owned()),
|
||||||
has_update: true,
|
has_update: true,
|
||||||
update_cached: true,
|
update_cached: true,
|
||||||
update_warning: Some("internal-update-warning".to_owned()),
|
update_warning: Some("internal-update-warning".to_owned()),
|
||||||
|
|||||||
@@ -21,6 +21,8 @@ pub use quota_settings::{
|
|||||||
};
|
};
|
||||||
mod proxy;
|
mod proxy;
|
||||||
pub use proxy::{InvalidOutboundProxy, OutboundProxy};
|
pub use proxy::{InvalidOutboundProxy, OutboundProxy};
|
||||||
|
mod recent_requests;
|
||||||
|
pub use recent_requests::{InvalidRecentRequestSnapshot, RecentRequestSnapshot};
|
||||||
mod scheduling;
|
mod scheduling;
|
||||||
pub mod scope;
|
pub mod scope;
|
||||||
mod selection;
|
mod selection;
|
||||||
@@ -36,6 +38,6 @@ pub(crate) use selection::smart_score;
|
|||||||
pub use selection::*;
|
pub use selection::*;
|
||||||
pub use store::{
|
pub use store::{
|
||||||
AccountCatalogObservation, AccountCatalogOmissions, ProviderAccountStore, QuotaWarmupState,
|
AccountCatalogObservation, AccountCatalogOmissions, ProviderAccountStore, QuotaWarmupState,
|
||||||
QuotaWarmupStateUpdate, StoredAccountCatalog,
|
QuotaWarmupStateUpdate, RecentRequestStore, StoredAccountCatalog,
|
||||||
};
|
};
|
||||||
pub use upstream::*;
|
pub use upstream::*;
|
||||||
|
|||||||
@@ -0,0 +1,230 @@
|
|||||||
|
//! 账号与模型的近期请求计数,按秒滚动并在进程内回收过期记录
|
||||||
|
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::time::{Duration, Instant, SystemTime};
|
||||||
|
|
||||||
|
use crate::identity::ProviderKind;
|
||||||
|
|
||||||
|
use super::ProviderAccountId;
|
||||||
|
|
||||||
|
const WINDOW_SECONDS: u64 = 60;
|
||||||
|
|
||||||
|
/// 快照内容不满足账号标识、秒桶或计数约束
|
||||||
|
#[derive(Debug, Clone, Copy, thiserror::Error)]
|
||||||
|
#[error("recent request snapshot is invalid")]
|
||||||
|
pub struct InvalidRecentRequestSnapshot;
|
||||||
|
|
||||||
|
/// 可丢失的近期请求快照,保留观测时间与每个秒桶的年龄
|
||||||
|
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||||
|
pub struct RecentRequestSnapshot {
|
||||||
|
captured_at: SystemTime,
|
||||||
|
windows: Vec<PersistedWindow>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||||
|
struct PersistedWindow {
|
||||||
|
provider: ProviderKind,
|
||||||
|
account: String,
|
||||||
|
model: String,
|
||||||
|
buckets: Vec<(Duration, u64)>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub(super) struct RecentRequests {
|
||||||
|
epoch: Instant,
|
||||||
|
last_cleanup: u64,
|
||||||
|
windows: HashMap<(ProviderKind, ProviderAccountId, String), RequestWindow>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
struct RequestWindow {
|
||||||
|
buckets: [u64; WINDOW_SECONDS as usize],
|
||||||
|
second: u64,
|
||||||
|
total: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RequestWindow {
|
||||||
|
fn advance(&mut self, second: u64) {
|
||||||
|
let elapsed = second.saturating_sub(self.second);
|
||||||
|
if elapsed >= WINDOW_SECONDS {
|
||||||
|
self.buckets.fill(0);
|
||||||
|
self.total = 0;
|
||||||
|
} else {
|
||||||
|
for offset in 1..=elapsed {
|
||||||
|
let index = ((self.second + offset) % WINDOW_SECONDS) as usize;
|
||||||
|
self.total -= self.buckets[index];
|
||||||
|
self.buckets[index] = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.second = self.second.max(second);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for RecentRequests {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
epoch: Instant::now(),
|
||||||
|
last_cleanup: 0,
|
||||||
|
windows: HashMap::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RecentRequests {
|
||||||
|
pub(super) fn snapshot(&mut self, now: Instant, wall_now: SystemTime) -> RecentRequestSnapshot {
|
||||||
|
let second = self.second(now);
|
||||||
|
let mut windows = Vec::with_capacity(self.windows.len());
|
||||||
|
for ((provider, account, model), window) in &mut self.windows {
|
||||||
|
window.advance(second);
|
||||||
|
if window.total == 0 {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let buckets = (0..WINDOW_SECONDS.min(second + 1))
|
||||||
|
.filter_map(|age| {
|
||||||
|
let index = ((second - age) % WINDOW_SECONDS) as usize;
|
||||||
|
let count = window.buckets[index];
|
||||||
|
(count > 0).then(|| {
|
||||||
|
let started = self.epoch + Duration::from_secs(second - age);
|
||||||
|
(now.saturating_duration_since(started), count)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
windows.push(PersistedWindow {
|
||||||
|
provider: provider.clone(),
|
||||||
|
account: account.as_str().to_owned(),
|
||||||
|
model: model.clone(),
|
||||||
|
buckets,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
RecentRequestSnapshot {
|
||||||
|
captured_at: wall_now,
|
||||||
|
windows,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn restore(
|
||||||
|
snapshot: RecentRequestSnapshot,
|
||||||
|
now: Instant,
|
||||||
|
wall_now: SystemTime,
|
||||||
|
) -> Result<Self, InvalidRecentRequestSnapshot> {
|
||||||
|
let mut restored = Self {
|
||||||
|
epoch: now,
|
||||||
|
last_cleanup: 0,
|
||||||
|
windows: HashMap::new(),
|
||||||
|
};
|
||||||
|
// 墙钟只用于跨进程计算停机时长,回拨或过期快照从空窗口重新积累
|
||||||
|
let Ok(downtime) = wall_now.duration_since(snapshot.captured_at) else {
|
||||||
|
return Ok(restored);
|
||||||
|
};
|
||||||
|
if downtime.as_secs() >= WINDOW_SECONDS {
|
||||||
|
return Ok(restored);
|
||||||
|
}
|
||||||
|
// 单调时钟无法容纳完整窗口时重新积累,避免延长历史计数寿命
|
||||||
|
let Some(epoch) = now.checked_sub(Duration::from_secs(WINDOW_SECONDS)) else {
|
||||||
|
return Ok(restored);
|
||||||
|
};
|
||||||
|
restored.epoch = epoch;
|
||||||
|
let second = restored.second(now);
|
||||||
|
for entry in snapshot.windows {
|
||||||
|
let account =
|
||||||
|
ProviderAccountId::new(entry.account).map_err(|_| InvalidRecentRequestSnapshot)?;
|
||||||
|
if entry.buckets.len() > WINDOW_SECONDS as usize {
|
||||||
|
return Err(InvalidRecentRequestSnapshot);
|
||||||
|
}
|
||||||
|
let mut window = RequestWindow {
|
||||||
|
buckets: [0; WINDOW_SECONDS as usize],
|
||||||
|
second,
|
||||||
|
total: 0,
|
||||||
|
};
|
||||||
|
for (age, count) in entry.buckets {
|
||||||
|
let age = age.saturating_add(downtime);
|
||||||
|
if age.as_secs() >= WINDOW_SECONDS || count == 0 {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let Some(started) = now.checked_sub(age) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let offset = started.saturating_duration_since(restored.epoch).as_secs();
|
||||||
|
let index = (offset % WINDOW_SECONDS) as usize;
|
||||||
|
window.buckets[index] = window.buckets[index]
|
||||||
|
.checked_add(count)
|
||||||
|
.ok_or(InvalidRecentRequestSnapshot)?;
|
||||||
|
window.total = window
|
||||||
|
.total
|
||||||
|
.checked_add(count)
|
||||||
|
.ok_or(InvalidRecentRequestSnapshot)?;
|
||||||
|
}
|
||||||
|
if window.total > 0 {
|
||||||
|
restored
|
||||||
|
.windows
|
||||||
|
.insert((entry.provider, account, entry.model), window);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(restored)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn second(&mut self, now: Instant) -> u64 {
|
||||||
|
let second = now
|
||||||
|
.checked_duration_since(self.epoch)
|
||||||
|
.unwrap_or_default()
|
||||||
|
.as_secs();
|
||||||
|
if second.saturating_sub(self.last_cleanup) >= WINDOW_SECONDS {
|
||||||
|
self.windows.retain(|_, window| {
|
||||||
|
window.advance(second);
|
||||||
|
window.total > 0
|
||||||
|
});
|
||||||
|
self.last_cleanup = second;
|
||||||
|
}
|
||||||
|
second
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn record(
|
||||||
|
&mut self,
|
||||||
|
provider: &ProviderKind,
|
||||||
|
account: &ProviderAccountId,
|
||||||
|
model: &str,
|
||||||
|
started_at: Instant,
|
||||||
|
now: Instant,
|
||||||
|
) {
|
||||||
|
// 首个响应确认请求已发送,使用 attempt 开始时间,避免慢响应挤到完成时刻
|
||||||
|
if now.saturating_duration_since(started_at).as_secs() >= WINDOW_SECONDS {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let second = self.second(now);
|
||||||
|
let started = started_at
|
||||||
|
.checked_duration_since(self.epoch)
|
||||||
|
.unwrap_or_default()
|
||||||
|
.as_secs();
|
||||||
|
let window = self
|
||||||
|
.windows
|
||||||
|
.entry((provider.clone(), account.clone(), model.to_owned()))
|
||||||
|
.or_insert(RequestWindow {
|
||||||
|
buckets: [0; WINDOW_SECONDS as usize],
|
||||||
|
second,
|
||||||
|
total: 0,
|
||||||
|
});
|
||||||
|
window.advance(second);
|
||||||
|
if window.second.saturating_sub(started) < WINDOW_SECONDS {
|
||||||
|
window.buckets[(started % WINDOW_SECONDS) as usize] += 1;
|
||||||
|
window.total += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn count(
|
||||||
|
&mut self,
|
||||||
|
provider: &ProviderKind,
|
||||||
|
account: &ProviderAccountId,
|
||||||
|
model: &str,
|
||||||
|
now: Instant,
|
||||||
|
) -> u64 {
|
||||||
|
let second = self.second(now);
|
||||||
|
let Some(window) =
|
||||||
|
self.windows
|
||||||
|
.get_mut(&(provider.clone(), account.clone(), model.to_owned()))
|
||||||
|
else {
|
||||||
|
return 0;
|
||||||
|
};
|
||||||
|
window.advance(second);
|
||||||
|
window.total
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -108,6 +108,7 @@ pub struct RuntimeAccountDirectory {
|
|||||||
providers_with_accounts: BTreeSet<ProviderKind>,
|
providers_with_accounts: BTreeSet<ProviderKind>,
|
||||||
providers_by_group: BTreeMap<AccountGroupId, BTreeSet<ProviderKind>>,
|
providers_by_group: BTreeMap<AccountGroupId, BTreeSet<ProviderKind>>,
|
||||||
group_model_access: BTreeMap<AccountGroupId, AccountModelAccess>,
|
group_model_access: BTreeMap<AccountGroupId, AccountModelAccess>,
|
||||||
|
group_fast_modes: BTreeMap<AccountGroupId, FastMode>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl RuntimeAccountDirectory {
|
impl RuntimeAccountDirectory {
|
||||||
@@ -129,6 +130,7 @@ impl RuntimeAccountDirectory {
|
|||||||
providers_with_accounts,
|
providers_with_accounts,
|
||||||
providers_by_group,
|
providers_by_group,
|
||||||
group_model_access: BTreeMap::new(),
|
group_model_access: BTreeMap::new(),
|
||||||
|
group_fast_modes: BTreeMap::new(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -141,6 +143,12 @@ impl RuntimeAccountDirectory {
|
|||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[must_use]
|
||||||
|
pub fn with_group_fast_modes(mut self, policies: BTreeMap<AccountGroupId, FastMode>) -> Self {
|
||||||
|
self.group_fast_modes = policies;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
pub(crate) fn accounts_in_group(
|
pub(crate) fn accounts_in_group(
|
||||||
&self,
|
&self,
|
||||||
group: &AccountGroupId,
|
group: &AccountGroupId,
|
||||||
@@ -288,7 +296,7 @@ impl ClientRoutingScope {
|
|||||||
pub struct FrozenAccountScope {
|
pub struct FrozenAccountScope {
|
||||||
allow_image_generation: bool,
|
allow_image_generation: bool,
|
||||||
allow_subagents: bool,
|
allow_subagents: bool,
|
||||||
fast_mode: FastMode,
|
fast_mode_override: Option<FastMode>,
|
||||||
request_profiles: BTreeMap<ProviderKind, super::OpaqueProviderData>,
|
request_profiles: BTreeMap<ProviderKind, super::OpaqueProviderData>,
|
||||||
directory: Arc<RuntimeAccountDirectory>,
|
directory: Arc<RuntimeAccountDirectory>,
|
||||||
client_scope: ClientRoutingScope,
|
client_scope: ClientRoutingScope,
|
||||||
@@ -355,16 +363,34 @@ impl FrozenAccountScope {
|
|||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Key 绑定分组的冻结 Fast 策略,与账号成员资格无关
|
/// 显式请求覆盖独立于分组策略;None 表示按选中账号的有效分组计算
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub const fn with_fast_mode(mut self, fast_mode: FastMode) -> Self {
|
pub const fn with_fast_mode_override(mut self, fast_mode: Option<FastMode>) -> Self {
|
||||||
self.fast_mode = fast_mode;
|
self.fast_mode_override = fast_mode;
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub const fn fast_mode(&self) -> FastMode {
|
pub const fn fast_mode_override(&self) -> Option<FastMode> {
|
||||||
self.fast_mode
|
self.fast_mode_override
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 只合并当前 Key 授权该账号与模型的启用分组,换号仍使用同一冻结目录
|
||||||
|
#[must_use]
|
||||||
|
pub fn fast_mode_for_account(
|
||||||
|
&self,
|
||||||
|
account_id: &ProviderAccountId,
|
||||||
|
upstream_model: &str,
|
||||||
|
) -> FastMode {
|
||||||
|
if let Some(mode) = self.fast_mode_override {
|
||||||
|
return mode;
|
||||||
|
}
|
||||||
|
let Some(account) = self.directory.account(account_id) else {
|
||||||
|
return FastMode::Default;
|
||||||
|
};
|
||||||
|
self.matching_groups(account, |access| access.allows(upstream_model))
|
||||||
|
.filter_map(|id| self.directory.group_fast_modes.get(id))
|
||||||
|
.fold(FastMode::Default, |mode, other| mode.merge(*other))
|
||||||
}
|
}
|
||||||
|
|
||||||
#[must_use]
|
#[must_use]
|
||||||
@@ -376,7 +402,7 @@ impl FrozenAccountScope {
|
|||||||
Self {
|
Self {
|
||||||
allow_image_generation: true,
|
allow_image_generation: true,
|
||||||
allow_subagents: true,
|
allow_subagents: true,
|
||||||
fast_mode: FastMode::Default,
|
fast_mode_override: None,
|
||||||
request_profiles: BTreeMap::new(),
|
request_profiles: BTreeMap::new(),
|
||||||
directory,
|
directory,
|
||||||
client_scope,
|
client_scope,
|
||||||
@@ -460,18 +486,31 @@ impl FrozenAccountScope {
|
|||||||
}
|
}
|
||||||
match &self.client_scope {
|
match &self.client_scope {
|
||||||
ClientRoutingScope::AllAccounts => true,
|
ClientRoutingScope::AllAccounts => true,
|
||||||
|
ClientRoutingScope::Restricted { .. } => {
|
||||||
|
self.matching_groups(account, accepts).next().is_some()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn matching_groups<'a>(
|
||||||
|
&'a self,
|
||||||
|
account: &'a RuntimeAccount,
|
||||||
|
accepts: impl Fn(&AccountModelAccess) -> bool + 'a,
|
||||||
|
) -> impl Iterator<Item = &'a AccountGroupId> {
|
||||||
|
let enabled = match &self.client_scope {
|
||||||
|
ClientRoutingScope::AllAccounts => None,
|
||||||
ClientRoutingScope::Restricted {
|
ClientRoutingScope::Restricted {
|
||||||
enabled_group_ids, ..
|
enabled_group_ids, ..
|
||||||
} => account
|
} => Some(enabled_group_ids),
|
||||||
.group_ids()
|
};
|
||||||
.intersection(enabled_group_ids)
|
account.group_ids().iter().filter(move |id| {
|
||||||
.any(|id| {
|
enabled.is_some_and(|groups| groups.contains(*id))
|
||||||
self.directory
|
&& self
|
||||||
.group_model_access
|
.directory
|
||||||
.get(id)
|
.group_model_access
|
||||||
.is_none_or(&accepts)
|
.get(*id)
|
||||||
}),
|
.is_none_or(&accepts)
|
||||||
}
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
#[must_use]
|
#[must_use]
|
||||||
|
|||||||
@@ -257,6 +257,8 @@ impl AccountSelectionPolicy {
|
|||||||
pub struct AccountRuntimeSignals {
|
pub struct AccountRuntimeSignals {
|
||||||
/// 本次调度容量池的在途数,不合并其他独立池
|
/// 本次调度容量池的在途数,不合并其他独立池
|
||||||
pub in_flight: u32,
|
pub in_flight: u32,
|
||||||
|
/// 同模型最近一分钟已确认发送的请求数,按秒滚动
|
||||||
|
pub recent_requests: u64,
|
||||||
pub last_started_at: Option<SystemTime>,
|
pub last_started_at: Option<SystemTime>,
|
||||||
pub quota_reset_at: Option<SystemTime>,
|
pub quota_reset_at: Option<SystemTime>,
|
||||||
pub quota_reset_windows: Option<Arc<[AccountQuotaResetWindow]>>,
|
pub quota_reset_windows: Option<Arc<[AccountQuotaResetWindow]>>,
|
||||||
@@ -368,9 +370,82 @@ impl AccountFeedback {
|
|||||||
#[derive(Debug, Default)]
|
#[derive(Debug, Default)]
|
||||||
pub struct AccountFeedbackStats {
|
pub struct AccountFeedbackStats {
|
||||||
accounts: RwLock<HashMap<AccountFeedbackKey, AccountFeedback>>,
|
accounts: RwLock<HashMap<AccountFeedbackKey, AccountFeedback>>,
|
||||||
|
requests: Mutex<super::recent_requests::RecentRequests>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl AccountFeedbackStats {
|
impl AccountFeedbackStats {
|
||||||
|
/// 后台导出当前窗口,序列化与存储在释放锁后执行
|
||||||
|
#[must_use]
|
||||||
|
pub fn snapshot_recent_requests_at(
|
||||||
|
&self,
|
||||||
|
now: Instant,
|
||||||
|
wall_now: SystemTime,
|
||||||
|
) -> super::RecentRequestSnapshot {
|
||||||
|
self.requests
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||||
|
.snapshot(now, wall_now)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 仅在数据面启动前恢复窗口,按实际停机时长淘汰过期请求
|
||||||
|
pub fn restore_recent_requests_at(
|
||||||
|
&self,
|
||||||
|
snapshot: super::RecentRequestSnapshot,
|
||||||
|
now: Instant,
|
||||||
|
wall_now: SystemTime,
|
||||||
|
) -> Result<(), super::InvalidRecentRequestSnapshot> {
|
||||||
|
let restored = super::recent_requests::RecentRequests::restore(snapshot, now, wall_now)?;
|
||||||
|
*self
|
||||||
|
.requests
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(std::sync::PoisonError::into_inner) = restored;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 记录已确认发送的请求;同一 attempt 由 stream 边界保证只记录一次
|
||||||
|
pub fn record_request_at(
|
||||||
|
&self,
|
||||||
|
provider: &ProviderKind,
|
||||||
|
account: &ProviderAccountId,
|
||||||
|
model: &str,
|
||||||
|
started_at: Instant,
|
||||||
|
now: Instant,
|
||||||
|
) {
|
||||||
|
self.requests
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||||
|
.record(provider, account, model, started_at, now);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 读取指定模型的近期负载,未知模型不参与比较
|
||||||
|
#[must_use]
|
||||||
|
pub fn recent_requests(
|
||||||
|
&self,
|
||||||
|
provider: &ProviderKind,
|
||||||
|
account: &ProviderAccountId,
|
||||||
|
model: Option<&str>,
|
||||||
|
) -> u64 {
|
||||||
|
self.recent_requests_at(provider, account, model, Instant::now())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 在指定单调时刻读取秒级滚动窗口
|
||||||
|
#[doc(hidden)]
|
||||||
|
#[must_use]
|
||||||
|
pub fn recent_requests_at(
|
||||||
|
&self,
|
||||||
|
provider: &ProviderKind,
|
||||||
|
account: &ProviderAccountId,
|
||||||
|
model: Option<&str>,
|
||||||
|
now: Instant,
|
||||||
|
) -> u64 {
|
||||||
|
model.map_or(0, |model| {
|
||||||
|
self.requests
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||||
|
.count(provider, account, model, now)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
/// 读取账号当前的错误率与首个有效输出延迟 EWMA
|
/// 读取账号当前的错误率与首个有效输出延迟 EWMA
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn scheduling_signals(
|
pub fn scheduling_signals(
|
||||||
@@ -978,6 +1053,8 @@ impl AccountSelector {
|
|||||||
|
|
||||||
// 首输出 10 秒时延迟得分减半;固定尺度不随其他候选账号变化
|
// 首输出 10 秒时延迟得分减半;固定尺度不随其他候选账号变化
|
||||||
const SMART_LATENCY_HALF_SCORE_MS: f64 = 10_000.0;
|
const SMART_LATENCY_HALF_SCORE_MS: f64 = 10_000.0;
|
||||||
|
// 最近一分钟 10 次请求对应 0.5 的近期负载压力,固定尺度不代表上游 RPM 限额
|
||||||
|
const SMART_RECENT_REQUEST_HALF_LOAD: f64 = 10.0;
|
||||||
|
|
||||||
fn capacity_utilization(candidate: &AccountCandidate, context: &AccountSelectionContext) -> f64 {
|
fn capacity_utilization(candidate: &AccountCandidate, context: &AccountSelectionContext) -> f64 {
|
||||||
context
|
context
|
||||||
@@ -1012,7 +1089,10 @@ fn select_smart_candidate<'a>(
|
|||||||
pub(crate) fn smart_score(candidate: &AccountCandidate, context: &AccountSelectionContext) -> f64 {
|
pub(crate) fn smart_score(candidate: &AccountCandidate, context: &AccountSelectionContext) -> f64 {
|
||||||
let config = context.policy.smart_scheduling();
|
let config = context.policy.smart_scheduling();
|
||||||
let now = context.now;
|
let now = context.now;
|
||||||
let load = 1.0 - capacity_utilization(candidate, context).clamp(0.0, 1.0);
|
// 两类压力独立扣分,近期热度不能稀释当前并发占用的代价
|
||||||
|
let recent_requests = candidate.signals.recent_requests as f64;
|
||||||
|
let recent_load = recent_requests / (SMART_RECENT_REQUEST_HALF_LOAD + recent_requests);
|
||||||
|
let load = 1.0 - capacity_utilization(candidate, context).clamp(0.0, 1.0) - recent_load;
|
||||||
let quota = candidate
|
let quota = candidate
|
||||||
.signals
|
.signals
|
||||||
.quota_remaining_rank
|
.quota_remaining_rank
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
//! Provider 账号持久化端口
|
//! Provider 账号持久化端口
|
||||||
|
|
||||||
use async_trait::async_trait;
|
use async_trait::async_trait;
|
||||||
|
use futures::future::BoxFuture;
|
||||||
|
|
||||||
use crate::error::StoreError;
|
use crate::error::StoreError;
|
||||||
use crate::identity::ProviderKind;
|
use crate::identity::ProviderKind;
|
||||||
@@ -9,9 +10,19 @@ use super::{
|
|||||||
AccountStateChange, CredentialCasOutcome, CredentialCasUpdate, CredentialRevision,
|
AccountStateChange, CredentialCasOutcome, CredentialCasUpdate, CredentialRevision,
|
||||||
LoadedCredential, NewProviderAccount, ProviderAccount, ProviderAccountId,
|
LoadedCredential, NewProviderAccount, ProviderAccount, ProviderAccountId,
|
||||||
ProviderAccountUpdate, ProviderRefreshQuery, QuotaAccessChange, QuotaObservation,
|
ProviderAccountUpdate, ProviderRefreshQuery, QuotaAccessChange, QuotaObservation,
|
||||||
QuotaObservationTouch, QuotaObservationVersion, QuotaWriteOutcome,
|
QuotaObservationTouch, QuotaObservationVersion, QuotaWriteOutcome, RecentRequestSnapshot,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/// 快照存储只供启动与后台任务使用,数据面不依赖此端口
|
||||||
|
pub trait RecentRequestStore: Send + Sync {
|
||||||
|
fn load(&self) -> BoxFuture<'_, Result<Option<RecentRequestSnapshot>, StoreError>>;
|
||||||
|
fn save<'a>(
|
||||||
|
&'a self,
|
||||||
|
snapshot: &'a RecentRequestSnapshot,
|
||||||
|
ttl: std::time::Duration,
|
||||||
|
) -> BoxFuture<'a, Result<(), StoreError>>;
|
||||||
|
}
|
||||||
|
|
||||||
/// 一个账号最后成功的目录观测;正文由 Provider 解释,归属不能按相同正文合并
|
/// 一个账号最后成功的目录观测;正文由 Provider 解释,归属不能按相同正文合并
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct AccountCatalogObservation {
|
pub struct AccountCatalogObservation {
|
||||||
|
|||||||
@@ -41,6 +41,7 @@ impl TraceContext {
|
|||||||
"blocker": AccountSelector.scheduling_blocker(candidate, context)
|
"blocker": AccountSelector.scheduling_blocker(candidate, context)
|
||||||
.map(|blocker| format!("{blocker:?}")),
|
.map(|blocker| format!("{blocker:?}")),
|
||||||
"inFlight": signals.in_flight,
|
"inFlight": signals.in_flight,
|
||||||
|
"recentRequests": signals.recent_requests,
|
||||||
"concurrencyLimit": context.concurrency_limit(candidate).get(),
|
"concurrencyLimit": context.concurrency_limit(candidate).get(),
|
||||||
"quotaRemainingBasisPoints": signals.quota_remaining_rank,
|
"quotaRemainingBasisPoints": signals.quota_remaining_rank,
|
||||||
"quotaResetAtUnixMs": signals.quota_reset_at.and_then(|reset|
|
"quotaResetAtUnixMs": signals.quota_reset_at.and_then(|reset|
|
||||||
|
|||||||
@@ -1200,7 +1200,6 @@ where
|
|||||||
.with_lease_metadata(Arc::clone(&self.lease_metadata))
|
.with_lease_metadata(Arc::clone(&self.lease_metadata))
|
||||||
.with_response_control(self.response_control.clone())
|
.with_response_control(self.response_control.clone())
|
||||||
.with_request_profile(self.request_profiles.get(candidate.provider()).cloned())
|
.with_request_profile(self.request_profiles.get(candidate.provider()).cloned())
|
||||||
.with_fast_mode(self.plan.fast_mode())
|
|
||||||
.with_prompt_rewrite_rules(self.plan.prompt_rewrite_rules(candidate.provider()))
|
.with_prompt_rewrite_rules(self.plan.prompt_rewrite_rules(candidate.provider()))
|
||||||
.with_pricing(self.plan.pricing())
|
.with_pricing(self.plan.pricing())
|
||||||
.with_request_location(self.plan.request_location().cloned())
|
.with_request_location(self.plan.request_location().cloned())
|
||||||
@@ -1480,7 +1479,7 @@ where
|
|||||||
&& let Some(original) = self.last_retryable_failure.take()
|
&& let Some(original) = self.last_retryable_failure.take()
|
||||||
{
|
{
|
||||||
// 迁移只改变客户端恢复指令;失败分类、发送事实与运维正文仍属于原请求
|
// 迁移只改变客户端恢复指令;失败分类、发送事实与运维正文仍属于原请求
|
||||||
error = original.with_client_recovery_from(error);
|
error = original.with_client_recovery_from(error, &self.last_retryable_failure_events);
|
||||||
self.last_retryable_failure_events.clear();
|
self.last_retryable_failure_events.clear();
|
||||||
}
|
}
|
||||||
let kind = error.kind();
|
let kind = error.kind();
|
||||||
|
|||||||
@@ -48,11 +48,17 @@ pub(super) fn map_routing_error(error: crate::validation::RoutingError) -> Gatew
|
|||||||
"Mapped model unavailable for this API key. Check the model mapping."
|
"Mapped model unavailable for this API key. Check the model mapping."
|
||||||
},
|
},
|
||||||
),
|
),
|
||||||
crate::validation::RoutingError::NoCapableProvider { .. }
|
crate::validation::RoutingError::NoCapableProvider { .. } => GatewayError::new(
|
||||||
| crate::validation::RoutingError::NoCapableProviderEndpoint { .. }
|
|
||||||
| crate::validation::RoutingError::EmptyAccountScope => GatewayError::new(
|
|
||||||
GatewayErrorKind::NoAvailableProvider,
|
GatewayErrorKind::NoAvailableProvider,
|
||||||
"The gateway has no eligible provider for this request.",
|
"The gateway cannot select a provider for this model and the requested capabilities.",
|
||||||
|
),
|
||||||
|
crate::validation::RoutingError::NoCapableProviderEndpoint { .. } => GatewayError::new(
|
||||||
|
GatewayErrorKind::NoAvailableProvider,
|
||||||
|
"No eligible provider is available for the requested API endpoint.",
|
||||||
|
),
|
||||||
|
crate::validation::RoutingError::EmptyAccountScope => GatewayError::new(
|
||||||
|
GatewayErrorKind::NoAvailableProvider,
|
||||||
|
"This API key has no accounts in its scope. Add accounts or check its enabled account groups.",
|
||||||
),
|
),
|
||||||
crate::validation::RoutingError::UnsupportedProviderEndpoint { .. } => GatewayError::new(
|
crate::validation::RoutingError::UnsupportedProviderEndpoint { .. } => GatewayError::new(
|
||||||
GatewayErrorKind::Unsupported,
|
GatewayErrorKind::Unsupported,
|
||||||
|
|||||||
@@ -1547,11 +1547,8 @@ impl DefaultExecutionService {
|
|||||||
) -> AccountProbeError {
|
) -> AccountProbeError {
|
||||||
let (source, send_state, upstream_response) = match error {
|
let (source, send_state, upstream_response) = match error {
|
||||||
EngineError::Provider(provider_error) => {
|
EngineError::Provider(provider_error) => {
|
||||||
let upstream_response = provider_error
|
let upstream_response = AccountProbeUpstreamResponse::from_provider(provider_error);
|
||||||
.client_visible_upstream_response()
|
|
||||||
.map(AccountProbeUpstreamResponse::from_client_response);
|
|
||||||
let has_upstream_facts = provider_error.send_state() != UpstreamSendState::NotSent
|
let has_upstream_facts = provider_error.send_state() != UpstreamSendState::NotSent
|
||||||
|| provider_error.upstream_status().is_some()
|
|
||||||
|| provider_error.upstream_code().is_some()
|
|| provider_error.upstream_code().is_some()
|
||||||
|| provider_error.client_visible_upstream_error().is_some()
|
|| provider_error.client_visible_upstream_error().is_some()
|
||||||
|| upstream_response.is_some();
|
|| upstream_response.is_some();
|
||||||
|
|||||||
@@ -18,12 +18,14 @@ pub mod policy;
|
|||||||
pub mod probe;
|
pub mod probe;
|
||||||
mod prompt_rewrite;
|
mod prompt_rewrite;
|
||||||
pub mod provider;
|
pub mod provider;
|
||||||
|
mod recent_request_persistence;
|
||||||
pub mod response_control;
|
pub mod response_control;
|
||||||
pub mod upstream_adapter;
|
pub mod upstream_adapter;
|
||||||
|
|
||||||
use crate::lifecycle::{Deadline, LeaseGuard};
|
use crate::lifecycle::{Deadline, LeaseGuard};
|
||||||
|
|
||||||
pub use coordinator::{AttemptCoordinator, ResponseExecutionSession};
|
pub use coordinator::{AttemptCoordinator, ResponseExecutionSession};
|
||||||
|
pub use recent_request_persistence::RecentRequestPersistence;
|
||||||
|
|
||||||
use std::collections::BTreeSet;
|
use std::collections::BTreeSet;
|
||||||
use std::fmt;
|
use std::fmt;
|
||||||
@@ -328,7 +330,6 @@ pub struct RequestAttemptContext {
|
|||||||
prompt_rewrite_rules: Option<Arc<crate::settings::prompt_rewrite::ProviderPromptRules>>,
|
prompt_rewrite_rules: Option<Arc<crate::settings::prompt_rewrite::ProviderPromptRules>>,
|
||||||
pricing: Arc<crate::metering::PricingOverrides>,
|
pricing: Arc<crate::metering::PricingOverrides>,
|
||||||
request_profile: Option<crate::account::OpaqueProviderData>,
|
request_profile: Option<crate::account::OpaqueProviderData>,
|
||||||
fast_mode: FastMode,
|
|
||||||
openai_websocket_pool: crate::settings::OpenAiWebSocketPoolSettings,
|
openai_websocket_pool: crate::settings::OpenAiWebSocketPoolSettings,
|
||||||
openai_request_settings: crate::settings::OpenAiRequestSettings,
|
openai_request_settings: crate::settings::OpenAiRequestSettings,
|
||||||
request_location: Option<crate::account::RequestLocation>,
|
request_location: Option<crate::account::RequestLocation>,
|
||||||
@@ -422,12 +423,6 @@ impl RequestAttemptContext {
|
|||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
#[must_use]
|
|
||||||
pub const fn with_fast_mode(mut self, fast_mode: FastMode) -> Self {
|
|
||||||
self.fast_mode = fast_mode;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn with_privacy(
|
pub fn with_privacy(
|
||||||
mut self,
|
mut self,
|
||||||
@@ -476,7 +471,6 @@ impl RequestAttemptContext {
|
|||||||
request_profile: None,
|
request_profile: None,
|
||||||
prompt_rewrite_rules: None,
|
prompt_rewrite_rules: None,
|
||||||
pricing: Arc::default(),
|
pricing: Arc::default(),
|
||||||
fast_mode: FastMode::Default,
|
|
||||||
openai_websocket_pool: Default::default(),
|
openai_websocket_pool: Default::default(),
|
||||||
openai_request_settings: Default::default(),
|
openai_request_settings: Default::default(),
|
||||||
request_location: None,
|
request_location: None,
|
||||||
@@ -741,8 +735,14 @@ impl AttemptContext {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub const fn fast_mode(&self) -> FastMode {
|
pub fn fast_mode_for_account(
|
||||||
self.request.fast_mode
|
&self,
|
||||||
|
account: &ProviderAccountId,
|
||||||
|
upstream_model: &str,
|
||||||
|
) -> FastMode {
|
||||||
|
self.account_scope().map_or(FastMode::Default, |scope| {
|
||||||
|
scope.fast_mode_for_account(account, upstream_model)
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
#[must_use]
|
#[must_use]
|
||||||
|
|||||||
@@ -5,9 +5,7 @@ use std::fmt;
|
|||||||
use bytes::Bytes;
|
use bytes::Bytes;
|
||||||
use futures::future::BoxFuture;
|
use futures::future::BoxFuture;
|
||||||
|
|
||||||
use crate::error::{
|
use crate::error::{GatewayError, GatewayErrorKind, ProviderError, ProxyConnectionHint};
|
||||||
ClientVisibleUpstreamResponse, GatewayError, GatewayErrorKind, ProxyConnectionHint,
|
|
||||||
};
|
|
||||||
use crate::identity::ProviderKind;
|
use crate::identity::ProviderKind;
|
||||||
use crate::routing::UpstreamModelId;
|
use crate::routing::UpstreamModelId;
|
||||||
use crate::{
|
use crate::{
|
||||||
@@ -60,16 +58,18 @@ pub struct AccountProbeResult {
|
|||||||
pub struct AccountProbeUpstreamResponse {
|
pub struct AccountProbeUpstreamResponse {
|
||||||
status: u16,
|
status: u16,
|
||||||
content_type: Option<Vec<u8>>,
|
content_type: Option<Vec<u8>>,
|
||||||
body: Bytes,
|
body: Option<Bytes>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl AccountProbeUpstreamResponse {
|
impl AccountProbeUpstreamResponse {
|
||||||
pub(crate) fn from_client_response(response: &ClientVisibleUpstreamResponse) -> Self {
|
pub(crate) fn from_provider(error: &ProviderError) -> Option<Self> {
|
||||||
Self {
|
let response = error.client_visible_upstream_response();
|
||||||
status: response.status(),
|
// 即使没有可展示的响应正文,Provider 收到的状态码仍可用于诊断
|
||||||
content_type: response.content_type().map(<[u8]>::to_vec),
|
Some(Self {
|
||||||
body: response.body().clone(),
|
status: response.map(|r| r.status()).or(error.upstream_status())?,
|
||||||
}
|
content_type: response.and_then(|r| r.content_type()).map(<[u8]>::to_vec),
|
||||||
|
body: response.map(|r| r.body().clone()),
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
#[must_use]
|
#[must_use]
|
||||||
@@ -83,8 +83,8 @@ impl AccountProbeUpstreamResponse {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub const fn body(&self) -> &Bytes {
|
pub const fn body(&self) -> Option<&Bytes> {
|
||||||
&self.body
|
self.body.as_ref()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -97,7 +97,7 @@ impl fmt::Debug for AccountProbeUpstreamResponse {
|
|||||||
"content_type",
|
"content_type",
|
||||||
&self.content_type.as_ref().map(|_| "<present>"),
|
&self.content_type.as_ref().map(|_| "<present>"),
|
||||||
)
|
)
|
||||||
.field("body", &"<redacted>")
|
.field("body", &self.body.as_ref().map(|_| "<redacted>"))
|
||||||
.finish()
|
.finish()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -283,6 +283,8 @@ struct ProviderStreamAccountFeedback {
|
|||||||
provider_kind: ProviderKind,
|
provider_kind: ProviderKind,
|
||||||
account_id: ProviderAccountId,
|
account_id: ProviderAccountId,
|
||||||
failure_filter: fn(&ProviderError) -> bool,
|
failure_filter: fn(&ProviderError) -> bool,
|
||||||
|
upstream_model: Option<UpstreamModelId>,
|
||||||
|
request_recorded: bool,
|
||||||
started_at: Option<Instant>,
|
started_at: Option<Instant>,
|
||||||
first_output_ms: Option<u64>,
|
first_output_ms: Option<u64>,
|
||||||
reported: bool,
|
reported: bool,
|
||||||
@@ -297,7 +299,27 @@ impl ProviderStreamAccountFeedback {
|
|||||||
self.started_at.get_or_insert_with(Instant::now);
|
self.started_at.get_or_insert_with(Instant::now);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn record_request(&mut self) {
|
||||||
|
if self.request_recorded {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if let (Some(model), Some(started_at)) = (&self.upstream_model, self.started_at) {
|
||||||
|
self.stats.record_request_at(
|
||||||
|
&self.provider_kind,
|
||||||
|
&self.account_id,
|
||||||
|
model.as_str(),
|
||||||
|
started_at,
|
||||||
|
Instant::now(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
self.request_recorded = true;
|
||||||
|
}
|
||||||
|
|
||||||
fn observe(&mut self, event: &ProviderEvent) {
|
fn observe(&mut self, event: &ProviderEvent) {
|
||||||
|
// 纯连接观测可能出现在未发送失败之前,不能单独证明请求已送达
|
||||||
|
if event.has_client_event() {
|
||||||
|
self.record_request();
|
||||||
|
}
|
||||||
if self.first_output_ms.is_some()
|
if self.first_output_ms.is_some()
|
||||||
|| !event.canonical_facts().iter().any(|event| {
|
|| !event.canonical_facts().iter().any(|event| {
|
||||||
matches!(
|
matches!(
|
||||||
@@ -332,6 +354,9 @@ impl ProviderStreamAccountFeedback {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn report_failure(&mut self, error: &ProviderError) {
|
fn report_failure(&mut self, error: &ProviderError) {
|
||||||
|
if error.send_state() == UpstreamSendState::Sent {
|
||||||
|
self.record_request();
|
||||||
|
}
|
||||||
if self.reported
|
if self.reported
|
||||||
// `Ambiguous` 仍须关闭重放边界,但不能证明失败由账号造成;将它计入
|
// `Ambiguous` 仍须关闭重放边界,但不能证明失败由账号造成;将它计入
|
||||||
// 账号评分会把传输不确定性错误归因给账号
|
// 账号评分会把传输不确定性错误归因给账号
|
||||||
@@ -523,6 +548,8 @@ impl ProviderStream {
|
|||||||
provider_kind: self.metadata.provider().clone(),
|
provider_kind: self.metadata.provider().clone(),
|
||||||
account_id: self.metadata.provider_account_id().clone(),
|
account_id: self.metadata.provider_account_id().clone(),
|
||||||
failure_filter,
|
failure_filter,
|
||||||
|
upstream_model: self.metadata.upstream_model().cloned(),
|
||||||
|
request_recorded: false,
|
||||||
started_at: None,
|
started_at: None,
|
||||||
first_output_ms: None,
|
first_output_ms: None,
|
||||||
reported: false,
|
reported: false,
|
||||||
|
|||||||
@@ -0,0 +1,77 @@
|
|||||||
|
//! 近期请求统计的启动恢复、周期快照与有界关闭刷写
|
||||||
|
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::time::{Duration, Instant, SystemTime};
|
||||||
|
|
||||||
|
use futures::{FutureExt, future::BoxFuture};
|
||||||
|
use futures_timer::Delay;
|
||||||
|
|
||||||
|
use crate::account::{AccountFeedbackStats, RecentRequestStore};
|
||||||
|
use crate::error::{StoreError, StoreErrorKind};
|
||||||
|
use crate::task::{DaemonTask, WorkerDaemonContext, WorkerTaskError};
|
||||||
|
|
||||||
|
const FLUSH_INTERVAL: Duration = Duration::from_secs(1);
|
||||||
|
const IO_TIMEOUT: Duration = Duration::from_secs(2);
|
||||||
|
const SNAPSHOT_TTL: Duration = Duration::from_secs(120);
|
||||||
|
|
||||||
|
/// 由 Host 监督的单进程快照任务,不重放单次请求或恢复旧健康分
|
||||||
|
pub struct RecentRequestPersistence {
|
||||||
|
stats: Arc<AccountFeedbackStats>,
|
||||||
|
store: Arc<dyn RecentRequestStore>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RecentRequestPersistence {
|
||||||
|
#[must_use]
|
||||||
|
pub fn new(stats: Arc<AccountFeedbackStats>, store: Arc<dyn RecentRequestStore>) -> Self {
|
||||||
|
Self { stats, store }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 在 Provider 接收请求前恢复一次,后台任务重启不再次覆盖内存
|
||||||
|
pub async fn restore(&self) -> Result<(), StoreError> {
|
||||||
|
if let Some(snapshot) = bounded(self.store.load()).await? {
|
||||||
|
self.stats
|
||||||
|
.restore_recent_requests_at(snapshot, Instant::now(), SystemTime::now())
|
||||||
|
.map_err(|error| StoreError::caused_by(StoreErrorKind::InvalidData, error))?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn flush(&self) -> Result<(), StoreError> {
|
||||||
|
let snapshot = self
|
||||||
|
.stats
|
||||||
|
.snapshot_recent_requests_at(Instant::now(), SystemTime::now());
|
||||||
|
// 快照离开内存锁后才序列化和等待存储,慢 Redis 不占用选号锁
|
||||||
|
bounded(self.store.save(&snapshot, SNAPSHOT_TTL)).await
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DaemonTask for RecentRequestPersistence {
|
||||||
|
fn run(&self, context: WorkerDaemonContext) -> BoxFuture<'_, Result<(), WorkerTaskError>> {
|
||||||
|
Box::pin(async move {
|
||||||
|
loop {
|
||||||
|
let stopping = futures::select_biased! {
|
||||||
|
() = context.cancellation().cancelled().fuse() => true,
|
||||||
|
() = Delay::new(FLUSH_INTERVAL).fuse() => false,
|
||||||
|
};
|
||||||
|
self.flush().await.map_err(|error| {
|
||||||
|
WorkerTaskError::safe("近期请求统计保存失败").with_source(error)
|
||||||
|
})?;
|
||||||
|
if stopping {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
context.succeeded();
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn bounded<T>(
|
||||||
|
operation: impl std::future::Future<Output = Result<T, StoreError>>,
|
||||||
|
) -> Result<T, StoreError> {
|
||||||
|
let operation = operation.fuse();
|
||||||
|
futures::pin_mut!(operation);
|
||||||
|
futures::select_biased! {
|
||||||
|
result = operation => result,
|
||||||
|
() = Delay::new(IO_TIMEOUT).fuse() => Err(StoreError::new(StoreErrorKind::Unavailable)),
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1093,8 +1093,60 @@ impl ProviderError {
|
|||||||
self.client_visible_upstream_response.as_deref()
|
self.client_visible_upstream_response.as_deref()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 将原失败携带的等待头补入客户端响应,保留响应中已有的值
|
||||||
|
pub fn extend_client_retry_headers(
|
||||||
|
&self,
|
||||||
|
headers: &mut Vec<ProviderResponseHeader>,
|
||||||
|
events: &[ProviderEvent],
|
||||||
|
) {
|
||||||
|
let original = self.client_visible_upstream_response();
|
||||||
|
let body = std::cell::LazyCell::new(|| {
|
||||||
|
original.and_then(|response| serde_json::from_slice(response.body()).ok())
|
||||||
|
});
|
||||||
|
let event = events
|
||||||
|
.iter()
|
||||||
|
.rev()
|
||||||
|
.find_map(ProviderEvent::wire_event)
|
||||||
|
.map(|wire| wire.data());
|
||||||
|
for name in gateway_protocol::http::RETRY_AFTER_HEADERS {
|
||||||
|
if headers
|
||||||
|
.iter()
|
||||||
|
.any(|header| header.name().eq_ignore_ascii_case(name))
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if let Some(header) = original.and_then(|response| {
|
||||||
|
response
|
||||||
|
.headers()
|
||||||
|
.iter()
|
||||||
|
.rev()
|
||||||
|
.find(|header| header.name().eq_ignore_ascii_case(name))
|
||||||
|
}) {
|
||||||
|
headers.push(header.clone());
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let read = |value| gateway_protocol::openai::events::error_event_header(value, name);
|
||||||
|
if let Some(value) = event
|
||||||
|
.and_then(read)
|
||||||
|
.or_else(|| body.as_ref().and_then(read))
|
||||||
|
{
|
||||||
|
headers.push(ProviderResponseHeader::new(
|
||||||
|
name,
|
||||||
|
Bytes::copy_from_slice(value.as_bytes()),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// 绑定迁移完成后仅替换客户端恢复投影,保留原始失败的诊断与计费事实
|
/// 绑定迁移完成后仅替换客户端恢复投影,保留原始失败的诊断与计费事实
|
||||||
pub(crate) fn with_client_recovery_from(mut self, recovery: Self) -> Self {
|
pub(crate) fn with_client_recovery_from(
|
||||||
|
mut self,
|
||||||
|
mut recovery: Self,
|
||||||
|
events: &[ProviderEvent],
|
||||||
|
) -> Self {
|
||||||
|
if let Some(response) = recovery.client_visible_upstream_response.as_deref_mut() {
|
||||||
|
self.extend_client_retry_headers(&mut response.headers, events);
|
||||||
|
}
|
||||||
if let Some(reason) = recovery.continuation_unavailable_reason() {
|
if let Some(reason) = recovery.continuation_unavailable_reason() {
|
||||||
self = self.with_continuation_unavailable_reason(reason);
|
self = self.with_continuation_unavailable_reason(reason);
|
||||||
}
|
}
|
||||||
@@ -1384,14 +1436,14 @@ impl GatewayError {
|
|||||||
pub(crate) const fn concurrency_queue_full() -> Self {
|
pub(crate) const fn concurrency_queue_full() -> Self {
|
||||||
Self::new(
|
Self::new(
|
||||||
GatewayErrorKind::ConcurrencyQueueFull,
|
GatewayErrorKind::ConcurrencyQueueFull,
|
||||||
"The gateway request queue is full.",
|
"The gateway concurrency queue is full.",
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) const fn concurrency_queue_timeout() -> Self {
|
pub(crate) const fn concurrency_queue_timeout() -> Self {
|
||||||
Self::new(
|
Self::new(
|
||||||
GatewayErrorKind::ConcurrencyQueueTimeout,
|
GatewayErrorKind::ConcurrencyQueueTimeout,
|
||||||
"The request timed out in the gateway queue.",
|
"Timed out waiting for available concurrency in the gateway.",
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1464,20 +1516,25 @@ impl GatewayError {
|
|||||||
GatewayErrorKind::Unsupported,
|
GatewayErrorKind::Unsupported,
|
||||||
"Requested capability is unsupported.",
|
"Requested capability is unsupported.",
|
||||||
),
|
),
|
||||||
ProviderErrorKind::Unauthorized | ProviderErrorKind::PermissionDenied => Self::new(
|
ProviderErrorKind::Unauthorized => Self::new(
|
||||||
GatewayErrorKind::UpstreamUnavailable,
|
GatewayErrorKind::UpstreamUnavailable,
|
||||||
"The upstream account cannot access the service.",
|
"Upstream account authentication failed.",
|
||||||
|
),
|
||||||
|
ProviderErrorKind::PermissionDenied => Self::new(
|
||||||
|
GatewayErrorKind::UpstreamUnavailable,
|
||||||
|
"The upstream account does not have permission for this request.",
|
||||||
),
|
),
|
||||||
ProviderErrorKind::RequestPolicyDenied => error.denied_group_feature.map_or_else(
|
ProviderErrorKind::RequestPolicyDenied => error.denied_group_feature.map_or_else(
|
||||||
|| Self::new(GatewayErrorKind::PolicyDenied, "Request blocked by policy."),
|
|| Self::new(GatewayErrorKind::PolicyDenied, "Request blocked by policy."),
|
||||||
Self::from,
|
Self::from,
|
||||||
),
|
),
|
||||||
ProviderErrorKind::RateLimited => {
|
ProviderErrorKind::RateLimited => Self::new(
|
||||||
Self::new(GatewayErrorKind::RateLimited, "Request rate limit reached.")
|
GatewayErrorKind::RateLimited,
|
||||||
}
|
"Upstream request rate limit reached.",
|
||||||
|
),
|
||||||
ProviderErrorKind::QuotaExhausted => Self::new(
|
ProviderErrorKind::QuotaExhausted => Self::new(
|
||||||
GatewayErrorKind::QuotaExhausted,
|
GatewayErrorKind::QuotaExhausted,
|
||||||
"Account quota is exhausted.",
|
"Upstream account quota is exhausted.",
|
||||||
),
|
),
|
||||||
ProviderErrorKind::AccountPoolQuotaExhausted => Self::new(
|
ProviderErrorKind::AccountPoolQuotaExhausted => Self::new(
|
||||||
GatewayErrorKind::AccountPoolQuotaExhausted,
|
GatewayErrorKind::AccountPoolQuotaExhausted,
|
||||||
@@ -1487,7 +1544,7 @@ impl GatewayError {
|
|||||||
ProviderErrorKind::ConcurrencyQueueTimeout => Self::concurrency_queue_timeout(),
|
ProviderErrorKind::ConcurrencyQueueTimeout => Self::concurrency_queue_timeout(),
|
||||||
ProviderErrorKind::AccountCapacityUnavailable => Self::new(
|
ProviderErrorKind::AccountCapacityUnavailable => Self::new(
|
||||||
GatewayErrorKind::AccountCapacityUnavailable,
|
GatewayErrorKind::AccountCapacityUnavailable,
|
||||||
"The gateway account pool is busy.",
|
"No eligible account currently has capacity for this request.",
|
||||||
),
|
),
|
||||||
ProviderErrorKind::NoEligibleAccount => Self::new(
|
ProviderErrorKind::NoEligibleAccount => Self::new(
|
||||||
GatewayErrorKind::NoAvailableProvider,
|
GatewayErrorKind::NoAvailableProvider,
|
||||||
@@ -1507,11 +1564,23 @@ impl GatewayError {
|
|||||||
ProviderErrorKind::Cancelled => {
|
ProviderErrorKind::Cancelled => {
|
||||||
Self::new(GatewayErrorKind::Cancelled, "Request was cancelled.")
|
Self::new(GatewayErrorKind::Cancelled, "Request was cancelled.")
|
||||||
}
|
}
|
||||||
ProviderErrorKind::Transport
|
ProviderErrorKind::Transport => Self::new(
|
||||||
| ProviderErrorKind::Protocol
|
GatewayErrorKind::UpstreamUnavailable,
|
||||||
| ProviderErrorKind::Unavailable
|
"Communication with the upstream service failed.",
|
||||||
| ProviderErrorKind::UpstreamCapacityUnavailable
|
),
|
||||||
| ProviderErrorKind::ProcessTerminated => Self::new(
|
ProviderErrorKind::Protocol => Self::new(
|
||||||
|
GatewayErrorKind::UpstreamUnavailable,
|
||||||
|
"Upstream protocol handling failed.",
|
||||||
|
),
|
||||||
|
ProviderErrorKind::ProcessTerminated => Self::new(
|
||||||
|
GatewayErrorKind::UpstreamUnavailable,
|
||||||
|
"The gateway stopped before the request completed.",
|
||||||
|
),
|
||||||
|
ProviderErrorKind::UpstreamCapacityUnavailable => Self::new(
|
||||||
|
GatewayErrorKind::UpstreamUnavailable,
|
||||||
|
"The upstream service has no capacity for this request.",
|
||||||
|
),
|
||||||
|
ProviderErrorKind::Unavailable => Self::new(
|
||||||
GatewayErrorKind::UpstreamUnavailable,
|
GatewayErrorKind::UpstreamUnavailable,
|
||||||
"Upstream service is unavailable.",
|
"Upstream service is unavailable.",
|
||||||
),
|
),
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ use std::sync::{Arc, OnceLock};
|
|||||||
use std::time::{Duration, SystemTime};
|
use std::time::{Duration, SystemTime};
|
||||||
|
|
||||||
use event_listener::Event;
|
use event_listener::Event;
|
||||||
|
use futures::FutureExt as _;
|
||||||
use futures::future::{BoxFuture, pending};
|
use futures::future::{BoxFuture, pending};
|
||||||
use futures_timer::Delay;
|
use futures_timer::Delay;
|
||||||
|
|
||||||
@@ -142,6 +143,14 @@ impl CancellationToken {
|
|||||||
self.reason().is_some()
|
self.reason().is_some()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 取消优先于同时就绪的工作,只用于可安全丢弃的 future
|
||||||
|
pub async fn run_until_cancelled<T>(&self, work: impl Future<Output = T>) -> Option<T> {
|
||||||
|
futures::select_biased! {
|
||||||
|
() = self.cancelled().fuse() => None,
|
||||||
|
result = work.fuse() => Some(result),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub async fn cancelled(&self) {
|
pub async fn cancelled(&self) {
|
||||||
if self.is_cancelled() {
|
if self.is_cancelled() {
|
||||||
return;
|
return;
|
||||||
|
|||||||
@@ -158,7 +158,7 @@ impl RateLimits {
|
|||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub struct ClientSettings {
|
pub struct ClientSettings {
|
||||||
pub request_profiles: BTreeMap<ProviderKind, OpaqueProviderData>,
|
pub request_profiles: BTreeMap<ProviderKind, OpaqueProviderData>,
|
||||||
pub fast_mode: FastMode,
|
pub fast_mode_override: Option<FastMode>,
|
||||||
pub limits: RateLimits,
|
pub limits: RateLimits,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -185,18 +185,18 @@ impl ClientPolicy {
|
|||||||
pub(crate) fn with_settings(
|
pub(crate) fn with_settings(
|
||||||
mut self,
|
mut self,
|
||||||
profiles: &BTreeMap<ProviderKind, OpaqueProviderData>,
|
profiles: &BTreeMap<ProviderKind, OpaqueProviderData>,
|
||||||
fast_mode: FastMode,
|
fast_mode_override: Option<FastMode>,
|
||||||
limits: RateLimits,
|
limits: RateLimits,
|
||||||
) -> Self {
|
) -> Self {
|
||||||
if self.account_scope.request_profiles() != profiles
|
if self.account_scope.request_profiles() != profiles
|
||||||
|| self.account_scope.fast_mode() != fast_mode
|
|| self.account_scope.fast_mode_override() != fast_mode_override
|
||||||
{
|
{
|
||||||
self.account_scope = Arc::new(
|
self.account_scope = Arc::new(
|
||||||
self.account_scope
|
self.account_scope
|
||||||
.as_ref()
|
.as_ref()
|
||||||
.clone()
|
.clone()
|
||||||
.with_request_profiles(profiles.clone())
|
.with_request_profiles(profiles.clone())
|
||||||
.with_fast_mode(fast_mode),
|
.with_fast_mode_override(fast_mode_override),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
self.limits = limits;
|
self.limits = limits;
|
||||||
@@ -217,7 +217,7 @@ impl ClientPolicy {
|
|||||||
name_snapshot: None,
|
name_snapshot: None,
|
||||||
defaults: Arc::new(ClientSettings {
|
defaults: Arc::new(ClientSettings {
|
||||||
request_profiles: account_scope.request_profiles().clone(),
|
request_profiles: account_scope.request_profiles().clone(),
|
||||||
fast_mode: account_scope.fast_mode(),
|
fast_mode_override: account_scope.fast_mode_override(),
|
||||||
limits,
|
limits,
|
||||||
}),
|
}),
|
||||||
key_id,
|
key_id,
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ use std::fmt;
|
|||||||
use std::num::{NonZeroU32, NonZeroU64};
|
use std::num::{NonZeroU32, NonZeroU64};
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
use crate::account::{AccountSelectionPolicy, FastMode};
|
use crate::account::AccountSelectionPolicy;
|
||||||
use crate::operation::{CapabilityRequirements, Feature, OperationKind};
|
use crate::operation::{CapabilityRequirements, Feature, OperationKind};
|
||||||
use crate::validation::{IdentifierError, RoutingError, validate_text};
|
use crate::validation::{IdentifierError, RoutingError, validate_text};
|
||||||
|
|
||||||
@@ -767,11 +767,6 @@ impl RoutingPlan {
|
|||||||
Arc::clone(&self.pricing)
|
Arc::clone(&self.pricing)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[must_use]
|
|
||||||
pub fn fast_mode(&self) -> FastMode {
|
|
||||||
self.account_scope.fast_mode()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 本次请求冻结的已编译规则,重试不读取新的全局策略
|
/// 本次请求冻结的已编译规则,重试不读取新的全局策略
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn privacy(&self) -> Option<Arc<dyn crate::settings::privacy::CompiledPrivacyPolicy>> {
|
pub fn privacy(&self) -> Option<Arc<dyn crate::settings::privacy::CompiledPrivacyPolicy>> {
|
||||||
|
|||||||
@@ -19,7 +19,8 @@ use crate::settings::{InvalidSettings, SettingsValues};
|
|||||||
#[serde(deny_unknown_fields)]
|
#[serde(deny_unknown_fields)]
|
||||||
pub struct ExecutionSettings {
|
pub struct ExecutionSettings {
|
||||||
pub runtime: SettingsValues,
|
pub runtime: SettingsValues,
|
||||||
pub fast_mode: FastMode,
|
/// None 按选中账号的有效分组解析;Some(Default) 显式跟随客户端
|
||||||
|
pub fast_mode: Option<FastMode>,
|
||||||
pub client_limits: RateLimits,
|
pub client_limits: RateLimits,
|
||||||
/// null 表示不限制总时长;显式时限从请求开始计时,改写不重置计时原点
|
/// null 表示不限制总时长;显式时限从请求开始计时,改写不重置计时原点
|
||||||
pub timeout_ms: Option<u64>,
|
pub timeout_ms: Option<u64>,
|
||||||
@@ -38,7 +39,7 @@ struct ExecutionOverrides {
|
|||||||
defaults: Arc<ClientSettings>,
|
defaults: Arc<ClientSettings>,
|
||||||
client_key_id: String,
|
client_key_id: String,
|
||||||
input: Arc<ExecutionSettings>,
|
input: Arc<ExecutionSettings>,
|
||||||
fast_mode: Option<SettingOverride<FastMode>>,
|
fast_mode: Option<SettingOverride<Option<FastMode>>>,
|
||||||
client_limits: Option<SettingOverride<RateLimits>>,
|
client_limits: Option<SettingOverride<RateLimits>>,
|
||||||
timeout_ms: Option<SettingOverride<Option<u64>>>,
|
timeout_ms: Option<SettingOverride<Option<u64>>>,
|
||||||
}
|
}
|
||||||
@@ -186,9 +187,10 @@ impl RequestSettings {
|
|||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn apply_policy(&self, policy: ClientPolicy) -> ClientPolicy {
|
pub fn apply_policy(&self, policy: ClientPolicy) -> ClientPolicy {
|
||||||
let values = self.resolve_execution(policy.key_id().as_str(), policy.defaults(), None);
|
let values = self.resolve_execution(policy.key_id().as_str(), policy.defaults(), None);
|
||||||
|
let fast_mode = self.fast_mode_override(policy.key_id().as_str(), policy.defaults());
|
||||||
policy.with_settings(
|
policy.with_settings(
|
||||||
values.runtime.request_profiles(),
|
values.runtime.request_profiles(),
|
||||||
values.fast_mode,
|
fast_mode,
|
||||||
values.client_limits,
|
values.client_limits,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -247,9 +249,7 @@ impl RequestSettings {
|
|||||||
}
|
}
|
||||||
ExecutionSettings {
|
ExecutionSettings {
|
||||||
runtime,
|
runtime,
|
||||||
fast_mode: overrides
|
fast_mode: self.fast_mode_override(key, defaults),
|
||||||
.and_then(|scope| scope.fast_mode.as_ref())
|
|
||||||
.map_or(defaults.fast_mode, |change| change.value),
|
|
||||||
client_limits: overrides
|
client_limits: overrides
|
||||||
.and_then(|scope| scope.client_limits.as_ref())
|
.and_then(|scope| scope.client_limits.as_ref())
|
||||||
.map_or(defaults.limits, |change| change.value),
|
.map_or(defaults.limits, |change| change.value),
|
||||||
@@ -259,6 +259,15 @@ impl RequestSettings {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn fast_mode_override(&self, key: &str, defaults: &ClientSettings) -> Option<FastMode> {
|
||||||
|
self.execution
|
||||||
|
.as_ref()
|
||||||
|
.filter(|scope| scope.client_key_id == key)
|
||||||
|
.and_then(|scope| scope.fast_mode.as_ref())
|
||||||
|
.map(|change| change.value)
|
||||||
|
.unwrap_or(defaults.fast_mode_override)
|
||||||
|
}
|
||||||
|
|
||||||
pub(crate) fn execution_deadline(
|
pub(crate) fn execution_deadline(
|
||||||
&self,
|
&self,
|
||||||
key: &ClientApiKeyId,
|
key: &ClientApiKeyId,
|
||||||
|
|||||||
@@ -583,12 +583,19 @@ async fn compile_runtime_snapshot(
|
|||||||
.map(|group| (group.id.clone(), std::mem::take(&mut group.model_access)))
|
.map(|group| (group.id.clone(), std::mem::take(&mut group.model_access)))
|
||||||
.collect();
|
.collect();
|
||||||
let account_directory = Arc::new(
|
let account_directory = Arc::new(
|
||||||
RuntimeAccountDirectory::new(accounts).with_group_model_access(group_model_access),
|
RuntimeAccountDirectory::new(accounts)
|
||||||
|
.with_group_model_access(group_model_access)
|
||||||
|
.with_group_fast_modes(
|
||||||
|
groups
|
||||||
|
.values()
|
||||||
|
.filter(|group| group.enabled && group.fast_mode != FastMode::Default)
|
||||||
|
.map(|group| (group.id.clone(), group.fast_mode))
|
||||||
|
.collect(),
|
||||||
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
let mut client_policies = Vec::with_capacity(facts.client_policies.len());
|
let mut client_policies = Vec::with_capacity(facts.client_policies.len());
|
||||||
for policy in facts.client_policies {
|
for policy in facts.client_policies {
|
||||||
let mut fast_mode = FastMode::Default;
|
|
||||||
let mut allow_image_generation = true;
|
let mut allow_image_generation = true;
|
||||||
let mut allow_subagents = true;
|
let mut allow_subagents = true;
|
||||||
let account_scope = if policy.group_ids.is_empty() {
|
let account_scope = if policy.group_ids.is_empty() {
|
||||||
@@ -607,8 +614,7 @@ async fn compile_runtime_snapshot(
|
|||||||
let group = groups
|
let group = groups
|
||||||
.get(&group_id)
|
.get(&group_id)
|
||||||
.ok_or(RuntimeSnapshotCompileError::InvalidData)?;
|
.ok_or(RuntimeSnapshotCompileError::InvalidData)?;
|
||||||
// 停用只影响选号,仍绑定的分组继续贡献请求策略
|
// 功能权限仍按 Key 合并,停用分组不解除生图和子代理限制
|
||||||
fast_mode = fast_mode.merge(group.fast_mode);
|
|
||||||
allow_image_generation &= group.allow_image_generation;
|
allow_image_generation &= group.allow_image_generation;
|
||||||
allow_subagents &= group.allow_subagents;
|
allow_subagents &= group.allow_subagents;
|
||||||
bound_groups.push(RoutingGroupSnapshot::new(
|
bound_groups.push(RoutingGroupSnapshot::new(
|
||||||
@@ -635,7 +641,6 @@ async fn compile_runtime_snapshot(
|
|||||||
account_scope
|
account_scope
|
||||||
.with_image_generation(allow_image_generation)
|
.with_image_generation(allow_image_generation)
|
||||||
.with_subagents(allow_subagents)
|
.with_subagents(allow_subagents)
|
||||||
.with_fast_mode(fast_mode)
|
|
||||||
.with_request_profiles(policy.request_profiles),
|
.with_request_profiles(policy.request_profiles),
|
||||||
),
|
),
|
||||||
true,
|
true,
|
||||||
|
|||||||
@@ -399,14 +399,13 @@ struct RuntimeSnapshotReconciliationTask {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl ScheduledTask for RuntimeSnapshotReconciliationTask {
|
impl ScheduledTask for RuntimeSnapshotReconciliationTask {
|
||||||
fn run_cycle(
|
fn run_cycle(&self, context: WorkerCycleContext) -> BoxFuture<'_, Result<(), WorkerTaskError>> {
|
||||||
&self,
|
|
||||||
_context: WorkerCycleContext,
|
|
||||||
) -> BoxFuture<'_, Result<(), WorkerTaskError>> {
|
|
||||||
Box::pin(async move {
|
Box::pin(async move {
|
||||||
self.publisher
|
context
|
||||||
.refresh_with_mode(RefreshMode::Reconcile)
|
.cancellation()
|
||||||
|
.run_until_cancelled(self.publisher.refresh_with_mode(RefreshMode::Reconcile))
|
||||||
.await
|
.await
|
||||||
|
.transpose()
|
||||||
.map(|_| ())
|
.map(|_| ())
|
||||||
.map_err(|source| {
|
.map_err(|source| {
|
||||||
WorkerTaskError::safe("runtime snapshot reconciliation failed")
|
WorkerTaskError::safe("runtime snapshot reconciliation failed")
|
||||||
@@ -430,10 +429,12 @@ impl DaemonTask for RuntimeSnapshotSubscriptionTask {
|
|||||||
let cancellation = context.cancellation();
|
let cancellation = context.cancellation();
|
||||||
let mut retry_delay = INITIAL_BACKOFF;
|
let mut retry_delay = INITIAL_BACKOFF;
|
||||||
loop {
|
loop {
|
||||||
if cancellation.is_cancelled() {
|
let Some(subscription) = cancellation
|
||||||
|
.run_until_cancelled(self.subscriptions.subscribe_snapshot_revisions())
|
||||||
|
.await
|
||||||
|
else {
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
};
|
||||||
let subscription = self.subscriptions.subscribe_snapshot_revisions().await;
|
|
||||||
let mut subscription = match subscription {
|
let mut subscription = match subscription {
|
||||||
Ok(subscription) => {
|
Ok(subscription) => {
|
||||||
retry_delay = INITIAL_BACKOFF;
|
retry_delay = INITIAL_BACKOFF;
|
||||||
@@ -456,7 +457,13 @@ impl DaemonTask for RuntimeSnapshotSubscriptionTask {
|
|||||||
};
|
};
|
||||||
match notified {
|
match notified {
|
||||||
Some(Ok(_)) => {
|
Some(Ok(_)) => {
|
||||||
let _ = self.publisher.refresh().await;
|
if cancellation
|
||||||
|
.run_until_cancelled(self.publisher.refresh())
|
||||||
|
.await
|
||||||
|
.is_none()
|
||||||
|
{
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Some(Err(_)) | None => break,
|
Some(Err(_)) | None => break,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ mod model_access;
|
|||||||
mod proxy;
|
mod proxy;
|
||||||
mod quota_reset_priority;
|
mod quota_reset_priority;
|
||||||
mod quota_settings;
|
mod quota_settings;
|
||||||
|
mod recent_requests;
|
||||||
mod scope;
|
mod scope;
|
||||||
mod selection;
|
mod selection;
|
||||||
mod selection_diagnostics;
|
mod selection_diagnostics;
|
||||||
@@ -56,6 +57,7 @@ fn candidate(id: &str, in_flight: u32, remaining: Option<u64>) -> AccountCandida
|
|||||||
account: account(id),
|
account: account(id),
|
||||||
signals: AccountRuntimeSignals {
|
signals: AccountRuntimeSignals {
|
||||||
in_flight,
|
in_flight,
|
||||||
|
recent_requests: 0,
|
||||||
last_started_at: None,
|
last_started_at: None,
|
||||||
quota_reset_at: None,
|
quota_reset_at: None,
|
||||||
quota_reset_windows: None,
|
quota_reset_windows: None,
|
||||||
@@ -229,6 +231,7 @@ fn diagnostic_selection_bypasses_all_local_account_eligibility() {
|
|||||||
),
|
),
|
||||||
signals: AccountRuntimeSignals {
|
signals: AccountRuntimeSignals {
|
||||||
in_flight: 0,
|
in_flight: 0,
|
||||||
|
recent_requests: 0,
|
||||||
last_started_at: None,
|
last_started_at: None,
|
||||||
quota_reset_at: None,
|
quota_reset_at: None,
|
||||||
quota_reset_windows: None,
|
quota_reset_windows: None,
|
||||||
@@ -249,6 +252,7 @@ fn diagnostic_selection_bypasses_all_local_account_eligibility() {
|
|||||||
),
|
),
|
||||||
signals: AccountRuntimeSignals {
|
signals: AccountRuntimeSignals {
|
||||||
in_flight: 0,
|
in_flight: 0,
|
||||||
|
recent_requests: 0,
|
||||||
last_started_at: None,
|
last_started_at: None,
|
||||||
quota_reset_at: None,
|
quota_reset_at: None,
|
||||||
quota_reset_windows: None,
|
quota_reset_windows: None,
|
||||||
@@ -644,6 +648,7 @@ fn provider_quota_overlay_should_preserve_store_concurrency_facts() {
|
|||||||
let last_started_at = SystemTime::now();
|
let last_started_at = SystemTime::now();
|
||||||
let signals = AccountRuntimeSignals {
|
let signals = AccountRuntimeSignals {
|
||||||
in_flight: 2,
|
in_flight: 2,
|
||||||
|
recent_requests: 0,
|
||||||
last_started_at: Some(last_started_at),
|
last_started_at: Some(last_started_at),
|
||||||
quota_reset_at: None,
|
quota_reset_at: None,
|
||||||
quota_reset_windows: None,
|
quota_reset_windows: None,
|
||||||
|
|||||||
@@ -0,0 +1,182 @@
|
|||||||
|
//! 验证近期负载的模型隔离、滑动过期、延迟确认与并发计数
|
||||||
|
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
|
use gateway_core::account::{AccountFeedbackStats, ProviderAccountId};
|
||||||
|
use gateway_core::identity::ProviderKind;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn recent_requests_expire_by_start_time_and_isolate_accounts_models_and_providers() {
|
||||||
|
let stats = AccountFeedbackStats::default();
|
||||||
|
let provider = ProviderKind::new("openai").unwrap();
|
||||||
|
let other_provider = ProviderKind::new("xai").unwrap();
|
||||||
|
let account = ProviderAccountId::new("acct_recent").unwrap();
|
||||||
|
let other_account = ProviderAccountId::new("acct_other").unwrap();
|
||||||
|
let start = Instant::now();
|
||||||
|
for offset in [0, 30, 59] {
|
||||||
|
let now = start + Duration::from_secs(offset);
|
||||||
|
stats.record_request_at(&provider, &account, "model-a", now, now);
|
||||||
|
}
|
||||||
|
let now = start + Duration::from_secs(59);
|
||||||
|
assert_eq!(
|
||||||
|
stats.recent_requests_at(&provider, &account, Some("model-a"), now),
|
||||||
|
3
|
||||||
|
);
|
||||||
|
for (provider, account, model) in [
|
||||||
|
(&provider, &other_account, Some("model-a")),
|
||||||
|
(&other_provider, &account, Some("model-a")),
|
||||||
|
(&provider, &account, Some("model-b")),
|
||||||
|
(&provider, &account, None),
|
||||||
|
] {
|
||||||
|
assert_eq!(stats.recent_requests_at(provider, account, model, now), 0);
|
||||||
|
}
|
||||||
|
let now = start + Duration::from_secs(60);
|
||||||
|
assert_eq!(
|
||||||
|
stats.recent_requests_at(&provider, &account, Some("model-a"), now),
|
||||||
|
2
|
||||||
|
);
|
||||||
|
// 响应晚到时仍落在开始时的桶,已经过期的请求不重新进入窗口
|
||||||
|
stats.record_request_at(&provider, &account, "model-a", start, now);
|
||||||
|
stats.record_request_at(
|
||||||
|
&provider,
|
||||||
|
&account,
|
||||||
|
"model-a",
|
||||||
|
start + Duration::from_secs(30),
|
||||||
|
now,
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
stats.recent_requests_at(&provider, &account, Some("model-a"), now),
|
||||||
|
3
|
||||||
|
);
|
||||||
|
let now = start + Duration::from_secs(90);
|
||||||
|
assert_eq!(
|
||||||
|
stats.recent_requests_at(&provider, &account, Some("model-a"), now),
|
||||||
|
1
|
||||||
|
);
|
||||||
|
let now = start + Duration::from_secs(120);
|
||||||
|
assert_eq!(
|
||||||
|
stats.recent_requests_at(&provider, &account, Some("model-a"), now),
|
||||||
|
0
|
||||||
|
);
|
||||||
|
stats.record_request_at(&provider, &account, "model-a", now, now);
|
||||||
|
assert_eq!(
|
||||||
|
stats.recent_requests_at(&provider, &account, Some("model-a"), now),
|
||||||
|
1
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
AccountFeedbackStats::default().recent_requests(&provider, &account, Some("model-a")),
|
||||||
|
0
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn concurrent_requests_are_counted_once_per_record() {
|
||||||
|
let stats = AccountFeedbackStats::default();
|
||||||
|
let provider = ProviderKind::new("openai").unwrap();
|
||||||
|
let account = ProviderAccountId::new("acct_recent").unwrap();
|
||||||
|
std::thread::scope(|scope| {
|
||||||
|
for _ in 0..8 {
|
||||||
|
scope.spawn(|| {
|
||||||
|
for _ in 0..1000 {
|
||||||
|
let now = Instant::now();
|
||||||
|
stats.record_request_at(&provider, &account, "model", now, now);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
assert_eq!(
|
||||||
|
stats.recent_requests(&provider, &account, Some("model")),
|
||||||
|
8000
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn snapshot_restores_only_live_buckets_and_preserves_expiration_after_downtime() {
|
||||||
|
let stats = AccountFeedbackStats::default();
|
||||||
|
let provider = ProviderKind::new("openai").unwrap();
|
||||||
|
let account = ProviderAccountId::new("acct_restart").unwrap();
|
||||||
|
let start = Instant::now();
|
||||||
|
let wall_start = std::time::SystemTime::now();
|
||||||
|
for offset in [0, 30, 59] {
|
||||||
|
let now = start + Duration::from_secs(offset);
|
||||||
|
stats.record_request_at(&provider, &account, "model", now, now);
|
||||||
|
}
|
||||||
|
let snapshot = stats.snapshot_recent_requests_at(
|
||||||
|
start + Duration::from_secs(59),
|
||||||
|
wall_start + Duration::from_secs(59),
|
||||||
|
);
|
||||||
|
let bytes = serde_json::to_vec(&snapshot).unwrap();
|
||||||
|
let snapshot = serde_json::from_slice(&bytes).unwrap();
|
||||||
|
let restored = AccountFeedbackStats::default();
|
||||||
|
restored
|
||||||
|
.restore_recent_requests_at(
|
||||||
|
snapshot,
|
||||||
|
start + Duration::from_secs(79),
|
||||||
|
wall_start + Duration::from_secs(79),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
for (offset, expected) in [(79, 2), (91, 1), (120, 0)] {
|
||||||
|
assert_eq!(
|
||||||
|
restored.recent_requests_at(
|
||||||
|
&provider,
|
||||||
|
&account,
|
||||||
|
Some("model"),
|
||||||
|
start + Duration::from_secs(offset)
|
||||||
|
),
|
||||||
|
expected,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn stale_snapshots_and_backward_wall_clock_start_with_an_empty_window() {
|
||||||
|
let stats = AccountFeedbackStats::default();
|
||||||
|
let provider = ProviderKind::new("openai").unwrap();
|
||||||
|
let account = ProviderAccountId::new("acct_restart").unwrap();
|
||||||
|
let now = Instant::now();
|
||||||
|
let wall_now = std::time::SystemTime::now();
|
||||||
|
stats.record_request_at(&provider, &account, "model", now, now);
|
||||||
|
let snapshot = stats.snapshot_recent_requests_at(now, wall_now);
|
||||||
|
for wall_restart in [
|
||||||
|
wall_now + Duration::from_secs(60),
|
||||||
|
wall_now - Duration::from_secs(1),
|
||||||
|
] {
|
||||||
|
let restored = AccountFeedbackStats::default();
|
||||||
|
restored
|
||||||
|
.restore_recent_requests_at(snapshot.clone(), now, wall_restart)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
restored.recent_requests_at(&provider, &account, Some("model"), now),
|
||||||
|
0
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn invalid_snapshot_does_not_partially_replace_live_counts() {
|
||||||
|
let source = AccountFeedbackStats::default();
|
||||||
|
let live = AccountFeedbackStats::default();
|
||||||
|
let provider = ProviderKind::new("openai").unwrap();
|
||||||
|
let account = ProviderAccountId::new("acct_restart").unwrap();
|
||||||
|
let now = Instant::now();
|
||||||
|
let wall_now = std::time::SystemTime::now();
|
||||||
|
for _ in 0..2 {
|
||||||
|
source.record_request_at(&provider, &account, "model", now, now);
|
||||||
|
}
|
||||||
|
live.record_request_at(&provider, &account, "model", now, now);
|
||||||
|
let mut value =
|
||||||
|
serde_json::to_value(source.snapshot_recent_requests_at(now, wall_now)).unwrap();
|
||||||
|
let windows = value["windows"].as_array_mut().unwrap();
|
||||||
|
let mut invalid = windows[0].clone();
|
||||||
|
invalid["account"] = serde_json::json!("");
|
||||||
|
windows.push(invalid);
|
||||||
|
let snapshot = serde_json::from_value(value).unwrap();
|
||||||
|
assert!(
|
||||||
|
live.restore_recent_requests_at(snapshot, now, wall_now)
|
||||||
|
.is_err()
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
live.recent_requests_at(&provider, &account, Some("model"), now),
|
||||||
|
1,
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -36,6 +36,7 @@ fn reserved_pool_scoring_and_trace_use_its_capacity_instead_of_the_normal_limit(
|
|||||||
let selected = &snapshot["events"][0]["data"]["candidates"][0];
|
let selected = &snapshot["events"][0]["data"]["candidates"][0];
|
||||||
assert_eq!(selected["concurrencyLimit"], 5);
|
assert_eq!(selected["concurrencyLimit"], 5);
|
||||||
assert_eq!(selected["inFlight"], 1);
|
assert_eq!(selected["inFlight"], 1);
|
||||||
|
assert_eq!(selected["recentRequests"], 0);
|
||||||
assert_eq!(selected["smartScore"], 0.8);
|
assert_eq!(selected["smartScore"], 0.8);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -429,3 +430,189 @@ fn missing_expired_and_duplicate_periods_do_not_inflate_reset_score() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn smart_prefers_recently_idle_accounts_and_disables_recent_load_with_zero_weight() {
|
||||||
|
let candidates = (0..130)
|
||||||
|
.map(|index| {
|
||||||
|
let mut candidate = candidate_with_concurrency(&format!("acct_{index:03}"), 0, 8);
|
||||||
|
candidate.signals.recent_requests = index / 2;
|
||||||
|
candidate
|
||||||
|
})
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
let mut context = context(RotationStrategy::Smart);
|
||||||
|
for cursor in 0..260 {
|
||||||
|
context.round_robin_cursor = cursor;
|
||||||
|
let selected = AccountSelector.select(&candidates, &context).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
selected.candidate().account.id(),
|
||||||
|
candidates[(cursor % 2) as usize].account.id()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
// 系数归零时由其余维度和轮换决定,近期负载退出比较
|
||||||
|
context.policy = context
|
||||||
|
.policy
|
||||||
|
.with_smart_scheduling(SmartSchedulingConfig::new([0.0, 0.8, 1.0, 0.5, 0.0, 0.0]).unwrap());
|
||||||
|
for cursor in 0..130 {
|
||||||
|
context.round_robin_cursor = cursor;
|
||||||
|
let selected = AccountSelector.select(&candidates, &context).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
selected.candidate().account.id(),
|
||||||
|
candidates[cursor as usize].account.id()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn recent_load_respects_affinity_weight_capacity_and_configured_quota_weight() {
|
||||||
|
let mut candidates = [
|
||||||
|
candidate_with_concurrency("acct_busy", 0, 8),
|
||||||
|
candidate_with_concurrency("acct_idle", 0, 8),
|
||||||
|
];
|
||||||
|
candidates[0].signals.recent_requests = 20;
|
||||||
|
let mut context = context(RotationStrategy::Smart);
|
||||||
|
context.preferred_account = Some(candidates[0].account.id().clone());
|
||||||
|
assert_eq!(
|
||||||
|
AccountSelector
|
||||||
|
.select(&candidates, &context)
|
||||||
|
.unwrap()
|
||||||
|
.candidate()
|
||||||
|
.account
|
||||||
|
.id()
|
||||||
|
.as_str(),
|
||||||
|
"acct_busy"
|
||||||
|
);
|
||||||
|
context.preferred_account = None;
|
||||||
|
candidates[1].signals.in_flight = 8;
|
||||||
|
assert_eq!(
|
||||||
|
AccountSelector
|
||||||
|
.select(&candidates, &context)
|
||||||
|
.unwrap()
|
||||||
|
.candidate()
|
||||||
|
.account
|
||||||
|
.id()
|
||||||
|
.as_str(),
|
||||||
|
"acct_busy"
|
||||||
|
);
|
||||||
|
candidates[1].signals.in_flight = 0;
|
||||||
|
candidates[1].signals.quota_remaining_rank = Some(0);
|
||||||
|
candidates[0].signals.quota_remaining_rank = Some(10_000);
|
||||||
|
assert_eq!(
|
||||||
|
AccountSelector
|
||||||
|
.select(&candidates, &context)
|
||||||
|
.unwrap()
|
||||||
|
.candidate()
|
||||||
|
.account
|
||||||
|
.id()
|
||||||
|
.as_str(),
|
||||||
|
"acct_busy"
|
||||||
|
);
|
||||||
|
candidates[1].signals.quota_remaining_rank = Some(10_000);
|
||||||
|
candidates[0].account = candidates[0]
|
||||||
|
.account
|
||||||
|
.clone()
|
||||||
|
.with_scheduling(None, gateway_core::account::AccountWeight::new(2).unwrap());
|
||||||
|
candidates[1].account = candidates[1]
|
||||||
|
.account
|
||||||
|
.clone()
|
||||||
|
.with_scheduling(None, gateway_core::account::AccountWeight::new(1).unwrap());
|
||||||
|
assert_eq!(
|
||||||
|
AccountSelector
|
||||||
|
.select(&candidates, &context)
|
||||||
|
.unwrap()
|
||||||
|
.candidate()
|
||||||
|
.account
|
||||||
|
.id()
|
||||||
|
.as_str(),
|
||||||
|
"acct_busy"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn recent_model_load_competes_with_quota_and_cross_model_concurrency_before_score_filtering() {
|
||||||
|
for weights in [
|
||||||
|
[1.0, 0.1, 1.0, 0.0, 0.0, 0.0],
|
||||||
|
[1.0, 0.8, 1.0, 0.5, 0.0, 0.0],
|
||||||
|
] {
|
||||||
|
for limit in [6, 8] {
|
||||||
|
for (hot_requests, cool_requests, cool_in_flight, cool_quota) in [
|
||||||
|
(18, 0, 0, 9_000),
|
||||||
|
(18, 0, 0, 7_000),
|
||||||
|
(18, 0, 1, 10_000),
|
||||||
|
(16, 4, 1, 9_000),
|
||||||
|
(27, 3, 1, 7_000),
|
||||||
|
] {
|
||||||
|
let mut candidates = [
|
||||||
|
candidate_with_concurrency("acct_hot", 0, limit),
|
||||||
|
candidate_with_concurrency("acct_cool", cool_in_flight, limit),
|
||||||
|
];
|
||||||
|
candidates[0].signals.quota_remaining_rank = Some(10_000);
|
||||||
|
candidates[0].signals.recent_requests = hot_requests;
|
||||||
|
candidates[1].signals.quota_remaining_rank = Some(cool_quota);
|
||||||
|
candidates[1].signals.recent_requests = cool_requests;
|
||||||
|
let mut context = context(RotationStrategy::Smart);
|
||||||
|
context.policy = context
|
||||||
|
.policy
|
||||||
|
.with_smart_scheduling(SmartSchedulingConfig::new(weights).unwrap());
|
||||||
|
let selected = AccountSelector.select(&candidates, &context).unwrap();
|
||||||
|
assert_eq!(selected.candidate().account.id().as_str(), "acct_cool");
|
||||||
|
|
||||||
|
let trace = gateway_core::diagnostics::TraceContext::new("req_recent_score");
|
||||||
|
trace.account_selection(&candidates, &context, Some(&selected));
|
||||||
|
let snapshot = trace.snapshot().unwrap();
|
||||||
|
let scores = &snapshot["events"][0]["data"]["candidates"];
|
||||||
|
assert!(
|
||||||
|
scores[0]["smartScore"].as_f64().unwrap()
|
||||||
|
> scores[1]["smartScore"].as_f64().unwrap()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn recent_heat_does_not_dilute_concurrency_pressure_or_require_nonnegative_load_scores() {
|
||||||
|
let mut candidates = [
|
||||||
|
candidate_with_concurrency("acct_busy", 5, 6),
|
||||||
|
candidate_with_concurrency("acct_idle", 4, 6),
|
||||||
|
];
|
||||||
|
candidates[0].signals.quota_remaining_rank = Some(10_000);
|
||||||
|
candidates[1].signals.quota_remaining_rank = Some(9_000);
|
||||||
|
for candidate in &mut candidates {
|
||||||
|
candidate.signals.recent_requests = 30;
|
||||||
|
}
|
||||||
|
let mut context = context(RotationStrategy::Smart);
|
||||||
|
for quota_weight in [0.0, 0.8] {
|
||||||
|
context.policy = context.policy.with_smart_scheduling(
|
||||||
|
SmartSchedulingConfig::new([1.0, quota_weight, 0.0, 0.0, 0.0, 0.0]).unwrap(),
|
||||||
|
);
|
||||||
|
let selected = AccountSelector.select(&candidates, &context).unwrap();
|
||||||
|
assert_eq!(selected.candidate().account.id().as_str(), "acct_idle");
|
||||||
|
if quota_weight == 0.0 {
|
||||||
|
let trace = gateway_core::diagnostics::TraceContext::new("req_negative_load");
|
||||||
|
trace.account_selection(&candidates, &context, Some(&selected));
|
||||||
|
assert!(
|
||||||
|
trace.snapshot().unwrap()["events"][0]["data"]["candidates"][0]["smartScore"]
|
||||||
|
.as_f64()
|
||||||
|
.unwrap()
|
||||||
|
< 0.0
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn recent_load_remains_effective_without_a_concurrency_limit() {
|
||||||
|
let mut candidates = [
|
||||||
|
super::candidate("acct_hot", 0, None),
|
||||||
|
super::candidate("acct_cool", 1, None),
|
||||||
|
];
|
||||||
|
candidates[0].signals.recent_requests = u64::MAX;
|
||||||
|
let mut context = context(RotationStrategy::Smart);
|
||||||
|
context.policy = gateway_core::account::AccountSelectionPolicy::new(
|
||||||
|
RotationStrategy::Smart,
|
||||||
|
gateway_core::account::AccountConcurrency::new(0),
|
||||||
|
);
|
||||||
|
let selected = AccountSelector.select(&candidates, &context).unwrap();
|
||||||
|
assert_eq!(selected.candidate().account.id().as_str(), "acct_cool");
|
||||||
|
}
|
||||||
|
|||||||
@@ -1138,26 +1138,12 @@ fn plan_with_location(
|
|||||||
operation: &Operation,
|
operation: &Operation,
|
||||||
account_selection_policy: AccountSelectionPolicy,
|
account_selection_policy: AccountSelectionPolicy,
|
||||||
request_location: gateway_core::account::RequestLocation,
|
request_location: gateway_core::account::RequestLocation,
|
||||||
) -> RoutingPlan {
|
|
||||||
plan_with_location_and_fast_policy(
|
|
||||||
operation,
|
|
||||||
account_selection_policy,
|
|
||||||
request_location,
|
|
||||||
FastMode::Default,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn plan_with_location_and_fast_policy(
|
|
||||||
operation: &Operation,
|
|
||||||
account_selection_policy: AccountSelectionPolicy,
|
|
||||||
request_location: gateway_core::account::RequestLocation,
|
|
||||||
fast_mode: FastMode,
|
|
||||||
) -> RoutingPlan {
|
) -> RoutingPlan {
|
||||||
plan_with_profiles(
|
plan_with_profiles(
|
||||||
operation,
|
operation,
|
||||||
account_selection_policy,
|
account_selection_policy,
|
||||||
request_location,
|
request_location,
|
||||||
fast_mode,
|
FastMode::Default,
|
||||||
Default::default(),
|
Default::default(),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -1255,7 +1241,7 @@ fn plan_with_protection(
|
|||||||
operation,
|
operation,
|
||||||
Arc::new(
|
Arc::new(
|
||||||
FrozenAccountScope::new(directory, ClientRoutingScope::all_accounts())
|
FrozenAccountScope::new(directory, ClientRoutingScope::all_accounts())
|
||||||
.with_fast_mode(fast_mode)
|
.with_fast_mode_override(Some(fast_mode))
|
||||||
.with_request_profiles(profiles),
|
.with_request_profiles(profiles),
|
||||||
),
|
),
|
||||||
&RoutingContext {
|
&RoutingContext {
|
||||||
@@ -2525,11 +2511,33 @@ fn native_capacity_above_wait_limit_rotates_before_requesting_client_replay() {
|
|||||||
.with_continuation_recovery_disposition(
|
.with_continuation_recovery_disposition(
|
||||||
ContinuationRecoveryDisposition::ClientReplayRequired,
|
ContinuationRecoveryDisposition::ClientReplayRequired,
|
||||||
);
|
);
|
||||||
|
let original = if committed_prelude {
|
||||||
|
let event = json!({"type":"response.failed", "response":{"error":{
|
||||||
|
"headers":{"Retry-After":seconds.to_string(), "Retry-After-Ms":"317001", "x-private":"omit"}
|
||||||
|
}}});
|
||||||
|
original.with_atomic_client_events(vec![ProviderEvent::wire(
|
||||||
|
ProtocolWireEvent::json("openai", Some("response.failed".to_owned()), event)
|
||||||
|
.unwrap(),
|
||||||
|
)])
|
||||||
|
} else {
|
||||||
|
original.with_client_visible_upstream_response(
|
||||||
|
ClientVisibleUpstreamResponse::new(503, None, Bytes::from(original_body.clone()))
|
||||||
|
.with_headers(vec![gateway_core::event::ProviderResponseHeader::new(
|
||||||
|
"Retry-After-Ms",
|
||||||
|
Bytes::from_static(b"309001"),
|
||||||
|
)]),
|
||||||
|
)
|
||||||
|
};
|
||||||
let recovery = if replacement {
|
let recovery = if replacement {
|
||||||
ProviderError::new(
|
ProviderError::new(
|
||||||
ProviderErrorKind::ContinuationRecoveryRequired,
|
ProviderErrorKind::ContinuationRecoveryRequired,
|
||||||
UpstreamSendState::NotSent,
|
UpstreamSendState::NotSent,
|
||||||
)
|
)
|
||||||
|
.with_client_visible_upstream_response(ClientVisibleUpstreamResponse::new(
|
||||||
|
400,
|
||||||
|
None,
|
||||||
|
Bytes::from_static(b"{}"),
|
||||||
|
))
|
||||||
.with_continuation_unavailable_reason("account_rotated")
|
.with_continuation_unavailable_reason("account_rotated")
|
||||||
.with_continuation_recovery_disposition(
|
.with_continuation_recovery_disposition(
|
||||||
ContinuationRecoveryDisposition::ClientReplayRequired,
|
ContinuationRecoveryDisposition::ClientReplayRequired,
|
||||||
@@ -2602,6 +2610,29 @@ fn native_capacity_above_wait_limit_rotates_before_requesting_client_replay() {
|
|||||||
error.continuation_unavailable_reason(),
|
error.continuation_unavailable_reason(),
|
||||||
(replacement && expected_attempts == 2).then_some("account_rotated")
|
(replacement && expected_attempts == 2).then_some("account_rotated")
|
||||||
);
|
);
|
||||||
|
if replacement && expected_attempts == 2 {
|
||||||
|
let response = error.client_visible_upstream_response().unwrap();
|
||||||
|
assert_eq!(response.status(), 400);
|
||||||
|
let headers: Vec<_> = response
|
||||||
|
.headers()
|
||||||
|
.iter()
|
||||||
|
.map(|header| (header.name().to_ascii_lowercase(), header.value().as_ref()))
|
||||||
|
.collect();
|
||||||
|
assert_eq!(
|
||||||
|
headers,
|
||||||
|
vec![
|
||||||
|
("retry-after".to_owned(), seconds.to_string().as_bytes()),
|
||||||
|
(
|
||||||
|
"retry-after-ms".to_owned(),
|
||||||
|
if committed_prelude {
|
||||||
|
b"317001"
|
||||||
|
} else {
|
||||||
|
b"309001"
|
||||||
|
}
|
||||||
|
),
|
||||||
|
]
|
||||||
|
);
|
||||||
|
}
|
||||||
let contexts = provider.contexts.lock().unwrap();
|
let contexts = provider.contexts.lock().unwrap();
|
||||||
assert_eq!(contexts.len(), expected_attempts);
|
assert_eq!(contexts.len(), expected_attempts);
|
||||||
if contexts.len() == 2 {
|
if contexts.len() == 2 {
|
||||||
@@ -6369,6 +6400,8 @@ fn deadline_before_first_event_is_persisted_as_failed_attempt() {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn global_location_and_group_fast_policy_reach_every_account_retry() {
|
fn global_location_and_group_fast_policy_reach_every_account_retry() {
|
||||||
|
use gateway_core::routing::{AccountGroupId, RoutingGroupSnapshot};
|
||||||
|
|
||||||
for mode in [
|
for mode in [
|
||||||
FastMode::Default,
|
FastMode::Default,
|
||||||
FastMode::Enabled,
|
FastMode::Enabled,
|
||||||
@@ -6380,12 +6413,67 @@ fn global_location_and_group_fast_policy_reach_every_account_retry() {
|
|||||||
timezone: "Asia/Tokyo".parse().unwrap(),
|
timezone: "Asia/Tokyo".parse().unwrap(),
|
||||||
..Default::default()
|
..Default::default()
|
||||||
};
|
};
|
||||||
let route_plan = plan_with_location_and_fast_policy(
|
let kind = ProviderKind::new("openai").unwrap();
|
||||||
&operation,
|
let first_group = AccountGroupId::new(format!("grp_{:032x}", 1)).unwrap();
|
||||||
plan(&operation).account_selection_policy(),
|
let second_group = AccountGroupId::new(format!("grp_{:032x}", 2)).unwrap();
|
||||||
location.clone(),
|
let second_mode = if mode == FastMode::Disabled {
|
||||||
mode,
|
FastMode::Default
|
||||||
|
} else {
|
||||||
|
FastMode::Disabled
|
||||||
|
};
|
||||||
|
let directory = Arc::new(
|
||||||
|
RuntimeAccountDirectory::new(
|
||||||
|
[
|
||||||
|
("acct_first", first_group.clone()),
|
||||||
|
("acct_second", second_group.clone()),
|
||||||
|
]
|
||||||
|
.into_iter()
|
||||||
|
.map(|(account, group)| {
|
||||||
|
(
|
||||||
|
ProviderAccountId::new(account).unwrap(),
|
||||||
|
RuntimeAccount::new(kind.clone(), BTreeSet::from([group])),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.collect(),
|
||||||
|
)
|
||||||
|
.with_group_fast_modes(BTreeMap::from([
|
||||||
|
(first_group.clone(), mode),
|
||||||
|
(second_group.clone(), second_mode),
|
||||||
|
])),
|
||||||
);
|
);
|
||||||
|
let scope = Arc::new(FrozenAccountScope::new(
|
||||||
|
Arc::clone(&directory),
|
||||||
|
ClientRoutingScope::restricted(
|
||||||
|
vec![
|
||||||
|
RoutingGroupSnapshot::new(first_group.clone(), "A".into()),
|
||||||
|
RoutingGroupSnapshot::new(second_group.clone(), "B".into()),
|
||||||
|
],
|
||||||
|
BTreeSet::from([first_group, second_group]),
|
||||||
|
BTreeSet::from([kind.clone()]),
|
||||||
|
)
|
||||||
|
.unwrap(),
|
||||||
|
));
|
||||||
|
let route_plan = RuntimeSnapshot::new(
|
||||||
|
ConfigRevision::new(1).unwrap(),
|
||||||
|
gateway_core::settings::SettingsValues::new(2, "smart", Default::default(), None, None)
|
||||||
|
.with_request_location(location.clone(), true),
|
||||||
|
vec![kind.clone()],
|
||||||
|
vec![ProviderModel::new(
|
||||||
|
kind,
|
||||||
|
UpstreamModelId::new("gpt-5").unwrap(),
|
||||||
|
ModelCapabilities::new(BTreeSet::from([operation.kind()]), Some(32_000)),
|
||||||
|
)],
|
||||||
|
Vec::new(),
|
||||||
|
)
|
||||||
|
.unwrap()
|
||||||
|
.with_account_directory(directory)
|
||||||
|
.plan(
|
||||||
|
&PublicModelId::new("gpt-5").unwrap(),
|
||||||
|
&operation,
|
||||||
|
Arc::clone(&scope),
|
||||||
|
&RoutingContext::default(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
let (coordinator, _, provider) = coordinator(vec![
|
let (coordinator, _, provider) = coordinator(vec![
|
||||||
Script::Stream {
|
Script::Stream {
|
||||||
account_id: "acct_first",
|
account_id: "acct_first",
|
||||||
@@ -6414,12 +6502,17 @@ fn global_location_and_group_fast_policy_reach_every_account_retry() {
|
|||||||
block_on(session.commit_downstream(Some(200))).unwrap();
|
block_on(session.commit_downstream(Some(200))).unwrap();
|
||||||
let contexts = provider.contexts.lock().unwrap();
|
let contexts = provider.contexts.lock().unwrap();
|
||||||
assert_eq!(contexts.len(), 2);
|
assert_eq!(contexts.len(), 2);
|
||||||
assert!(
|
for (context, account, expected) in [
|
||||||
contexts
|
(&contexts[0], "acct_first", mode),
|
||||||
.iter()
|
(&contexts[1], "acct_second", second_mode),
|
||||||
.all(|context| context.request_location() == Some(&location)
|
] {
|
||||||
&& context.fast_mode() == mode)
|
assert_eq!(context.request_location(), Some(&location));
|
||||||
);
|
assert!(Arc::ptr_eq(context.account_scope().unwrap(), &scope));
|
||||||
|
assert_eq!(
|
||||||
|
context.fast_mode_for_account(&ProviderAccountId::new(account).unwrap(), "gpt-5"),
|
||||||
|
expected,
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2470,6 +2470,7 @@ impl Provider for PolicySelectingProvider {
|
|||||||
account,
|
account,
|
||||||
signals: AccountRuntimeSignals {
|
signals: AccountRuntimeSignals {
|
||||||
in_flight: 0,
|
in_flight: 0,
|
||||||
|
recent_requests: 0,
|
||||||
last_started_at: None,
|
last_started_at: None,
|
||||||
quota_reset_at: None,
|
quota_reset_at: None,
|
||||||
quota_reset_windows: None,
|
quota_reset_windows: None,
|
||||||
@@ -3067,8 +3068,14 @@ impl Provider for ChargedProvider {
|
|||||||
request: ProviderRequest,
|
request: ProviderRequest,
|
||||||
context: AttemptContext,
|
context: AttemptContext,
|
||||||
) -> Result<ProviderStream, ProviderError> {
|
) -> Result<ProviderStream, ProviderError> {
|
||||||
self.policies.lock().unwrap().push(context.fast_mode());
|
|
||||||
let candidate = request.candidate();
|
let candidate = request.candidate();
|
||||||
|
self.policies
|
||||||
|
.lock()
|
||||||
|
.unwrap()
|
||||||
|
.push(context.fast_mode_for_account(
|
||||||
|
&ProviderAccountId::new("acct_start").unwrap(),
|
||||||
|
candidate.upstream_model().unwrap().as_str(),
|
||||||
|
));
|
||||||
let metadata = ProviderCallMetadata::new(
|
let metadata = ProviderCallMetadata::new(
|
||||||
candidate.provider().clone(),
|
candidate.provider().clone(),
|
||||||
candidate.upstream_model().unwrap().clone(),
|
candidate.upstream_model().unwrap().clone(),
|
||||||
@@ -3509,8 +3516,10 @@ fn account_probe_should_not_write_to_the_persistent_execution_store() {
|
|||||||
#[test]
|
#[test]
|
||||||
fn probe_failures_should_be_observable_without_a_model_request_row() {
|
fn probe_failures_should_be_observable_without_a_model_request_row() {
|
||||||
let store = Arc::new(TrackingExecutionStore::default());
|
let store = Arc::new(TrackingExecutionStore::default());
|
||||||
let providers = ProviderRegistry::new([Arc::new(FailingProvider) as Arc<dyn Provider>])
|
let providers = ProviderRegistry::new([
|
||||||
.expect("provider registry");
|
Arc::new(FailingProvider { include_body: true }) as Arc<dyn Provider>
|
||||||
|
])
|
||||||
|
.expect("provider registry");
|
||||||
let service = DefaultExecutionService::new(
|
let service = DefaultExecutionService::new(
|
||||||
RuntimeSnapshotHandle::new(probe_snapshot()),
|
RuntimeSnapshotHandle::new(probe_snapshot()),
|
||||||
store.clone(),
|
store.clone(),
|
||||||
@@ -3547,7 +3556,9 @@ fn probe_failures_should_be_observable_without_a_model_request_row() {
|
|||||||
);
|
);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
upstream.body(),
|
upstream.body(),
|
||||||
&Bytes::from_static(br#"{"error":{"message":"source upstream failure"}}"#),
|
Some(&Bytes::from_static(
|
||||||
|
br#"{"error":{"message":"source upstream failure"}}"#
|
||||||
|
)),
|
||||||
);
|
);
|
||||||
assert!(!format!("{error:?}").contains("source upstream failure"));
|
assert!(!format!("{error:?}").contains("source upstream failure"));
|
||||||
assert!(!store.touched.load(Ordering::SeqCst));
|
assert!(!store.touched.load(Ordering::SeqCst));
|
||||||
@@ -3687,8 +3698,10 @@ fn probe_observation_store_failure_preserves_the_provider_error() {
|
|||||||
fail_probe_observation: AtomicBool::new(true),
|
fail_probe_observation: AtomicBool::new(true),
|
||||||
..TrackingExecutionStore::default()
|
..TrackingExecutionStore::default()
|
||||||
});
|
});
|
||||||
let providers = ProviderRegistry::new([Arc::new(FailingProvider) as Arc<dyn Provider>])
|
let providers = ProviderRegistry::new([Arc::new(FailingProvider {
|
||||||
.expect("provider registry");
|
include_body: false,
|
||||||
|
}) as Arc<dyn Provider>])
|
||||||
|
.expect("provider registry");
|
||||||
let service = DefaultExecutionService::new(
|
let service = DefaultExecutionService::new(
|
||||||
RuntimeSnapshotHandle::new(probe_snapshot()),
|
RuntimeSnapshotHandle::new(probe_snapshot()),
|
||||||
store.clone(),
|
store.clone(),
|
||||||
@@ -3715,9 +3728,15 @@ fn probe_observation_store_failure_preserves_the_provider_error() {
|
|||||||
assert_eq!(error.kind(), GatewayErrorKind::UpstreamUnavailable);
|
assert_eq!(error.kind(), GatewayErrorKind::UpstreamUnavailable);
|
||||||
assert!(!store.touched.load(Ordering::SeqCst));
|
assert!(!store.touched.load(Ordering::SeqCst));
|
||||||
assert!(store.probe_failures().is_empty());
|
assert!(store.probe_failures().is_empty());
|
||||||
|
let upstream = error.upstream_response().unwrap();
|
||||||
|
assert_eq!(upstream.status(), 403);
|
||||||
|
assert!(upstream.body().is_none());
|
||||||
|
assert!(upstream.content_type().is_none());
|
||||||
}
|
}
|
||||||
|
|
||||||
struct FailingProvider;
|
struct FailingProvider {
|
||||||
|
include_body: bool,
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Clone, Copy)]
|
#[derive(Clone, Copy)]
|
||||||
enum CatalogProvider {
|
enum CatalogProvider {
|
||||||
@@ -4055,6 +4074,13 @@ impl Provider for FailingProvider {
|
|||||||
_request: ProviderRequest,
|
_request: ProviderRequest,
|
||||||
_context: AttemptContext,
|
_context: AttemptContext,
|
||||||
) -> Result<ProviderStream, ProviderError> {
|
) -> Result<ProviderStream, ProviderError> {
|
||||||
|
if !self.include_body {
|
||||||
|
return Err(ProviderError::new(
|
||||||
|
ProviderErrorKind::PermissionDenied,
|
||||||
|
UpstreamSendState::Sent,
|
||||||
|
)
|
||||||
|
.with_status(403));
|
||||||
|
}
|
||||||
Err(
|
Err(
|
||||||
ProviderError::new(ProviderErrorKind::Transport, UpstreamSendState::NotSent)
|
ProviderError::new(ProviderErrorKind::Transport, UpstreamSendState::NotSent)
|
||||||
.with_client_visible_upstream_response(ClientVisibleUpstreamResponse::new(
|
.with_client_visible_upstream_response(ClientVisibleUpstreamResponse::new(
|
||||||
@@ -4772,7 +4798,7 @@ fn start_snapshot_with_image_policy(
|
|||||||
account_scope(&provider, "acct_start")
|
account_scope(&provider, "acct_start")
|
||||||
.as_ref()
|
.as_ref()
|
||||||
.clone()
|
.clone()
|
||||||
.with_fast_mode(fast_mode)
|
.with_fast_mode_override(Some(fast_mode))
|
||||||
.with_image_generation(allow_image_generation),
|
.with_image_generation(allow_image_generation),
|
||||||
),
|
),
|
||||||
enabled,
|
enabled,
|
||||||
@@ -5506,7 +5532,7 @@ fn entry_settings_freeze_authentication_and_rebase_only_explicit_overrides() {
|
|||||||
.execution_values()
|
.execution_values()
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.fast_mode,
|
.fast_mode,
|
||||||
FastMode::Disabled
|
Some(FastMode::Disabled)
|
||||||
);
|
);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
prepared
|
prepared
|
||||||
@@ -5629,7 +5655,7 @@ fn child_settings_recompute_key_scope_without_inheriting_parent_defaults() {
|
|||||||
account_scope(&provider, "acct_start")
|
account_scope(&provider, "acct_start")
|
||||||
.as_ref()
|
.as_ref()
|
||||||
.clone()
|
.clone()
|
||||||
.with_fast_mode(FastMode::Disabled)
|
.with_fast_mode_override(Some(FastMode::Disabled))
|
||||||
.with_request_profiles(profiles(name)),
|
.with_request_profiles(profiles(name)),
|
||||||
),
|
),
|
||||||
true,
|
true,
|
||||||
@@ -5668,7 +5694,7 @@ fn child_settings_recompute_key_scope_without_inheriting_parent_defaults() {
|
|||||||
let configuration = RequestSettings::new(snapshots.acquire().unwrap())
|
let configuration = RequestSettings::new(snapshots.acquire().unwrap())
|
||||||
.with_execution(parent.client().policy(), previous.timeout_ms);
|
.with_execution(parent.client().policy(), previous.timeout_ms);
|
||||||
let mut values = previous.clone();
|
let mut values = previous.clone();
|
||||||
values.fast_mode = FastMode::Default;
|
values.fast_mode = Some(FastMode::Default);
|
||||||
values.client_limits = RateLimits::unlimited();
|
values.client_limits = RateLimits::unlimited();
|
||||||
values.timeout_ms = Some(90_000);
|
values.timeout_ms = Some(90_000);
|
||||||
let mut runtime = serde_json::to_value(&values.runtime).unwrap();
|
let mut runtime = serde_json::to_value(&values.runtime).unwrap();
|
||||||
@@ -5702,7 +5728,7 @@ fn child_settings_recompute_key_scope_without_inheriting_parent_defaults() {
|
|||||||
Some(actual.clone())
|
Some(actual.clone())
|
||||||
);
|
);
|
||||||
assert_eq!(actual.client_limits.max_concurrency, expected_limit);
|
assert_eq!(actual.client_limits.max_concurrency, expected_limit);
|
||||||
assert_eq!(actual.fast_mode, expected_fast);
|
assert_eq!(actual.fast_mode, Some(expected_fast));
|
||||||
assert_eq!(actual.timeout_ms, expected_timeout);
|
assert_eq!(actual.timeout_ms, expected_timeout);
|
||||||
let facts = serde_json::to_value(actual.runtime).unwrap();
|
let facts = serde_json::to_value(actual.runtime).unwrap();
|
||||||
assert_eq!(facts["request_profiles"]["openai"]["identity"], profile);
|
assert_eq!(facts["request_profiles"]["openai"]["identity"], profile);
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ mod extensions;
|
|||||||
mod middleware;
|
mod middleware;
|
||||||
mod policy;
|
mod policy;
|
||||||
mod provider;
|
mod provider;
|
||||||
|
mod recent_request_persistence;
|
||||||
mod response_control;
|
mod response_control;
|
||||||
|
|
||||||
use gateway_core::engine::AttemptTrigger;
|
use gateway_core::engine::AttemptTrigger;
|
||||||
|
|||||||
@@ -75,6 +75,7 @@ fn candidate(id: &str) -> AccountCandidate {
|
|||||||
.with_scheduling(None, AccountWeight::new(100).unwrap()),
|
.with_scheduling(None, AccountWeight::new(100).unwrap()),
|
||||||
signals: AccountRuntimeSignals {
|
signals: AccountRuntimeSignals {
|
||||||
in_flight: 0,
|
in_flight: 0,
|
||||||
|
recent_requests: 0,
|
||||||
last_started_at: None,
|
last_started_at: None,
|
||||||
quota_reset_at: None,
|
quota_reset_at: None,
|
||||||
quota_reset_windows: None,
|
quota_reset_windows: None,
|
||||||
|
|||||||
@@ -242,6 +242,10 @@ fn provider_stream_should_report_common_account_success_and_first_output() {
|
|||||||
let (failure_rate, first_output_ms) = feedback.scheduling_signals(&provider, &account);
|
let (failure_rate, first_output_ms) = feedback.scheduling_signals(&provider, &account);
|
||||||
assert_eq!(failure_rate, Some(0));
|
assert_eq!(failure_rate, Some(0));
|
||||||
assert!(first_output_ms.is_some_and(|value| value >= 2));
|
assert!(first_output_ms.is_some_and(|value| value >= 2));
|
||||||
|
assert_eq!(
|
||||||
|
feedback.recent_requests(&provider, &account, Some("gpt-5")),
|
||||||
|
1
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -367,16 +371,25 @@ fn provider_stream_should_report_confirmed_sent_failure_but_ignore_unconfirmed_f
|
|||||||
let metadata = ProviderCallMetadata::new(
|
let metadata = ProviderCallMetadata::new(
|
||||||
provider.clone(),
|
provider.clone(),
|
||||||
UpstreamModelId::new("grok-4.5").expect("valid model"),
|
UpstreamModelId::new("grok-4.5").expect("valid model"),
|
||||||
account,
|
account.clone(),
|
||||||
UpstreamTransport::new("http_sse").expect("valid transport"),
|
UpstreamTransport::new("http_sse").expect("valid transport"),
|
||||||
);
|
);
|
||||||
let events: EventStream = Box::pin(stream::iter([Err(ProviderError::new(
|
let events: EventStream = Box::pin(stream::iter([
|
||||||
ProviderErrorKind::Transport,
|
Ok(gateway_core::event::ProviderEvent::observation(
|
||||||
send_state,
|
gateway_core::event::ProviderResponseObservation::new(
|
||||||
))]));
|
UpstreamTransport::new("http_sse").unwrap(),
|
||||||
|
),
|
||||||
|
)),
|
||||||
|
Err(ProviderError::new(ProviderErrorKind::Transport, send_state)),
|
||||||
|
]));
|
||||||
let mut provider_stream =
|
let mut provider_stream =
|
||||||
ProviderStream::new(metadata, events, ()).with_account_feedback(Arc::clone(&feedback));
|
ProviderStream::new(metadata, events, ()).with_account_feedback(Arc::clone(&feedback));
|
||||||
futures::executor::block_on(async {
|
futures::executor::block_on(async {
|
||||||
|
provider_stream.next().await.unwrap().unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
feedback.recent_requests(&provider, &account, Some("grok-4.5")),
|
||||||
|
0
|
||||||
|
);
|
||||||
assert!(
|
assert!(
|
||||||
provider_stream
|
provider_stream
|
||||||
.next()
|
.next()
|
||||||
@@ -386,6 +399,17 @@ fn provider_stream_should_report_confirmed_sent_failure_but_ignore_unconfirmed_f
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
for (account, count) in [
|
||||||
|
(&sent_account, 1),
|
||||||
|
(&ambiguous_account, 0),
|
||||||
|
(¬_sent_account, 0),
|
||||||
|
] {
|
||||||
|
assert_eq!(
|
||||||
|
feedback.recent_requests(&provider, account, Some("grok-4.5")),
|
||||||
|
count
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
feedback.scheduling_signals(&provider, &sent_account).0,
|
feedback.scheduling_signals(&provider, &sent_account).0,
|
||||||
Some(2_000)
|
Some(2_000)
|
||||||
@@ -434,6 +458,10 @@ fn provider_stream_should_ignore_repeated_failures_rejected_by_the_filter() {
|
|||||||
feedback.scheduling_signals(&provider, &account),
|
feedback.scheduling_signals(&provider, &account),
|
||||||
(None, None)
|
(None, None)
|
||||||
);
|
);
|
||||||
|
assert_eq!(
|
||||||
|
feedback.recent_requests(&provider, &account, Some("gpt-5")),
|
||||||
|
100
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|||||||
@@ -0,0 +1,162 @@
|
|||||||
|
//! 验证近期请求快照异步合并、慢存储隔离、关闭刷写及失败预算
|
||||||
|
|
||||||
|
use std::sync::{
|
||||||
|
Arc, Mutex,
|
||||||
|
atomic::{AtomicUsize, Ordering},
|
||||||
|
};
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
|
use futures::{channel::oneshot, future::BoxFuture};
|
||||||
|
use gateway_core::{
|
||||||
|
account::{AccountFeedbackStats, ProviderAccountId, RecentRequestSnapshot, RecentRequestStore},
|
||||||
|
engine::RecentRequestPersistence,
|
||||||
|
error::{StoreError, StoreErrorKind},
|
||||||
|
identity::ProviderKind,
|
||||||
|
lifecycle::CancellationToken,
|
||||||
|
task::{DaemonTask, WorkerDaemonContext},
|
||||||
|
};
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
|
struct MemoryStore {
|
||||||
|
snapshot: Mutex<Option<RecentRequestSnapshot>>,
|
||||||
|
saves: AtomicUsize,
|
||||||
|
loads: AtomicUsize,
|
||||||
|
started: Mutex<Option<oneshot::Sender<()>>>,
|
||||||
|
gate: Mutex<Option<oneshot::Receiver<()>>>,
|
||||||
|
fail: bool,
|
||||||
|
stalled: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RecentRequestStore for MemoryStore {
|
||||||
|
fn load(&self) -> BoxFuture<'_, Result<Option<RecentRequestSnapshot>, StoreError>> {
|
||||||
|
Box::pin(async move {
|
||||||
|
self.loads.fetch_add(1, Ordering::SeqCst);
|
||||||
|
if self.stalled {
|
||||||
|
return std::future::pending().await;
|
||||||
|
}
|
||||||
|
Ok(self.snapshot.lock().unwrap().clone())
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn save<'a>(
|
||||||
|
&'a self,
|
||||||
|
snapshot: &'a RecentRequestSnapshot,
|
||||||
|
ttl: Duration,
|
||||||
|
) -> BoxFuture<'a, Result<(), StoreError>> {
|
||||||
|
Box::pin(async move {
|
||||||
|
assert_eq!(ttl, Duration::from_secs(120));
|
||||||
|
self.saves.fetch_add(1, Ordering::SeqCst);
|
||||||
|
if let Some(started) = self.started.lock().unwrap().take() {
|
||||||
|
started.send(()).unwrap();
|
||||||
|
}
|
||||||
|
let gate = self.gate.lock().unwrap().take();
|
||||||
|
if let Some(gate) = gate {
|
||||||
|
gate.await.unwrap();
|
||||||
|
}
|
||||||
|
if self.stalled {
|
||||||
|
return std::future::pending().await;
|
||||||
|
}
|
||||||
|
if self.fail {
|
||||||
|
return Err(StoreError::new(StoreErrorKind::Unavailable));
|
||||||
|
}
|
||||||
|
*self.snapshot.lock().unwrap() = Some(snapshot.clone());
|
||||||
|
Ok(())
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn periodic_snapshot_keeps_traffic_live_during_slow_save_and_flushes_latest_on_shutdown() {
|
||||||
|
futures::executor::block_on(async {
|
||||||
|
let stats = Arc::new(AccountFeedbackStats::default());
|
||||||
|
let provider = ProviderKind::new("openai").unwrap();
|
||||||
|
let account = ProviderAccountId::new("acct_async").unwrap();
|
||||||
|
let (entered, entering) = oneshot::channel();
|
||||||
|
let (release, released) = oneshot::channel();
|
||||||
|
let store = Arc::new(MemoryStore {
|
||||||
|
started: Mutex::new(Some(entered)),
|
||||||
|
gate: Mutex::new(Some(released)),
|
||||||
|
..Default::default()
|
||||||
|
});
|
||||||
|
let persistence = RecentRequestPersistence::new(stats.clone(), store.clone());
|
||||||
|
for _ in 0..100 {
|
||||||
|
let now = Instant::now();
|
||||||
|
stats.record_request_at(&provider, &account, "model", now, now);
|
||||||
|
}
|
||||||
|
assert_eq!(store.saves.load(Ordering::SeqCst), 0);
|
||||||
|
let cancellation = CancellationToken::new();
|
||||||
|
let context = WorkerDaemonContext::new(cancellation.clone());
|
||||||
|
let driver = async {
|
||||||
|
entering.await.unwrap();
|
||||||
|
let now = Instant::now();
|
||||||
|
stats.record_request_at(&provider, &account, "model", now, now);
|
||||||
|
assert_eq!(
|
||||||
|
stats.recent_requests(&provider, &account, Some("model")),
|
||||||
|
101
|
||||||
|
);
|
||||||
|
assert_eq!(store.loads.load(Ordering::SeqCst), 0);
|
||||||
|
cancellation.cancel();
|
||||||
|
release.send(()).unwrap();
|
||||||
|
};
|
||||||
|
let (result, ()) = futures::join!(persistence.run(context), driver);
|
||||||
|
result.unwrap();
|
||||||
|
assert_eq!(store.saves.load(Ordering::SeqCst), 2);
|
||||||
|
let restarted = Arc::new(AccountFeedbackStats::default());
|
||||||
|
RecentRequestPersistence::new(restarted.clone(), store)
|
||||||
|
.restore()
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
restarted.recent_requests(&provider, &account, Some("model")),
|
||||||
|
101
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn failed_save_preserves_memory_and_reports_failure_to_supervision() {
|
||||||
|
futures::executor::block_on(async {
|
||||||
|
let stats = Arc::new(AccountFeedbackStats::default());
|
||||||
|
let provider = ProviderKind::new("openai").unwrap();
|
||||||
|
let account = ProviderAccountId::new("acct_failed").unwrap();
|
||||||
|
let now = Instant::now();
|
||||||
|
stats.record_request_at(&provider, &account, "model", now, now);
|
||||||
|
let store = Arc::new(MemoryStore {
|
||||||
|
fail: true,
|
||||||
|
..Default::default()
|
||||||
|
});
|
||||||
|
let persistence = RecentRequestPersistence::new(stats.clone(), store.clone());
|
||||||
|
let stopping = CancellationToken::new();
|
||||||
|
stopping.cancel();
|
||||||
|
assert!(
|
||||||
|
persistence
|
||||||
|
.run(WorkerDaemonContext::new(stopping))
|
||||||
|
.await
|
||||||
|
.is_err()
|
||||||
|
);
|
||||||
|
assert_eq!(store.saves.load(Ordering::SeqCst), 1);
|
||||||
|
assert_eq!(stats.recent_requests(&provider, &account, Some("model")), 1);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn stalled_restore_and_shutdown_have_bounded_waits() {
|
||||||
|
futures::executor::block_on(async {
|
||||||
|
let stats = Arc::new(AccountFeedbackStats::default());
|
||||||
|
let store = Arc::new(MemoryStore {
|
||||||
|
stalled: true,
|
||||||
|
..Default::default()
|
||||||
|
});
|
||||||
|
let persistence = RecentRequestPersistence::new(stats, store);
|
||||||
|
let stopping = CancellationToken::new();
|
||||||
|
stopping.cancel();
|
||||||
|
let began = Instant::now();
|
||||||
|
let (restore, save) = futures::join!(
|
||||||
|
persistence.restore(),
|
||||||
|
persistence.run(WorkerDaemonContext::new(stopping)),
|
||||||
|
);
|
||||||
|
assert!(restore.is_err());
|
||||||
|
assert!(save.is_err());
|
||||||
|
assert!(began.elapsed() < Duration::from_secs(4));
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -186,7 +186,10 @@ fn gateway_error_should_keep_client_visible_upstream_fields_out_of_safe_diagnost
|
|||||||
));
|
));
|
||||||
let gateway = GatewayError::from_provider(&error);
|
let gateway = GatewayError::from_provider(&error);
|
||||||
|
|
||||||
assert_eq!(gateway.safe_message(), "Account quota is exhausted.");
|
assert_eq!(
|
||||||
|
gateway.safe_message(),
|
||||||
|
"Upstream account quota is exhausted."
|
||||||
|
);
|
||||||
assert_eq!(gateway.client_message(), message);
|
assert_eq!(gateway.client_message(), message);
|
||||||
assert_eq!(gateway.client_error_code(), Some("quota_exhausted"));
|
assert_eq!(gateway.client_error_code(), Some("quota_exhausted"));
|
||||||
assert_eq!(gateway.client_error_type(), Some("rate_limit_error"));
|
assert_eq!(gateway.client_error_type(), Some("rate_limit_error"));
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ fn scheduling_state_preserves_provider_neutral_signals() {
|
|||||||
account.clone(),
|
account.clone(),
|
||||||
AccountRuntimeSignals {
|
AccountRuntimeSignals {
|
||||||
in_flight: 2,
|
in_flight: 2,
|
||||||
|
recent_requests: 0,
|
||||||
last_started_at: None,
|
last_started_at: None,
|
||||||
quota_reset_at: None,
|
quota_reset_at: None,
|
||||||
quota_reset_windows: None,
|
quota_reset_windows: None,
|
||||||
|
|||||||
@@ -37,6 +37,7 @@ fn candidate(id: &str, busy: bool) -> AccountCandidate {
|
|||||||
inherited_concurrency: None,
|
inherited_concurrency: None,
|
||||||
signals: AccountRuntimeSignals {
|
signals: AccountRuntimeSignals {
|
||||||
in_flight: u32::from(busy),
|
in_flight: u32::from(busy),
|
||||||
|
recent_requests: 0,
|
||||||
last_started_at: None,
|
last_started_at: None,
|
||||||
quota_reset_at: None,
|
quota_reset_at: None,
|
||||||
quota_reset_windows: None,
|
quota_reset_windows: None,
|
||||||
|
|||||||
@@ -53,7 +53,7 @@ fn policy_with_profiles(
|
|||||||
Arc::new(
|
Arc::new(
|
||||||
FrozenAccountScope::new(Arc::default(), ClientRoutingScope::all_accounts())
|
FrozenAccountScope::new(Arc::default(), ClientRoutingScope::all_accounts())
|
||||||
.with_request_profiles(overrides)
|
.with_request_profiles(overrides)
|
||||||
.with_fast_mode(FastMode::Disabled),
|
.with_fast_mode_override(Some(FastMode::Disabled)),
|
||||||
),
|
),
|
||||||
true,
|
true,
|
||||||
RateLimits {
|
RateLimits {
|
||||||
@@ -153,7 +153,7 @@ fn scope_changes_recompute_defaults_and_inherit_only_explicit_overrides() {
|
|||||||
values.runtime = values
|
values.runtime = values
|
||||||
.runtime
|
.runtime
|
||||||
.with_model_mappings(BTreeMap::from([("alias".into(), "model".into())]));
|
.with_model_mappings(BTreeMap::from([("alias".into(), "model".into())]));
|
||||||
values.fast_mode = FastMode::Default;
|
values.fast_mode = Some(FastMode::Default);
|
||||||
values.client_limits = RateLimits::unlimited();
|
values.client_limits = RateLimits::unlimited();
|
||||||
values.timeout_ms = Some(90_000);
|
values.timeout_ms = Some(90_000);
|
||||||
let changed = original.replace_execution(&values, "plugin").unwrap();
|
let changed = original.replace_execution(&values, "plugin").unwrap();
|
||||||
@@ -168,14 +168,14 @@ fn scope_changes_recompute_defaults_and_inherit_only_explicit_overrides() {
|
|||||||
parent_values.runtime.request_profiles(),
|
parent_values.runtime.request_profiles(),
|
||||||
&profiles(&[("openai", "parent"), ("xai", "second")])
|
&profiles(&[("openai", "parent"), ("xai", "second")])
|
||||||
);
|
);
|
||||||
assert_eq!(parent_values.fast_mode, FastMode::Default);
|
assert_eq!(parent_values.fast_mode, Some(FastMode::Default));
|
||||||
let child_settings = rebased.with_execution(&child, Some(60_000));
|
let child_settings = rebased.with_execution(&child, Some(60_000));
|
||||||
let child_values = child_settings.execution_values().unwrap();
|
let child_values = child_settings.execution_values().unwrap();
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
child_values.runtime.request_profiles(),
|
child_values.runtime.request_profiles(),
|
||||||
&profiles(&[("openai", "child"), ("xai", "second")])
|
&profiles(&[("openai", "child"), ("xai", "second")])
|
||||||
);
|
);
|
||||||
assert_eq!(child_values.fast_mode, FastMode::Disabled);
|
assert_eq!(child_values.fast_mode, Some(FastMode::Disabled));
|
||||||
assert_eq!(child_values.client_limits, child.limits());
|
assert_eq!(child_values.client_limits, child.limits());
|
||||||
assert_eq!(child_values.timeout_ms, Some(60_000));
|
assert_eq!(child_values.timeout_ms, Some(60_000));
|
||||||
assert_eq!(child_settings.snapshot().mapped_model("alias"), "model");
|
assert_eq!(child_settings.snapshot().mapped_model("alias"), "model");
|
||||||
@@ -186,6 +186,81 @@ fn scope_changes_recompute_defaults_and_inherit_only_explicit_overrides() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn group_fast_policy_survives_settings_resolution_until_explicitly_overridden() {
|
||||||
|
use gateway_core::{
|
||||||
|
account::ProviderAccountId,
|
||||||
|
routing::{AccountGroupId, RoutingGroupSnapshot, RuntimeAccount, RuntimeAccountDirectory},
|
||||||
|
};
|
||||||
|
let group = AccountGroupId::new(format!("grp_{:032x}", 1)).unwrap();
|
||||||
|
let account = ProviderAccountId::new("acct_group_fast").unwrap();
|
||||||
|
let provider = ProviderKind::new("openai").unwrap();
|
||||||
|
let scope = Arc::new(FrozenAccountScope::new(
|
||||||
|
Arc::new(
|
||||||
|
RuntimeAccountDirectory::new(BTreeMap::from([(
|
||||||
|
account.clone(),
|
||||||
|
RuntimeAccount::new(provider.clone(), [group.clone()].into()),
|
||||||
|
)]))
|
||||||
|
.with_group_fast_modes([(group.clone(), FastMode::Disabled)].into()),
|
||||||
|
),
|
||||||
|
ClientRoutingScope::restricted(
|
||||||
|
vec![RoutingGroupSnapshot::new(group.clone(), "Standard".into())],
|
||||||
|
[group].into(),
|
||||||
|
[provider].into(),
|
||||||
|
)
|
||||||
|
.unwrap(),
|
||||||
|
));
|
||||||
|
let key = |name: &str| {
|
||||||
|
ClientPolicy::new(
|
||||||
|
ClientApiKeyId::new(name).unwrap(),
|
||||||
|
PlaintextClientApiKey::new(format!("fixture-{name}")).unwrap(),
|
||||||
|
scope.clone(),
|
||||||
|
true,
|
||||||
|
RateLimits::unlimited(),
|
||||||
|
)
|
||||||
|
};
|
||||||
|
let parent = key("parent");
|
||||||
|
let settings = RequestSettings::new(snapshot(1, "host")).with_execution(&parent, None);
|
||||||
|
assert_eq!(settings.execution_values().unwrap().fast_mode, None);
|
||||||
|
let resolved = |settings: &RequestSettings, key| {
|
||||||
|
settings
|
||||||
|
.apply_policy(key)
|
||||||
|
.account_scope()
|
||||||
|
.fast_mode_for_account(&account, "model")
|
||||||
|
};
|
||||||
|
assert_eq!(resolved(&settings, parent.clone()), FastMode::Disabled);
|
||||||
|
let unchanged = settings
|
||||||
|
.replace_execution(&settings.execution_values().unwrap(), "pass-through")
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(resolved(&unchanged, parent.clone()), FastMode::Disabled);
|
||||||
|
|
||||||
|
let mut values = settings.execution_values().unwrap();
|
||||||
|
values.fast_mode = Some(FastMode::Default);
|
||||||
|
let direct_default = settings
|
||||||
|
.replace_execution(&values, "follow-client")
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(resolved(&direct_default, parent.clone()), FastMode::Default);
|
||||||
|
values.fast_mode = Some(FastMode::Enabled);
|
||||||
|
let enabled = settings.replace_execution(&values, "force-fast").unwrap();
|
||||||
|
assert_eq!(resolved(&enabled, parent.clone()), FastMode::Enabled);
|
||||||
|
values.fast_mode = Some(FastMode::Default);
|
||||||
|
let default = enabled.replace_execution(&values, "follow-client").unwrap();
|
||||||
|
assert_eq!(resolved(&default, parent.clone()), FastMode::Default);
|
||||||
|
values.fast_mode = None;
|
||||||
|
let cleared = default.replace_execution(&values, "group-policy").unwrap();
|
||||||
|
assert_eq!(resolved(&cleared, parent.clone()), FastMode::Disabled);
|
||||||
|
assert_eq!(
|
||||||
|
cleared.inspect()["execution"]["fast_mode"]["value"],
|
||||||
|
serde_json::Value::Null
|
||||||
|
);
|
||||||
|
let child = key("child");
|
||||||
|
assert_eq!(
|
||||||
|
resolved(&default.with_execution(&child, None), child),
|
||||||
|
FastMode::Disabled
|
||||||
|
);
|
||||||
|
assert_eq!(resolved(&settings, parent), FastMode::Disabled);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn explicitly_selecting_the_host_profiles_overrides_keys_after_rebase() {
|
fn explicitly_selecting_the_host_profiles_overrides_keys_after_rebase() {
|
||||||
let host = snapshot(1, "first");
|
let host = snapshot(1, "first");
|
||||||
|
|||||||
@@ -2727,7 +2727,7 @@ fn decompression_setting_should_validate_and_remain_frozen_across_publication()
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn fast_mode_merges_only_bound_groups_without_changing_account_scope() {
|
fn fast_mode_merges_only_enabled_bound_groups_of_the_selected_account() {
|
||||||
use gateway_core::account::ProviderAccountId;
|
use gateway_core::account::ProviderAccountId;
|
||||||
use gateway_core::routing::AccountGroupId;
|
use gateway_core::routing::AccountGroupId;
|
||||||
for (mode, other_mode, expected) in [
|
for (mode, other_mode, expected) in [
|
||||||
@@ -2758,6 +2758,8 @@ fn fast_mode_merges_only_bound_groups_without_changing_account_scope() {
|
|||||||
let open_group_id =
|
let open_group_id =
|
||||||
AccountGroupId::new("grp_00000000000000000000000000000002").unwrap();
|
AccountGroupId::new("grp_00000000000000000000000000000002").unwrap();
|
||||||
let account_id = ProviderAccountId::new("acct_fast_policy").unwrap();
|
let account_id = ProviderAccountId::new("acct_fast_policy").unwrap();
|
||||||
|
let first_account = ProviderAccountId::new("acct_first_group").unwrap();
|
||||||
|
let second_account = ProviderAccountId::new("acct_second_group").unwrap();
|
||||||
let facts = SnapshotFacts::new(
|
let facts = SnapshotFacts::new(
|
||||||
revision(1),
|
revision(1),
|
||||||
revision(1),
|
revision(1),
|
||||||
@@ -2786,11 +2788,19 @@ fn fast_mode_merges_only_bound_groups_without_changing_account_scope() {
|
|||||||
)
|
)
|
||||||
.with_fast_mode(other_mode),
|
.with_fast_mode(other_mode),
|
||||||
],
|
],
|
||||||
vec![SnapshotProviderAccountFacts::new(
|
[&account_id, &first_account, &second_account]
|
||||||
account_id.clone(),
|
.into_iter()
|
||||||
"alpha",
|
.map(|id| SnapshotProviderAccountFacts::new(id.clone(), "alpha"))
|
||||||
)],
|
.collect(),
|
||||||
vec![
|
vec![
|
||||||
|
SnapshotAccountGroupMemberFacts::new(
|
||||||
|
group_id.clone(),
|
||||||
|
first_account.clone(),
|
||||||
|
),
|
||||||
|
SnapshotAccountGroupMemberFacts::new(
|
||||||
|
open_group_id.clone(),
|
||||||
|
second_account.clone(),
|
||||||
|
),
|
||||||
SnapshotAccountGroupMemberFacts::new(group_id, account_id.clone()),
|
SnapshotAccountGroupMemberFacts::new(group_id, account_id.clone()),
|
||||||
SnapshotAccountGroupMemberFacts::new(open_group_id, account_id.clone()),
|
SnapshotAccountGroupMemberFacts::new(open_group_id, account_id.clone()),
|
||||||
],
|
],
|
||||||
@@ -2818,16 +2828,99 @@ fn fast_mode_merges_only_bound_groups_without_changing_account_scope() {
|
|||||||
&Default::default(),
|
&Default::default(),
|
||||||
)
|
)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
for (account, effective) in [
|
||||||
|
(
|
||||||
|
&account_id,
|
||||||
|
if group_enabled { expected } else { other_mode },
|
||||||
|
),
|
||||||
|
(
|
||||||
|
&first_account,
|
||||||
|
if group_enabled {
|
||||||
|
mode
|
||||||
|
} else {
|
||||||
|
FastMode::Default
|
||||||
|
},
|
||||||
|
),
|
||||||
|
(&second_account, other_mode),
|
||||||
|
] {
|
||||||
|
assert_eq!(
|
||||||
|
plan.account_scope()
|
||||||
|
.fast_mode_for_account(account, "public-model"),
|
||||||
|
if bound { effective } else { FastMode::Default },
|
||||||
|
"account={account}, mode={mode:?}, other={other_mode:?}, enabled={group_enabled}, bound={bound}"
|
||||||
|
);
|
||||||
|
}
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
plan.fast_mode(),
|
plan.account_scope().allows(&first_account),
|
||||||
if bound { expected } else { FastMode::Default },
|
!bound || group_enabled
|
||||||
"mode={mode:?}, other={other_mode:?}, enabled={group_enabled}, bound={bound}"
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn fast_mode_ignores_unbound_groups_and_groups_that_deny_the_model() {
|
||||||
|
use gateway_core::account::{AccountModelAccess, AccountModelAccessMode, ProviderAccountId};
|
||||||
|
use gateway_core::routing::AccountGroupId;
|
||||||
|
|
||||||
|
let group = |id| AccountGroupId::new(format!("grp_{id:032x}")).unwrap();
|
||||||
|
let account = ProviderAccountId::new("acct_model_fast").unwrap();
|
||||||
|
let facts = SnapshotFacts::new(
|
||||||
|
revision(1),
|
||||||
|
revision(1),
|
||||||
|
SettingsValues::new(3, "smart", BTreeMap::new(), None, None),
|
||||||
|
vec![SnapshotClientPolicyFacts::new(
|
||||||
|
ClientApiKeyId::new("key_model_fast").unwrap(),
|
||||||
|
PlaintextClientApiKey::new("fixture-model-fast").unwrap(),
|
||||||
|
vec![group(1), group(2)],
|
||||||
|
RateLimits::unlimited(),
|
||||||
|
)],
|
||||||
|
vec![
|
||||||
|
SnapshotAccountGroupFacts::new(group(1), "Fast".into(), true)
|
||||||
|
.with_fast_mode(FastMode::Enabled)
|
||||||
|
.with_model_access(
|
||||||
|
AccountModelAccess::new(
|
||||||
|
AccountModelAccessMode::Allowlist,
|
||||||
|
vec!["fast-model".into()],
|
||||||
|
)
|
||||||
|
.unwrap(),
|
||||||
|
),
|
||||||
|
SnapshotAccountGroupFacts::new(group(2), "Standard".into(), true)
|
||||||
|
.with_fast_mode(FastMode::Disabled)
|
||||||
|
.with_model_access(
|
||||||
|
AccountModelAccess::new(
|
||||||
|
AccountModelAccessMode::Denylist,
|
||||||
|
vec!["fast-model".into()],
|
||||||
|
)
|
||||||
|
.unwrap(),
|
||||||
|
),
|
||||||
|
SnapshotAccountGroupFacts::new(group(3), "Unbound".into(), true)
|
||||||
|
.with_fast_mode(FastMode::Disabled),
|
||||||
|
],
|
||||||
|
vec![SnapshotProviderAccountFacts::new(account.clone(), "alpha")],
|
||||||
|
(1..=3)
|
||||||
|
.map(|id| SnapshotAccountGroupMemberFacts::new(group(id), account.clone()))
|
||||||
|
.collect(),
|
||||||
|
);
|
||||||
|
let snapshot = block_on(
|
||||||
|
RuntimeSnapshotCompiler::new(
|
||||||
|
Arc::new(TestSnapshotStore::new(Ok(facts))),
|
||||||
|
Arc::new(TestCatalog::Unavailable),
|
||||||
|
)
|
||||||
|
.compile(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let scope = snapshot.client_policies().next().unwrap().account_scope();
|
||||||
|
for (model, expected) in [
|
||||||
|
("fast-model", FastMode::Enabled),
|
||||||
|
("standard-model", FastMode::Disabled),
|
||||||
|
] {
|
||||||
|
assert!(scope.allows_model(&account, model));
|
||||||
|
assert_eq!(scope.fast_mode_for_account(&account, model), expected);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn group_feature_permissions_merge_independently_with_deny_precedence() {
|
fn group_feature_permissions_merge_independently_with_deny_precedence() {
|
||||||
use gateway_core::account::ProviderAccountId;
|
use gateway_core::account::ProviderAccountId;
|
||||||
|
|||||||
@@ -48,6 +48,7 @@ tracing = "0.1.44"
|
|||||||
tracing-appender = "0.2.5"
|
tracing-appender = "0.2.5"
|
||||||
tracing-subscriber = { version = "0.3.23", features = ["env-filter", "json"] }
|
tracing-subscriber = { version = "0.3.23", features = ["env-filter", "json"] }
|
||||||
yaml-rust2 = "0.13.0"
|
yaml-rust2 = "0.13.0"
|
||||||
|
uuid = { version = "1.23.3", features = ["v4"] }
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
hyper = { version = "=1.11.1", default-features = false, features = ["server"] }
|
hyper = { version = "=1.11.1", default-features = false, features = ["server"] }
|
||||||
|
|||||||
@@ -13,9 +13,7 @@ use yaml_rust2::Yaml;
|
|||||||
|
|
||||||
use super::diagnostics::Diagnostics;
|
use super::diagnostics::Diagnostics;
|
||||||
use super::metadata::{Metadata, published_version};
|
use super::metadata::{Metadata, published_version};
|
||||||
use super::release::{
|
use super::release::{GitHubRelease, base_update_detail, update_target_allowed};
|
||||||
GitHubRelease, base_update_detail, detail_from_release, update_target_allowed,
|
|
||||||
};
|
|
||||||
use super::{OperationError, SystemUpdateConfig, conflict, upstream};
|
use super::{OperationError, SystemUpdateConfig, conflict, upstream};
|
||||||
|
|
||||||
const NORMAL: Duration = Duration::from_secs(1200);
|
const NORMAL: Duration = Duration::from_secs(1200);
|
||||||
@@ -155,11 +153,14 @@ impl ReleaseCache {
|
|||||||
let (mut detail, target) = candidate(config, channel, &index)?;
|
let (mut detail, target) = candidate(config, channel, &index)?;
|
||||||
detail.cached = cached;
|
detail.cached = cached;
|
||||||
if check != Check::Summary || detail.has_update {
|
if check != Check::Summary || detail.has_update {
|
||||||
let (release, reused) = self.exact(config, &target, age, diagnostics).await?;
|
let (release, reused) = self
|
||||||
|
.exact(config, &target, detail.has_update, age, diagnostics)
|
||||||
|
.await?;
|
||||||
if let Some(release) = release
|
if let Some(release) = release
|
||||||
&& check != Check::Summary
|
&& check != Check::Summary
|
||||||
{
|
{
|
||||||
detail = detail_from_release(config, &release, channel);
|
detail.release_url.clone_from(&release.html_url);
|
||||||
|
detail.notes = release.body.clone().or_else(|| release.name.clone());
|
||||||
}
|
}
|
||||||
detail.cached = cached && reused;
|
detail.cached = cached && reused;
|
||||||
}
|
}
|
||||||
@@ -173,6 +174,7 @@ impl ReleaseCache {
|
|||||||
&self,
|
&self,
|
||||||
config: &SystemUpdateConfig,
|
config: &SystemUpdateConfig,
|
||||||
target: &Version,
|
target: &Version,
|
||||||
|
has_update: bool,
|
||||||
age: Duration,
|
age: Duration,
|
||||||
diagnostics: &Diagnostics,
|
diagnostics: &Diagnostics,
|
||||||
) -> Result<(Option<Arc<GitHubRelease>>, bool), OperationError> {
|
) -> Result<(Option<Arc<GitHubRelease>>, bool), OperationError> {
|
||||||
@@ -191,8 +193,12 @@ impl ReleaseCache {
|
|||||||
entries.push_back((target.clone(), Arc::clone(&slot)));
|
entries.push_back((target.clone(), Arc::clone(&slot)));
|
||||||
slot
|
slot
|
||||||
};
|
};
|
||||||
slot.get(age, self.metadata.release(config, target), diagnostics)
|
slot.get(
|
||||||
.await
|
age,
|
||||||
|
self.metadata.release(config, target, has_update),
|
||||||
|
diagnostics,
|
||||||
|
)
|
||||||
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(super) async fn install(
|
pub(super) async fn install(
|
||||||
@@ -209,10 +215,10 @@ impl ReleaseCache {
|
|||||||
.get(Duration::ZERO, self.metadata.index(config), diagnostics)
|
.get(Duration::ZERO, self.metadata.index(config), diagnostics)
|
||||||
.await?;
|
.await?;
|
||||||
let (detail, target) = candidate(config, channel, &index)?;
|
let (detail, target) = candidate(config, channel, &index)?;
|
||||||
if !detail.has_update || detail.latest_version != confirmed {
|
if !detail.has_update || detail.latest_version.as_deref() != Some(confirmed) {
|
||||||
return Err(conflict("远端最新版本已变化,请重新检查并确认"));
|
return Err(conflict("远端最新版本已变化,请重新检查并确认"));
|
||||||
}
|
}
|
||||||
self.exact(config, &target, Duration::ZERO, diagnostics)
|
self.exact(config, &target, true, Duration::ZERO, diagnostics)
|
||||||
.await?
|
.await?
|
||||||
.0
|
.0
|
||||||
.ok_or_else(|| upstream("发布索引指向的 Release 不存在"))
|
.ok_or_else(|| upstream("发布索引指向的 Release 不存在"))
|
||||||
@@ -231,11 +237,7 @@ fn candidate(
|
|||||||
.map_err(|_| conflict("当前版本号无效"))?;
|
.map_err(|_| conflict("当前版本号无效"))?;
|
||||||
let target = published_version(index, ¤t, channel)?;
|
let target = published_version(index, ¤t, channel)?;
|
||||||
let mut detail = base_update_detail(config, channel, None, None);
|
let mut detail = base_update_detail(config, channel, None, None);
|
||||||
if update_target_allowed(¤t, &target, channel) {
|
detail.latest_version = Some(target.to_string());
|
||||||
detail.latest_version = target.to_string();
|
detail.has_update = update_target_allowed(¤t, &target, channel);
|
||||||
detail.has_update = true;
|
Ok((detail, target))
|
||||||
Ok((detail, target))
|
|
||||||
} else {
|
|
||||||
Ok((detail, current))
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -83,6 +83,7 @@ impl Metadata {
|
|||||||
&self,
|
&self,
|
||||||
config: &SystemUpdateConfig,
|
config: &SystemUpdateConfig,
|
||||||
version: &Version,
|
version: &Version,
|
||||||
|
has_update: bool,
|
||||||
) -> Result<Option<Arc<GitHubRelease>>, OperationError> {
|
) -> Result<Option<Arc<GitHubRelease>>, OperationError> {
|
||||||
let mut url =
|
let mut url =
|
||||||
Url::parse(&config.github_api_base).map_err(|_| invalid("发行查询地址无效"))?;
|
Url::parse(&config.github_api_base).map_err(|_| invalid("发行查询地址无效"))?;
|
||||||
@@ -109,7 +110,7 @@ impl Metadata {
|
|||||||
if release.tag_name != tag || release.draft || release.prerelease != prerelease {
|
if release.tag_name != tag || release.draft || release.prerelease != prerelease {
|
||||||
return Err(upstream("GitHub 发行身份与发布索引不符"));
|
return Err(upstream("GitHub 发行身份与发布索引不符"));
|
||||||
}
|
}
|
||||||
if config.version.trim_start_matches('v') != version {
|
if has_update {
|
||||||
release.install_assets(&version, &config.github_api_base)?;
|
release.install_assets(&version, &config.github_api_base)?;
|
||||||
}
|
}
|
||||||
Ok(Some(Arc::new(release)))
|
Ok(Some(Arc::new(release)))
|
||||||
|
|||||||
@@ -37,6 +37,7 @@ const MAX_OFFICIAL_PLUGIN_MANIFEST_SIZE: u64 = 256 * 1024;
|
|||||||
/// gateway-admin 消费的真实进程/文件系统操作实现
|
/// gateway-admin 消费的真实进程/文件系统操作实现
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct ProcessSystemOperations {
|
pub struct ProcessSystemOperations {
|
||||||
|
instance_id: String,
|
||||||
cancellation: CancellationToken,
|
cancellation: CancellationToken,
|
||||||
events: Arc<UpdateEvents>,
|
events: Arc<UpdateEvents>,
|
||||||
config: Arc<SystemUpdateConfig>,
|
config: Arc<SystemUpdateConfig>,
|
||||||
@@ -62,6 +63,7 @@ impl ProcessSystemOperations {
|
|||||||
ReleaseFiles::installed(&config)
|
ReleaseFiles::installed(&config)
|
||||||
}));
|
}));
|
||||||
Self {
|
Self {
|
||||||
|
instance_id: uuid::Uuid::new_v4().to_string(),
|
||||||
cancellation,
|
cancellation,
|
||||||
events: Arc::new(UpdateEvents::default()),
|
events: Arc::new(UpdateEvents::default()),
|
||||||
config: Arc::new(config),
|
config: Arc::new(config),
|
||||||
@@ -350,6 +352,8 @@ impl SystemOperations for ProcessSystemOperations {
|
|||||||
.await;
|
.await;
|
||||||
Ok(SystemVersion {
|
Ok(SystemVersion {
|
||||||
version: self.config.version.clone(),
|
version: self.config.version.clone(),
|
||||||
|
instance_id: self.instance_id.clone(),
|
||||||
|
restart_supported: self.config.self_restart_enabled,
|
||||||
git_sha: self.config.git_sha.clone(),
|
git_sha: self.config.git_sha.clone(),
|
||||||
build_time: self.config.build_time.clone(),
|
build_time: self.config.build_time.clone(),
|
||||||
deployment_mode: self.config.deployment_mode.clone(),
|
deployment_mode: self.config.deployment_mode.clone(),
|
||||||
|
|||||||
@@ -72,36 +72,6 @@ impl GitHubRelease {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn detail_from_release(
|
|
||||||
config: &SystemUpdateConfig,
|
|
||||||
release: &GitHubRelease,
|
|
||||||
channel: UpdateChannel,
|
|
||||||
) -> SystemUpdateDetail {
|
|
||||||
let unsupported_reason = config.update_support_error();
|
|
||||||
let latest_version = normalize_version(&release.tag_name);
|
|
||||||
let has_update = validate_update_target(&config.version, &latest_version, channel).is_ok();
|
|
||||||
if unsupported_reason.is_some()
|
|
||||||
|| (!has_update && latest_version != normalize_version(&config.version))
|
|
||||||
{
|
|
||||||
return base_update_detail(config, channel, unsupported_reason, None);
|
|
||||||
}
|
|
||||||
SystemUpdateDetail {
|
|
||||||
policy: update_policy(config, channel),
|
|
||||||
current_version: config.version.clone(),
|
|
||||||
latest_version,
|
|
||||||
has_update,
|
|
||||||
deployment_mode: config.deployment_mode.clone(),
|
|
||||||
build_type: config.build_type.clone(),
|
|
||||||
release_url: release.html_url.clone(),
|
|
||||||
notes: release.body.clone().or_else(|| release.name.clone()),
|
|
||||||
cached: false,
|
|
||||||
update_supported: true,
|
|
||||||
unsupported_reason: None,
|
|
||||||
warning: None,
|
|
||||||
retry_at: None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn confirmed_target(target: Option<String>) -> Result<String, OperationError> {
|
pub(crate) fn confirmed_target(target: Option<String>) -> Result<String, OperationError> {
|
||||||
let target = target.ok_or_else(|| conflict("请先确认目标版本"))?;
|
let target = target.ok_or_else(|| conflict("请先确认目标版本"))?;
|
||||||
let target = normalize_version(&target);
|
let target = normalize_version(&target);
|
||||||
@@ -364,14 +334,14 @@ pub(super) fn base_update_detail(
|
|||||||
SystemUpdateDetail {
|
SystemUpdateDetail {
|
||||||
policy: update_policy(config, channel),
|
policy: update_policy(config, channel),
|
||||||
current_version: config.version.clone(),
|
current_version: config.version.clone(),
|
||||||
latest_version: config.version.clone(),
|
latest_version: None,
|
||||||
has_update: false,
|
has_update: false,
|
||||||
deployment_mode: config.deployment_mode.clone(),
|
deployment_mode: config.deployment_mode.clone(),
|
||||||
build_type: config.build_type.clone(),
|
build_type: config.build_type.clone(),
|
||||||
release_url: None,
|
release_url: None,
|
||||||
notes: None,
|
notes: None,
|
||||||
cached: false,
|
cached: false,
|
||||||
update_supported: unsupported_reason.is_none() && warning.is_none(),
|
update_supported: unsupported_reason.is_none(),
|
||||||
unsupported_reason,
|
unsupported_reason,
|
||||||
warning: warning.map(|error| error.message().to_owned()),
|
warning: warning.map(|error| error.message().to_owned()),
|
||||||
retry_at: warning.and_then(OperationError::retry_at),
|
retry_at: warning.and_then(OperationError::retry_at),
|
||||||
|
|||||||
@@ -122,11 +122,12 @@ impl WorkerSupervisor {
|
|||||||
health: &self.health,
|
health: &self.health,
|
||||||
};
|
};
|
||||||
let deadline = tokio::time::Instant::now() + timeout;
|
let deadline = tokio::time::Instant::now() + timeout;
|
||||||
for (_, handle) in &mut shutdown.handles {
|
for (worker, handle) in &mut shutdown.handles {
|
||||||
if tokio::time::timeout_at(deadline, &mut *handle)
|
if tokio::time::timeout_at(deadline, &mut *handle)
|
||||||
.await
|
.await
|
||||||
.is_err()
|
.is_err()
|
||||||
{
|
{
|
||||||
|
tracing::warn!(target: "gateway_shutdown", %worker, "后台任务收尾超时,强制终止");
|
||||||
handle.abort();
|
handle.abort();
|
||||||
let _ = handle.await;
|
let _ = handle.await;
|
||||||
}
|
}
|
||||||
@@ -459,6 +460,7 @@ async fn acquire_and_run(
|
|||||||
let acquisition = AssertUnwindSafe(leader_lease.try_acquire(request)).catch_unwind();
|
let acquisition = AssertUnwindSafe(leader_lease.try_acquire(request)).catch_unwind();
|
||||||
tokio::pin!(acquisition);
|
tokio::pin!(acquisition);
|
||||||
let acquisition = tokio::select! {
|
let acquisition = tokio::select! {
|
||||||
|
biased;
|
||||||
() = cancellation.cancelled() => return ScheduledOutcome::ShuttingDown,
|
() = cancellation.cancelled() => return ScheduledOutcome::ShuttingDown,
|
||||||
acquisition = &mut acquisition => acquisition,
|
acquisition = &mut acquisition => acquisition,
|
||||||
};
|
};
|
||||||
@@ -490,12 +492,13 @@ async fn run_local_cycle(
|
|||||||
.catch_unwind();
|
.catch_unwind();
|
||||||
tokio::pin!(cycle);
|
tokio::pin!(cycle);
|
||||||
tokio::select! {
|
tokio::select! {
|
||||||
outcome = &mut cycle => task_result(outcome),
|
biased;
|
||||||
() = cancellation.cancelled() => {
|
() = cancellation.cancelled() => {
|
||||||
cycle_cancel.cancel();
|
cycle_cancel.cancel();
|
||||||
let _ = cycle.await;
|
let _ = cycle.await;
|
||||||
ScheduledOutcome::ShuttingDown
|
ScheduledOutcome::ShuttingDown
|
||||||
}
|
}
|
||||||
|
outcome = &mut cycle => task_result(outcome),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -527,17 +530,21 @@ async fn run_leased_cycle(
|
|||||||
|
|
||||||
let outcome = loop {
|
let outcome = loop {
|
||||||
tokio::select! {
|
tokio::select! {
|
||||||
result = &mut cycle => break task_result(result),
|
biased;
|
||||||
() = cancellation.cancelled() => {
|
() = cancellation.cancelled() => {
|
||||||
cycle_cancel.cancel();
|
cycle_cancel.cancel();
|
||||||
let _ = cycle.await;
|
let _ = cycle.await;
|
||||||
break ScheduledOutcome::ShuttingDown;
|
break ScheduledOutcome::ShuttingDown;
|
||||||
}
|
}
|
||||||
|
result = &mut cycle => break task_result(result),
|
||||||
() = &mut renewal => {
|
() = &mut renewal => {
|
||||||
let renewed = renew_guard(
|
let Some(renewed) = cancellation.run_until_cancelled(renew_guard(
|
||||||
guard.as_mut(),
|
guard.as_mut(),
|
||||||
schedule.leader_lease_renewal_interval(),
|
schedule.leader_lease_renewal_interval(),
|
||||||
).await;
|
)).await else {
|
||||||
|
// 返回循环首个取消分支,统一等待正在执行的周期收尾
|
||||||
|
continue;
|
||||||
|
};
|
||||||
if let Err(error) = renewed {
|
if let Err(error) = renewed {
|
||||||
cycle_cancel.cancel();
|
cycle_cancel.cancel();
|
||||||
let _ = cycle.await;
|
let _ = cycle.await;
|
||||||
|
|||||||
@@ -30,7 +30,7 @@ async fn temporary_channel_should_filter_future_releases_without_changing_runnin
|
|||||||
.update_detail(SystemUpdateCheck::Detail, Some(channel))
|
.update_detail(SystemUpdateCheck::Detail, Some(channel))
|
||||||
.await
|
.await
|
||||||
.expect("detail");
|
.expect("detail");
|
||||||
assert_eq!(detail.latest_version, target);
|
assert_eq!(detail.latest_version.as_deref(), Some(target));
|
||||||
assert_eq!(detail.policy.channel, channel);
|
assert_eq!(detail.policy.channel, channel);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
detail.policy.available_channels,
|
detail.policy.available_channels,
|
||||||
@@ -42,11 +42,11 @@ async fn temporary_channel_should_filter_future_releases_without_changing_runnin
|
|||||||
.await
|
.await
|
||||||
.expect("cached");
|
.expect("cached");
|
||||||
assert!(cached.cached);
|
assert!(cached.cached);
|
||||||
assert_eq!(cached.latest_version, target);
|
assert_eq!(cached.latest_version.as_deref(), Some(target));
|
||||||
}
|
}
|
||||||
let version = service.version().await.expect("default check");
|
let version = service.version().await.expect("default check");
|
||||||
assert_eq!(version.update_channel, "stable");
|
assert_eq!(version.update_channel, "stable");
|
||||||
assert_eq!(version.latest_version, "1.1.0");
|
assert_eq!(version.latest_version.as_deref(), Some("1.1.0"));
|
||||||
assert!(!fixture.state().exists(), "检查通道不能写入实例偏好");
|
assert!(!fixture.state().exists(), "检查通道不能写入实例偏好");
|
||||||
let requests = server.received_requests().await.expect("requests");
|
let requests = server.received_requests().await.expect("requests");
|
||||||
assert_eq!(requests.len(), 5);
|
assert_eq!(requests.len(), 5);
|
||||||
@@ -56,17 +56,27 @@ async fn temporary_channel_should_filter_future_releases_without_changing_runnin
|
|||||||
async fn reopening_should_infer_running_channel_and_switching_to_stable_should_not_downgrade() {
|
async fn reopening_should_infer_running_channel_and_switching_to_stable_should_not_downgrade() {
|
||||||
let server = MockServer::start().await;
|
let server = MockServer::start().await;
|
||||||
let fixture = Fixture::new();
|
let fixture = Fixture::new();
|
||||||
fixture.mount_release_once(&server, "1.0.0").await;
|
mount_index(&server, fixture_index("1.0.0")).await;
|
||||||
|
Mock::given(path("/repos/owner/repository/releases/tags/v1.0.0"))
|
||||||
|
.respond_with(release_response("1.0.0", Vec::new()))
|
||||||
|
.mount(&server)
|
||||||
|
.await;
|
||||||
let mut config = fixture.config(&format!("{}/repos", server.uri()));
|
let mut config = fixture.config(&format!("{}/repos", server.uri()));
|
||||||
config.version = "1.1.0-beta.1".into();
|
config.version = "1.1.0-beta.1".into();
|
||||||
let service = ProcessSystemOperations::new(CancellationToken::new(), config.clone());
|
let service = ProcessSystemOperations::new(CancellationToken::new(), config.clone());
|
||||||
let temporary = service
|
for check in [SystemUpdateCheck::Summary, SystemUpdateCheck::Refresh] {
|
||||||
.update_detail(SystemUpdateCheck::Refresh, Some(Stable))
|
let temporary = service
|
||||||
.await
|
.update_detail(check, Some(Stable))
|
||||||
.expect("view stable");
|
.await
|
||||||
assert_eq!(temporary.policy.channel, Stable);
|
.expect("view stable");
|
||||||
assert!(!temporary.has_update);
|
assert_eq!(temporary.policy.channel, Stable);
|
||||||
assert_eq!(temporary.latest_version, "1.1.0-beta.1");
|
assert!(!temporary.has_update);
|
||||||
|
assert_eq!(temporary.latest_version.as_deref(), Some("1.0.0"));
|
||||||
|
assert_eq!(
|
||||||
|
temporary.notes.is_some(),
|
||||||
|
check != SystemUpdateCheck::Summary
|
||||||
|
);
|
||||||
|
}
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
service
|
service
|
||||||
.update_detail(SystemUpdateCheck::Detail, None)
|
.update_detail(SystemUpdateCheck::Detail, None)
|
||||||
@@ -231,7 +241,7 @@ async fn inferred_prerelease_policy_should_follow_future_minor_and_patch_release
|
|||||||
.await
|
.await
|
||||||
.expect("check");
|
.expect("check");
|
||||||
assert!(detail.has_update);
|
assert!(detail.has_update);
|
||||||
assert_eq!(detail.latest_version, target);
|
assert_eq!(detail.latest_version.as_deref(), Some(target));
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
complete_update(&service, target).await.operation.status,
|
complete_update(&service, target).await.operation.status,
|
||||||
SystemOperationStatus::Succeeded
|
SystemOperationStatus::Succeeded
|
||||||
|
|||||||
@@ -78,7 +78,7 @@ async fn discovery_request_budget_is_constant_under_load() {
|
|||||||
.update_detail(SystemUpdateCheck::Summary, None)
|
.update_detail(SystemUpdateCheck::Summary, None)
|
||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
assert_eq!(summary.latest_version, target);
|
assert_eq!(summary.latest_version.as_deref(), Some(target.as_str()));
|
||||||
assert!(summary.notes.is_none());
|
assert!(summary.notes.is_none());
|
||||||
assert_eq!(server.received_requests().await.unwrap().len(), 2);
|
assert_eq!(server.received_requests().await.unwrap().len(), 2);
|
||||||
|
|
||||||
@@ -96,7 +96,7 @@ async fn discovery_request_budget_is_constant_under_load() {
|
|||||||
}
|
}
|
||||||
while let Some(detail) = callers.join_next().await {
|
while let Some(detail) = callers.join_next().await {
|
||||||
let detail = detail.unwrap();
|
let detail = detail.unwrap();
|
||||||
assert_eq!(detail.latest_version, target);
|
assert_eq!(detail.latest_version.as_deref(), Some(target.as_str()));
|
||||||
assert_eq!(detail.notes.as_deref(), Some("notes"));
|
assert_eq!(detail.notes.as_deref(), Some("notes"));
|
||||||
}
|
}
|
||||||
for _ in 0..64 {
|
for _ in 0..64 {
|
||||||
@@ -199,6 +199,10 @@ async fn api_cooldown_is_shared_and_summary_does_not_advertise_an_unverified_rel
|
|||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
assert!(first.warning.is_some());
|
assert!(first.warning.is_some());
|
||||||
|
assert!(first.update_supported);
|
||||||
|
assert!(first.unsupported_reason.is_none());
|
||||||
|
assert!(!first.has_update);
|
||||||
|
assert!(first.latest_version.is_none());
|
||||||
let retry_at = first.retry_at.expect("限流应提供重试时间");
|
let retry_at = first.retry_at.expect("限流应提供重试时间");
|
||||||
assert!((298..=300).contains(&(retry_at - chrono::Utc::now()).num_seconds()));
|
assert!((298..=300).contains(&(retry_at - chrono::Utc::now()).num_seconds()));
|
||||||
for _ in 0..32 {
|
for _ in 0..32 {
|
||||||
@@ -306,7 +310,11 @@ async fn install_rechecks_even_a_warm_candidate_and_never_downloads_a_changed_ta
|
|||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
assert!(detail.has_update);
|
assert!(detail.has_update);
|
||||||
let status = complete_update(&service, &detail.latest_version).await;
|
let status = complete_update(
|
||||||
|
&service,
|
||||||
|
detail.latest_version.as_deref().expect("confirmed target"),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
assert_eq!(status.operation.status, SystemOperationStatus::Failed);
|
assert_eq!(status.operation.status, SystemOperationStatus::Failed);
|
||||||
assert!(status.operation.error.unwrap().contains("重新检查并确认"));
|
assert!(status.operation.error.unwrap().contains("重新检查并确认"));
|
||||||
assert_eq!(server.received_requests().await.unwrap().len(), 3);
|
assert_eq!(server.received_requests().await.unwrap().len(), 3);
|
||||||
|
|||||||
@@ -142,6 +142,8 @@ async fn restart_should_request_process_restart_inside_docker() {
|
|||||||
config.deployment_mode = "docker".to_owned();
|
config.deployment_mode = "docker".to_owned();
|
||||||
let shutdown = CancellationToken::new();
|
let shutdown = CancellationToken::new();
|
||||||
let service = ProcessSystemOperations::new(shutdown.clone(), config);
|
let service = ProcessSystemOperations::new(shutdown.clone(), config);
|
||||||
|
assert!(!service.update_status().await.expect("status").need_restart);
|
||||||
|
assert!(service.version().await.expect("version").restart_supported);
|
||||||
service
|
service
|
||||||
.restart(Arc::new(AllowingUpdatePreflight))
|
.restart(Arc::new(AllowingUpdatePreflight))
|
||||||
.await
|
.await
|
||||||
@@ -152,6 +154,48 @@ async fn restart_should_request_process_restart_inside_docker() {
|
|||||||
.expect("shutdown requested");
|
.expect("shutdown requested");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn version_should_distinguish_same_version_service_instances() {
|
||||||
|
let fixture = Fixture::new();
|
||||||
|
let config = fixture.config("http://127.0.0.1:1/repos");
|
||||||
|
let service = ProcessSystemOperations::new(CancellationToken::new(), config.clone());
|
||||||
|
let version = service.version().await.expect("version");
|
||||||
|
assert!(!version.instance_id.is_empty());
|
||||||
|
assert_eq!(
|
||||||
|
service
|
||||||
|
.clone()
|
||||||
|
.version()
|
||||||
|
.await
|
||||||
|
.expect("same instance")
|
||||||
|
.instance_id,
|
||||||
|
version.instance_id
|
||||||
|
);
|
||||||
|
|
||||||
|
let replacement = ProcessSystemOperations::new(CancellationToken::new(), config);
|
||||||
|
let restarted = replacement.version().await.expect("new instance");
|
||||||
|
assert_eq!(restarted.version, version.version);
|
||||||
|
assert_ne!(restarted.instance_id, version.instance_id);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn version_should_report_restart_disabled_when_host_rejects_it() {
|
||||||
|
let fixture = Fixture::new();
|
||||||
|
let mut config = fixture.config("http://127.0.0.1:1/repos");
|
||||||
|
config.self_restart_enabled = false;
|
||||||
|
let shutdown = CancellationToken::new();
|
||||||
|
let service = ProcessSystemOperations::new(shutdown.clone(), config);
|
||||||
|
assert!(!service.version().await.expect("version").restart_supported);
|
||||||
|
assert_eq!(
|
||||||
|
service
|
||||||
|
.restart(Arc::new(AllowingUpdatePreflight))
|
||||||
|
.await
|
||||||
|
.expect_err("restart disabled")
|
||||||
|
.kind(),
|
||||||
|
SystemOperationErrorKind::Conflict
|
||||||
|
);
|
||||||
|
assert!(!shutdown.is_cancelled());
|
||||||
|
}
|
||||||
|
|
||||||
#[tokio::test(start_paused = true)]
|
#[tokio::test(start_paused = true)]
|
||||||
async fn accepted_restart_excludes_system_operations_until_service_release() {
|
async fn accepted_restart_excludes_system_operations_until_service_release() {
|
||||||
let fixture = Fixture::new();
|
let fixture = Fixture::new();
|
||||||
|
|||||||
@@ -59,7 +59,7 @@ async fn update_detail_should_withhold_updates_for_source_builds() {
|
|||||||
.update_detail(SystemUpdateCheck::Refresh, None)
|
.update_detail(SystemUpdateCheck::Refresh, None)
|
||||||
.await
|
.await
|
||||||
.expect("detail");
|
.expect("detail");
|
||||||
assert_eq!(detail.latest_version, "1.0.0");
|
assert!(detail.latest_version.is_none());
|
||||||
assert!(!detail.update_supported);
|
assert!(!detail.update_supported);
|
||||||
assert!(detail.unsupported_reason.is_some());
|
assert!(detail.unsupported_reason.is_some());
|
||||||
assert!(!detail.has_update);
|
assert!(!detail.has_update);
|
||||||
@@ -107,10 +107,7 @@ async fn update_checks_should_follow_stage_promotion_and_experimental_isolation(
|
|||||||
.await
|
.await
|
||||||
.expect("detail");
|
.expect("detail");
|
||||||
assert_eq!(detail.has_update, allowed, "{current} -> {target}");
|
assert_eq!(detail.has_update, allowed, "{current} -> {target}");
|
||||||
assert_eq!(
|
assert_eq!(detail.latest_version.as_deref(), allowed.then_some(target));
|
||||||
detail.latest_version,
|
|
||||||
if allowed { target } else { current }
|
|
||||||
);
|
|
||||||
assert_eq!(detail.notes.is_some(), allowed);
|
assert_eq!(detail.notes.is_some(), allowed);
|
||||||
assert_eq!(detail.release_url.is_some(), allowed);
|
assert_eq!(detail.release_url.is_some(), allowed);
|
||||||
assert_eq!(detail.warning.is_none(), allowed);
|
assert_eq!(detail.warning.is_none(), allowed);
|
||||||
@@ -161,7 +158,7 @@ async fn update_detail_should_keep_current_release_notes_without_allowing_reinst
|
|||||||
.update_detail(SystemUpdateCheck::Refresh, None)
|
.update_detail(SystemUpdateCheck::Refresh, None)
|
||||||
.await
|
.await
|
||||||
.expect("current release");
|
.expect("current release");
|
||||||
assert_eq!(detail.latest_version, current);
|
assert_eq!(detail.latest_version.as_deref(), Some(current));
|
||||||
assert!(!detail.has_update);
|
assert!(!detail.has_update);
|
||||||
assert!(detail.update_supported);
|
assert!(detail.update_supported);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
@@ -193,15 +190,15 @@ async fn update_detail_should_keep_current_release_notes_without_allowing_reinst
|
|||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn update_checks_should_ignore_downgrades_unknown_stages_and_build_metadata() {
|
async fn update_checks_should_ignore_downgrades_unknown_stages_and_build_metadata() {
|
||||||
for (current, target) in [
|
for (current, target, published) in [
|
||||||
("3.12.0-beta.2", "3.12.0-beta.1"),
|
("3.12.0-beta.2", "3.12.0-beta.1", true),
|
||||||
("3.12.0", "3.12.0+new-build"),
|
("3.12.0", "3.12.0+new-build", true),
|
||||||
("3.12.0-beta.1+aaa", "3.12.0-beta.1+zzz"),
|
("3.12.0-beta.1+aaa", "3.12.0-beta.1+zzz", true),
|
||||||
("3.12.0", "3.11.0"),
|
("3.12.0", "3.11.0", true),
|
||||||
("3.12.0-alpha.1", "3.12.0-preview.2"),
|
("3.12.0-alpha.1", "3.12.0-preview.2", false),
|
||||||
("3.12.0-alpha.1", "3.12.0-beta"),
|
("3.12.0-alpha.1", "3.12.0-beta", false),
|
||||||
("3.12.0-alpha.1", "3.12.0-beta.0"),
|
("3.12.0-alpha.1", "3.12.0-beta.0", false),
|
||||||
("3.12.0-alpha.1", "3.12.0-beta.2.extra"),
|
("3.12.0-alpha.1", "3.12.0-beta.2.extra", false),
|
||||||
] {
|
] {
|
||||||
let server = MockServer::start().await;
|
let server = MockServer::start().await;
|
||||||
let fixture = Fixture::new();
|
let fixture = Fixture::new();
|
||||||
@@ -214,9 +211,12 @@ async fn update_checks_should_ignore_downgrades_unknown_stages_and_build_metadat
|
|||||||
.await
|
.await
|
||||||
.expect("detail");
|
.expect("detail");
|
||||||
assert!(!detail.has_update, "{current} -> {target}");
|
assert!(!detail.has_update, "{current} -> {target}");
|
||||||
assert_eq!(detail.latest_version, current);
|
assert_eq!(
|
||||||
assert!(detail.notes.is_none());
|
detail.latest_version.as_deref(),
|
||||||
assert!(detail.release_url.is_none());
|
published.then_some(target)
|
||||||
|
);
|
||||||
|
assert_eq!(detail.notes.is_some(), published);
|
||||||
|
assert_eq!(detail.release_url.is_some(), published);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -219,6 +219,7 @@ enum LeaseStep {
|
|||||||
enum RenewStep {
|
enum RenewStep {
|
||||||
Success,
|
Success,
|
||||||
Error,
|
Error,
|
||||||
|
Pending,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Default)]
|
#[derive(Default)]
|
||||||
@@ -268,11 +269,12 @@ impl WorkerLeaderLeaseGuard for FakeLeaseGuard {
|
|||||||
fn renew(&mut self) -> BoxFuture<'_, Result<(), WorkerLeaseError>> {
|
fn renew(&mut self) -> BoxFuture<'_, Result<(), WorkerLeaseError>> {
|
||||||
Box::pin(async move {
|
Box::pin(async move {
|
||||||
lock_unpoisoned(&self.renewals).push(self.worker.clone());
|
lock_unpoisoned(&self.renewals).push(self.worker.clone());
|
||||||
match lock_unpoisoned(&self.renew_scripts)
|
let step = lock_unpoisoned(&self.renew_scripts)
|
||||||
.get_mut(&self.worker)
|
.get_mut(&self.worker)
|
||||||
.and_then(VecDeque::pop_front)
|
.and_then(VecDeque::pop_front)
|
||||||
.unwrap_or(RenewStep::Success)
|
.unwrap_or(RenewStep::Success);
|
||||||
{
|
match step {
|
||||||
|
RenewStep::Pending => pending().await,
|
||||||
RenewStep::Success => Ok(()),
|
RenewStep::Success => Ok(()),
|
||||||
RenewStep::Error => Err(WorkerLeaseError::safe("expected renewal failure")),
|
RenewStep::Error => Err(WorkerLeaseError::safe("expected renewal failure")),
|
||||||
}
|
}
|
||||||
@@ -510,6 +512,31 @@ async fn long_cycle_renews_leader_lease_before_ttl() {
|
|||||||
supervisor.shutdown(Duration::from_secs(1)).await;
|
supervisor.shutdown(Duration::from_secs(1)).await;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test(start_paused = true)]
|
||||||
|
async fn shutdown_signals_the_cycle_while_lease_renewal_is_pending() {
|
||||||
|
let leases = Arc::new(FakeLeasePort::default());
|
||||||
|
leases.renew_script(target_worker(), [RenewStep::Pending]);
|
||||||
|
let task = CancellationTask {
|
||||||
|
entered: Arc::new(AtomicUsize::new(0)),
|
||||||
|
observed: Arc::new(AtomicUsize::new(0)),
|
||||||
|
};
|
||||||
|
let supervisor = supervisor();
|
||||||
|
supervisor
|
||||||
|
.start(
|
||||||
|
target_plan(task.clone(), renewal_schedule()),
|
||||||
|
leases.clone(),
|
||||||
|
Arc::new(RecordingDiagnostics::default()),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
yield_until(|| task.entered.load(Ordering::SeqCst) != 0).await;
|
||||||
|
tokio::time::advance(Duration::from_millis(10)).await;
|
||||||
|
yield_until(|| leases.renewal_count(&target_worker()) == 1).await;
|
||||||
|
// 关闭预算短于续租超时,协作取消仍应完成
|
||||||
|
supervisor.shutdown(Duration::from_millis(1)).await;
|
||||||
|
assert_eq!(task.observed.load(Ordering::SeqCst), 1);
|
||||||
|
assert!(lock_unpoisoned(&leases.active_guards).is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
#[tokio::test(start_paused = true)]
|
#[tokio::test(start_paused = true)]
|
||||||
async fn renewal_failure_cancels_old_cycle_before_another_leader_cycle_starts() {
|
async fn renewal_failure_cancels_old_cycle_before_another_leader_cycle_starts() {
|
||||||
let task = ConcurrentCycleTask {
|
let task = ConcurrentCycleTask {
|
||||||
|
|||||||
@@ -248,21 +248,21 @@ impl Execution {
|
|||||||
request_body_limit,
|
request_body_limit,
|
||||||
)
|
)
|
||||||
.map_err(|error| fault_error(error, UpstreamSendState::NotSent))?;
|
.map_err(|error| fault_error(error, UpstreamSendState::NotSent))?;
|
||||||
|
let upstream_model = invocation.metadata.upstream_model().ok_or_else(invalid)?;
|
||||||
let request = UpstreamAdapterRequest {
|
let request = UpstreamAdapterRequest {
|
||||||
adapter_id: declaration.id.clone(),
|
adapter_id: declaration.id.clone(),
|
||||||
provider: declaration.provider,
|
provider: declaration.provider,
|
||||||
upstream_model: invocation
|
upstream_model: upstream_model.as_str().to_owned(),
|
||||||
.metadata
|
|
||||||
.upstream_model()
|
|
||||||
.ok_or_else(invalid)?
|
|
||||||
.as_str()
|
|
||||||
.to_owned(),
|
|
||||||
client_key_id: invocation.context.client_api_key_ref().as_str().to_owned(),
|
client_key_id: invocation.context.client_api_key_ref().as_str().to_owned(),
|
||||||
account_id: invocation.account.account_id().as_str().to_owned(),
|
account_id: invocation.account.account_id().as_str().to_owned(),
|
||||||
credential_revision: invocation.account.credential_revision().get(),
|
credential_revision: invocation.account.credential_revision().get(),
|
||||||
protocol: invocation.operation.protocol().to_owned(),
|
protocol: invocation.operation.protocol().to_owned(),
|
||||||
client_transport: invocation.context.client_transport().as_str().to_owned(),
|
client_transport: invocation.context.client_transport().as_str().to_owned(),
|
||||||
fast_mode: invocation.context.fast_mode().as_str().to_owned(),
|
fast_mode: invocation
|
||||||
|
.context
|
||||||
|
.fast_mode_for_account(invocation.account.account_id(), upstream_model.as_str())
|
||||||
|
.as_str()
|
||||||
|
.to_owned(),
|
||||||
request_elapsed_ms: u64::try_from(
|
request_elapsed_ms: u64::try_from(
|
||||||
invocation.context.timing_started_at().elapsed().as_millis(),
|
invocation.context.timing_started_at().elapsed().as_millis(),
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -7,13 +7,16 @@ use serde_json::{Value, json};
|
|||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn middleware_preserves_fast_modes_and_sources() {
|
async fn middleware_preserves_fast_modes_and_sources() {
|
||||||
for (mode, expected) in [
|
for (mode, expected) in [
|
||||||
(FastMode::Default, FastMode::Default),
|
(None, None),
|
||||||
(FastMode::Enabled, FastMode::Enabled),
|
(None, Some(FastMode::Default)),
|
||||||
(FastMode::Disabled, FastMode::Disabled),
|
(Some(FastMode::Default), Some(FastMode::Default)),
|
||||||
(FastMode::Enabled, FastMode::Disabled),
|
(Some(FastMode::Enabled), Some(FastMode::Enabled)),
|
||||||
(FastMode::Ultrafast, FastMode::Ultrafast),
|
(Some(FastMode::Disabled), Some(FastMode::Disabled)),
|
||||||
(FastMode::Enabled, FastMode::Ultrafast),
|
(Some(FastMode::Enabled), Some(FastMode::Disabled)),
|
||||||
(FastMode::Disabled, FastMode::Default),
|
(Some(FastMode::Ultrafast), Some(FastMode::Ultrafast)),
|
||||||
|
(Some(FastMode::Enabled), Some(FastMode::Ultrafast)),
|
||||||
|
(Some(FastMode::Disabled), Some(FastMode::Default)),
|
||||||
|
(Some(FastMode::Enabled), None),
|
||||||
] {
|
] {
|
||||||
let snapshot = gateway_core::routing::RuntimeSnapshot::new(
|
let snapshot = gateway_core::routing::RuntimeSnapshot::new(
|
||||||
ConfigRevision::new(1).unwrap(),
|
ConfigRevision::new(1).unwrap(),
|
||||||
@@ -43,8 +46,7 @@ async fn middleware_preserves_fast_modes_and_sources() {
|
|||||||
let settings = settings.replace_execution(&seed, "seed").unwrap();
|
let settings = settings.replace_execution(&seed, "seed").unwrap();
|
||||||
let wire = serde_json::to_value(&seed).unwrap();
|
let wire = serde_json::to_value(&seed).unwrap();
|
||||||
let mut updated = wire.clone();
|
let mut updated = wire.clone();
|
||||||
updated["fast_mode"] = json!(expected.as_str());
|
updated["fast_mode"] = json!(expected);
|
||||||
updated["timeout_ms"] = json!(90_000);
|
|
||||||
let contribution = crate::support::contribution(
|
let contribution = crate::support::contribution(
|
||||||
Capability::Middleware,
|
Capability::Middleware,
|
||||||
vec![Stage::Request],
|
vec![Stage::Request],
|
||||||
@@ -61,8 +63,8 @@ async fn middleware_preserves_fast_modes_and_sources() {
|
|||||||
id: "fast-settings",
|
id: "fast-settings",
|
||||||
configuration: json!({
|
configuration: json!({
|
||||||
"mode":"settings", "expected_settings":wire, "settings":updated,
|
"mode":"settings", "expected_settings":wire, "settings":updated,
|
||||||
"expected_fast_source": if mode == FastMode::Default { Value::Null } else {
|
"expected_fast_source": if mode.is_none() { Value::Null } else {
|
||||||
json!({"instance_id":"seed", "order":1, "value":mode.as_str()})
|
json!({"instance_id":"seed", "order":1, "value":mode})
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
bindings: vec![binding(
|
bindings: vec![binding(
|
||||||
@@ -102,11 +104,11 @@ async fn middleware_preserves_fast_modes_and_sources() {
|
|||||||
assert_eq!(settings.execution_values().unwrap().fast_mode, expected);
|
assert_eq!(settings.execution_values().unwrap().fast_mode, expected);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
settings.execution_values().unwrap().timeout_ms,
|
settings.execution_values().unwrap().timeout_ms,
|
||||||
Some(90_000)
|
Some(60_000)
|
||||||
);
|
);
|
||||||
let sources = settings.inspect();
|
let sources = settings.inspect();
|
||||||
let fast_source = &sources["execution"]["fast_mode"];
|
let fast_source = &sources["execution"]["fast_mode"];
|
||||||
if mode == FastMode::Default && expected == FastMode::Default {
|
if mode.is_none() && expected.is_none() {
|
||||||
assert!(fast_source.is_null());
|
assert!(fast_source.is_null());
|
||||||
} else {
|
} else {
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
@@ -117,12 +119,9 @@ async fn middleware_preserves_fast_modes_and_sources() {
|
|||||||
"fast-settings"
|
"fast-settings"
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
assert_eq!(fast_source["value"], expected.as_str());
|
assert_eq!(fast_source["value"], json!(expected));
|
||||||
}
|
}
|
||||||
assert_eq!(
|
assert!(sources["execution"]["timeout_ms"].is_null());
|
||||||
sources["execution"]["timeout_ms"]["instance_id"],
|
|
||||||
"fast-settings"
|
|
||||||
);
|
|
||||||
next.run(request).await
|
next.run(request).await
|
||||||
})
|
})
|
||||||
}),
|
}),
|
||||||
|
|||||||
@@ -628,6 +628,7 @@ fn candidate(id: &str, weight: u16) -> AccountCandidate {
|
|||||||
.with_scheduling(None, AccountWeight::new(weight).unwrap()),
|
.with_scheduling(None, AccountWeight::new(weight).unwrap()),
|
||||||
signals: AccountRuntimeSignals {
|
signals: AccountRuntimeSignals {
|
||||||
in_flight: 0,
|
in_flight: 0,
|
||||||
|
recent_requests: 0,
|
||||||
last_started_at: None,
|
last_started_at: None,
|
||||||
quota_reset_at: None,
|
quota_reset_at: None,
|
||||||
quota_reset_windows: None,
|
quota_reset_windows: None,
|
||||||
@@ -1276,7 +1277,7 @@ async fn real_request_plugins_rewrite_settings_in_onion_order() {
|
|||||||
let baseline = ExecutionSettings {
|
let baseline = ExecutionSettings {
|
||||||
runtime: SettingsValues::new(3, "smart", BTreeMap::new(), None, None)
|
runtime: SettingsValues::new(3, "smart", BTreeMap::new(), None, None)
|
||||||
.with_request_profiles(profiles("key-default")),
|
.with_request_profiles(profiles("key-default")),
|
||||||
fast_mode: FastMode::Disabled,
|
fast_mode: Some(FastMode::Disabled),
|
||||||
client_limits: RateLimits {
|
client_limits: RateLimits {
|
||||||
max_concurrency: 2,
|
max_concurrency: 2,
|
||||||
requests_per_minute: 10,
|
requests_per_minute: 10,
|
||||||
@@ -1313,7 +1314,7 @@ async fn real_request_plugins_rewrite_settings_in_onion_order() {
|
|||||||
gateway_core::routing::ClientRoutingScope::all_accounts(),
|
gateway_core::routing::ClientRoutingScope::all_accounts(),
|
||||||
)
|
)
|
||||||
.with_request_profiles(profiles("key-default"))
|
.with_request_profiles(profiles("key-default"))
|
||||||
.with_fast_mode(baseline.fast_mode),
|
.with_fast_mode_override(baseline.fast_mode),
|
||||||
),
|
),
|
||||||
true,
|
true,
|
||||||
baseline.client_limits,
|
baseline.client_limits,
|
||||||
|
|||||||
@@ -179,7 +179,6 @@ fn context_with_body_limit(
|
|||||||
ClientApiKeyId::new(key).unwrap(),
|
ClientApiKeyId::new(key).unwrap(),
|
||||||
)
|
)
|
||||||
.with_upstream_adapters(runtime.execution_registry().upstream_adapters(generation))
|
.with_upstream_adapters(runtime.execution_registry().upstream_adapters(generation))
|
||||||
.with_fast_mode(mode)
|
|
||||||
.with_request_body_limit(bytes),
|
.with_request_body_limit(bytes),
|
||||||
NonZeroU32::new(1).unwrap(),
|
NonZeroU32::new(1).unwrap(),
|
||||||
SystemTime::now() + Duration::from_secs(5),
|
SystemTime::now() + Duration::from_secs(5),
|
||||||
@@ -187,7 +186,13 @@ fn context_with_body_limit(
|
|||||||
gateway_core::account::RotationStrategy::RoundRobin,
|
gateway_core::account::RotationStrategy::RoundRobin,
|
||||||
std::num::NonZeroU32::new(1).unwrap(),
|
std::num::NonZeroU32::new(1).unwrap(),
|
||||||
),
|
),
|
||||||
AccountAttemptContext::new(Default::default(), None, None),
|
AccountAttemptContext::new(Default::default(), None, None).with_account_scope(Arc::new(
|
||||||
|
gateway_core::routing::FrozenAccountScope::new(
|
||||||
|
Arc::default(),
|
||||||
|
gateway_core::routing::ClientRoutingScope::all_accounts(),
|
||||||
|
)
|
||||||
|
.with_fast_mode_override(Some(mode)),
|
||||||
|
)),
|
||||||
None,
|
None,
|
||||||
CancellationToken::new(),
|
CancellationToken::new(),
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -588,7 +588,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
);
|
);
|
||||||
if let Some(expected) = configuration.get("expected_fast_source") {
|
if let Some(expected) = configuration.get("expected_fast_source") {
|
||||||
let sources = &call.request.head.settings_sources["execution"];
|
let sources = &call.request.head.settings_sources["execution"];
|
||||||
assert_eq!(sources["input"]["fast_mode"], "default");
|
assert!(sources["input"]["fast_mode"].is_null());
|
||||||
assert_eq!(&sources["fast_mode"], expected);
|
assert_eq!(&sources["fast_mode"], expected);
|
||||||
}
|
}
|
||||||
if let Some(settings) = configuration.get("settings") {
|
if let Some(settings) = configuration.get("settings") {
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user