mirror of
https://github.com/zyycn/codex-proxy-rs.git
synced 2026-12-03 00:00:58 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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,6 +23,9 @@
|
|||||||
|
|
||||||
普通维护和新增业务页面沿用现有设计;设计技能中的配色、字体、布局探索不覆盖项目规范,主题算法只在涉及时读取
|
普通维护和新增业务页面沿用现有设计;设计技能中的配色、字体、布局探索不覆盖项目规范,主题算法只在涉及时读取
|
||||||
|
|
||||||
|
- 页面和组件不添加浏览器原生提示的 `title` 属性。确需补充说明时,按内容复用已有的 Tooltip 或 Popover
|
||||||
|
- 列表行需要快速展示少量字段时,先核对列表接口已返回的字段和后端查询已读取的数据。能随当前页低成本返回的字段直接用于展示,完整详情在用户打开详情时加载
|
||||||
|
|
||||||
## 验收范围与收尾
|
## 验收范围与收尾
|
||||||
|
|
||||||
验证前按[界面验证](../../../../CONTRIBUTING.md#界面验证)明确本次受影响的用户路径、状态和通过条件。局部修改围绕受影响区域及相关操作验收;主题、窗口尺寸和空/加载/错误状态仅在受影响时补充,共用主题或基础组件变更按主题规范扩大范围
|
验证前按[界面验证](../../../../CONTRIBUTING.md#界面验证)明确本次受影响的用户路径、状态和通过条件。局部修改围绕受影响区域及相关操作验收;主题、窗口尺寸和空/加载/错误状态仅在受影响时补充,共用主题或基础组件变更按主题规范扩大范围
|
||||||
|
|||||||
@@ -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
|
||||||
|
|||||||
@@ -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>,
|
||||||
/// 仅账号维度补充当前互联识别结果
|
/// 仅账号维度补充当前互联识别结果
|
||||||
|
|||||||
@@ -54,7 +54,7 @@ pub struct SystemVersion {
|
|||||||
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 +67,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,
|
||||||
|
|||||||
@@ -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,
|
||||||
|
|||||||
@@ -32,7 +32,7 @@ impl SystemOperations for RecordingSystemOperations {
|
|||||||
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 +50,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>,
|
||||||
|
|||||||
@@ -86,7 +86,7 @@ struct SystemVersionView {
|
|||||||
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>,
|
||||||
@@ -114,7 +114,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)
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ 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 +109,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 +140,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 +162,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;
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -830,7 +830,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 +896,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 +942,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 +979,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())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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(),
|
||||||
),
|
),
|
||||||
|
|||||||
@@ -173,8 +173,13 @@ 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");
|
headers.remove("x-request-id");
|
||||||
|
|||||||
@@ -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");
|
||||||
|
|||||||
@@ -216,7 +216,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(),
|
||||||
|
|||||||
@@ -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 {
|
||||||
|
|||||||
@@ -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"));
|
||||||
|
|||||||
@@ -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");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -720,7 +720,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 +731,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]
|
||||||
|
|||||||
@@ -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,
|
||||||
|
|||||||
@@ -96,7 +96,7 @@ impl SystemOperations for VersionSystem {
|
|||||||
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
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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|
|
||||||
|
|||||||
@@ -1480,7 +1480,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();
|
||||||
|
|||||||
@@ -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;
|
||||||
|
|||||||
@@ -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);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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");
|
||||||
|
}
|
||||||
|
|||||||
@@ -2525,11 +2525,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 +2624,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 {
|
||||||
|
|||||||
@@ -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,
|
||||||
@@ -3509,8 +3510,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 +3550,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 +3692,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 +3722,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 +4068,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(
|
||||||
|
|||||||
@@ -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));
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -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,
|
||||||
|
|||||||
@@ -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)))
|
||||||
|
|||||||
@@ -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),
|
||||||
|
|||||||
@@ -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);
|
||||||
|
|||||||
@@ -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);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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,
|
||||||
|
|||||||
@@ -1,5 +1,8 @@
|
|||||||
//! 跨协议 HTTP 传输、下游环境头分类与重试时间解析
|
//! 跨协议 HTTP 传输、下游环境头分类与重试时间解析
|
||||||
|
|
||||||
|
/// 上游可交给客户端的秒级与毫秒级重试等待头
|
||||||
|
pub const RETRY_AFTER_HEADERS: [&str; 2] = ["retry-after", "retry-after-ms"];
|
||||||
|
|
||||||
/// 解析 HTTP 和流内错误共用的 Retry-After,保留零延迟并向上取整剩余秒数
|
/// 解析 HTTP 和流内错误共用的 Retry-After,保留零延迟并向上取整剩余秒数
|
||||||
pub fn parse_retry_after_seconds(value: &str) -> Option<u64> {
|
pub fn parse_retry_after_seconds(value: &str) -> Option<u64> {
|
||||||
let now = std::time::SystemTime::now();
|
let now = std::time::SystemTime::now();
|
||||||
|
|||||||
@@ -228,12 +228,32 @@ fn retry_after_seconds_field(value: &Value) -> Option<u64> {
|
|||||||
|
|
||||||
/// 同时保留原始头值与解析秒数,供事件转换和重试观测共用官方头部规则
|
/// 同时保留原始头值与解析秒数,供事件转换和重试观测共用官方头部规则
|
||||||
pub(super) fn retry_after_header(value: &Value) -> Option<(&Value, u64)> {
|
pub(super) fn retry_after_header(value: &Value) -> Option<(&Value, u64)> {
|
||||||
|
let (value, header) = event_header(value, "retry-after")?;
|
||||||
|
let seconds = crate::http::parse_retry_after_seconds(header.to_str().ok()?)?;
|
||||||
|
Some((value, seconds))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 从客户端可见的错误事件读取指定头,嵌套错误优先于事件头
|
||||||
|
pub fn error_event_header(event: &Value, name: &str) -> Option<http::HeaderValue> {
|
||||||
|
let error = event
|
||||||
|
.pointer("/response/error")
|
||||||
|
.or_else(|| event.get("error"));
|
||||||
|
error
|
||||||
|
.and_then(|error| event_header(error, name))
|
||||||
|
.or_else(|| event_header(event, name))
|
||||||
|
.map(|(_, header)| header)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn event_header<'a>(
|
||||||
|
value: &'a Value,
|
||||||
|
wanted: &str,
|
||||||
|
) -> Option<(&'a Value, http::HeaderValue)> {
|
||||||
let headers = value.get("headers")?.as_object()?;
|
let headers = value.get("headers")?.as_object()?;
|
||||||
// 官方先按 HTTP 头值校验,再覆盖大小写不同的同名头;最后才解释重试时间
|
// 官方先按 HTTP 头值校验,再覆盖大小写不同的同名头;最后才解释重试时间
|
||||||
// 合法但无法解析为时间的末项也会覆盖前值,非法头值和数组不参与覆盖
|
// 合法但无法解析为时间的末项也会覆盖前值,非法头值和数组不参与覆盖
|
||||||
let (value, header) = headers
|
headers
|
||||||
.iter()
|
.iter()
|
||||||
.filter(|(name, _)| name.eq_ignore_ascii_case("retry-after"))
|
.filter(|(name, _)| name.eq_ignore_ascii_case(wanted))
|
||||||
.filter_map(|(_, value)| {
|
.filter_map(|(_, value)| {
|
||||||
let header = match value {
|
let header = match value {
|
||||||
Value::String(value) => http::HeaderValue::from_str(value).ok(),
|
Value::String(value) => http::HeaderValue::from_str(value).ok(),
|
||||||
@@ -244,9 +264,7 @@ pub(super) fn retry_after_header(value: &Value) -> Option<(&Value, u64)> {
|
|||||||
}?;
|
}?;
|
||||||
Some((value, header))
|
Some((value, header))
|
||||||
})
|
})
|
||||||
.next_back()?;
|
.next_back()
|
||||||
let seconds = crate::http::parse_retry_after_seconds(header.to_str().ok()?)?;
|
|
||||||
Some((value, seconds))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 判断上游错误是否携带 `x-retry-metadata: NO_MORE_RETRY`
|
/// 判断上游错误是否携带 `x-retry-metadata: NO_MORE_RETRY`
|
||||||
|
|||||||
@@ -322,9 +322,18 @@ pub fn response_failed_sse_data_from_error_event(
|
|||||||
let mut error = event.remove("error").filter(Value::is_object)?;
|
let mut error = event.remove("error").filter(Value::is_object)?;
|
||||||
// 官方 WS 先读错误头、再读事件头,SSE 只读 response.error.headers
|
// 官方 WS 先读错误头、再读事件头,SSE 只读 response.error.headers
|
||||||
// 仅补充有效的等待建议,保留原始日期或秒数,不复制其他事件级响应头
|
// 仅补充有效的等待建议,保留原始日期或秒数,不复制其他事件级响应头
|
||||||
if super::events::retry_after_header(&error).is_none()
|
let seconds = super::events::retry_after_header(&error)
|
||||||
&& let Some((retry_after, _)) = super::events::retry_after_header(error_event)
|
.is_none()
|
||||||
{
|
.then(|| super::events::retry_after_header(error_event))
|
||||||
|
.flatten()
|
||||||
|
.map(|(value, _)| value);
|
||||||
|
let millis = super::events::event_header(&error, "retry-after-ms")
|
||||||
|
.is_none()
|
||||||
|
.then(|| super::events::event_header(error_event, "retry-after-ms"))
|
||||||
|
.flatten()
|
||||||
|
.map(|(value, _)| value);
|
||||||
|
for (name, value) in [("retry-after", seconds), ("retry-after-ms", millis)] {
|
||||||
|
let Some(value) = value else { continue };
|
||||||
let headers = error
|
let headers = error
|
||||||
.as_object_mut()?
|
.as_object_mut()?
|
||||||
.entry("headers")
|
.entry("headers")
|
||||||
@@ -333,8 +342,8 @@ pub fn response_failed_sse_data_from_error_event(
|
|||||||
*headers = json!({});
|
*headers = json!({});
|
||||||
}
|
}
|
||||||
let headers = headers.as_object_mut()?;
|
let headers = headers.as_object_mut()?;
|
||||||
headers.retain(|name, _| !name.eq_ignore_ascii_case("retry-after"));
|
headers.retain(|key, _| !key.eq_ignore_ascii_case(name));
|
||||||
headers.insert("retry-after".to_owned(), retry_after.clone());
|
headers.insert(name.to_owned(), value.clone());
|
||||||
}
|
}
|
||||||
let mut response = response
|
let mut response = response
|
||||||
.and_then(Value::as_object)
|
.and_then(Value::as_object)
|
||||||
|
|||||||
@@ -301,6 +301,21 @@ async fn connect(
|
|||||||
oauth_pending,
|
oauth_pending,
|
||||||
diagnostics.clone(),
|
diagnostics.clone(),
|
||||||
);
|
);
|
||||||
|
let recent_requests = if matches!(mode, StoreMode::Runtime) && !read_only {
|
||||||
|
let persistence = gateway_core::engine::RecentRequestPersistence::new(
|
||||||
|
provider_ports.account_feedback(),
|
||||||
|
Arc::new(redis::RedisRecentRequestRepository::new(
|
||||||
|
redis_connection.clone(),
|
||||||
|
REDIS_NAMESPACE,
|
||||||
|
)?),
|
||||||
|
);
|
||||||
|
if let Err(error) = persistence.restore().await {
|
||||||
|
tracing::warn!(%error, "近期请求统计恢复失败,将重新积累");
|
||||||
|
}
|
||||||
|
Some(persistence)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
let worker_leader_lease = Arc::new(redis::worker_lease::RedisWorkerLeaderLeasePort::new(
|
let worker_leader_lease = Arc::new(redis::worker_lease::RedisWorkerLeaderLeasePort::new(
|
||||||
credential_leases,
|
credential_leases,
|
||||||
));
|
));
|
||||||
@@ -322,6 +337,7 @@ async fn connect(
|
|||||||
admission_release_writer,
|
admission_release_writer,
|
||||||
budget_writer,
|
budget_writer,
|
||||||
lease_cleanup,
|
lease_cleanup,
|
||||||
|
recent_requests,
|
||||||
)?,
|
)?,
|
||||||
None,
|
None,
|
||||||
),
|
),
|
||||||
|
|||||||
@@ -634,6 +634,7 @@ impl<'a> AnalyticsSnapshot<'a> {
|
|||||||
observations.push(DiagnosticObservation {
|
observations.push(DiagnosticObservation {
|
||||||
key: key.clone(),
|
key: key.clone(),
|
||||||
name: key,
|
name: key,
|
||||||
|
account_email: None,
|
||||||
providers: state.providers.iter().cloned().collect(),
|
providers: state.providers.iter().cloned().collect(),
|
||||||
platform_icon: None,
|
platform_icon: None,
|
||||||
account_authentication_kind: None,
|
account_authentication_kind: None,
|
||||||
@@ -672,9 +673,29 @@ impl<'a> AnalyticsSnapshot<'a> {
|
|||||||
.map(|item| item.key.clone())
|
.map(|item| item.key.clone())
|
||||||
.collect::<Vec<_>>();
|
.collect::<Vec<_>>();
|
||||||
let statement = if dimension == DiagnosticDimension::Account {
|
let statement = if dimension == DiagnosticDimension::Account {
|
||||||
"select requested.id, coalesce(historical.provider_kind,a.provider_kind) as provider_kind, a.platform_icon, historical.provider_account_authentication_kind_snapshot as authentication_kind, historical.provider_account_plan_type_snapshot as plan_type, historical.provider_account_plan_type_display_snapshot as plan_type_display, coalesce(historical.provider_account_email_snapshot,historical.provider_account_name_snapshot,requested.id) as name from unnest($1::text[]) requested(id) left join provider_accounts a on a.id=requested.id left join lateral (select provider_kind,provider_account_authentication_kind_snapshot,provider_account_plan_type_snapshot,provider_account_plan_type_display_snapshot,provider_account_email_snapshot,provider_account_name_snapshot from model_request_observations mr where mr.provider_account_ref=requested.id order by mr.started_at desc,mr.id desc limit 1) historical on true"
|
"select requested.id, coalesce(h.provider_kind, a.provider_kind) as provider_kind,
|
||||||
|
a.platform_icon, h.authentication_kind, h.plan_type, h.plan_type_display,
|
||||||
|
coalesce(h.account_name, h.account_email, requested.id) as name, h.account_email
|
||||||
|
from unnest($1::text[]) requested(id)
|
||||||
|
left join provider_accounts a on a.id = requested.id
|
||||||
|
left join lateral (
|
||||||
|
select provider_kind, provider_account_authentication_kind_snapshot as authentication_kind,
|
||||||
|
provider_account_plan_type_snapshot as plan_type,
|
||||||
|
provider_account_plan_type_display_snapshot as plan_type_display,
|
||||||
|
nullif(btrim(provider_account_name_snapshot), '') as account_name,
|
||||||
|
nullif(btrim(provider_account_email_snapshot), '') as account_email
|
||||||
|
from model_request_observations where provider_account_ref = requested.id
|
||||||
|
order by started_at desc, id desc limit 1
|
||||||
|
) h on true"
|
||||||
} else {
|
} else {
|
||||||
"select requested.id, null::text as provider_kind, null::text as platform_icon, null::text as authentication_kind, null::text as plan_type, null::text as plan_type_display, coalesce(historical.client_api_key_name_snapshot,requested.id) as name from unnest($1::text[]) requested(id) left join lateral (select client_api_key_name_snapshot from model_request_observations mr where mr.client_api_key_ref=requested.id order by mr.started_at desc,mr.id desc limit 1) historical on true"
|
"select requested.id, null::text as provider_kind, null::text as platform_icon,
|
||||||
|
null::text as authentication_kind, null::text as plan_type, null::text as plan_type_display,
|
||||||
|
coalesce(h.client_api_key_name_snapshot, requested.id) as name, null::text as account_email
|
||||||
|
from unnest($1::text[]) requested(id)
|
||||||
|
left join lateral (
|
||||||
|
select client_api_key_name_snapshot from model_request_observations
|
||||||
|
where client_api_key_ref = requested.id order by started_at desc, id desc limit 1
|
||||||
|
) h on true"
|
||||||
};
|
};
|
||||||
let labels = sqlx::query(statement)
|
let labels = sqlx::query(statement)
|
||||||
.bind(ids)
|
.bind(ids)
|
||||||
@@ -685,6 +706,7 @@ impl<'a> AnalyticsSnapshot<'a> {
|
|||||||
let id: String = get(&row, "id")?;
|
let id: String = get(&row, "id")?;
|
||||||
if let Some(item) = observations.iter_mut().find(|item| item.key == id) {
|
if let Some(item) = observations.iter_mut().find(|item| item.key == id) {
|
||||||
item.name = get(&row, "name")?;
|
item.name = get(&row, "name")?;
|
||||||
|
item.account_email = get(&row, "account_email")?;
|
||||||
item.providers = get::<Option<String>>(&row, "provider_kind")?
|
item.providers = get::<Option<String>>(&row, "provider_kind")?
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.collect();
|
.collect();
|
||||||
|
|||||||
@@ -280,6 +280,7 @@ fn admin_diagnostic_observation(
|
|||||||
admin_observability::DiagnosticObservation {
|
admin_observability::DiagnosticObservation {
|
||||||
key: observation.key,
|
key: observation.key,
|
||||||
name: observation.name,
|
name: observation.name,
|
||||||
|
account_email: observation.account_email,
|
||||||
providers: observation.providers,
|
providers: observation.providers,
|
||||||
platform_icon: observation.platform_icon,
|
platform_icon: observation.platform_icon,
|
||||||
account_authentication_kind: observation.account_authentication_kind,
|
account_authentication_kind: observation.account_authentication_kind,
|
||||||
@@ -369,6 +370,8 @@ pub(crate) fn usage_list_record_from_row(
|
|||||||
)?;
|
)?;
|
||||||
Ok(UsageListRecord {
|
Ok(UsageListRecord {
|
||||||
has_upstream_error: get(row, "has_upstream_error")?,
|
has_upstream_error: get(row, "has_upstream_error")?,
|
||||||
|
upstream_error_message: get(row, "upstream_error_message")?,
|
||||||
|
retry_after_ms: optional_unsigned(row, "retry_after_ms")?,
|
||||||
error_code: get(row, "error_code")?,
|
error_code: get(row, "error_code")?,
|
||||||
error_message: get(row, "error_message")?,
|
error_message: get(row, "error_message")?,
|
||||||
error_kind: get(row, "error_kind")?,
|
error_kind: get(row, "error_kind")?,
|
||||||
|
|||||||
@@ -384,6 +384,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>,
|
||||||
|
|||||||
@@ -130,7 +130,7 @@ pub(crate) fn push_usage_filter(
|
|||||||
pub(crate) const USAGE_LIST_RECORD_SELECT: &str =
|
pub(crate) const USAGE_LIST_RECORD_SELECT: &str =
|
||||||
"select mr.id, mr.outcome, mr.provider_error_code as error_code, mr.error_message, mr.client_status_code, mr.client_api_key_name_snapshot as client_api_key_name, mr.endpoint, mr.client_transport, mr.requested_model_id,
|
"select mr.id, mr.outcome, mr.provider_error_code as error_code, mr.error_message, mr.client_status_code, mr.client_api_key_name_snapshot as client_api_key_name, mr.endpoint, mr.client_transport, mr.requested_model_id,
|
||||||
mr.error_kind, mr.upstream_status_code,
|
mr.error_kind, mr.upstream_status_code,
|
||||||
facts.has_upstream_error, facts.websocket_close_code,
|
facts.has_upstream_error, facts.websocket_close_code, facts.upstream_error_message, mr.retry_after_ms,
|
||||||
mr.continuation_unavailable_reason, mr.upstream_connection_exit_reason,
|
mr.continuation_unavailable_reason, mr.upstream_connection_exit_reason,
|
||||||
(mr.recovery_request_id is not null and mr.recovered_at is not null) as recovered,
|
(mr.recovery_request_id is not null and mr.recovered_at is not null) as recovered,
|
||||||
mr.provider_kind, mr.provider_account_ref,
|
mr.provider_kind, mr.provider_account_ref,
|
||||||
@@ -166,6 +166,13 @@ const SAVED_ERROR_FACTS: &str = "(select exists (
|
|||||||
) as field(value)
|
) as field(value)
|
||||||
where jsonb_typeof(field.value) = 'string' and field.value <> '\"\"'::jsonb
|
where jsonb_typeof(field.value) = 'string' and field.value <> '\"\"'::jsonb
|
||||||
) as has_upstream_error,
|
) as has_upstream_error,
|
||||||
|
coalesce(
|
||||||
|
case when jsonb_typeof(saved_error.body -> 'message') = 'string'
|
||||||
|
then nullif(saved_error.body ->> 'message', '') end,
|
||||||
|
case when saved_upstream.body ->> 'type' = 'websocket.close'
|
||||||
|
and jsonb_typeof(saved_upstream.body -> 'reason') = 'string'
|
||||||
|
then nullif(saved_upstream.body ->> 'reason', '') end
|
||||||
|
) as upstream_error_message,
|
||||||
case when saved_upstream.body ->> 'type' = 'websocket.close'
|
case when saved_upstream.body ->> 'type' = 'websocket.close'
|
||||||
and jsonb_typeof(saved_upstream.body -> 'code') = 'number'
|
and jsonb_typeof(saved_upstream.body -> 'code') = 'number'
|
||||||
and (saved_upstream.body ->> 'code') ~ '^[0-9]{1,5}$'
|
and (saved_upstream.body ->> 'code') ~ '^[0-9]{1,5}$'
|
||||||
|
|||||||
@@ -253,7 +253,9 @@ fn admin_account_order(sort: Option<AdminAccountSort>) -> String {
|
|||||||
return "a.id asc".to_owned();
|
return "a.id asc".to_owned();
|
||||||
};
|
};
|
||||||
let expression = match sort.field {
|
let expression = match sort.field {
|
||||||
AdminAccountSortField::Email => "a.email",
|
AdminAccountSortField::Name => {
|
||||||
|
"lower(coalesce(nullif(btrim(a.name), ''), nullif(btrim(a.email), ''), a.upstream_account_id, a.id))"
|
||||||
|
}
|
||||||
AdminAccountSortField::Status => {
|
AdminAccountSortField::Status => {
|
||||||
"case filtered.admin_status when 'normal' then 0 when 'rate_limited' then 1 when 'quota_exhausted' then 2 when 'quota_paused' then 3 when 'error' then 4 else 5 end"
|
"case filtered.admin_status when 'normal' then 0 when 'rate_limited' then 1 when 'quota_exhausted' then 2 when 'quota_paused' then 3 when 'error' then 4 else 5 end"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -674,6 +674,7 @@ impl RedisProviderLeaseCoordinator {
|
|||||||
account,
|
account,
|
||||||
AccountRuntimeSignals {
|
AccountRuntimeSignals {
|
||||||
in_flight: signal.in_flight,
|
in_flight: signal.in_flight,
|
||||||
|
recent_requests: 0,
|
||||||
last_started_at: signal.last_started_at.map(Into::into),
|
last_started_at: signal.last_started_at.map(Into::into),
|
||||||
quota_reset_at: None,
|
quota_reset_at: None,
|
||||||
quota_reset_windows: None,
|
quota_reset_windows: None,
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ mod native_continuation;
|
|||||||
mod oauth_pending;
|
mod oauth_pending;
|
||||||
mod provider_session_affinity;
|
mod provider_session_affinity;
|
||||||
mod provider_session_exclusion;
|
mod provider_session_exclusion;
|
||||||
|
mod recent_requests;
|
||||||
mod runtime_change;
|
mod runtime_change;
|
||||||
pub(crate) mod worker_lease;
|
pub(crate) mod worker_lease;
|
||||||
|
|
||||||
@@ -32,6 +33,7 @@ pub use native_continuation::*;
|
|||||||
pub use oauth_pending::*;
|
pub use oauth_pending::*;
|
||||||
pub use provider_session_affinity::*;
|
pub use provider_session_affinity::*;
|
||||||
pub use provider_session_exclusion::*;
|
pub use provider_session_exclusion::*;
|
||||||
|
pub use recent_requests::*;
|
||||||
pub use runtime_change::*;
|
pub use runtime_change::*;
|
||||||
|
|
||||||
use crate::{StoreError, StoreResult, require_nonempty};
|
use crate::{StoreError, StoreResult, require_nonempty};
|
||||||
|
|||||||
@@ -0,0 +1,69 @@
|
|||||||
|
//! 原子替换单进程近期请求快照并设置过期时间
|
||||||
|
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use futures::future::BoxFuture;
|
||||||
|
use gateway_core::account::{RecentRequestSnapshot, RecentRequestStore};
|
||||||
|
use gateway_core::error::{StoreError as CoreStoreError, StoreErrorKind};
|
||||||
|
use redis::aio::ConnectionManager;
|
||||||
|
|
||||||
|
use super::namespace;
|
||||||
|
use crate::StoreResult;
|
||||||
|
|
||||||
|
pub struct RedisRecentRequestRepository {
|
||||||
|
connection: ConnectionManager,
|
||||||
|
key: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RedisRecentRequestRepository {
|
||||||
|
pub fn new(connection: ConnectionManager, key_namespace: &str) -> StoreResult<Self> {
|
||||||
|
Ok(Self {
|
||||||
|
connection,
|
||||||
|
key: format!("{}:scheduler:recent-requests:v1", namespace(key_namespace)?),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RecentRequestStore for RedisRecentRequestRepository {
|
||||||
|
fn load(&self) -> BoxFuture<'_, Result<Option<RecentRequestSnapshot>, CoreStoreError>> {
|
||||||
|
Box::pin(async move {
|
||||||
|
let mut connection = self.connection.clone();
|
||||||
|
let value: Option<Vec<u8>> = redis::cmd("GET")
|
||||||
|
.arg(&self.key)
|
||||||
|
.query_async(&mut connection)
|
||||||
|
.await
|
||||||
|
.map_err(unavailable)?;
|
||||||
|
value
|
||||||
|
.map(|bytes| {
|
||||||
|
serde_json::from_slice(&bytes).map_err(|error| {
|
||||||
|
CoreStoreError::caused_by(StoreErrorKind::InvalidData, error)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.transpose()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn save<'a>(
|
||||||
|
&'a self,
|
||||||
|
snapshot: &'a RecentRequestSnapshot,
|
||||||
|
ttl: Duration,
|
||||||
|
) -> BoxFuture<'a, Result<(), CoreStoreError>> {
|
||||||
|
Box::pin(async move {
|
||||||
|
let value = serde_json::to_vec(snapshot)
|
||||||
|
.map_err(|error| CoreStoreError::caused_by(StoreErrorKind::InvalidData, error))?;
|
||||||
|
let mut connection = self.connection.clone();
|
||||||
|
redis::cmd("SET")
|
||||||
|
.arg(&self.key)
|
||||||
|
.arg(value)
|
||||||
|
.arg("PX")
|
||||||
|
.arg(u64::try_from(ttl.as_millis()).unwrap_or(u64::MAX))
|
||||||
|
.query_async::<()>(&mut connection)
|
||||||
|
.await
|
||||||
|
.map_err(unavailable)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn unavailable(error: redis::RedisError) -> CoreStoreError {
|
||||||
|
CoreStoreError::caused_by(StoreErrorKind::Unavailable, error)
|
||||||
|
}
|
||||||
@@ -106,6 +106,7 @@ pub(crate) fn store_worker_contributions(
|
|||||||
admission_release_writer: redis::ClientAdmissionReleaseWriter,
|
admission_release_writer: redis::ClientAdmissionReleaseWriter,
|
||||||
budget_writer: postgres::ClientBudgetWriter,
|
budget_writer: postgres::ClientBudgetWriter,
|
||||||
lease_cleanup: impl DaemonTask + 'static,
|
lease_cleanup: impl DaemonTask + 'static,
|
||||||
|
recent_requests: Option<gateway_core::engine::RecentRequestPersistence>,
|
||||||
) -> StoreResult<Vec<WorkerContribution>> {
|
) -> StoreResult<Vec<WorkerContribution>> {
|
||||||
let stale_id = WorkerId::try_new(WorkerKind::StaleModelRequestRecovery, "postgres")
|
let stale_id = WorkerId::try_new(WorkerKind::StaleModelRequestRecovery, "postgres")
|
||||||
.map_err(worker_definition_error)?;
|
.map_err(worker_definition_error)?;
|
||||||
@@ -123,7 +124,7 @@ pub(crate) fn store_worker_contributions(
|
|||||||
let ops_flush_restart =
|
let ops_flush_restart =
|
||||||
DaemonRestartPolicy::try_new(Duration::from_secs(1), Duration::from_secs(60))
|
DaemonRestartPolicy::try_new(Duration::from_secs(1), Duration::from_secs(60))
|
||||||
.map_err(worker_definition_error)?;
|
.map_err(worker_definition_error)?;
|
||||||
Ok(vec![
|
let mut contributions = vec![
|
||||||
WorkerContribution::Registration(
|
WorkerContribution::Registration(
|
||||||
WorkerRegistration::try_new(
|
WorkerRegistration::try_new(
|
||||||
lease_cleanup_id,
|
lease_cleanup_id,
|
||||||
@@ -179,7 +180,21 @@ pub(crate) fn store_worker_contributions(
|
|||||||
)
|
)
|
||||||
.map_err(worker_definition_error)?,
|
.map_err(worker_definition_error)?,
|
||||||
),
|
),
|
||||||
])
|
];
|
||||||
|
if let Some(persistence) = recent_requests {
|
||||||
|
contributions.push(WorkerContribution::Registration(
|
||||||
|
WorkerRegistration::try_new(
|
||||||
|
WorkerId::try_new(WorkerKind::OpsFlush, "redis_account_load")
|
||||||
|
.map_err(worker_definition_error)?,
|
||||||
|
WorkerRunnable::Daemon {
|
||||||
|
restart: ops_flush_restart,
|
||||||
|
task: Box::new(persistence),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.map_err(worker_definition_error)?,
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Ok(contributions)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn scheduled_worker(
|
pub(crate) fn scheduled_worker(
|
||||||
|
|||||||
@@ -125,7 +125,7 @@ async fn usage_error_origins_agree_for_saved_errors_without_failure_status() {
|
|||||||
"update model_requests
|
"update model_requests
|
||||||
set client_status_code = 200, upstream_status_code = 200, error_kind = 'unavailable',
|
set client_status_code = 200, upstream_status_code = 200, error_kind = 'unavailable',
|
||||||
request_observation_json = jsonb_set(request_observation_json, '{error}',
|
request_observation_json = jsonb_set(request_observation_json, '{error}',
|
||||||
'{\"message\":\"Upstream error summary\"}'::jsonb)
|
'{\"message\":\"Upstream error summary\",\"retryAfterMs\":30000}'::jsonb)
|
||||||
where id = 'req_observe_failed'",
|
where id = 'req_observe_failed'",
|
||||||
)
|
)
|
||||||
.execute(&database.pool)
|
.execute(&database.pool)
|
||||||
@@ -191,6 +191,13 @@ async fn usage_error_origins_agree_for_saved_errors_without_failure_status() {
|
|||||||
assert_eq!(detail.request.provider_error_code, None);
|
assert_eq!(detail.request.provider_error_code, None);
|
||||||
assert_eq!(list.client_status_code, Some(200));
|
assert_eq!(list.client_status_code, Some(200));
|
||||||
assert_eq!(list.upstream_status_code, Some(200));
|
assert_eq!(list.upstream_status_code, Some(200));
|
||||||
|
let expected_message = error
|
||||||
|
.get("message")
|
||||||
|
.and_then(serde_json::Value::as_str)
|
||||||
|
.filter(|value| !value.is_empty());
|
||||||
|
assert_eq!(list.upstream_error_message.as_deref(), expected_message);
|
||||||
|
assert_eq!(list.retry_after_ms, Some(30_000));
|
||||||
|
assert_eq!(list.retry_after_ms, detail.request.retry_after_ms);
|
||||||
assert_eq!(list.error_origin(), origin, "list: {body}");
|
assert_eq!(list.error_origin(), origin, "list: {body}");
|
||||||
assert_eq!(detail.request.error_origin(), origin, "detail: {body}");
|
assert_eq!(detail.request.error_origin(), origin, "detail: {body}");
|
||||||
}
|
}
|
||||||
@@ -437,6 +444,12 @@ async fn usage_error_facts_preserve_recovery_and_validate_saved_close_frames() {
|
|||||||
.await
|
.await
|
||||||
.expect("detail with saved error facts");
|
.expect("detail with saved error facts");
|
||||||
assert_eq!(detail.request.websocket_close_code, close_code);
|
assert_eq!(detail.request.websocket_close_code, close_code);
|
||||||
|
let close_reason = detail
|
||||||
|
.request
|
||||||
|
.upstream_error
|
||||||
|
.as_ref()
|
||||||
|
.and_then(|error| error.close_reason.as_deref());
|
||||||
|
assert_eq!(record.upstream_error_message.as_deref(), close_reason);
|
||||||
assert!(detail.request.recovered);
|
assert!(detail.request.recovered);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
detail.request.continuation_unavailable_reason,
|
detail.request.continuation_unavailable_reason,
|
||||||
@@ -2386,7 +2399,11 @@ async fn admin_observability_adapter_preserves_utc_queries_metrics_costs_and_det
|
|||||||
.expect("admin diagnostics")
|
.expect("admin diagnostics")
|
||||||
.items;
|
.items;
|
||||||
assert_eq!(diagnostics[0].key, "acct_observe");
|
assert_eq!(diagnostics[0].key, "acct_observe");
|
||||||
assert_eq!(diagnostics[0].name, "account@example.invalid");
|
assert_eq!(diagnostics[0].name, "primary");
|
||||||
|
assert_eq!(
|
||||||
|
diagnostics[0].account_email.as_deref(),
|
||||||
|
Some("account@example.invalid")
|
||||||
|
);
|
||||||
assert_eq!(diagnostics[0].cost_coverage.provider_reported_count, 1);
|
assert_eq!(diagnostics[0].cost_coverage.provider_reported_count, 1);
|
||||||
assert_eq!(diagnostics[0].costs[0].amount.as_str(), "1.25");
|
assert_eq!(diagnostics[0].costs[0].amount.as_str(), "1.25");
|
||||||
|
|
||||||
@@ -2914,7 +2931,11 @@ async fn observability_queries_preserve_request_account_cost_and_diagnostic_fact
|
|||||||
.expect("usage diagnostics")
|
.expect("usage diagnostics")
|
||||||
.items;
|
.items;
|
||||||
assert_eq!(diagnostics[0].key, "acct_observe");
|
assert_eq!(diagnostics[0].key, "acct_observe");
|
||||||
assert_eq!(diagnostics[0].name, "account@example.invalid");
|
assert_eq!(diagnostics[0].name, "primary");
|
||||||
|
assert_eq!(
|
||||||
|
diagnostics[0].account_email.as_deref(),
|
||||||
|
Some("account@example.invalid")
|
||||||
|
);
|
||||||
assert_eq!(diagnostics[0].request_count, 3);
|
assert_eq!(diagnostics[0].request_count, 3);
|
||||||
assert_eq!(diagnostics[0].success_count, 2);
|
assert_eq!(diagnostics[0].success_count, 2);
|
||||||
assert_eq!(diagnostics[0].failure_count, 1);
|
assert_eq!(diagnostics[0].failure_count, 1);
|
||||||
|
|||||||
@@ -715,14 +715,18 @@ async fn terminal_admin_list_filters_and_sorts_before_pagination_with_retained_u
|
|||||||
let now = Utc::now();
|
let now = Utc::now();
|
||||||
|
|
||||||
let mut alpha = account("acct_alpha", "user-alpha");
|
let mut alpha = account("acct_alpha", "user-alpha");
|
||||||
|
alpha.name = "Zulu".to_owned();
|
||||||
alpha.email = Some("alpha@example.invalid".to_owned());
|
alpha.email = Some("alpha@example.invalid".to_owned());
|
||||||
let mut beta = account("acct_beta", "user-beta");
|
let mut beta = account("acct_beta", "user-beta");
|
||||||
beta.provider_kind = "xai".to_owned();
|
beta.provider_kind = "xai".to_owned();
|
||||||
|
beta.name = "Team".to_owned();
|
||||||
beta.email = Some("beta@example.invalid".to_owned());
|
beta.email = Some("beta@example.invalid".to_owned());
|
||||||
beta.credential_state = CredentialState::Banned;
|
beta.credential_state = CredentialState::Banned;
|
||||||
let mut charlie = account("acct_charlie", "user-charlie");
|
let mut charlie = account("acct_charlie", "user-charlie");
|
||||||
|
charlie.name = "Team".to_owned();
|
||||||
charlie.email = Some("charlie@example.invalid".to_owned());
|
charlie.email = Some("charlie@example.invalid".to_owned());
|
||||||
let mut invalid = account("acct_invalid", "user-invalid");
|
let mut invalid = account("acct_invalid", "user-invalid");
|
||||||
|
invalid.name = " ".to_owned();
|
||||||
invalid.email = Some("invalid@example.invalid".to_owned());
|
invalid.email = Some("invalid@example.invalid".to_owned());
|
||||||
invalid.credential_state = CredentialState::Invalid;
|
invalid.credential_state = CredentialState::Invalid;
|
||||||
let mut disabled = account("acct_disabled", "user-disabled");
|
let mut disabled = account("acct_disabled", "user-disabled");
|
||||||
@@ -850,6 +854,33 @@ async fn terminal_admin_list_filters_and_sorts_before_pagination_with_retained_u
|
|||||||
["acct_charlie", "acct_beta"]
|
["acct_charlie", "acct_beta"]
|
||||||
);
|
);
|
||||||
|
|
||||||
|
let name_page = store
|
||||||
|
.list_accounts(
|
||||||
|
AccountListQuery {
|
||||||
|
page: 1,
|
||||||
|
page_size: PageSize::new(4).expect("page size"),
|
||||||
|
provider_kind: None,
|
||||||
|
group_filter: None,
|
||||||
|
search: None,
|
||||||
|
status: None,
|
||||||
|
sort: Some(AccountSort {
|
||||||
|
field: AccountSortField::Name,
|
||||||
|
direction: SortDirection::Desc,
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
Default::default(),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.expect("sort accounts by display name");
|
||||||
|
assert_eq!(
|
||||||
|
name_page
|
||||||
|
.items
|
||||||
|
.iter()
|
||||||
|
.map(|item| item.account.id.as_str())
|
||||||
|
.collect::<Vec<_>>(),
|
||||||
|
["acct_alpha", "acct_charlie", "acct_beta", "acct_invalid"]
|
||||||
|
);
|
||||||
|
|
||||||
let last_used_page = store
|
let last_used_page = store
|
||||||
.list_accounts(
|
.list_accounts(
|
||||||
AccountListQuery {
|
AccountListQuery {
|
||||||
|
|||||||
@@ -572,18 +572,17 @@ async fn diagnostics_should_group_same_email_accounts_by_stable_ref() {
|
|||||||
.await
|
.await
|
||||||
.expect("account diagnostics")
|
.expect("account diagnostics")
|
||||||
.items;
|
.items;
|
||||||
assert_eq!(diagnostics.len(), 2);
|
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
diagnostics
|
diagnostics
|
||||||
.iter()
|
.iter()
|
||||||
.map(|item| item.key.as_str())
|
.map(|item| (item.key.as_str(), item.name.as_str()))
|
||||||
.collect::<Vec<_>>(),
|
.collect::<Vec<_>>(),
|
||||||
vec!["acct_snap_a", "acct_snap_b"]
|
[("acct_snap_a", "Alpha"), ("acct_snap_b", "Beta")]
|
||||||
);
|
);
|
||||||
assert!(
|
assert!(
|
||||||
diagnostics
|
diagnostics
|
||||||
.iter()
|
.iter()
|
||||||
.all(|item| item.name == "same@example.invalid")
|
.all(|item| item.account_email.as_deref() == Some("same@example.invalid"))
|
||||||
);
|
);
|
||||||
assert!(diagnostics.iter().all(|item| item.request_count == 1));
|
assert!(diagnostics.iter().all(|item| item.request_count == 1));
|
||||||
|
|
||||||
|
|||||||
@@ -12,4 +12,5 @@ mod native_continuation;
|
|||||||
mod oauth_pending;
|
mod oauth_pending;
|
||||||
mod provider_session_affinity;
|
mod provider_session_affinity;
|
||||||
mod provider_session_exclusion;
|
mod provider_session_exclusion;
|
||||||
|
mod recent_requests;
|
||||||
mod worker_lease;
|
mod worker_lease;
|
||||||
|
|||||||
@@ -0,0 +1,163 @@
|
|||||||
|
//! 验证真实 Redis 快照替换、两分钟 TTL、重启恢复与损坏数据处理
|
||||||
|
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::time::{Duration, Instant, SystemTime};
|
||||||
|
|
||||||
|
use gateway_core::account::{AccountFeedbackStats, ProviderAccountId, RecentRequestStore};
|
||||||
|
use gateway_core::engine::RecentRequestPersistence;
|
||||||
|
use gateway_core::identity::ProviderKind;
|
||||||
|
use gateway_core::lifecycle::CancellationToken;
|
||||||
|
use gateway_core::task::{DaemonTask, WorkerDaemonContext};
|
||||||
|
use gateway_store::redis::RedisRecentRequestRepository;
|
||||||
|
use redis::aio::ConnectionManager;
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
async fn repository() -> Option<(Arc<RedisRecentRequestRepository>, ConnectionManager, String)> {
|
||||||
|
let url = crate::support::test_env("CPR_TEST_REDIS_URL")?;
|
||||||
|
let client = redis::Client::open(url).unwrap();
|
||||||
|
let connection = client.get_connection_manager().await.unwrap();
|
||||||
|
let namespace = format!("recent-requests-test-{}", Uuid::new_v4());
|
||||||
|
let key = format!("{namespace}:scheduler:recent-requests:v1");
|
||||||
|
Some((
|
||||||
|
Arc::new(RedisRecentRequestRepository::new(connection.clone(), &namespace).unwrap()),
|
||||||
|
connection,
|
||||||
|
key,
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn background_save_replaces_snapshot_and_restores_after_restart_with_two_minute_ttl() {
|
||||||
|
let Some((store, mut connection, key)) = repository().await else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
assert!(store.load().await.unwrap().is_none());
|
||||||
|
let stats = Arc::new(AccountFeedbackStats::default());
|
||||||
|
let provider = ProviderKind::new("openai").unwrap();
|
||||||
|
let account = ProviderAccountId::new("acct_persisted").unwrap();
|
||||||
|
for _ in 0..20 {
|
||||||
|
let now = Instant::now();
|
||||||
|
stats.record_request_at(&provider, &account, "model-a", now, now);
|
||||||
|
}
|
||||||
|
let now = Instant::now();
|
||||||
|
stats.record_request_at(&provider, &account, "model-b", now, now);
|
||||||
|
let persistence = RecentRequestPersistence::new(stats, store.clone());
|
||||||
|
// 多次保存同一内存窗口仍为原值,不把快照当成增量累加
|
||||||
|
for _ in 0..2 {
|
||||||
|
let stopping = CancellationToken::new();
|
||||||
|
stopping.cancel();
|
||||||
|
persistence
|
||||||
|
.run(WorkerDaemonContext::new(stopping))
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
let ttl: i64 = redis::cmd("PTTL")
|
||||||
|
.arg(&key)
|
||||||
|
.query_async(&mut connection)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert!(ttl > 115_000 && ttl <= 120_000, "TTL was {ttl}");
|
||||||
|
let restarted = Arc::new(AccountFeedbackStats::default());
|
||||||
|
RecentRequestPersistence::new(restarted.clone(), store.clone())
|
||||||
|
.restore()
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
restarted.recent_requests(&provider, &account, Some("model-a")),
|
||||||
|
20
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
restarted.recent_requests(&provider, &account, Some("model-b")),
|
||||||
|
1
|
||||||
|
);
|
||||||
|
// 加速 Redis 回收,验证缓存失效后启动恢复保持空窗口
|
||||||
|
redis::cmd("PEXPIRE")
|
||||||
|
.arg(&key)
|
||||||
|
.arg(30)
|
||||||
|
.query_async::<()>(&mut connection)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
tokio::time::timeout(Duration::from_secs(2), async {
|
||||||
|
while store.load().await.unwrap().is_some() {
|
||||||
|
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let empty = Arc::new(AccountFeedbackStats::default());
|
||||||
|
RecentRequestPersistence::new(empty.clone(), store)
|
||||||
|
.restore()
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
empty.recent_requests(&provider, &account, Some("model-a")),
|
||||||
|
0
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn still_retained_redis_snapshot_does_not_revive_expired_requests() {
|
||||||
|
let Some((store, mut connection, key)) = repository().await else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let stats = AccountFeedbackStats::default();
|
||||||
|
let provider = ProviderKind::new("openai").unwrap();
|
||||||
|
let account = ProviderAccountId::new("acct_old").unwrap();
|
||||||
|
let now = Instant::now();
|
||||||
|
stats.record_request_at(&provider, &account, "model", now, now);
|
||||||
|
let snapshot =
|
||||||
|
stats.snapshot_recent_requests_at(now, SystemTime::now() - Duration::from_secs(65));
|
||||||
|
store
|
||||||
|
.save(&snapshot, Duration::from_secs(120))
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let restored = Arc::new(AccountFeedbackStats::default());
|
||||||
|
RecentRequestPersistence::new(restored.clone(), store.clone())
|
||||||
|
.restore()
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert!(store.load().await.unwrap().is_some());
|
||||||
|
assert_eq!(
|
||||||
|
restored.recent_requests(&provider, &account, Some("model")),
|
||||||
|
0
|
||||||
|
);
|
||||||
|
redis::cmd("DEL")
|
||||||
|
.arg(&key)
|
||||||
|
.query_async::<()>(&mut connection)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn corrupt_snapshot_is_reported_without_installing_partial_counts() {
|
||||||
|
let Some((store, mut connection, key)) = repository().await else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
redis::cmd("SET")
|
||||||
|
.arg(&key)
|
||||||
|
.arg("{broken")
|
||||||
|
.arg("EX")
|
||||||
|
.arg(120)
|
||||||
|
.query_async::<()>(&mut connection)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let stats = Arc::new(AccountFeedbackStats::default());
|
||||||
|
assert!(
|
||||||
|
RecentRequestPersistence::new(stats.clone(), store)
|
||||||
|
.restore()
|
||||||
|
.await
|
||||||
|
.is_err()
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
stats.recent_requests(
|
||||||
|
&ProviderKind::new("openai").unwrap(),
|
||||||
|
&ProviderAccountId::new("acct_missing").unwrap(),
|
||||||
|
Some("model")
|
||||||
|
),
|
||||||
|
0,
|
||||||
|
);
|
||||||
|
redis::cmd("DEL")
|
||||||
|
.arg(&key)
|
||||||
|
.query_async::<()>(&mut connection)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
@@ -69,7 +69,7 @@ impl ProviderAdmin for AntigravityAdmin {
|
|||||||
gateway_admin::model::accounts::ProviderAccountCapabilities {
|
gateway_admin::model::accounts::ProviderAccountCapabilities {
|
||||||
credential_refresh: oauth,
|
credential_refresh: oauth,
|
||||||
reauthorize: oauth,
|
reauthorize: oauth,
|
||||||
credential_export: oauth,
|
credential_export: oauth || authentication_kind == crate::credential::api_key::API_KEY,
|
||||||
quota: oauth,
|
quota: oauth,
|
||||||
quota_refresh: oauth,
|
quota_refresh: oauth,
|
||||||
quota_credits: oauth,
|
quota_credits: oauth,
|
||||||
@@ -194,6 +194,21 @@ impl ProviderAdmin for AntigravityAdmin {
|
|||||||
) -> Result<ProviderModels, ProviderAdminError> {
|
) -> Result<ProviderModels, ProviderAdminError> {
|
||||||
self.catalog.account_models(id, refresh).await
|
self.catalog.account_models(id, refresh).await
|
||||||
}
|
}
|
||||||
|
async fn account_configuration(
|
||||||
|
&self,
|
||||||
|
id: &ProviderAccountId,
|
||||||
|
) -> Result<
|
||||||
|
Option<gateway_admin::model::provider_credentials::ProviderDocument>,
|
||||||
|
ProviderAdminError,
|
||||||
|
> {
|
||||||
|
let current = self.credentials.current(id).await?;
|
||||||
|
if current.account.authentication_kind() != crate::credential::api_key::API_KEY {
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
Ok(Some(
|
||||||
|
crate::credential::api_key::ApiKeyMaterial::load(¤t)?.configuration(),
|
||||||
|
))
|
||||||
|
}
|
||||||
async fn connection_test_operation(
|
async fn connection_test_operation(
|
||||||
&self,
|
&self,
|
||||||
_: &UpstreamModelId,
|
_: &UpstreamModelId,
|
||||||
|
|||||||
@@ -0,0 +1,219 @@
|
|||||||
|
//! GenAI API Key 凭据、连接更新与可重导入的账号文档
|
||||||
|
|
||||||
|
use super::{CredentialService, oauth::error};
|
||||||
|
use chrono::Utc;
|
||||||
|
use gateway_admin::{
|
||||||
|
model::{
|
||||||
|
Revision,
|
||||||
|
provider_credentials::{
|
||||||
|
CredentialCommitGuard, PreparedCredentialCreate, PreparedCredentialRotation,
|
||||||
|
PreparedCredentialRotationFacts, ProviderDocument,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
ports::provider::{ProviderAdminError, ProviderAdminErrorKind as Kind},
|
||||||
|
};
|
||||||
|
use gateway_core::account::{
|
||||||
|
CredentialState, LoadedCredential, OpaqueProviderData, OutboundProxy, ProviderAccountId,
|
||||||
|
};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use serde_json::{Value, json};
|
||||||
|
use url::Url;
|
||||||
|
|
||||||
|
pub(crate) const API_KEY: &str = "api_key";
|
||||||
|
|
||||||
|
#[derive(Deserialize, Serialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub(crate) struct ApiKeyMaterial {
|
||||||
|
schema_version: u32,
|
||||||
|
pub(crate) base_url: Url,
|
||||||
|
pub(crate) api_key: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize, Serialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub(super) struct ApiKeyDocument {
|
||||||
|
authentication_kind: String,
|
||||||
|
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||||
|
name: String,
|
||||||
|
base_url: String,
|
||||||
|
api_key: String,
|
||||||
|
#[serde(default, rename = "createdAt", skip_serializing_if = "Option::is_none")]
|
||||||
|
created_at: Option<chrono::DateTime<Utc>>,
|
||||||
|
#[serde(default, rename = "updatedAt", skip_serializing_if = "Option::is_none")]
|
||||||
|
updated_at: Option<chrono::DateTime<Utc>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ApiKeyMaterial {
|
||||||
|
fn validate(&self) -> Result<(), ProviderAdminError> {
|
||||||
|
if self.schema_version != 1
|
||||||
|
|| !matches!(self.base_url.scheme(), "http" | "https")
|
||||||
|
|| self.base_url.host_str().is_none()
|
||||||
|
|| !self.base_url.username().is_empty()
|
||||||
|
|| self.base_url.password().is_some()
|
||||||
|
|| self.base_url.query().is_some()
|
||||||
|
|| self.base_url.fragment().is_some()
|
||||||
|
|| self.base_url.as_str().len() > 2048
|
||||||
|
|| self.api_key.is_empty()
|
||||||
|
|| self.api_key.len() > 16 * 1024
|
||||||
|
|| !self.api_key.bytes().all(|byte| byte.is_ascii_graphic())
|
||||||
|
{
|
||||||
|
return Err(error(Kind::Invalid).with_public_message("API Key 或上游地址无效"));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn load(current: &LoadedCredential) -> Result<Self, ProviderAdminError> {
|
||||||
|
if current.account.authentication_kind() != API_KEY {
|
||||||
|
return Err(error(Kind::Unsupported));
|
||||||
|
}
|
||||||
|
let material: Self = serde_json::from_value(Value::Object(
|
||||||
|
current.credential.expose_to_provider().clone(),
|
||||||
|
))
|
||||||
|
.map_err(|_| error(Kind::Invalid))?;
|
||||||
|
material.validate()?;
|
||||||
|
Ok(material)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn configuration(&self) -> ProviderDocument {
|
||||||
|
ProviderDocument::new(OpaqueProviderData::new(serde_json::Map::from_iter([(
|
||||||
|
"base_url".into(),
|
||||||
|
json!(self.base_url),
|
||||||
|
)])))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn from_document(document: ProviderDocument) -> Result<Self, ProviderAdminError> {
|
||||||
|
let material: Self =
|
||||||
|
serde_json::from_value(Value::Object(document.into_provider_data().into_inner()))
|
||||||
|
.map_err(|_| error(Kind::Invalid))?;
|
||||||
|
material.validate()?;
|
||||||
|
Ok(material)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn document(self) -> Result<ProviderDocument, ProviderAdminError> {
|
||||||
|
let Value::Object(value) = serde_json::to_value(self).map_err(|_| error(Kind::Internal))?
|
||||||
|
else {
|
||||||
|
return Err(error(Kind::Internal));
|
||||||
|
};
|
||||||
|
Ok(ProviderDocument::new(OpaqueProviderData::new(value)))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn export(
|
||||||
|
self,
|
||||||
|
account: gateway_admin::model::accounts::AccountRecord,
|
||||||
|
) -> ApiKeyDocument {
|
||||||
|
ApiKeyDocument {
|
||||||
|
authentication_kind: API_KEY.into(),
|
||||||
|
name: account.name,
|
||||||
|
base_url: self.base_url.into(),
|
||||||
|
api_key: self.api_key,
|
||||||
|
created_at: Some(account.created_at),
|
||||||
|
updated_at: Some(account.updated_at),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ApiKeyDocument {
|
||||||
|
pub(super) fn validate(&self) -> Result<(), ProviderAdminError> {
|
||||||
|
if self.authentication_kind != API_KEY
|
||||||
|
|| self.name.chars().any(char::is_control)
|
||||||
|
|| self.base_url.chars().any(char::is_control)
|
||||||
|
{
|
||||||
|
return Err(error(Kind::Invalid));
|
||||||
|
}
|
||||||
|
ApiKeyMaterial {
|
||||||
|
schema_version: 1,
|
||||||
|
base_url: Url::parse(&self.base_url).map_err(|_| error(Kind::Invalid))?,
|
||||||
|
api_key: self.api_key.clone(),
|
||||||
|
}
|
||||||
|
.validate()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct CommitGuard;
|
||||||
|
impl CredentialCommitGuard for CommitGuard {
|
||||||
|
fn finish(self: Box<Self>) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl CredentialService {
|
||||||
|
pub(super) fn prepare_api_key(
|
||||||
|
&self,
|
||||||
|
input: ApiKeyDocument,
|
||||||
|
outbound_proxy: Option<OutboundProxy>,
|
||||||
|
) -> Result<PreparedCredentialCreate, ProviderAdminError> {
|
||||||
|
input.validate()?;
|
||||||
|
let material = ApiKeyMaterial {
|
||||||
|
schema_version: 1,
|
||||||
|
base_url: Url::parse(&input.base_url).map_err(|_| error(Kind::Invalid))?,
|
||||||
|
api_key: input.api_key,
|
||||||
|
};
|
||||||
|
Ok(PreparedCredentialCreate {
|
||||||
|
account_id: ProviderAccountId::new(format!("acct_{}", uuid::Uuid::now_v7().simple()))
|
||||||
|
.map_err(|_| error(Kind::Internal))?,
|
||||||
|
provider_kind: self.kind.clone(),
|
||||||
|
name: if input.name.trim().is_empty() {
|
||||||
|
"密钥账号".into()
|
||||||
|
} else {
|
||||||
|
input.name
|
||||||
|
},
|
||||||
|
email: None,
|
||||||
|
upstream_user_id: None,
|
||||||
|
upstream_account_id: None,
|
||||||
|
plan_type: None,
|
||||||
|
authentication_kind: API_KEY.into(),
|
||||||
|
provider_material: material.document()?,
|
||||||
|
has_refresh_token: false,
|
||||||
|
access_token_expires_at: None,
|
||||||
|
next_refresh_at: None,
|
||||||
|
enabled: true,
|
||||||
|
credential_state: CredentialState::Ready,
|
||||||
|
credential_observed_at: Utc::now(),
|
||||||
|
model_access: None,
|
||||||
|
outbound_proxy,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn rotate_api_key(
|
||||||
|
&self,
|
||||||
|
current: &LoadedCredential,
|
||||||
|
document: ProviderDocument,
|
||||||
|
) -> Result<PreparedCredentialRotation, ProviderAdminError> {
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
struct Update {
|
||||||
|
base_url: String,
|
||||||
|
api_key: Option<String>,
|
||||||
|
}
|
||||||
|
let update: Update =
|
||||||
|
serde_json::from_value(Value::Object(document.into_provider_data().into_inner()))
|
||||||
|
.map_err(|_| error(Kind::Invalid))?;
|
||||||
|
if update.base_url.chars().any(char::is_control) {
|
||||||
|
return Err(error(Kind::Invalid));
|
||||||
|
}
|
||||||
|
let mut material = ApiKeyMaterial::load(current)?;
|
||||||
|
material.base_url = Url::parse(&update.base_url).map_err(|_| error(Kind::Invalid))?;
|
||||||
|
if let Some(key) = update.api_key {
|
||||||
|
material.api_key = key;
|
||||||
|
}
|
||||||
|
material.validate()?;
|
||||||
|
Ok(PreparedCredentialRotation::new(
|
||||||
|
PreparedCredentialRotationFacts {
|
||||||
|
account_id: current.account.id().clone(),
|
||||||
|
provider_kind: self.kind.clone(),
|
||||||
|
expected_credential_revision: Revision::new(current.account.revision().get())
|
||||||
|
.map_err(|_| error(Kind::Internal))?,
|
||||||
|
replacement_identity: None,
|
||||||
|
name: current.account.name().into(),
|
||||||
|
email: None,
|
||||||
|
plan_type: None,
|
||||||
|
preserve_profile: false,
|
||||||
|
preserve_credential_state: false,
|
||||||
|
preserve_access_token_expiry: false,
|
||||||
|
provider_material: material.document()?,
|
||||||
|
has_refresh_token: false,
|
||||||
|
access_token_expires_at: None,
|
||||||
|
next_refresh_at: None,
|
||||||
|
},
|
||||||
|
Box::new(CommitGuard),
|
||||||
|
))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -106,8 +106,16 @@ impl AuthorizationService {
|
|||||||
if mutation.provider_kind() != &self.kind {
|
if mutation.provider_kind() != &self.kind {
|
||||||
return Err(error(Kind::Invalid));
|
return Err(error(Kind::Invalid));
|
||||||
}
|
}
|
||||||
if let AuthorizationMutationTarget::Reauthorize { account_id } = mutation.target() {
|
if let AuthorizationMutationTarget::Reauthorize { account_id } = mutation.target()
|
||||||
self.credentials.current(account_id).await?;
|
&& self
|
||||||
|
.credentials
|
||||||
|
.current(account_id)
|
||||||
|
.await?
|
||||||
|
.account
|
||||||
|
.authentication_kind()
|
||||||
|
!= "oauth"
|
||||||
|
{
|
||||||
|
return Err(error(Kind::Unsupported));
|
||||||
}
|
}
|
||||||
let flow_id = random_value()?;
|
let flow_id = random_value()?;
|
||||||
let state = random_value()?;
|
let state = random_value()?;
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ use gateway_core::{
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
use std::{
|
use std::{
|
||||||
collections::BTreeMap,
|
collections::{BTreeMap, BTreeSet},
|
||||||
sync::{
|
sync::{
|
||||||
Arc, Mutex,
|
Arc, Mutex,
|
||||||
atomic::{AtomicU64, AtomicUsize, Ordering},
|
atomic::{AtomicU64, AtomicUsize, Ordering},
|
||||||
@@ -139,7 +139,10 @@ impl CatalogService {
|
|||||||
for StoredAccountCatalog { accounts, document } in docs {
|
for StoredAccountCatalog { accounts, document } in docs {
|
||||||
let accounts: Vec<_> = accounts
|
let accounts: Vec<_> = accounts
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.filter(|a| a.etag.as_ref() == Some(registration))
|
.filter(|a| {
|
||||||
|
a.etag.as_ref() == Some(registration)
|
||||||
|
|| a.etag.as_deref() == Some("genai_api_key_v1")
|
||||||
|
})
|
||||||
.collect();
|
.collect();
|
||||||
if !accounts.is_empty() {
|
if !accounts.is_empty() {
|
||||||
let catalog = serde_json::from_slice(&document)
|
let catalog = serde_json::from_slice(&document)
|
||||||
@@ -170,6 +173,7 @@ impl CatalogService {
|
|||||||
BTreeMap::<UpstreamModelId, BTreeMap<ProviderAccountId, AccountModelMetadata>>::new();
|
BTreeMap::<UpstreamModelId, BTreeMap<ProviderAccountId, AccountModelMetadata>>::new();
|
||||||
let mut groups = BTreeMap::new();
|
let mut groups = BTreeMap::new();
|
||||||
let mut search_models = BTreeMap::new();
|
let mut search_models = BTreeMap::new();
|
||||||
|
let mut operations = BTreeMap::<UpstreamModelId, BTreeSet<OperationKind>>::new();
|
||||||
for (accounts, catalog) in self.catalogs().await? {
|
for (accounts, catalog) in self.catalogs().await? {
|
||||||
super::model_groups::collect(&mut groups, &catalog, &accounts);
|
super::model_groups::collect(&mut groups, &catalog, &accounts);
|
||||||
if let Some(search_model) = catalog
|
if let Some(search_model) = catalog
|
||||||
@@ -185,6 +189,13 @@ impl CatalogService {
|
|||||||
let discovery_order = catalog.discovery_order();
|
let discovery_order = catalog.discovery_order();
|
||||||
for (key, model) in catalog.models {
|
for (key, model) in catalog.models {
|
||||||
let id = UpstreamModelId::new(key).map_err(|_| unsent(Kind::Protocol))?;
|
let id = UpstreamModelId::new(key).map_err(|_| unsent(Kind::Protocol))?;
|
||||||
|
let methods = operations.entry(id.clone()).or_default();
|
||||||
|
if model.supports_method("generateContent") {
|
||||||
|
methods.insert(OperationKind::Generate);
|
||||||
|
}
|
||||||
|
if model.supports_method("countTokens") {
|
||||||
|
methods.insert(OperationKind::CountTokens);
|
||||||
|
}
|
||||||
let metadata = account_metadata(&id, model, discovery_order.as_ref());
|
let metadata = account_metadata(&id, model, discovery_order.as_ref());
|
||||||
members.entry(id).or_default().extend(
|
members.entry(id).or_default().extend(
|
||||||
accounts
|
accounts
|
||||||
@@ -193,20 +204,25 @@ impl CatalogService {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
let capabilities = ModelCapabilities::new(
|
let capabilities = |operations| {
|
||||||
[OperationKind::Generate, OperationKind::CountTokens].into(),
|
ModelCapabilities::new(operations, None)
|
||||||
None,
|
.with_native_web_search_helper(
|
||||||
)
|
"gemini-3.1-flash-lite-preview",
|
||||||
.with_native_web_search_helper("gemini-3.1-flash-lite-preview", search_models)
|
search_models.clone(),
|
||||||
.with_generation_protocol(gateway_protocol::genai::GENAI_PROTOCOL)
|
)
|
||||||
.with_translated_generation_protocols([gateway_protocol::chat_completions::CHAT_PROTOCOL])
|
.with_generation_protocol(gateway_protocol::genai::GENAI_PROTOCOL)
|
||||||
.with_upstream_feature_validation();
|
.with_translated_generation_protocols([
|
||||||
|
gateway_protocol::chat_completions::CHAT_PROTOCOL,
|
||||||
|
])
|
||||||
|
.with_upstream_feature_validation()
|
||||||
|
};
|
||||||
let mut models = BTreeMap::new();
|
let mut models = BTreeMap::new();
|
||||||
for (id, metadata) in members {
|
for (id, metadata) in members {
|
||||||
let accounts = metadata.keys().cloned().collect();
|
let accounts = metadata.keys().cloned().collect();
|
||||||
let model = ProviderModelCapabilities::new(
|
let model = ProviderModelCapabilities::new(
|
||||||
id.clone(),
|
id.clone(),
|
||||||
capabilities.clone().with_account_metadata(metadata),
|
capabilities(operations.remove(&id).unwrap_or_default())
|
||||||
|
.with_account_metadata(metadata),
|
||||||
);
|
);
|
||||||
models.insert(id, model.with_catalog_accounts(accounts));
|
models.insert(id, model.with_catalog_accounts(accounts));
|
||||||
}
|
}
|
||||||
@@ -219,7 +235,8 @@ impl CatalogService {
|
|||||||
.collect();
|
.collect();
|
||||||
ProviderModelCapabilities::new(
|
ProviderModelCapabilities::new(
|
||||||
id,
|
id,
|
||||||
capabilities.clone().with_reasoning_variants(variants),
|
capabilities([OperationKind::Generate, OperationKind::CountTokens].into())
|
||||||
|
.with_reasoning_variants(variants),
|
||||||
)
|
)
|
||||||
.with_catalog_accounts(accounts)
|
.with_catalog_accounts(accounts)
|
||||||
});
|
});
|
||||||
@@ -291,6 +308,23 @@ impl CatalogService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if current.account.authentication_kind() == super::api_key::API_KEY {
|
||||||
|
let material = super::api_key::ApiKeyMaterial::load(¤t)?;
|
||||||
|
let client = crate::transport::GenAiClient::new(
|
||||||
|
material.base_url,
|
||||||
|
current.account.outbound_proxy(),
|
||||||
|
)
|
||||||
|
.map_err(|e| error(AdminKind::Unavailable).with_source(e))?;
|
||||||
|
let observed_at = SystemTime::now();
|
||||||
|
let catalog = client.catalog(&material.api_key).await.map_err(|e| {
|
||||||
|
error(AdminKind::Unavailable)
|
||||||
|
.with_public_message("GenAI 模型目录查询失败")
|
||||||
|
.with_source(e)
|
||||||
|
})?;
|
||||||
|
return self
|
||||||
|
.publish(¤t.account, None, catalog, observed_at)
|
||||||
|
.await;
|
||||||
|
}
|
||||||
let material = self
|
let material = self
|
||||||
.credentials
|
.credentials
|
||||||
.material(¤t)
|
.material(¤t)
|
||||||
@@ -332,7 +366,13 @@ impl CatalogService {
|
|||||||
account_id: account.id().clone(),
|
account_id: account.id().clone(),
|
||||||
revision: account.revision(),
|
revision: account.revision(),
|
||||||
plan,
|
plan,
|
||||||
etag: Some(self.registration.clone()),
|
etag: Some(
|
||||||
|
if account.authentication_kind() == super::api_key::API_KEY {
|
||||||
|
"genai_api_key_v1".into()
|
||||||
|
} else {
|
||||||
|
self.registration.clone()
|
||||||
|
},
|
||||||
|
),
|
||||||
observed_at,
|
observed_at,
|
||||||
};
|
};
|
||||||
let body = serde_json::to_vec(&catalog).map_err(|_| error(AdminKind::Internal))?;
|
let body = serde_json::to_vec(&catalog).map_err(|_| error(AdminKind::Internal))?;
|
||||||
@@ -429,7 +469,7 @@ impl CatalogService {
|
|||||||
.await
|
.await
|
||||||
.map_err(|e| WorkerTaskError::safe("读取 Antigravity 账号失败").with_source(e))?;
|
.map_err(|e| WorkerTaskError::safe("读取 Antigravity 账号失败").with_source(e))?;
|
||||||
due.retain(|account| {
|
due.retain(|account| {
|
||||||
account.authentication_kind() == "oauth"
|
matches!(account.authentication_kind(), "oauth" | "api_key")
|
||||||
&& observations.get(account.id()).is_none_or(|observation| {
|
&& observations.get(account.id()).is_none_or(|observation| {
|
||||||
observation.revision != account.revision()
|
observation.revision != account.revision()
|
||||||
|| observation.observed_at.elapsed().unwrap_or_default()
|
|| observation.observed_at.elapsed().unwrap_or_default()
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
use super::{
|
use super::{
|
||||||
CredentialService, Material,
|
CredentialService, Material,
|
||||||
|
api_key::{API_KEY, ApiKeyDocument, ApiKeyMaterial},
|
||||||
oauth::{error, valid_token},
|
oauth::{error, valid_token},
|
||||||
};
|
};
|
||||||
use chrono::{DateTime, Utc};
|
use chrono::{DateTime, Utc};
|
||||||
@@ -23,7 +24,14 @@ use std::collections::HashSet;
|
|||||||
struct AccountFile {
|
struct AccountFile {
|
||||||
provider: String,
|
provider: String,
|
||||||
version: u32,
|
version: u32,
|
||||||
accounts: Vec<AccountEntry>,
|
accounts: Vec<Entry>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize, Serialize)]
|
||||||
|
#[serde(untagged)]
|
||||||
|
enum Entry {
|
||||||
|
ApiKey(ApiKeyDocument),
|
||||||
|
OAuth(AccountEntry),
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Deserialize, Serialize)]
|
#[derive(Deserialize, Serialize)]
|
||||||
@@ -56,16 +64,29 @@ impl CredentialService {
|
|||||||
&self,
|
&self,
|
||||||
input: PrepareCredentialImport,
|
input: PrepareCredentialImport,
|
||||||
) -> Result<PreparedCredentialImport, ProviderAdminError> {
|
) -> Result<PreparedCredentialImport, ProviderAdminError> {
|
||||||
let file: AccountFile = serde_json::from_value(Value::Object(
|
let document = Value::Object(input.document.into_provider_data().into_inner());
|
||||||
input.document.into_provider_data().into_inner(),
|
if document.get("authentication_kind").and_then(Value::as_str) == Some(API_KEY) {
|
||||||
))
|
let entry = serde_json::from_value(document).map_err(|_| error(Kind::Invalid))?;
|
||||||
.map_err(|_| error(Kind::Invalid))?;
|
return Ok(PreparedCredentialImport {
|
||||||
|
provider_kind: self.kind.clone(),
|
||||||
|
credentials: vec![self.prepare_api_key(entry, input.default_outbound_proxy)?],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let file: AccountFile =
|
||||||
|
serde_json::from_value(document).map_err(|_| error(Kind::Invalid))?;
|
||||||
if file.provider != self.kind.as_str() || file.version != 1 || file.accounts.is_empty() {
|
if file.provider != self.kind.as_str() || file.version != 1 || file.accounts.is_empty() {
|
||||||
return Err(error(Kind::Invalid));
|
return Err(error(Kind::Invalid));
|
||||||
}
|
}
|
||||||
let mut tokens = HashSet::new();
|
let mut tokens = HashSet::new();
|
||||||
// 全部本地格式检查先于任何可能轮换 RT 的上游请求
|
// 全部本地格式检查先于任何可能轮换 RT 的上游请求
|
||||||
for entry in &file.accounts {
|
for entry in &file.accounts {
|
||||||
|
let entry = match entry {
|
||||||
|
Entry::ApiKey(entry) => {
|
||||||
|
entry.validate()?;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
Entry::OAuth(entry) => entry,
|
||||||
|
};
|
||||||
if entry.label.chars().any(char::is_control)
|
if entry.label.chars().any(char::is_control)
|
||||||
|| !valid_token(&entry.refresh_token)
|
|| !valid_token(&entry.refresh_token)
|
||||||
|| !tokens.insert(entry.refresh_token.as_str())
|
|| !tokens.insert(entry.refresh_token.as_str())
|
||||||
@@ -75,14 +96,30 @@ impl CredentialService {
|
|||||||
}
|
}
|
||||||
let mut credentials = Vec::with_capacity(file.accounts.len());
|
let mut credentials = Vec::with_capacity(file.accounts.len());
|
||||||
let mut subjects = HashSet::new();
|
let mut subjects = HashSet::new();
|
||||||
let profile = self.request_profile().await?;
|
let profile = if file
|
||||||
|
.accounts
|
||||||
|
.iter()
|
||||||
|
.any(|entry| matches!(entry, Entry::OAuth(_)))
|
||||||
|
{
|
||||||
|
Some(self.request_profile().await?)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
for entry in file.accounts {
|
for entry in file.accounts {
|
||||||
|
let entry = match entry {
|
||||||
|
Entry::ApiKey(entry) => {
|
||||||
|
credentials
|
||||||
|
.push(self.prepare_api_key(entry, input.default_outbound_proxy.clone())?);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
Entry::OAuth(entry) => entry,
|
||||||
|
};
|
||||||
let grant = self
|
let grant = self
|
||||||
.oauth
|
.oauth
|
||||||
.verify_import(
|
.verify_import(
|
||||||
&entry.refresh_token,
|
&entry.refresh_token,
|
||||||
input.default_outbound_proxy.as_ref(),
|
input.default_outbound_proxy.as_ref(),
|
||||||
&profile,
|
profile.as_ref().ok_or_else(|| error(Kind::Internal))?,
|
||||||
)
|
)
|
||||||
.await?;
|
.await?;
|
||||||
if !subjects.insert(grant.material.subject.clone()) {
|
if !subjects.insert(grant.material.subject.clone()) {
|
||||||
@@ -106,16 +143,20 @@ impl CredentialService {
|
|||||||
&self,
|
&self,
|
||||||
input: PrepareCredentialRotation,
|
input: PrepareCredentialRotation,
|
||||||
) -> Result<PreparedCredentialRotation, ProviderAdminError> {
|
) -> Result<PreparedCredentialRotation, ProviderAdminError> {
|
||||||
if input.account.provider_kind != self.kind || input.account.authentication_kind != "oauth"
|
if input.account.provider_kind != self.kind {
|
||||||
{
|
|
||||||
return Err(error(Kind::Invalid));
|
return Err(error(Kind::Invalid));
|
||||||
}
|
}
|
||||||
let account_id =
|
let account_id =
|
||||||
ProviderAccountId::new(input.account.id).map_err(|_| error(Kind::Invalid))?;
|
ProviderAccountId::new(input.account.id).map_err(|_| error(Kind::Invalid))?;
|
||||||
let current = self.current(&account_id).await?;
|
let current = self.current(&account_id).await?;
|
||||||
if current.account.revision().get() != input.account.credential_revision.get() {
|
if current.account.revision().get() != input.account.credential_revision.get()
|
||||||
|
|| current.account.authentication_kind() != input.account.authentication_kind
|
||||||
|
{
|
||||||
return Err(error(Kind::Conflict));
|
return Err(error(Kind::Conflict));
|
||||||
}
|
}
|
||||||
|
if current.account.authentication_kind() == API_KEY {
|
||||||
|
return self.rotate_api_key(¤t, input.provider_material);
|
||||||
|
}
|
||||||
let entry: AccountEntry = serde_json::from_value(Value::Object(
|
let entry: AccountEntry = serde_json::from_value(Value::Object(
|
||||||
input.provider_material.into_provider_data().into_inner(),
|
input.provider_material.into_provider_data().into_inner(),
|
||||||
))
|
))
|
||||||
@@ -141,9 +182,19 @@ impl CredentialService {
|
|||||||
let mut account_ids = Vec::with_capacity(credentials.len());
|
let mut account_ids = Vec::with_capacity(credentials.len());
|
||||||
let mut accounts = Vec::with_capacity(credentials.len());
|
let mut accounts = Vec::with_capacity(credentials.len());
|
||||||
for input in credentials {
|
for input in credentials {
|
||||||
if input.account.provider_kind != self.kind
|
if input.account.provider_kind != self.kind {
|
||||||
|| input.account.authentication_kind != "oauth"
|
return Err(error(Kind::Invalid));
|
||||||
{
|
}
|
||||||
|
if input.account.authentication_kind == API_KEY {
|
||||||
|
let material = ApiKeyMaterial::from_document(input.provider_material)?;
|
||||||
|
account_ids.push(
|
||||||
|
ProviderAccountId::new(input.account.id.clone())
|
||||||
|
.map_err(|_| error(Kind::Invalid))?,
|
||||||
|
);
|
||||||
|
accounts.push(Entry::ApiKey(material.export(input.account)));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if input.account.authentication_kind != "oauth" {
|
||||||
return Err(error(Kind::Invalid));
|
return Err(error(Kind::Invalid));
|
||||||
}
|
}
|
||||||
let material: Material = serde_json::from_value(Value::Object(
|
let material: Material = serde_json::from_value(Value::Object(
|
||||||
@@ -158,7 +209,7 @@ impl CredentialService {
|
|||||||
}
|
}
|
||||||
account_ids
|
account_ids
|
||||||
.push(ProviderAccountId::new(input.account.id).map_err(|_| error(Kind::Invalid))?);
|
.push(ProviderAccountId::new(input.account.id).map_err(|_| error(Kind::Invalid))?);
|
||||||
accounts.push(AccountEntry {
|
accounts.push(Entry::OAuth(AccountEntry {
|
||||||
label: input.account.name,
|
label: input.account.name,
|
||||||
refresh_token: material.refresh_token,
|
refresh_token: material.refresh_token,
|
||||||
access_token: Some(material.access_token),
|
access_token: Some(material.access_token),
|
||||||
@@ -169,7 +220,7 @@ impl CredentialService {
|
|||||||
plan_type: input.account.plan_type,
|
plan_type: input.account.plan_type,
|
||||||
created_at: Some(input.account.created_at),
|
created_at: Some(input.account.created_at),
|
||||||
updated_at: Some(input.account.updated_at),
|
updated_at: Some(input.account.updated_at),
|
||||||
});
|
}));
|
||||||
}
|
}
|
||||||
let Value::Object(document) = serde_json::to_value(AccountFile {
|
let Value::Object(document) = serde_json::to_value(AccountFile {
|
||||||
provider: self.kind.as_str().to_owned(),
|
provider: self.kind.as_str().to_owned(),
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
//! OAuth 流程、账号凭据与文件导入导出
|
//! OAuth 流程、账号凭据与文件导入导出
|
||||||
|
|
||||||
|
pub(crate) mod api_key;
|
||||||
mod authorization;
|
mod authorization;
|
||||||
pub(crate) mod catalog;
|
pub(crate) mod catalog;
|
||||||
mod documents;
|
mod documents;
|
||||||
@@ -10,4 +11,4 @@ mod refresh;
|
|||||||
mod service;
|
mod service;
|
||||||
pub(crate) use authorization::AuthorizationService;
|
pub(crate) use authorization::AuthorizationService;
|
||||||
pub(crate) use oauth::{GoogleOAuth, Material};
|
pub(crate) use oauth::{GoogleOAuth, Material};
|
||||||
pub(crate) use service::CredentialService;
|
pub(crate) use service::{Authentication, CredentialService};
|
||||||
|
|||||||
@@ -143,6 +143,9 @@ impl QuotaService {
|
|||||||
.map_err(unavailable)?
|
.map_err(unavailable)?
|
||||||
.filter(|a| a.provider() == &self.kind)
|
.filter(|a| a.provider() == &self.kind)
|
||||||
.ok_or_else(|| error(Kind::NotFound))?;
|
.ok_or_else(|| error(Kind::NotFound))?;
|
||||||
|
if account.authentication_kind() == super::super::api_key::API_KEY {
|
||||||
|
return Ok(ProviderQuota::default());
|
||||||
|
}
|
||||||
let observations = self
|
let observations = self
|
||||||
.accounts
|
.accounts
|
||||||
.get_quotas(std::slice::from_ref(id))
|
.get_quotas(std::slice::from_ref(id))
|
||||||
@@ -160,6 +163,9 @@ impl QuotaService {
|
|||||||
|
|
||||||
pub(crate) async fn refresh(&self, id: &ProviderAccountId) -> Result<(), ProviderAdminError> {
|
pub(crate) async fn refresh(&self, id: &ProviderAccountId) -> Result<(), ProviderAdminError> {
|
||||||
let current = self.credentials.current(id).await?;
|
let current = self.credentials.current(id).await?;
|
||||||
|
if current.account.authentication_kind() != "oauth" {
|
||||||
|
return Err(error(Kind::Unsupported));
|
||||||
|
}
|
||||||
let material = self
|
let material = self
|
||||||
.credentials
|
.credentials
|
||||||
.material(¤t)
|
.material(¤t)
|
||||||
@@ -253,7 +259,11 @@ impl QuotaService {
|
|||||||
accounts: &[ProviderAccount],
|
accounts: &[ProviderAccount],
|
||||||
model: &str,
|
model: &str,
|
||||||
) -> Result<BTreeMap<ProviderAccountId, CandidateQuota>, ProviderAdminError> {
|
) -> Result<BTreeMap<ProviderAccountId, CandidateQuota>, ProviderAdminError> {
|
||||||
let owners: BTreeMap<_, _> = accounts.iter().map(|a| (a.id().clone(), a)).collect();
|
let owners: BTreeMap<_, _> = accounts
|
||||||
|
.iter()
|
||||||
|
.filter(|a| a.authentication_kind() == "oauth")
|
||||||
|
.map(|a| (a.id().clone(), a))
|
||||||
|
.collect();
|
||||||
let ids: Vec<_> = owners.keys().cloned().collect();
|
let ids: Vec<_> = owners.keys().cloned().collect();
|
||||||
let observations = self.accounts.get_quotas(&ids).await.map_err(unavailable)?;
|
let observations = self.accounts.get_quotas(&ids).await.map_err(unavailable)?;
|
||||||
let now = SystemTime::now();
|
let now = SystemTime::now();
|
||||||
|
|||||||
@@ -32,6 +32,26 @@ use serde_json::Value;
|
|||||||
use std::{sync::Arc, time::SystemTime};
|
use std::{sync::Arc, time::SystemTime};
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
pub(crate) enum Authentication {
|
||||||
|
OAuth(Material),
|
||||||
|
ApiKey(super::api_key::ApiKeyMaterial),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Authentication {
|
||||||
|
pub(crate) fn token(&self) -> &str {
|
||||||
|
match self {
|
||||||
|
Self::OAuth(material) => &material.access_token,
|
||||||
|
Self::ApiKey(material) => &material.api_key,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub(crate) fn into_token(self) -> String {
|
||||||
|
match self {
|
||||||
|
Self::OAuth(material) => material.access_token,
|
||||||
|
Self::ApiKey(material) => material.api_key,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub(crate) struct CredentialService {
|
pub(crate) struct CredentialService {
|
||||||
pub(super) kind: ProviderKind,
|
pub(super) kind: ProviderKind,
|
||||||
pub(super) accounts: Arc<dyn ProviderAccountStore>,
|
pub(super) accounts: Arc<dyn ProviderAccountStore>,
|
||||||
@@ -72,6 +92,9 @@ impl CredentialService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
pub(crate) fn material(&self, current: &LoadedCredential) -> Result<Material, ProviderError> {
|
pub(crate) fn material(&self, current: &LoadedCredential) -> Result<Material, ProviderError> {
|
||||||
|
if current.account.authentication_kind() != "oauth" {
|
||||||
|
return Err(unsent(ProviderErrorKind::InvalidRequest));
|
||||||
|
}
|
||||||
let material: Material = serde_json::from_value(serde_json::Value::Object(
|
let material: Material = serde_json::from_value(serde_json::Value::Object(
|
||||||
current.credential.expose_to_provider().clone(),
|
current.credential.expose_to_provider().clone(),
|
||||||
))
|
))
|
||||||
@@ -87,6 +110,18 @@ impl CredentialService {
|
|||||||
}
|
}
|
||||||
Ok(material)
|
Ok(material)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub(crate) fn authentication(
|
||||||
|
&self,
|
||||||
|
current: &LoadedCredential,
|
||||||
|
) -> Result<super::Authentication, ProviderError> {
|
||||||
|
if current.account.authentication_kind() == super::api_key::API_KEY {
|
||||||
|
return super::api_key::ApiKeyMaterial::load(current)
|
||||||
|
.map(super::Authentication::ApiKey)
|
||||||
|
.map_err(|_| unsent(ProviderErrorKind::ProviderInfrastructureUnavailable));
|
||||||
|
}
|
||||||
|
self.material(current).map(super::Authentication::OAuth)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
pub(super) struct RefreshGuards {
|
pub(super) struct RefreshGuards {
|
||||||
_account: Box<dyn ProviderLeaseGuard>,
|
_account: Box<dyn ProviderLeaseGuard>,
|
||||||
@@ -123,7 +158,7 @@ impl CredentialService {
|
|||||||
.with_source(e)
|
.with_source(e)
|
||||||
})?;
|
})?;
|
||||||
if loaded.account.provider() != &self.kind
|
if loaded.account.provider() != &self.kind
|
||||||
|| loaded.account.authentication_kind() != "oauth"
|
|| !matches!(loaded.account.authentication_kind(), "oauth" | "api_key")
|
||||||
{
|
{
|
||||||
return Err(error(Kind::NotFound));
|
return Err(error(Kind::NotFound));
|
||||||
}
|
}
|
||||||
@@ -231,6 +266,9 @@ impl CredentialService {
|
|||||||
&self,
|
&self,
|
||||||
current: &LoadedCredential,
|
current: &LoadedCredential,
|
||||||
) -> Result<PreparedCredentialRotation, ProviderAdminError> {
|
) -> Result<PreparedCredentialRotation, ProviderAdminError> {
|
||||||
|
if current.account.authentication_kind() != "oauth" {
|
||||||
|
return Err(error(Kind::Unsupported));
|
||||||
|
}
|
||||||
let guards = self.lock_rotation(¤t.account).await?;
|
let guards = self.lock_rotation(¤t.account).await?;
|
||||||
let previous: Material = serde_json::from_value(Value::Object(
|
let previous: Material = serde_json::from_value(Value::Object(
|
||||||
current.credential.expose_to_provider().clone(),
|
current.credential.expose_to_provider().clone(),
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ use std::{collections::BTreeMap, time::SystemTime};
|
|||||||
pub(super) enum Project {
|
pub(super) enum Project {
|
||||||
Catalog(String),
|
Catalog(String),
|
||||||
Discover,
|
Discover,
|
||||||
|
GenAi,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(super) struct CandidatePool {
|
pub(super) struct CandidatePool {
|
||||||
@@ -32,6 +33,7 @@ impl AntigravityProvider {
|
|||||||
model: &UpstreamModelId,
|
model: &UpstreamModelId,
|
||||||
ctx: &AttemptContext,
|
ctx: &AttemptContext,
|
||||||
search: bool,
|
search: bool,
|
||||||
|
method: &'static str,
|
||||||
) -> Result<CandidatePool, ProviderError> {
|
) -> Result<CandidatePool, ProviderError> {
|
||||||
let required = ctx.required_account();
|
let required = ctx.required_account();
|
||||||
let diagnostic = ctx.is_diagnostic_required_account();
|
let diagnostic = ctx.is_diagnostic_required_account();
|
||||||
@@ -52,7 +54,7 @@ impl AntigravityProvider {
|
|||||||
let projects = BTreeMap::from([(id.clone(), (account.revision(), Project::Discover))]);
|
let projects = BTreeMap::from([(id.clone(), (account.revision(), Project::Discover))]);
|
||||||
(vec![account], projects)
|
(vec![account], projects)
|
||||||
} else {
|
} else {
|
||||||
let projects = self.catalog_projects(model, ctx, search).await?;
|
let projects = self.catalog_projects(model, ctx, search, method).await?;
|
||||||
let ids: Vec<_> = projects.keys().cloned().collect();
|
let ids: Vec<_> = projects.keys().cloned().collect();
|
||||||
if ids.is_empty() && search {
|
if ids.is_empty() && search {
|
||||||
return Err(ProviderError::invalid_request(
|
return Err(ProviderError::invalid_request(
|
||||||
@@ -136,13 +138,16 @@ impl AntigravityProvider {
|
|||||||
}
|
}
|
||||||
let (failure_rate, first_output_latency) =
|
let (failure_rate, first_output_latency) =
|
||||||
self.feedback.scheduling_signals(&self.kind, account.id());
|
self.feedback.scheduling_signals(&self.kind, account.id());
|
||||||
let signals = scheduling
|
let mut signals = scheduling
|
||||||
.signals()
|
.signals()
|
||||||
.get(account.id())
|
.get(account.id())
|
||||||
.cloned()
|
.cloned()
|
||||||
.ok_or_else(|| unsent(Kind::ProviderInfrastructureUnavailable))?
|
.ok_or_else(|| unsent(Kind::ProviderInfrastructureUnavailable))?
|
||||||
.with_runtime_health(failure_rate, first_output_latency)
|
.with_runtime_health(failure_rate, first_output_latency)
|
||||||
.with_provider_quota(quota.and_then(|q| q.signals.take()));
|
.with_provider_quota(quota.and_then(|q| q.signals.take()));
|
||||||
|
signals.recent_requests =
|
||||||
|
self.feedback
|
||||||
|
.recent_requests(&self.kind, account.id(), Some(model.as_str()));
|
||||||
candidates.push(AccountCandidate {
|
candidates.push(AccountCandidate {
|
||||||
account,
|
account,
|
||||||
signals,
|
signals,
|
||||||
@@ -179,6 +184,7 @@ impl AntigravityProvider {
|
|||||||
model: &UpstreamModelId,
|
model: &UpstreamModelId,
|
||||||
ctx: &AttemptContext,
|
ctx: &AttemptContext,
|
||||||
search: bool,
|
search: bool,
|
||||||
|
method: &'static str,
|
||||||
) -> Result<BTreeMap<ProviderAccountId, (CredentialRevision, Project)>, ProviderError> {
|
) -> Result<BTreeMap<ProviderAccountId, (CredentialRevision, Project)>, ProviderError> {
|
||||||
let required = ctx.required_account();
|
let required = ctx.required_account();
|
||||||
let mut projects = BTreeMap::new();
|
let mut projects = BTreeMap::new();
|
||||||
@@ -188,7 +194,10 @@ impl AntigravityProvider {
|
|||||||
.web_search_model()
|
.web_search_model()
|
||||||
.is_some_and(|id| id == model.as_str())
|
.is_some_and(|id| id == model.as_str())
|
||||||
} else {
|
} else {
|
||||||
catalog.models.contains_key(model.as_str())
|
catalog
|
||||||
|
.models
|
||||||
|
.get(model.as_str())
|
||||||
|
.is_some_and(|model| model.supports_method(method))
|
||||||
};
|
};
|
||||||
if !supports {
|
if !supports {
|
||||||
continue;
|
continue;
|
||||||
@@ -204,7 +213,10 @@ impl AntigravityProvider {
|
|||||||
account_id,
|
account_id,
|
||||||
(
|
(
|
||||||
observation.revision,
|
observation.revision,
|
||||||
Project::Catalog(catalog.project.clone()),
|
catalog
|
||||||
|
.project
|
||||||
|
.clone()
|
||||||
|
.map_or(Project::GenAi, Project::Catalog),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ use serde_json::{Map, Value};
|
|||||||
pub(super) fn prepare(
|
pub(super) fn prepare(
|
||||||
operation: Operation,
|
operation: Operation,
|
||||||
context: &AttemptContext,
|
context: &AttemptContext,
|
||||||
|
api_model: Option<&str>,
|
||||||
) -> Result<(Operation, Option<Translator>), ProviderError> {
|
) -> Result<(Operation, Option<Translator>), ProviderError> {
|
||||||
let Operation::CountTokens(request) = &operation else {
|
let Operation::CountTokens(request) = &operation else {
|
||||||
return Err(unsent(ProviderErrorKind::Unsupported));
|
return Err(unsent(ProviderErrorKind::Unsupported));
|
||||||
@@ -23,9 +24,15 @@ pub(super) fn prepare(
|
|||||||
}
|
}
|
||||||
let body: Map<String, Value> = serde_json::from_slice(request.payload().body())
|
let body: Map<String, Value> = serde_json::from_slice(request.payload().body())
|
||||||
.map_err(|error| unsent(ProviderErrorKind::InvalidRequest).with_source(error))?;
|
.map_err(|error| unsent(ProviderErrorKind::InvalidRequest).with_source(error))?;
|
||||||
let mut body = into_count_tokens_request(body)
|
let body = match api_model {
|
||||||
.map_err(|error| unsent(ProviderErrorKind::InvalidRequest).with_source(error))?;
|
Some(model) => api_count_body(body, source, model, context)?,
|
||||||
context.rewrite_count_prompt(GENAI_PROTOCOL, &mut body);
|
None => {
|
||||||
|
let mut body = into_count_tokens_request(body)
|
||||||
|
.map_err(|error| unsent(ProviderErrorKind::InvalidRequest).with_source(error))?;
|
||||||
|
context.rewrite_count_prompt(GENAI_PROTOCOL, &mut body);
|
||||||
|
body
|
||||||
|
}
|
||||||
|
};
|
||||||
let bytes = serde_json::to_vec(&body).map_err(|_| unsent(ProviderErrorKind::InvalidRequest))?;
|
let bytes = serde_json::to_vec(&body).map_err(|_| unsent(ProviderErrorKind::InvalidRequest))?;
|
||||||
let translated = source == "token-count";
|
let translated = source == "token-count";
|
||||||
let operation = if translated {
|
let operation = if translated {
|
||||||
@@ -38,6 +45,39 @@ pub(super) fn prepare(
|
|||||||
Ok((operation, translated.then_some(Translator)))
|
Ok((operation, translated.then_some(Translator)))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn api_count_body(
|
||||||
|
mut body: Map<String, Value>,
|
||||||
|
source: &str,
|
||||||
|
model: &str,
|
||||||
|
context: &AttemptContext,
|
||||||
|
) -> Result<Map<String, Value>, ProviderError> {
|
||||||
|
if source == "token-count" {
|
||||||
|
let mut request = into_count_tokens_request(body)
|
||||||
|
.map_err(|error| unsent(ProviderErrorKind::InvalidRequest).with_source(error))?;
|
||||||
|
request.insert("model".into(), Value::String(format!("models/{model}")));
|
||||||
|
context.rewrite_count_prompt(GENAI_PROTOCOL, &mut request);
|
||||||
|
return Ok(Map::from_iter([(
|
||||||
|
"generateContentRequest".into(),
|
||||||
|
Value::Object(request),
|
||||||
|
)]));
|
||||||
|
}
|
||||||
|
// 公开 GenAI 计数保留原生封套;内部模型必须与本轮实际选型一致
|
||||||
|
let nested = ["generateContentRequest", "generate_content_request"]
|
||||||
|
.into_iter()
|
||||||
|
.find(|field| body.contains_key(*field));
|
||||||
|
if let Some(field) = nested {
|
||||||
|
let request = body
|
||||||
|
.get_mut(field)
|
||||||
|
.and_then(Value::as_object_mut)
|
||||||
|
.ok_or_else(|| unsent(ProviderErrorKind::InvalidRequest))?;
|
||||||
|
request.insert("model".into(), Value::String(format!("models/{model}")));
|
||||||
|
context.rewrite_count_prompt(GENAI_PROTOCOL, request);
|
||||||
|
} else {
|
||||||
|
context.rewrite_count_prompt(GENAI_PROTOCOL, &mut body);
|
||||||
|
}
|
||||||
|
Ok(body)
|
||||||
|
}
|
||||||
|
|
||||||
pub(super) struct Translator;
|
pub(super) struct Translator;
|
||||||
|
|
||||||
impl NativeResponseTranslator for Translator {
|
impl NativeResponseTranslator for Translator {
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ use super::{AntigravityProvider, candidates::Project};
|
|||||||
use crate::transport::unsent;
|
use crate::transport::unsent;
|
||||||
use futures::StreamExt;
|
use futures::StreamExt;
|
||||||
use gateway_core::{
|
use gateway_core::{
|
||||||
|
account::AccountEligibilityPolicy,
|
||||||
engine::{
|
engine::{
|
||||||
AttemptContext,
|
AttemptContext,
|
||||||
provider::{
|
provider::{
|
||||||
@@ -17,6 +18,11 @@ use gateway_core::{
|
|||||||
use gateway_protocol::genai::GENAI_PROTOCOL;
|
use gateway_protocol::genai::GENAI_PROTOCOL;
|
||||||
use std::{sync::Arc, time::Instant};
|
use std::{sync::Arc, time::Instant};
|
||||||
|
|
||||||
|
enum Resource {
|
||||||
|
CloudCode(crate::transport::CloudCodeClient),
|
||||||
|
GenAi(crate::transport::GenAiClient),
|
||||||
|
}
|
||||||
|
|
||||||
impl AntigravityProvider {
|
impl AntigravityProvider {
|
||||||
pub(super) async fn execute_native(
|
pub(super) async fn execute_native(
|
||||||
self: Arc<Self>,
|
self: Arc<Self>,
|
||||||
@@ -42,22 +48,38 @@ impl AntigravityProvider {
|
|||||||
let affinity =
|
let affinity =
|
||||||
super::affinity::session_key(request.operation(), ctx.client_api_key_ref(), &model);
|
super::affinity::session_key(request.operation(), ctx.client_api_key_ref(), &model);
|
||||||
let search = request.candidate().uses_dedicated_web_search();
|
let search = request.candidate().uses_dedicated_web_search();
|
||||||
|
let method = if matches!(request.operation(), Operation::CountTokens(_)) {
|
||||||
|
"countTokens"
|
||||||
|
} else {
|
||||||
|
"generateContent"
|
||||||
|
};
|
||||||
let selected = self
|
let selected = self
|
||||||
.select_account(&model, &ctx, affinity.as_ref(), search)
|
.select_account(&model, &ctx, affinity.as_ref(), search, method)
|
||||||
.await?;
|
.await?;
|
||||||
let selection = ProviderSelectionObservation::new(
|
let selection = ProviderSelectionObservation::new(
|
||||||
u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX),
|
u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX),
|
||||||
selected.capacity,
|
selected.capacity,
|
||||||
);
|
);
|
||||||
let profile = ctx
|
let resource = match &selected.material {
|
||||||
.request_profile()
|
crate::credential::Authentication::OAuth(_) => {
|
||||||
.map(crate::profile::ClientProfile::from_frozen)
|
let profile = ctx
|
||||||
.transpose()
|
.request_profile()
|
||||||
.map_err(|e| unsent(Kind::ProviderInfrastructureUnavailable).with_source(e))?
|
.map(crate::profile::ClientProfile::from_frozen)
|
||||||
.unwrap_or_else(|| crate::profile::default_profile(&self.release));
|
.transpose()
|
||||||
let resource = self
|
.map_err(|e| unsent(Kind::ProviderInfrastructureUnavailable).with_source(e))?
|
||||||
.clients
|
.unwrap_or_else(|| crate::profile::default_profile(&self.release));
|
||||||
.client(&self.origin, &selected.account, &profile)?;
|
Resource::CloudCode(self.clients.client(
|
||||||
|
&self.origin,
|
||||||
|
&selected.account,
|
||||||
|
&profile,
|
||||||
|
)?)
|
||||||
|
}
|
||||||
|
crate::credential::Authentication::ApiKey(material) => Resource::GenAi(
|
||||||
|
self.clients
|
||||||
|
.genai(material.base_url.clone(), &selected.account)?,
|
||||||
|
),
|
||||||
|
};
|
||||||
|
let native_api = matches!(resource, Resource::GenAi(_));
|
||||||
let metadata = ProviderCallMetadata::new(
|
let metadata = ProviderCallMetadata::new(
|
||||||
self.kind.clone(),
|
self.kind.clone(),
|
||||||
model.clone(),
|
model.clone(),
|
||||||
@@ -94,10 +116,10 @@ impl AntigravityProvider {
|
|||||||
return Err(ProviderError::invalid_request("Middleware changed the required web search after model selection."));
|
return Err(ProviderError::invalid_request("Middleware changed the required web search after model selection."));
|
||||||
}
|
}
|
||||||
let (operation, translator, count_translator) = if matches!(operation, Operation::CountTokens(_)) {
|
let (operation, translator, count_translator) = if matches!(operation, Operation::CountTokens(_)) {
|
||||||
let (operation, translator) = super::count::prepare(operation, &terminal_context)?;
|
let (operation, translator) = super::count::prepare(operation, &terminal_context, native_api.then_some(model.as_str()))?;
|
||||||
(operation, None, translator)
|
(operation, None, translator)
|
||||||
} else {
|
} else {
|
||||||
let (operation, translator) = super::chat::prepare(operation, &terminal_context, affinity.as_ref())?;
|
let (operation, translator) = super::chat::prepare(operation, &terminal_context, affinity.as_ref().filter(|_| !native_api))?;
|
||||||
(operation, translator, None)
|
(operation, translator, None)
|
||||||
};
|
};
|
||||||
let headers = crate::transport::request_headers(&operation, headers, selected.account_switch);
|
let headers = crate::transport::request_headers(&operation, headers, selected.account_switch);
|
||||||
@@ -122,7 +144,13 @@ impl AntigravityProvider {
|
|||||||
if deadline.is_elapsed() {
|
if deadline.is_elapsed() {
|
||||||
Err(unsent(Kind::Timeout))?;
|
Err(unsent(Kind::Timeout))?;
|
||||||
}
|
}
|
||||||
|
let probe_token = (terminal_context.account_eligibility() == AccountEligibilityPolicy::BypassForDiagnostic)
|
||||||
|
.then(|| selected.material.token().to_owned());
|
||||||
let record_failure = async |error| {
|
let record_failure = async |error| {
|
||||||
|
let error = match &probe_token {
|
||||||
|
Some(token) => crate::transport::connection_test_error(error, token),
|
||||||
|
None => error,
|
||||||
|
};
|
||||||
feedback.record_failure(&selected.account, &model, records_account_feedback, error).await
|
feedback.record_failure(&selected.account, &model, records_account_feedback, error).await
|
||||||
};
|
};
|
||||||
let response = tokio::select! {
|
let response = tokio::select! {
|
||||||
@@ -130,7 +158,14 @@ impl AntigravityProvider {
|
|||||||
_ = cancellation.cancelled() => Err(ProviderError::new(Kind::Cancelled, UpstreamSendState::Ambiguous)),
|
_ = cancellation.cancelled() => Err(ProviderError::new(Kind::Cancelled, UpstreamSendState::Ambiguous)),
|
||||||
_ = deadline.wait() => Err(ProviderError::new(Kind::Timeout, UpstreamSendState::Ambiguous)),
|
_ = deadline.wait() => Err(ProviderError::new(Kind::Timeout, UpstreamSendState::Ambiguous)),
|
||||||
response = async {
|
response = async {
|
||||||
let token = &selected.material.access_token;
|
let token = selected.material.token();
|
||||||
|
let resource = match &resource {
|
||||||
|
Resource::GenAi(resource) => {
|
||||||
|
let action = if counted { "countTokens" } else if stream { "streamGenerateContent" } else { "generateContent" };
|
||||||
|
return resource.execute(model.as_str(), token, &body, action, &headers).await;
|
||||||
|
}
|
||||||
|
Resource::CloudCode(resource) => resource,
|
||||||
|
};
|
||||||
if counted {
|
if counted {
|
||||||
return resource.count_tokens(token, &body, &headers).await;
|
return resource.count_tokens(token, &body, &headers).await;
|
||||||
}
|
}
|
||||||
@@ -138,6 +173,7 @@ impl AntigravityProvider {
|
|||||||
Project::Catalog(project) => project,
|
Project::Catalog(project) => project,
|
||||||
// 固定探测使用该账号实际授权的项目,包括尚无公开目录的停用账号
|
// 固定探测使用该账号实际授权的项目,包括尚无公开目录的停用账号
|
||||||
Project::Discover => resource.account_info(token).await?.project,
|
Project::Discover => resource.account_info(token).await?.project,
|
||||||
|
Project::GenAi => return Err(unsent(Kind::ProviderInfrastructureUnavailable)),
|
||||||
};
|
};
|
||||||
let mode = if search {
|
let mode = if search {
|
||||||
crate::transport::GenerateMode::WebSearch
|
crate::transport::GenerateMode::WebSearch
|
||||||
@@ -155,10 +191,12 @@ impl AntigravityProvider {
|
|||||||
};
|
};
|
||||||
let context = crate::transport::ResponseContext {
|
let context = crate::transport::ResponseContext {
|
||||||
stream, model: model.clone(), deadline, cancel: cancellation,
|
stream, model: model.clone(), deadline, cancel: cancellation,
|
||||||
token: selected.material.access_token, pricing, started_at,
|
token: selected.material.into_token(), pricing, started_at,
|
||||||
};
|
};
|
||||||
let mut events: gateway_core::engine::provider::EventStream = if counted {
|
let mut events: gateway_core::engine::provider::EventStream = if counted {
|
||||||
Box::pin(crate::transport::count_events(response, context))
|
Box::pin(crate::transport::count_events(response, context))
|
||||||
|
} else if native_api {
|
||||||
|
Box::pin(crate::transport::genai_events(response, context))
|
||||||
} else {
|
} else {
|
||||||
Box::pin(crate::transport::events(response, context))
|
Box::pin(crate::transport::events(response, context))
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -31,6 +31,22 @@ impl AntigravityProvider {
|
|||||||
let feedback = async {
|
let feedback = async {
|
||||||
match error.kind() {
|
match error.kind() {
|
||||||
Kind::Unauthorized => {
|
Kind::Unauthorized => {
|
||||||
|
if account.authentication_kind() == crate::credential::api_key::API_KEY {
|
||||||
|
self.accounts
|
||||||
|
.apply_state_change(gateway_core::account::AccountStateChange {
|
||||||
|
account_id: account.id().clone(),
|
||||||
|
expected_revision: account.revision(),
|
||||||
|
credential_state: gateway_core::account::CredentialState::Invalid,
|
||||||
|
observed_at: SystemTime::now(),
|
||||||
|
error_reason: Some(
|
||||||
|
gateway_core::account::AccountErrorReason::CredentialInvalid,
|
||||||
|
),
|
||||||
|
message: Some("上游拒绝 API Key".into()),
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.map_err(|_| ())?;
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
// 资源服务拒绝 AT 不能证明 RT 失效,续期仍由已有 OAuth worker 负责
|
// 资源服务拒绝 AT 不能证明 RT 失效,续期仍由已有 OAuth worker 负责
|
||||||
self.accounts
|
self.accounts
|
||||||
.expire_access_token(account, SystemTime::now())
|
.expire_access_token(account, SystemTime::now())
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ use super::{
|
|||||||
AntigravityProvider,
|
AntigravityProvider,
|
||||||
candidates::{CandidatePool, Project},
|
candidates::{CandidatePool, Project},
|
||||||
};
|
};
|
||||||
use crate::{credential::Material, transport::unsent};
|
use crate::{credential::Authentication, transport::unsent};
|
||||||
use gateway_admin::model::provider_credentials::resolve_observed_plan;
|
use gateway_admin::model::provider_credentials::resolve_observed_plan;
|
||||||
use gateway_core::{
|
use gateway_core::{
|
||||||
account::{
|
account::{
|
||||||
@@ -29,7 +29,7 @@ use std::time::Duration;
|
|||||||
pub(super) struct SelectedAccount {
|
pub(super) struct SelectedAccount {
|
||||||
pub(super) account: ProviderAccount,
|
pub(super) account: ProviderAccount,
|
||||||
pub(super) capacity: Option<AccountCapacitySnapshot>,
|
pub(super) capacity: Option<AccountCapacitySnapshot>,
|
||||||
pub(super) material: Material,
|
pub(super) material: Authentication,
|
||||||
pub(super) snapshot: AccountHistorySnapshot,
|
pub(super) snapshot: AccountHistorySnapshot,
|
||||||
pub(super) project: Project,
|
pub(super) project: Project,
|
||||||
pub(super) lease: Box<dyn ProviderLeaseGuard>,
|
pub(super) lease: Box<dyn ProviderLeaseGuard>,
|
||||||
@@ -51,9 +51,11 @@ impl AntigravityProvider {
|
|||||||
ctx: &AttemptContext,
|
ctx: &AttemptContext,
|
||||||
affinity_key: Option<&ProviderSessionAffinityKey>,
|
affinity_key: Option<&ProviderSessionAffinityKey>,
|
||||||
search: bool,
|
search: bool,
|
||||||
|
method: &'static str,
|
||||||
) -> Result<SelectedAccount, ProviderError> {
|
) -> Result<SelectedAccount, ProviderError> {
|
||||||
let policy = ctx.account_selection_policy();
|
let policy = ctx.account_selection_policy();
|
||||||
let select = |queue| self.select_with_queue(model, ctx, queue, affinity_key, search);
|
let select =
|
||||||
|
|queue| self.select_with_queue(model, ctx, queue, affinity_key, search, method);
|
||||||
let result = match select(policy.queue_policy()).await {
|
let result = match select(policy.queue_policy()).await {
|
||||||
Err(SelectionError::Queue(reason)) if ctx.required_account().is_none() => {
|
Err(SelectionError::Queue(reason)) if ctx.required_account().is_none() => {
|
||||||
policy
|
policy
|
||||||
@@ -86,6 +88,7 @@ impl AntigravityProvider {
|
|||||||
queue: ConcurrencyQueuePolicy,
|
queue: ConcurrencyQueuePolicy,
|
||||||
affinity_key: Option<&ProviderSessionAffinityKey>,
|
affinity_key: Option<&ProviderSessionAffinityKey>,
|
||||||
search: bool,
|
search: bool,
|
||||||
|
method: &'static str,
|
||||||
) -> Result<SelectedAccount, SelectionError> {
|
) -> Result<SelectedAccount, SelectionError> {
|
||||||
let mut waiting = CapacityWait::new(
|
let mut waiting = CapacityWait::new(
|
||||||
&self.waiting,
|
&self.waiting,
|
||||||
@@ -106,7 +109,7 @@ impl AntigravityProvider {
|
|||||||
mut projects,
|
mut projects,
|
||||||
mut quotas,
|
mut quotas,
|
||||||
mut selection,
|
mut selection,
|
||||||
} = self.load_candidates(model, ctx, search).await?;
|
} = self.load_candidates(model, ctx, search, method).await?;
|
||||||
let affinity = match affinity_key.filter(|_| !ctx.is_diagnostic_required_account()) {
|
let affinity = match affinity_key.filter(|_| !ctx.is_diagnostic_required_account()) {
|
||||||
Some(key) => Some(ProviderSessionAffinityState::new(
|
Some(key) => Some(ProviderSessionAffinityState::new(
|
||||||
key,
|
key,
|
||||||
@@ -328,7 +331,7 @@ impl AntigravityProvider {
|
|||||||
&self,
|
&self,
|
||||||
account: &ProviderAccount,
|
account: &ProviderAccount,
|
||||||
ctx: &AttemptContext,
|
ctx: &AttemptContext,
|
||||||
) -> Result<(ProviderAccount, Material), ProviderError> {
|
) -> Result<(ProviderAccount, Authentication), ProviderError> {
|
||||||
let current = self
|
let current = self
|
||||||
.credentials
|
.credentials
|
||||||
.current(account.id())
|
.current(account.id())
|
||||||
@@ -339,7 +342,7 @@ impl AntigravityProvider {
|
|||||||
{
|
{
|
||||||
return Err(unsent(Kind::NoEligibleAccount));
|
return Err(unsent(Kind::NoEligibleAccount));
|
||||||
}
|
}
|
||||||
let material = self.credentials.material(¤t)?;
|
let material = self.credentials.authentication(¤t)?;
|
||||||
Ok((current.account, material))
|
Ok((current.account, material))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,155 @@
|
|||||||
|
//! GenAI API Key 上游仅使用公开模型路径,不携带 Cloud Code 身份和封套
|
||||||
|
|
||||||
|
use super::{
|
||||||
|
Catalog, Model,
|
||||||
|
client::{control, send},
|
||||||
|
failure::{sent, unsent},
|
||||||
|
};
|
||||||
|
use gateway_core::{
|
||||||
|
account::OutboundProxy,
|
||||||
|
engine::middleware::MiddlewareHeader,
|
||||||
|
error::{ProviderError, ProviderErrorKind as Kind},
|
||||||
|
};
|
||||||
|
use reqwest::{Client, Response};
|
||||||
|
use serde::Deserialize;
|
||||||
|
use std::{
|
||||||
|
collections::{BTreeMap, HashSet},
|
||||||
|
time::Duration,
|
||||||
|
};
|
||||||
|
use url::Url;
|
||||||
|
|
||||||
|
pub(crate) struct GenAiClient {
|
||||||
|
client: Client,
|
||||||
|
base_url: Url,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl GenAiClient {
|
||||||
|
pub(crate) fn new(base_url: Url, proxy: Option<&OutboundProxy>) -> Result<Self, ProviderError> {
|
||||||
|
Ok(Self::with_client(base_url, Self::build_client(proxy)?))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn build_client(proxy: Option<&OutboundProxy>) -> Result<Client, ProviderError> {
|
||||||
|
gateway_egress::http_client(proxy)
|
||||||
|
.map_err(|e| unsent(Kind::ProviderInfrastructureUnavailable).with_source(e))?
|
||||||
|
.use_rustls_tls()
|
||||||
|
.read_timeout(Duration::from_secs(600))
|
||||||
|
.redirect(reqwest::redirect::Policy::none())
|
||||||
|
.retry(reqwest::retry::never())
|
||||||
|
.build()
|
||||||
|
.map_err(|e| {
|
||||||
|
unsent(Kind::ProviderInfrastructureUnavailable).with_source(e.without_url())
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn with_client(base_url: Url, client: Client) -> Self {
|
||||||
|
Self { client, base_url }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn endpoint(&self, suffix: Option<&str>) -> Result<Url, ProviderError> {
|
||||||
|
let mut url = self.base_url.clone();
|
||||||
|
{
|
||||||
|
let mut path = url
|
||||||
|
.path_segments_mut()
|
||||||
|
.map_err(|_| unsent(Kind::ProviderInfrastructureUnavailable))?;
|
||||||
|
path.pop_if_empty().push("models");
|
||||||
|
if let Some(suffix) = suffix {
|
||||||
|
path.push(suffix);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(url)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) async fn catalog(&self, key: &str) -> Result<Catalog, ProviderError> {
|
||||||
|
tokio::time::timeout(Duration::from_secs(20), self.fetch_catalog(key))
|
||||||
|
.await
|
||||||
|
.map_err(|_| sent(Kind::Timeout))?
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn fetch_catalog(&self, key: &str) -> Result<Catalog, ProviderError> {
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
struct Page {
|
||||||
|
#[serde(default)]
|
||||||
|
models: Vec<Model>,
|
||||||
|
next_page_token: Option<String>,
|
||||||
|
}
|
||||||
|
let mut models = BTreeMap::new();
|
||||||
|
let mut seen = HashSet::new();
|
||||||
|
let mut next = None;
|
||||||
|
let mut total_bytes = 0usize;
|
||||||
|
for _ in 0..100 {
|
||||||
|
let mut request = self
|
||||||
|
.client
|
||||||
|
.get(self.endpoint(None)?)
|
||||||
|
.header("x-goog-api-key", key);
|
||||||
|
if let Some(token) = next {
|
||||||
|
request = request.query(&[("pageToken", token)]);
|
||||||
|
}
|
||||||
|
let page: Page = control(request, key).await?;
|
||||||
|
for model in page.models {
|
||||||
|
total_bytes = total_bytes.saturating_add(
|
||||||
|
serde_json::to_vec(&model)
|
||||||
|
.map_err(|_| sent(Kind::Protocol))?
|
||||||
|
.len(),
|
||||||
|
);
|
||||||
|
if total_bytes > 8 * 1024 * 1024 {
|
||||||
|
return Err(sent(Kind::MessageTooBig));
|
||||||
|
}
|
||||||
|
let id = model
|
||||||
|
.0
|
||||||
|
.get("name")
|
||||||
|
.and_then(serde_json::Value::as_str)
|
||||||
|
.and_then(|name| name.strip_prefix("models/"))
|
||||||
|
.filter(|id| !id.contains('/'))
|
||||||
|
.ok_or_else(|| sent(Kind::Protocol))?;
|
||||||
|
gateway_core::routing::UpstreamModelId::new(id)
|
||||||
|
.map_err(|_| sent(Kind::Protocol))?;
|
||||||
|
if model.supports_method("generateContent") || model.supports_method("countTokens")
|
||||||
|
{
|
||||||
|
models.insert(id.to_owned(), model);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
next = page.next_page_token.filter(|token| !token.is_empty());
|
||||||
|
let Some(token) = &next else {
|
||||||
|
return Ok(Catalog {
|
||||||
|
project: None,
|
||||||
|
models,
|
||||||
|
metadata: Default::default(),
|
||||||
|
});
|
||||||
|
};
|
||||||
|
if !seen.insert(token.clone()) {
|
||||||
|
return Err(sent(Kind::Protocol));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(sent(Kind::Protocol))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) async fn execute(
|
||||||
|
&self,
|
||||||
|
model: &str,
|
||||||
|
key: &str,
|
||||||
|
body: &[u8],
|
||||||
|
action: &str,
|
||||||
|
headers: &[MiddlewareHeader],
|
||||||
|
) -> Result<Response, ProviderError> {
|
||||||
|
let mut url = self.endpoint(Some(&format!("{model}:{action}")))?;
|
||||||
|
let media = if action == "streamGenerateContent" {
|
||||||
|
url.query_pairs_mut().append_pair("alt", "sse");
|
||||||
|
"text/event-stream"
|
||||||
|
} else {
|
||||||
|
"application/json"
|
||||||
|
};
|
||||||
|
send(
|
||||||
|
self.client
|
||||||
|
.post(url)
|
||||||
|
.header("x-goog-api-key", key)
|
||||||
|
.header(reqwest::header::CONTENT_TYPE, "application/json")
|
||||||
|
.header(reqwest::header::ACCEPT, media)
|
||||||
|
.body(body.to_vec()),
|
||||||
|
key,
|
||||||
|
headers,
|
||||||
|
media,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user