mirror of
https://github.com/zyycn/codex-proxy-rs.git
synced 2026-12-02 08:01:05 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cad1a9245e | ||
|
|
d4d1114e73 | ||
|
|
9e8a5a9b61 | ||
|
|
9a5bf55bdf | ||
|
|
f57a375407 | ||
|
|
82cb91e1af | ||
|
|
441c012613 | ||
|
|
983eca5fe7 | ||
|
|
e0b0ab14da | ||
|
|
b4bb97d1dc | ||
|
|
9f979110d2 | ||
|
|
a5cddfe4a5 |
@@ -4,7 +4,9 @@
|
||||
|
||||
## 领域必读
|
||||
|
||||
确定页面方案或审查结论前,读取[前端职责](../../../../docs/architecture.md#34-前端模块职责)、[文案与信息层级](../../../../docs/theme.md#界面文案与信息层级)和[界面验证](../../../../CONTRIBUTING.md#界面验证)的完整章节,局部修改同样读取。明确本次用户操作、原页面、最接近的同类实现及可复用基础组件,沿用既有设计与请求层,按本轮验收分工留存所需截图
|
||||
确定页面方案或审查结论前,读取[前端职责](../../../../docs/architecture.md#34-前端模块职责)、[文案与信息层级](../../../../docs/theme.md#界面文案与信息层级)和[界面验证](../../../../CONTRIBUTING.md#界面验证)的完整章节,局部修改同样读取。新增或移动文件时,页面与布局按同一套目录规则,根据调用范围和导出内容区分组件私有实现、共享常量和共享纯函数
|
||||
|
||||
明确本次用户操作、原页面、最接近的同类实现及可复用基础组件,沿用既有设计与请求层,按本轮验收分工留存所需截图
|
||||
|
||||
## 按改动补齐规范
|
||||
|
||||
|
||||
@@ -46,7 +46,9 @@ release/publish "$release_version"
|
||||
|
||||
- 尚未推送:补齐缺失的步骤,按入口原子推送分支和 tag
|
||||
- 已推送但未触发:使用入口提示的 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 的版本、正式版/预发行状态和中文变更正文;对照平台清单与工作流确认归档、校验和及镜像产物。
|
||||
工作流附加的安装说明和自动提交列表按其当前配置处理,不用它们替代手写的中文变更说明。
|
||||
- 回读 `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` 附件
|
||||
- 返回版本、tag 对应提交、Release/工作流链接及实际结果。失败、仍在构建或缺失产物时明确说明,不能称为发布成功;
|
||||
Release 和镜像已生成也不表示用户的运行实例已经升级。
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
require_relative 'release-metadata'
|
||||
require_relative 'published-channels'
|
||||
|
||||
# 构建和验证可以并行;调用方必须在仓库级发布锁内执行本脚本
|
||||
module ReleasePublication
|
||||
@@ -39,44 +39,69 @@ module ReleasePublication
|
||||
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)
|
||||
ref = "#{image}:#{name}"
|
||||
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 actual == digest
|
||||
raise "Promoted image digest changed: #{ref}" unless image_digest(ref) == digest
|
||||
end
|
||||
|
||||
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 GitHub release ID' unless release_id.match?(/\A\d+\z/)
|
||||
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')
|
||||
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)
|
||||
puts "Published #{version}; latest remains at #{current_versions.compact.join(', ')}"
|
||||
return
|
||||
end
|
||||
|
||||
# 两个服务不能原子更新;同时检查两侧版本,让失败重试可以补齐而旧版不能回退
|
||||
tag(image, digest, 'latest')
|
||||
run('gh', 'api', '--method', 'PATCH', endpoint, '-f', 'make_latest=true')
|
||||
tag(image, digest, 'latest') unless docker_latest == version && image_digest("#{image}:latest") == digest
|
||||
run('gh', 'api', '--method', 'PATCH', endpoint, '-f', 'make_latest=true') unless github_latest == "v#{version}"
|
||||
puts "Published #{version} and promoted latest"
|
||||
end
|
||||
end
|
||||
|
||||
if $PROGRAM_NAME == __FILE__
|
||||
begin
|
||||
ReleasePublication.publish(
|
||||
version: ENV.fetch('VERSION'), image: "#{ENV.fetch('REGISTRY')}/#{ENV.fetch('IMAGE_NAME')}",
|
||||
digest: ENV.fetch('DIGEST'), repository: ENV.fetch('GITHUB_REPOSITORY'),
|
||||
release_id: ENV.fetch('RELEASE_ID')
|
||||
)
|
||||
image = "#{ENV.fetch('REGISTRY')}/#{ENV.fetch('IMAGE_NAME')}"
|
||||
repository = ENV.fetch('GITHUB_REPOSITORY')
|
||||
case ARGV
|
||||
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
|
||||
warn "error: #{error.message}"
|
||||
exit 1
|
||||
|
||||
@@ -67,11 +67,12 @@ module PublishedChannels
|
||||
end
|
||||
missing = expected - uploaded
|
||||
raise "Incomplete release #{tag}: #{missing.join(', ')}" unless missing.empty?
|
||||
release
|
||||
end
|
||||
|
||||
def check_unpublished(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
|
||||
|
||||
def publish(version)
|
||||
|
||||
@@ -20,6 +20,31 @@ module ReleaseMetadata
|
||||
version(value).split('+', 2).first.include?('-')
|
||||
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)
|
||||
Gem::Version.new(version(value).split('+', 2).first)
|
||||
end
|
||||
@@ -67,7 +92,7 @@ module ReleaseMetadata
|
||||
end
|
||||
|
||||
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}"
|
||||
validate_notes(value)
|
||||
entries = platforms
|
||||
@@ -80,7 +105,6 @@ module ReleaseMetadata
|
||||
{
|
||||
'tag' => tag,
|
||||
'version' => value,
|
||||
'docker_version' => value.tr('+', '-'),
|
||||
'build_time' => Time.now.utc.iso8601,
|
||||
'git_sha' => git('rev-parse', 'HEAD'),
|
||||
'platform_matrix' => JSON.generate('include' => entries),
|
||||
@@ -113,13 +137,16 @@ end
|
||||
|
||||
if $PROGRAM_NAME == __FILE__
|
||||
begin
|
||||
command, value = ARGV
|
||||
raise 'usage: release-metadata.rb validate VERSION | outputs TAG' unless ARGV.length == 2
|
||||
command, value, ref = ARGV
|
||||
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
|
||||
when 'validate'
|
||||
value = ReleaseMetadata.version(value)
|
||||
value = ReleaseMetadata.validate_branch(value, ref)
|
||||
ReleaseMetadata.validate_notes(value)
|
||||
puts value
|
||||
when 'tag-commit'
|
||||
puts ReleaseMetadata.tag_commit(value, ref)
|
||||
when 'outputs'
|
||||
metadata = ReleaseMetadata.outputs(value)
|
||||
ReleaseMetadata.seal_manifest(metadata)
|
||||
|
||||
@@ -11,6 +11,10 @@ on:
|
||||
description: 'Recover the index for an already public release without rebuilding'
|
||||
type: boolean
|
||||
default: false
|
||||
recover_latest:
|
||||
description: 'Recover latest and the channel index for an already public stable release'
|
||||
type: boolean
|
||||
default: false
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -25,7 +29,7 @@ env:
|
||||
|
||||
jobs:
|
||||
release-info:
|
||||
if: ${{ !inputs.index_only }}
|
||||
if: ${{ !inputs.index_only && !inputs.recover_latest }}
|
||||
runs-on: ubuntu-26.04
|
||||
timeout-minutes: 10
|
||||
permissions:
|
||||
@@ -34,7 +38,6 @@ jobs:
|
||||
outputs:
|
||||
tag: ${{ steps.version.outputs.tag }}
|
||||
version: ${{ steps.version.outputs.version }}
|
||||
docker_version: ${{ steps.version.outputs.docker_version }}
|
||||
build_time: ${{ steps.version.outputs.build_time }}
|
||||
git_sha: ${{ steps.version.outputs.git_sha }}
|
||||
platform_matrix: ${{ steps.version.outputs.platform_matrix }}
|
||||
@@ -53,9 +56,15 @@ jobs:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
ref: ${{ inputs.tag }}
|
||||
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
|
||||
id: version
|
||||
env:
|
||||
@@ -273,7 +282,7 @@ jobs:
|
||||
shell: bash
|
||||
env:
|
||||
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 }}
|
||||
run: ruby .github/scripts/package-release.rb archives
|
||||
|
||||
@@ -443,6 +452,12 @@ jobs:
|
||||
username: ${{ github.actor }}
|
||||
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
|
||||
id: manifest
|
||||
shell: bash
|
||||
@@ -507,6 +522,7 @@ jobs:
|
||||
- name: Prepare release notes
|
||||
shell: bash
|
||||
env:
|
||||
BUILD_TYPE: ${{ needs.release-info.outputs.build_type }}
|
||||
INSTALLATION_NOTES: |
|
||||
## Linux 一键安装(Docker Compose)
|
||||
|
||||
@@ -521,17 +537,11 @@ jobs:
|
||||
run: |
|
||||
ruby <<'RUBY'
|
||||
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')
|
||||
File.write(output, "#{notes}\n\n#{installation}\n")
|
||||
File.write(output, "#{notes}\n")
|
||||
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
|
||||
uses: actions/attest@1e69f48acb82d1966a394da916b4c1698aa569d6 # v4.2.2
|
||||
with:
|
||||
@@ -542,7 +552,7 @@ jobs:
|
||||
uses: softprops/action-gh-release@8a0cd651e5b2365bd640854a3fa5dfc70e4875f3 # v3.0.4
|
||||
with:
|
||||
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 }}
|
||||
prerelease: ${{ needs.release-info.outputs.prerelease == 'true' }}
|
||||
# action 保留已公开 Release 的状态,新 Release 上传完成后仍保持草稿
|
||||
@@ -567,8 +577,34 @@ jobs:
|
||||
VERSION: ${{ needs.release-info.outputs.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:
|
||||
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
|
||||
concurrency:
|
||||
group: release-publication
|
||||
|
||||
@@ -54,7 +54,7 @@ pub struct SystemVersion {
|
||||
pub build_time: String,
|
||||
pub deployment_mode: String,
|
||||
pub update_channel: String,
|
||||
pub latest_version: String,
|
||||
pub latest_version: Option<String>,
|
||||
pub has_update: bool,
|
||||
pub update_cached: bool,
|
||||
pub update_warning: Option<String>,
|
||||
@@ -67,7 +67,7 @@ pub struct SystemVersion {
|
||||
pub struct SystemUpdateDetail {
|
||||
pub policy: SystemUpdatePolicy,
|
||||
pub current_version: String,
|
||||
pub latest_version: String,
|
||||
pub latest_version: Option<String>,
|
||||
pub has_update: bool,
|
||||
pub deployment_mode: String,
|
||||
pub build_type: String,
|
||||
|
||||
@@ -4,7 +4,7 @@ mod flow;
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use gateway_core::{routing::ProviderKind, runtime::SnapshotControl};
|
||||
use gateway_core::{account::ProviderAccountId, routing::ProviderKind, runtime::SnapshotControl};
|
||||
|
||||
use crate::{
|
||||
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> {
|
||||
let provider = self
|
||||
.providers
|
||||
|
||||
@@ -1,5 +1,108 @@
|
||||
//! 按 Provider 组织凭据导入、授权与提交边界测试
|
||||
//! 验证账号归属分派,并组织凭据导入、授权与提交边界测试
|
||||
|
||||
mod openai;
|
||||
mod peer;
|
||||
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());
|
||||
}
|
||||
|
||||
@@ -32,7 +32,7 @@ impl SystemOperations for RecordingSystemOperations {
|
||||
deployment_mode: "source".to_owned(),
|
||||
update_channel: "stable".to_owned(),
|
||||
|
||||
latest_version: "1.0.0".to_owned(),
|
||||
latest_version: None,
|
||||
has_update: false,
|
||||
update_cached: false,
|
||||
update_warning: None,
|
||||
@@ -50,7 +50,7 @@ impl SystemOperations for RecordingSystemOperations {
|
||||
available_channels: vec![gateway_admin::model::system::SystemUpdateChannel::Stable],
|
||||
},
|
||||
current_version: "1.0.0".to_owned(),
|
||||
latest_version: "1.0.0".to_owned(),
|
||||
latest_version: None,
|
||||
has_update: false,
|
||||
deployment_mode: "source".to_owned(),
|
||||
build_type: "source".to_owned(),
|
||||
|
||||
@@ -288,13 +288,13 @@ impl UpdateAccountRequest {
|
||||
}
|
||||
}
|
||||
|
||||
/// 编辑 OpenAI 账号的连接设置;OAuth 仅接受传输方式
|
||||
/// 连接字段由 Provider 按账号类型校验,未提供的选项不注入凭据文档
|
||||
#[derive(Clone, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct AccountConnectionUpdateRequest {
|
||||
pub protocol: Option<String>,
|
||||
pub base_url: Option<String>,
|
||||
pub transport: String,
|
||||
pub transport: Option<String>,
|
||||
pub api_key: Option<String>,
|
||||
}
|
||||
|
||||
@@ -310,7 +310,11 @@ impl AccountConnectionUpdateRequest {
|
||||
if let Some(base_url) = &self.base_url {
|
||||
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"));
|
||||
}
|
||||
if self.api_key.as_ref().is_some_and(|key| {
|
||||
@@ -324,8 +328,10 @@ impl AccountConnectionUpdateRequest {
|
||||
}
|
||||
|
||||
fn into_document(self) -> ProviderDocument {
|
||||
let mut material =
|
||||
Map::from_iter([("transport".to_owned(), Value::String(self.transport))]);
|
||||
let mut material = Map::new();
|
||||
if let Some(transport) = self.transport {
|
||||
material.insert("transport".to_owned(), Value::String(transport));
|
||||
}
|
||||
if let Some(protocol) = self.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 context = auth.context().mutation_context();
|
||||
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())
|
||||
.map_err(|_| AdminError::internal())?;
|
||||
let result = state
|
||||
.admin_services()
|
||||
.credentials()
|
||||
.for_provider(&provider)
|
||||
.for_account(&account_id)
|
||||
.await
|
||||
.map_err(map_service_error)?
|
||||
.rotate(RotateCredential {
|
||||
mutation: CredentialMutation {
|
||||
|
||||
@@ -86,7 +86,7 @@ struct SystemVersionView {
|
||||
deployment_mode: String,
|
||||
deployment_mode_label: String,
|
||||
update_channel: String,
|
||||
latest_version: String,
|
||||
latest_version: Option<String>,
|
||||
has_update: bool,
|
||||
update_cached: bool,
|
||||
update_warning: Option<String>,
|
||||
@@ -114,7 +114,7 @@ impl From<SystemVersion> for SystemVersionView {
|
||||
struct SystemUpdateDetailView {
|
||||
policy: SystemUpdatePolicy,
|
||||
current_version: String,
|
||||
latest_version: String,
|
||||
latest_version: Option<String>,
|
||||
has_update: bool,
|
||||
deployment_mode: String,
|
||||
deployment_mode_label: String,
|
||||
|
||||
@@ -109,27 +109,22 @@ pub fn model_not_found_response() -> (StatusCode, Json<Value>) {
|
||||
)
|
||||
}
|
||||
|
||||
/// 已提交的 Responses 流通过终止事件交付容量错误的等待头
|
||||
pub(crate) fn capacity_retry_headers(error: &EngineError) -> serde_json::Map<String, Value> {
|
||||
let mut headers = serde_json::Map::new();
|
||||
if let EngineError::Provider(provider) = error
|
||||
&& provider.kind() == ProviderErrorKind::UpstreamCapacityUnavailable
|
||||
&& let Some(response) = provider.client_visible_upstream_response()
|
||||
{
|
||||
for header in response.headers() {
|
||||
if (header.name().eq_ignore_ascii_case("retry-after")
|
||||
|| header.name().eq_ignore_ascii_case("retry-after-ms"))
|
||||
&& let Ok(value) = HeaderValue::from_bytes(header.value())
|
||||
&& let Ok(value) = value.to_str()
|
||||
{
|
||||
headers.insert(
|
||||
header.name().to_ascii_lowercase(),
|
||||
Value::String(value.to_owned()),
|
||||
);
|
||||
}
|
||||
}
|
||||
/// 将上游实际给出的等待头交给客户端错误事件
|
||||
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 失败响应,并应用客户端容量恢复合同
|
||||
|
||||
@@ -832,7 +832,7 @@ impl StreamingExecutionBody {
|
||||
Err(error) if self.committed => {
|
||||
self.push_stream_error(
|
||||
gateway_error_from_engine(&error),
|
||||
crate::data_plane::error::capacity_retry_headers(&error),
|
||||
crate::data_plane::error::upstream_retry_headers(&error),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -113,15 +113,9 @@ async fn stream_failure(
|
||||
error_encoder: Option<fn(&Value) -> Bytes>,
|
||||
append_done: bool,
|
||||
) -> Body {
|
||||
let status = response.status();
|
||||
let retry_after = response
|
||||
.headers()
|
||||
.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 (parts, body) = response.into_parts();
|
||||
let status = parts.status;
|
||||
let bytes = to_bytes(body, usize::MAX).await.unwrap_or_default();
|
||||
let json = serde_json::from_slice::<Value>(&bytes).ok();
|
||||
let raw_message = std::str::from_utf8(&bytes)
|
||||
.ok()
|
||||
@@ -144,16 +138,20 @@ async fn stream_failure(
|
||||
)
|
||||
});
|
||||
// HTTP 头已提交,按官方 SSE 错误合同保留允许下发的重试建议
|
||||
if let Some(retry_after) = retry_after
|
||||
&& let Some(error) = data["response"]["error"].as_object_mut()
|
||||
&& let Some(headers) = error
|
||||
.entry("headers")
|
||||
.or_insert_with(|| serde_json::json!({}))
|
||||
.as_object_mut()
|
||||
{
|
||||
headers
|
||||
.entry("retry-after")
|
||||
.or_insert(Value::String(retry_after));
|
||||
for name in gateway_protocol::http::RETRY_AFTER_HEADERS {
|
||||
if let Some(value) = parts
|
||||
.headers
|
||||
.get(name)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
&& let Some(error) = data["response"]["error"].as_object_mut()
|
||||
&& let Some(headers) = error
|
||||
.entry("headers")
|
||||
.or_insert_with(|| serde_json::json!({}))
|
||||
.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 {
|
||||
Some(encode) => encode(&data).to_vec(),
|
||||
|
||||
@@ -577,7 +577,7 @@ impl WebSocketExecutionBody {
|
||||
Err(error) if self.committed => {
|
||||
self.push_gateway_error(
|
||||
gateway_error_from_engine(&error),
|
||||
crate::data_plane::error::capacity_retry_headers(&error),
|
||||
crate::data_plane::error::upstream_retry_headers(&error),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -173,8 +173,13 @@ pub(super) fn initial_engine_error_event(
|
||||
};
|
||||
let upstream = provider.and_then(|error| error.client_visible_upstream_response());
|
||||
// 最终失败响应优先于会话快照,避免混入先前 attempt 或 opening 的关联头
|
||||
let mut headers =
|
||||
response_event_headers(upstream.map_or(response_headers, |response| response.headers()));
|
||||
let mut headers = if let Some((provider, response)) = provider.zip(upstream) {
|
||||
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() {
|
||||
// 会话 opening 身份不证明当前失败属于该请求;仅保留其他允许的会话头
|
||||
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"}
|
||||
});
|
||||
for (authenticated, transport, oauth, expected) in [
|
||||
(false, "http", false, StatusCode::UNAUTHORIZED),
|
||||
(true, "invalid", false, StatusCode::BAD_REQUEST),
|
||||
(false, Some("http"), false, StatusCode::UNAUTHORIZED),
|
||||
(true, Some("invalid"), false, StatusCode::BAD_REQUEST),
|
||||
// 夹具没有凭据 Store,合法输入必须进入服务,不能按普通设置静默保存
|
||||
(true, "http", false, StatusCode::SERVICE_UNAVAILABLE),
|
||||
(true, "http", true, StatusCode::SERVICE_UNAVAILABLE),
|
||||
(true, Some("http"), false, StatusCode::SERVICE_UNAVAILABLE),
|
||||
(true, Some("http"), true, StatusCode::SERVICE_UNAVAILABLE),
|
||||
(true, None, false, StatusCode::SERVICE_UNAVAILABLE),
|
||||
] {
|
||||
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 {
|
||||
input["connection"]
|
||||
.as_object_mut()
|
||||
|
||||
@@ -724,6 +724,20 @@ mod actions {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_api_key_connection_accepts_address_and_key_without_transport() {
|
||||
let request: UpdateAccountRequest = serde_json::from_value(json!({
|
||||
"accountId":"acct_api", "enabled":true, "concurrencyLimit":null,
|
||||
"weight":1, "groupIds":[],
|
||||
"connection":{"baseUrl":"https://relay.example/antigravity/v1beta","apiKey":"fixture-key"}
|
||||
})).unwrap();
|
||||
request.validate().unwrap();
|
||||
let connection = request.connection.unwrap();
|
||||
assert!(connection.protocol.is_none());
|
||||
assert!(connection.transport.is_none());
|
||||
assert_eq!(connection.api_key.as_deref(), Some("fixture-key"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn account_connection_update_rejects_invalid_fields_and_generic_credentials() {
|
||||
let request = json!({
|
||||
|
||||
@@ -216,7 +216,7 @@ impl SystemOperations for ProgressSystem {
|
||||
available_channels: vec![SystemUpdateChannel::Stable, SystemUpdateChannel::Beta],
|
||||
},
|
||||
current_version: "0.1.0".into(),
|
||||
latest_version: "0.2.0".into(),
|
||||
latest_version: Some("0.2.0".into()),
|
||||
has_update: true,
|
||||
deployment_mode: "docker".into(),
|
||||
build_type: "release".into(),
|
||||
|
||||
@@ -1416,7 +1416,7 @@ async fn streaming_bad_request_preserves_extended_error_fields_before_and_after_
|
||||
Some(b"application/json".to_vec()),
|
||||
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(
|
||||
@@ -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"))
|
||||
.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!(bytes.ends_with(b"data: [DONE]\n\n"));
|
||||
}
|
||||
@@ -2340,29 +2340,38 @@ async fn streaming_upstream_error_event_should_be_translated_to_response_failed_
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn streaming_capacity_error_after_commit_offers_client_retry() {
|
||||
for (code, expected) in [
|
||||
("server_is_overloaded", "server_error"),
|
||||
("slow_down", "server_error"),
|
||||
("previous_response_not_found", "previous_response_not_found"),
|
||||
async fn streaming_errors_after_commit_preserve_upstream_retry_headers() {
|
||||
for (kind, code, expected) in [
|
||||
(
|
||||
ProviderErrorKind::UpstreamCapacityUnavailable,
|
||||
"server_is_overloaded",
|
||||
"server_error",
|
||||
),
|
||||
(
|
||||
ProviderErrorKind::UpstreamCapacityUnavailable,
|
||||
"slow_down",
|
||||
"server_error",
|
||||
),
|
||||
(
|
||||
ProviderErrorKind::QuotaExhausted,
|
||||
"previous_response_not_found",
|
||||
"previous_response_not_found",
|
||||
),
|
||||
] {
|
||||
let trace = Arc::new(Trace::default());
|
||||
let error = ProviderError::new(
|
||||
ProviderErrorKind::UpstreamCapacityUnavailable,
|
||||
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 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(
|
||||
Arc::clone(&trace),
|
||||
vec![
|
||||
|
||||
@@ -720,7 +720,9 @@ async fn initial_quota_recovery_delivers_client_projection_instead_of_upstream_s
|
||||
ClientVisibleUpstreamResponse::new(
|
||||
400,
|
||||
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")]),
|
||||
);
|
||||
@@ -729,6 +731,7 @@ async fn initial_quota_recovery_delivers_client_projection_instead_of_upstream_s
|
||||
assert_eq!(error["error"], detail);
|
||||
assert_eq!(error["headers"]["x-request-id"], "req-quota-rejected");
|
||||
assert!(error["headers"].get("retry-after").is_none());
|
||||
assert_eq!(error["headers"]["retry-after-ms"], "777");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
||||
@@ -96,7 +96,7 @@ impl SystemOperations for VersionSystem {
|
||||
deployment_mode: "binary".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,
|
||||
update_cached: true,
|
||||
update_warning: Some("internal-update-warning".to_owned()),
|
||||
|
||||
@@ -21,6 +21,8 @@ pub use quota_settings::{
|
||||
};
|
||||
mod proxy;
|
||||
pub use proxy::{InvalidOutboundProxy, OutboundProxy};
|
||||
mod recent_requests;
|
||||
pub use recent_requests::{InvalidRecentRequestSnapshot, RecentRequestSnapshot};
|
||||
mod scheduling;
|
||||
pub mod scope;
|
||||
mod selection;
|
||||
@@ -36,6 +38,6 @@ pub(crate) use selection::smart_score;
|
||||
pub use selection::*;
|
||||
pub use store::{
|
||||
AccountCatalogObservation, AccountCatalogOmissions, ProviderAccountStore, QuotaWarmupState,
|
||||
QuotaWarmupStateUpdate, StoredAccountCatalog,
|
||||
QuotaWarmupStateUpdate, RecentRequestStore, StoredAccountCatalog,
|
||||
};
|
||||
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 in_flight: u32,
|
||||
/// 同模型最近一分钟已确认发送的请求数,按秒滚动
|
||||
pub recent_requests: u64,
|
||||
pub last_started_at: Option<SystemTime>,
|
||||
pub quota_reset_at: Option<SystemTime>,
|
||||
pub quota_reset_windows: Option<Arc<[AccountQuotaResetWindow]>>,
|
||||
@@ -368,9 +370,82 @@ impl AccountFeedback {
|
||||
#[derive(Debug, Default)]
|
||||
pub struct AccountFeedbackStats {
|
||||
accounts: RwLock<HashMap<AccountFeedbackKey, AccountFeedback>>,
|
||||
requests: Mutex<super::recent_requests::RecentRequests>,
|
||||
}
|
||||
|
||||
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
|
||||
#[must_use]
|
||||
pub fn scheduling_signals(
|
||||
@@ -978,6 +1053,8 @@ impl AccountSelector {
|
||||
|
||||
// 首输出 10 秒时延迟得分减半;固定尺度不随其他候选账号变化
|
||||
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 {
|
||||
context
|
||||
@@ -1012,7 +1089,10 @@ fn select_smart_candidate<'a>(
|
||||
pub(crate) fn smart_score(candidate: &AccountCandidate, context: &AccountSelectionContext) -> f64 {
|
||||
let config = context.policy.smart_scheduling();
|
||||
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
|
||||
.signals
|
||||
.quota_remaining_rank
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Provider 账号持久化端口
|
||||
|
||||
use async_trait::async_trait;
|
||||
use futures::future::BoxFuture;
|
||||
|
||||
use crate::error::StoreError;
|
||||
use crate::identity::ProviderKind;
|
||||
@@ -9,9 +10,19 @@ use super::{
|
||||
AccountStateChange, CredentialCasOutcome, CredentialCasUpdate, CredentialRevision,
|
||||
LoadedCredential, NewProviderAccount, ProviderAccount, ProviderAccountId,
|
||||
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 解释,归属不能按相同正文合并
|
||||
#[derive(Clone)]
|
||||
pub struct AccountCatalogObservation {
|
||||
|
||||
@@ -41,6 +41,7 @@ impl TraceContext {
|
||||
"blocker": AccountSelector.scheduling_blocker(candidate, context)
|
||||
.map(|blocker| format!("{blocker:?}")),
|
||||
"inFlight": signals.in_flight,
|
||||
"recentRequests": signals.recent_requests,
|
||||
"concurrencyLimit": context.concurrency_limit(candidate).get(),
|
||||
"quotaRemainingBasisPoints": signals.quota_remaining_rank,
|
||||
"quotaResetAtUnixMs": signals.quota_reset_at.and_then(|reset|
|
||||
|
||||
@@ -18,12 +18,14 @@ pub mod policy;
|
||||
pub mod probe;
|
||||
mod prompt_rewrite;
|
||||
pub mod provider;
|
||||
mod recent_request_persistence;
|
||||
pub mod response_control;
|
||||
pub mod upstream_adapter;
|
||||
|
||||
use crate::lifecycle::{Deadline, LeaseGuard};
|
||||
|
||||
pub use coordinator::{AttemptCoordinator, ResponseExecutionSession};
|
||||
pub use recent_request_persistence::RecentRequestPersistence;
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::fmt;
|
||||
|
||||
@@ -283,6 +283,8 @@ struct ProviderStreamAccountFeedback {
|
||||
provider_kind: ProviderKind,
|
||||
account_id: ProviderAccountId,
|
||||
failure_filter: fn(&ProviderError) -> bool,
|
||||
upstream_model: Option<UpstreamModelId>,
|
||||
request_recorded: bool,
|
||||
started_at: Option<Instant>,
|
||||
first_output_ms: Option<u64>,
|
||||
reported: bool,
|
||||
@@ -297,7 +299,27 @@ impl ProviderStreamAccountFeedback {
|
||||
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) {
|
||||
// 纯连接观测可能出现在未发送失败之前,不能单独证明请求已送达
|
||||
if event.has_client_event() {
|
||||
self.record_request();
|
||||
}
|
||||
if self.first_output_ms.is_some()
|
||||
|| !event.canonical_facts().iter().any(|event| {
|
||||
matches!(
|
||||
@@ -332,6 +354,9 @@ impl ProviderStreamAccountFeedback {
|
||||
}
|
||||
|
||||
fn report_failure(&mut self, error: &ProviderError) {
|
||||
if error.send_state() == UpstreamSendState::Sent {
|
||||
self.record_request();
|
||||
}
|
||||
if self.reported
|
||||
// `Ambiguous` 仍须关闭重放边界,但不能证明失败由账号造成;将它计入
|
||||
// 账号评分会把传输不确定性错误归因给账号
|
||||
@@ -523,6 +548,8 @@ impl ProviderStream {
|
||||
provider_kind: self.metadata.provider().clone(),
|
||||
account_id: self.metadata.provider_account_id().clone(),
|
||||
failure_filter,
|
||||
upstream_model: self.metadata.upstream_model().cloned(),
|
||||
request_recorded: false,
|
||||
started_at: None,
|
||||
first_output_ms: None,
|
||||
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,43 +1093,59 @@ impl ProviderError {
|
||||
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,
|
||||
mut recovery: Self,
|
||||
events: &[ProviderEvent],
|
||||
) -> Self {
|
||||
if self.kind() == ProviderErrorKind::UpstreamCapacityUnavailable
|
||||
&& let Some(response) = recovery.client_visible_upstream_response.as_deref_mut()
|
||||
{
|
||||
// 迁移响应继承原失败的等待头;其余旧账号头和错误正文不属于新响应
|
||||
let original = self.client_visible_upstream_response();
|
||||
let body = original.and_then(|original| serde_json::from_slice(original.body()).ok());
|
||||
let event = events
|
||||
.iter()
|
||||
.rev()
|
||||
.find_map(ProviderEvent::wire_event)
|
||||
.map(|wire| wire.data());
|
||||
for name in ["retry-after", "retry-after-ms"] {
|
||||
if let Some(header) = original.and_then(|original| {
|
||||
original
|
||||
.headers()
|
||||
.iter()
|
||||
.rev()
|
||||
.find(|h| h.name().eq_ignore_ascii_case(name))
|
||||
}) {
|
||||
response.headers.push(header.clone());
|
||||
} else if let Some(value) =
|
||||
event.into_iter().chain(body.as_ref()).find_map(|value| {
|
||||
gateway_protocol::openai::events::error_event_header(value, name)
|
||||
})
|
||||
{
|
||||
response.headers.push(ProviderResponseHeader::new(
|
||||
name,
|
||||
Bytes::copy_from_slice(value.as_bytes()),
|
||||
));
|
||||
}
|
||||
}
|
||||
if let Some(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() {
|
||||
self = self.with_continuation_unavailable_reason(reason);
|
||||
|
||||
@@ -5,6 +5,7 @@ mod model_access;
|
||||
mod proxy;
|
||||
mod quota_reset_priority;
|
||||
mod quota_settings;
|
||||
mod recent_requests;
|
||||
mod scope;
|
||||
mod selection;
|
||||
mod selection_diagnostics;
|
||||
@@ -56,6 +57,7 @@ fn candidate(id: &str, in_flight: u32, remaining: Option<u64>) -> AccountCandida
|
||||
account: account(id),
|
||||
signals: AccountRuntimeSignals {
|
||||
in_flight,
|
||||
recent_requests: 0,
|
||||
last_started_at: None,
|
||||
quota_reset_at: None,
|
||||
quota_reset_windows: None,
|
||||
@@ -229,6 +231,7 @@ fn diagnostic_selection_bypasses_all_local_account_eligibility() {
|
||||
),
|
||||
signals: AccountRuntimeSignals {
|
||||
in_flight: 0,
|
||||
recent_requests: 0,
|
||||
last_started_at: None,
|
||||
quota_reset_at: None,
|
||||
quota_reset_windows: None,
|
||||
@@ -249,6 +252,7 @@ fn diagnostic_selection_bypasses_all_local_account_eligibility() {
|
||||
),
|
||||
signals: AccountRuntimeSignals {
|
||||
in_flight: 0,
|
||||
recent_requests: 0,
|
||||
last_started_at: None,
|
||||
quota_reset_at: 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 signals = AccountRuntimeSignals {
|
||||
in_flight: 2,
|
||||
recent_requests: 0,
|
||||
last_started_at: Some(last_started_at),
|
||||
quota_reset_at: 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];
|
||||
assert_eq!(selected["concurrencyLimit"], 5);
|
||||
assert_eq!(selected["inFlight"], 1);
|
||||
assert_eq!(selected["recentRequests"], 0);
|
||||
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");
|
||||
}
|
||||
|
||||
@@ -2470,6 +2470,7 @@ impl Provider for PolicySelectingProvider {
|
||||
account,
|
||||
signals: AccountRuntimeSignals {
|
||||
in_flight: 0,
|
||||
recent_requests: 0,
|
||||
last_started_at: None,
|
||||
quota_reset_at: None,
|
||||
quota_reset_windows: None,
|
||||
|
||||
@@ -10,6 +10,7 @@ mod extensions;
|
||||
mod middleware;
|
||||
mod policy;
|
||||
mod provider;
|
||||
mod recent_request_persistence;
|
||||
mod response_control;
|
||||
|
||||
use gateway_core::engine::AttemptTrigger;
|
||||
|
||||
@@ -75,6 +75,7 @@ fn candidate(id: &str) -> AccountCandidate {
|
||||
.with_scheduling(None, AccountWeight::new(100).unwrap()),
|
||||
signals: AccountRuntimeSignals {
|
||||
in_flight: 0,
|
||||
recent_requests: 0,
|
||||
last_started_at: None,
|
||||
quota_reset_at: 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);
|
||||
assert_eq!(failure_rate, Some(0));
|
||||
assert!(first_output_ms.is_some_and(|value| value >= 2));
|
||||
assert_eq!(
|
||||
feedback.recent_requests(&provider, &account, Some("gpt-5")),
|
||||
1
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -367,16 +371,25 @@ fn provider_stream_should_report_confirmed_sent_failure_but_ignore_unconfirmed_f
|
||||
let metadata = ProviderCallMetadata::new(
|
||||
provider.clone(),
|
||||
UpstreamModelId::new("grok-4.5").expect("valid model"),
|
||||
account,
|
||||
account.clone(),
|
||||
UpstreamTransport::new("http_sse").expect("valid transport"),
|
||||
);
|
||||
let events: EventStream = Box::pin(stream::iter([Err(ProviderError::new(
|
||||
ProviderErrorKind::Transport,
|
||||
send_state,
|
||||
))]));
|
||||
let events: EventStream = Box::pin(stream::iter([
|
||||
Ok(gateway_core::event::ProviderEvent::observation(
|
||||
gateway_core::event::ProviderResponseObservation::new(
|
||||
UpstreamTransport::new("http_sse").unwrap(),
|
||||
),
|
||||
)),
|
||||
Err(ProviderError::new(ProviderErrorKind::Transport, send_state)),
|
||||
]));
|
||||
let mut provider_stream =
|
||||
ProviderStream::new(metadata, events, ()).with_account_feedback(Arc::clone(&feedback));
|
||||
futures::executor::block_on(async {
|
||||
provider_stream.next().await.unwrap().unwrap();
|
||||
assert_eq!(
|
||||
feedback.recent_requests(&provider, &account, Some("grok-4.5")),
|
||||
0
|
||||
);
|
||||
assert!(
|
||||
provider_stream
|
||||
.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!(
|
||||
feedback.scheduling_signals(&provider, &sent_account).0,
|
||||
Some(2_000)
|
||||
@@ -434,6 +458,10 @@ fn provider_stream_should_ignore_repeated_failures_rejected_by_the_filter() {
|
||||
feedback.scheduling_signals(&provider, &account),
|
||||
(None, None)
|
||||
);
|
||||
assert_eq!(
|
||||
feedback.recent_requests(&provider, &account, Some("gpt-5")),
|
||||
100
|
||||
);
|
||||
}
|
||||
|
||||
#[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(),
|
||||
AccountRuntimeSignals {
|
||||
in_flight: 2,
|
||||
recent_requests: 0,
|
||||
last_started_at: None,
|
||||
quota_reset_at: None,
|
||||
quota_reset_windows: None,
|
||||
|
||||
@@ -37,6 +37,7 @@ fn candidate(id: &str, busy: bool) -> AccountCandidate {
|
||||
inherited_concurrency: None,
|
||||
signals: AccountRuntimeSignals {
|
||||
in_flight: u32::from(busy),
|
||||
recent_requests: 0,
|
||||
last_started_at: None,
|
||||
quota_reset_at: None,
|
||||
quota_reset_windows: None,
|
||||
|
||||
@@ -13,9 +13,7 @@ use yaml_rust2::Yaml;
|
||||
|
||||
use super::diagnostics::Diagnostics;
|
||||
use super::metadata::{Metadata, published_version};
|
||||
use super::release::{
|
||||
GitHubRelease, base_update_detail, detail_from_release, update_target_allowed,
|
||||
};
|
||||
use super::release::{GitHubRelease, base_update_detail, update_target_allowed};
|
||||
use super::{OperationError, SystemUpdateConfig, conflict, upstream};
|
||||
|
||||
const NORMAL: Duration = Duration::from_secs(1200);
|
||||
@@ -155,11 +153,14 @@ impl ReleaseCache {
|
||||
let (mut detail, target) = candidate(config, channel, &index)?;
|
||||
detail.cached = cached;
|
||||
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
|
||||
&& 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;
|
||||
}
|
||||
@@ -173,6 +174,7 @@ impl ReleaseCache {
|
||||
&self,
|
||||
config: &SystemUpdateConfig,
|
||||
target: &Version,
|
||||
has_update: bool,
|
||||
age: Duration,
|
||||
diagnostics: &Diagnostics,
|
||||
) -> Result<(Option<Arc<GitHubRelease>>, bool), OperationError> {
|
||||
@@ -191,8 +193,12 @@ impl ReleaseCache {
|
||||
entries.push_back((target.clone(), Arc::clone(&slot)));
|
||||
slot
|
||||
};
|
||||
slot.get(age, self.metadata.release(config, target), diagnostics)
|
||||
.await
|
||||
slot.get(
|
||||
age,
|
||||
self.metadata.release(config, target, has_update),
|
||||
diagnostics,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub(super) async fn install(
|
||||
@@ -209,10 +215,10 @@ impl ReleaseCache {
|
||||
.get(Duration::ZERO, self.metadata.index(config), diagnostics)
|
||||
.await?;
|
||||
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("远端最新版本已变化,请重新检查并确认"));
|
||||
}
|
||||
self.exact(config, &target, Duration::ZERO, diagnostics)
|
||||
self.exact(config, &target, true, Duration::ZERO, diagnostics)
|
||||
.await?
|
||||
.0
|
||||
.ok_or_else(|| upstream("发布索引指向的 Release 不存在"))
|
||||
@@ -231,11 +237,7 @@ fn candidate(
|
||||
.map_err(|_| conflict("当前版本号无效"))?;
|
||||
let target = published_version(index, ¤t, channel)?;
|
||||
let mut detail = base_update_detail(config, channel, None, None);
|
||||
if update_target_allowed(¤t, &target, channel) {
|
||||
detail.latest_version = target.to_string();
|
||||
detail.has_update = true;
|
||||
Ok((detail, target))
|
||||
} else {
|
||||
Ok((detail, current))
|
||||
}
|
||||
detail.latest_version = Some(target.to_string());
|
||||
detail.has_update = update_target_allowed(¤t, &target, channel);
|
||||
Ok((detail, target))
|
||||
}
|
||||
|
||||
@@ -83,6 +83,7 @@ impl Metadata {
|
||||
&self,
|
||||
config: &SystemUpdateConfig,
|
||||
version: &Version,
|
||||
has_update: bool,
|
||||
) -> Result<Option<Arc<GitHubRelease>>, OperationError> {
|
||||
let mut url =
|
||||
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 {
|
||||
return Err(upstream("GitHub 发行身份与发布索引不符"));
|
||||
}
|
||||
if config.version.trim_start_matches('v') != version {
|
||||
if has_update {
|
||||
release.install_assets(&version, &config.github_api_base)?;
|
||||
}
|
||||
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> {
|
||||
let target = target.ok_or_else(|| conflict("请先确认目标版本"))?;
|
||||
let target = normalize_version(&target);
|
||||
@@ -364,14 +334,14 @@ pub(super) fn base_update_detail(
|
||||
SystemUpdateDetail {
|
||||
policy: update_policy(config, channel),
|
||||
current_version: config.version.clone(),
|
||||
latest_version: config.version.clone(),
|
||||
latest_version: None,
|
||||
has_update: false,
|
||||
deployment_mode: config.deployment_mode.clone(),
|
||||
build_type: config.build_type.clone(),
|
||||
release_url: None,
|
||||
notes: None,
|
||||
cached: false,
|
||||
update_supported: unsupported_reason.is_none() && warning.is_none(),
|
||||
update_supported: unsupported_reason.is_none(),
|
||||
unsupported_reason,
|
||||
warning: warning.map(|error| error.message().to_owned()),
|
||||
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))
|
||||
.await
|
||||
.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.available_channels,
|
||||
@@ -42,11 +42,11 @@ async fn temporary_channel_should_filter_future_releases_without_changing_runnin
|
||||
.await
|
||||
.expect("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");
|
||||
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(), "检查通道不能写入实例偏好");
|
||||
let requests = server.received_requests().await.expect("requests");
|
||||
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() {
|
||||
let server = MockServer::start().await;
|
||||
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()));
|
||||
config.version = "1.1.0-beta.1".into();
|
||||
let service = ProcessSystemOperations::new(CancellationToken::new(), config.clone());
|
||||
let temporary = service
|
||||
.update_detail(SystemUpdateCheck::Refresh, Some(Stable))
|
||||
.await
|
||||
.expect("view stable");
|
||||
assert_eq!(temporary.policy.channel, Stable);
|
||||
assert!(!temporary.has_update);
|
||||
assert_eq!(temporary.latest_version, "1.1.0-beta.1");
|
||||
for check in [SystemUpdateCheck::Summary, SystemUpdateCheck::Refresh] {
|
||||
let temporary = service
|
||||
.update_detail(check, Some(Stable))
|
||||
.await
|
||||
.expect("view stable");
|
||||
assert_eq!(temporary.policy.channel, Stable);
|
||||
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!(
|
||||
service
|
||||
.update_detail(SystemUpdateCheck::Detail, None)
|
||||
@@ -231,7 +241,7 @@ async fn inferred_prerelease_policy_should_follow_future_minor_and_patch_release
|
||||
.await
|
||||
.expect("check");
|
||||
assert!(detail.has_update);
|
||||
assert_eq!(detail.latest_version, target);
|
||||
assert_eq!(detail.latest_version.as_deref(), Some(target));
|
||||
assert_eq!(
|
||||
complete_update(&service, target).await.operation.status,
|
||||
SystemOperationStatus::Succeeded
|
||||
|
||||
@@ -78,7 +78,7 @@ async fn discovery_request_budget_is_constant_under_load() {
|
||||
.update_detail(SystemUpdateCheck::Summary, None)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(summary.latest_version, target);
|
||||
assert_eq!(summary.latest_version.as_deref(), Some(target.as_str()));
|
||||
assert!(summary.notes.is_none());
|
||||
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 {
|
||||
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"));
|
||||
}
|
||||
for _ in 0..64 {
|
||||
@@ -199,6 +199,10 @@ async fn api_cooldown_is_shared_and_summary_does_not_advertise_an_unverified_rel
|
||||
.await
|
||||
.unwrap();
|
||||
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("限流应提供重试时间");
|
||||
assert!((298..=300).contains(&(retry_at - chrono::Utc::now()).num_seconds()));
|
||||
for _ in 0..32 {
|
||||
@@ -306,7 +310,11 @@ async fn install_rechecks_even_a_warm_candidate_and_never_downloads_a_changed_ta
|
||||
.await
|
||||
.unwrap();
|
||||
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!(status.operation.error.unwrap().contains("重新检查并确认"));
|
||||
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)
|
||||
.await
|
||||
.expect("detail");
|
||||
assert_eq!(detail.latest_version, "1.0.0");
|
||||
assert!(detail.latest_version.is_none());
|
||||
assert!(!detail.update_supported);
|
||||
assert!(detail.unsupported_reason.is_some());
|
||||
assert!(!detail.has_update);
|
||||
@@ -107,10 +107,7 @@ async fn update_checks_should_follow_stage_promotion_and_experimental_isolation(
|
||||
.await
|
||||
.expect("detail");
|
||||
assert_eq!(detail.has_update, allowed, "{current} -> {target}");
|
||||
assert_eq!(
|
||||
detail.latest_version,
|
||||
if allowed { target } else { current }
|
||||
);
|
||||
assert_eq!(detail.latest_version.as_deref(), allowed.then_some(target));
|
||||
assert_eq!(detail.notes.is_some(), allowed);
|
||||
assert_eq!(detail.release_url.is_some(), 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)
|
||||
.await
|
||||
.expect("current release");
|
||||
assert_eq!(detail.latest_version, current);
|
||||
assert_eq!(detail.latest_version.as_deref(), Some(current));
|
||||
assert!(!detail.has_update);
|
||||
assert!(detail.update_supported);
|
||||
assert_eq!(
|
||||
@@ -193,15 +190,15 @@ async fn update_detail_should_keep_current_release_notes_without_allowing_reinst
|
||||
|
||||
#[tokio::test]
|
||||
async fn update_checks_should_ignore_downgrades_unknown_stages_and_build_metadata() {
|
||||
for (current, target) in [
|
||||
("3.12.0-beta.2", "3.12.0-beta.1"),
|
||||
("3.12.0", "3.12.0+new-build"),
|
||||
("3.12.0-beta.1+aaa", "3.12.0-beta.1+zzz"),
|
||||
("3.12.0", "3.11.0"),
|
||||
("3.12.0-alpha.1", "3.12.0-preview.2"),
|
||||
("3.12.0-alpha.1", "3.12.0-beta"),
|
||||
("3.12.0-alpha.1", "3.12.0-beta.0"),
|
||||
("3.12.0-alpha.1", "3.12.0-beta.2.extra"),
|
||||
for (current, target, published) in [
|
||||
("3.12.0-beta.2", "3.12.0-beta.1", true),
|
||||
("3.12.0", "3.12.0+new-build", true),
|
||||
("3.12.0-beta.1+aaa", "3.12.0-beta.1+zzz", true),
|
||||
("3.12.0", "3.11.0", true),
|
||||
("3.12.0-alpha.1", "3.12.0-preview.2", false),
|
||||
("3.12.0-alpha.1", "3.12.0-beta", false),
|
||||
("3.12.0-alpha.1", "3.12.0-beta.0", false),
|
||||
("3.12.0-alpha.1", "3.12.0-beta.2.extra", false),
|
||||
] {
|
||||
let server = MockServer::start().await;
|
||||
let fixture = Fixture::new();
|
||||
@@ -214,9 +211,12 @@ async fn update_checks_should_ignore_downgrades_unknown_stages_and_build_metadat
|
||||
.await
|
||||
.expect("detail");
|
||||
assert!(!detail.has_update, "{current} -> {target}");
|
||||
assert_eq!(detail.latest_version, current);
|
||||
assert!(detail.notes.is_none());
|
||||
assert!(detail.release_url.is_none());
|
||||
assert_eq!(
|
||||
detail.latest_version.as_deref(),
|
||||
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()),
|
||||
signals: AccountRuntimeSignals {
|
||||
in_flight: 0,
|
||||
recent_requests: 0,
|
||||
last_started_at: None,
|
||||
quota_reset_at: None,
|
||||
quota_reset_windows: None,
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
//! 跨协议 HTTP 传输、下游环境头分类与重试时间解析
|
||||
|
||||
/// 上游可交给客户端的秒级与毫秒级重试等待头
|
||||
pub const RETRY_AFTER_HEADERS: [&str; 2] = ["retry-after", "retry-after-ms"];
|
||||
|
||||
/// 解析 HTTP 和流内错误共用的 Retry-After,保留零延迟并向上取整剩余秒数
|
||||
pub fn parse_retry_after_seconds(value: &str) -> Option<u64> {
|
||||
let now = std::time::SystemTime::now();
|
||||
|
||||
@@ -301,6 +301,21 @@ async fn connect(
|
||||
oauth_pending,
|
||||
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(
|
||||
credential_leases,
|
||||
));
|
||||
@@ -322,6 +337,7 @@ async fn connect(
|
||||
admission_release_writer,
|
||||
budget_writer,
|
||||
lease_cleanup,
|
||||
recent_requests,
|
||||
)?,
|
||||
None,
|
||||
),
|
||||
|
||||
@@ -674,6 +674,7 @@ impl RedisProviderLeaseCoordinator {
|
||||
account,
|
||||
AccountRuntimeSignals {
|
||||
in_flight: signal.in_flight,
|
||||
recent_requests: 0,
|
||||
last_started_at: signal.last_started_at.map(Into::into),
|
||||
quota_reset_at: None,
|
||||
quota_reset_windows: None,
|
||||
|
||||
@@ -16,6 +16,7 @@ mod native_continuation;
|
||||
mod oauth_pending;
|
||||
mod provider_session_affinity;
|
||||
mod provider_session_exclusion;
|
||||
mod recent_requests;
|
||||
mod runtime_change;
|
||||
pub(crate) mod worker_lease;
|
||||
|
||||
@@ -32,6 +33,7 @@ pub use native_continuation::*;
|
||||
pub use oauth_pending::*;
|
||||
pub use provider_session_affinity::*;
|
||||
pub use provider_session_exclusion::*;
|
||||
pub use recent_requests::*;
|
||||
pub use runtime_change::*;
|
||||
|
||||
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,
|
||||
budget_writer: postgres::ClientBudgetWriter,
|
||||
lease_cleanup: impl DaemonTask + 'static,
|
||||
recent_requests: Option<gateway_core::engine::RecentRequestPersistence>,
|
||||
) -> StoreResult<Vec<WorkerContribution>> {
|
||||
let stale_id = WorkerId::try_new(WorkerKind::StaleModelRequestRecovery, "postgres")
|
||||
.map_err(worker_definition_error)?;
|
||||
@@ -123,7 +124,7 @@ pub(crate) fn store_worker_contributions(
|
||||
let ops_flush_restart =
|
||||
DaemonRestartPolicy::try_new(Duration::from_secs(1), Duration::from_secs(60))
|
||||
.map_err(worker_definition_error)?;
|
||||
Ok(vec![
|
||||
let mut contributions = vec![
|
||||
WorkerContribution::Registration(
|
||||
WorkerRegistration::try_new(
|
||||
lease_cleanup_id,
|
||||
@@ -179,7 +180,21 @@ pub(crate) fn store_worker_contributions(
|
||||
)
|
||||
.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(
|
||||
|
||||
@@ -12,4 +12,5 @@ mod native_continuation;
|
||||
mod oauth_pending;
|
||||
mod provider_session_affinity;
|
||||
mod provider_session_exclusion;
|
||||
mod recent_requests;
|
||||
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 {
|
||||
credential_refresh: oauth,
|
||||
reauthorize: oauth,
|
||||
credential_export: oauth,
|
||||
credential_export: oauth || authentication_kind == crate::credential::api_key::API_KEY,
|
||||
quota: oauth,
|
||||
quota_refresh: oauth,
|
||||
quota_credits: oauth,
|
||||
@@ -194,6 +194,21 @@ impl ProviderAdmin for AntigravityAdmin {
|
||||
) -> Result<ProviderModels, ProviderAdminError> {
|
||||
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(
|
||||
&self,
|
||||
_: &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 {
|
||||
return Err(error(Kind::Invalid));
|
||||
}
|
||||
if let AuthorizationMutationTarget::Reauthorize { account_id } = mutation.target() {
|
||||
self.credentials.current(account_id).await?;
|
||||
if let AuthorizationMutationTarget::Reauthorize { account_id } = mutation.target()
|
||||
&& self
|
||||
.credentials
|
||||
.current(account_id)
|
||||
.await?
|
||||
.account
|
||||
.authentication_kind()
|
||||
!= "oauth"
|
||||
{
|
||||
return Err(error(Kind::Unsupported));
|
||||
}
|
||||
let flow_id = random_value()?;
|
||||
let state = random_value()?;
|
||||
|
||||
@@ -18,7 +18,7 @@ use gateway_core::{
|
||||
},
|
||||
};
|
||||
use std::{
|
||||
collections::BTreeMap,
|
||||
collections::{BTreeMap, BTreeSet},
|
||||
sync::{
|
||||
Arc, Mutex,
|
||||
atomic::{AtomicU64, AtomicUsize, Ordering},
|
||||
@@ -139,7 +139,10 @@ impl CatalogService {
|
||||
for StoredAccountCatalog { accounts, document } in docs {
|
||||
let accounts: Vec<_> = accounts
|
||||
.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();
|
||||
if !accounts.is_empty() {
|
||||
let catalog = serde_json::from_slice(&document)
|
||||
@@ -170,6 +173,7 @@ impl CatalogService {
|
||||
BTreeMap::<UpstreamModelId, BTreeMap<ProviderAccountId, AccountModelMetadata>>::new();
|
||||
let mut groups = BTreeMap::new();
|
||||
let mut search_models = BTreeMap::new();
|
||||
let mut operations = BTreeMap::<UpstreamModelId, BTreeSet<OperationKind>>::new();
|
||||
for (accounts, catalog) in self.catalogs().await? {
|
||||
super::model_groups::collect(&mut groups, &catalog, &accounts);
|
||||
if let Some(search_model) = catalog
|
||||
@@ -185,6 +189,13 @@ impl CatalogService {
|
||||
let discovery_order = catalog.discovery_order();
|
||||
for (key, model) in catalog.models {
|
||||
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());
|
||||
members.entry(id).or_default().extend(
|
||||
accounts
|
||||
@@ -193,20 +204,25 @@ impl CatalogService {
|
||||
);
|
||||
}
|
||||
}
|
||||
let capabilities = ModelCapabilities::new(
|
||||
[OperationKind::Generate, OperationKind::CountTokens].into(),
|
||||
None,
|
||||
)
|
||||
.with_native_web_search_helper("gemini-3.1-flash-lite-preview", search_models)
|
||||
.with_generation_protocol(gateway_protocol::genai::GENAI_PROTOCOL)
|
||||
.with_translated_generation_protocols([gateway_protocol::chat_completions::CHAT_PROTOCOL])
|
||||
.with_upstream_feature_validation();
|
||||
let capabilities = |operations| {
|
||||
ModelCapabilities::new(operations, None)
|
||||
.with_native_web_search_helper(
|
||||
"gemini-3.1-flash-lite-preview",
|
||||
search_models.clone(),
|
||||
)
|
||||
.with_generation_protocol(gateway_protocol::genai::GENAI_PROTOCOL)
|
||||
.with_translated_generation_protocols([
|
||||
gateway_protocol::chat_completions::CHAT_PROTOCOL,
|
||||
])
|
||||
.with_upstream_feature_validation()
|
||||
};
|
||||
let mut models = BTreeMap::new();
|
||||
for (id, metadata) in members {
|
||||
let accounts = metadata.keys().cloned().collect();
|
||||
let model = ProviderModelCapabilities::new(
|
||||
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));
|
||||
}
|
||||
@@ -219,7 +235,8 @@ impl CatalogService {
|
||||
.collect();
|
||||
ProviderModelCapabilities::new(
|
||||
id,
|
||||
capabilities.clone().with_reasoning_variants(variants),
|
||||
capabilities([OperationKind::Generate, OperationKind::CountTokens].into())
|
||||
.with_reasoning_variants(variants),
|
||||
)
|
||||
.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
|
||||
.credentials
|
||||
.material(¤t)
|
||||
@@ -332,7 +366,13 @@ impl CatalogService {
|
||||
account_id: account.id().clone(),
|
||||
revision: account.revision(),
|
||||
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,
|
||||
};
|
||||
let body = serde_json::to_vec(&catalog).map_err(|_| error(AdminKind::Internal))?;
|
||||
@@ -429,7 +469,7 @@ impl CatalogService {
|
||||
.await
|
||||
.map_err(|e| WorkerTaskError::safe("读取 Antigravity 账号失败").with_source(e))?;
|
||||
due.retain(|account| {
|
||||
account.authentication_kind() == "oauth"
|
||||
matches!(account.authentication_kind(), "oauth" | "api_key")
|
||||
&& observations.get(account.id()).is_none_or(|observation| {
|
||||
observation.revision != account.revision()
|
||||
|| observation.observed_at.elapsed().unwrap_or_default()
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
use super::{
|
||||
CredentialService, Material,
|
||||
api_key::{API_KEY, ApiKeyDocument, ApiKeyMaterial},
|
||||
oauth::{error, valid_token},
|
||||
};
|
||||
use chrono::{DateTime, Utc};
|
||||
@@ -23,7 +24,14 @@ use std::collections::HashSet;
|
||||
struct AccountFile {
|
||||
provider: String,
|
||||
version: u32,
|
||||
accounts: Vec<AccountEntry>,
|
||||
accounts: Vec<Entry>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
#[serde(untagged)]
|
||||
enum Entry {
|
||||
ApiKey(ApiKeyDocument),
|
||||
OAuth(AccountEntry),
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
@@ -56,16 +64,29 @@ impl CredentialService {
|
||||
&self,
|
||||
input: PrepareCredentialImport,
|
||||
) -> Result<PreparedCredentialImport, ProviderAdminError> {
|
||||
let file: AccountFile = serde_json::from_value(Value::Object(
|
||||
input.document.into_provider_data().into_inner(),
|
||||
))
|
||||
.map_err(|_| error(Kind::Invalid))?;
|
||||
let document = Value::Object(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))?;
|
||||
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() {
|
||||
return Err(error(Kind::Invalid));
|
||||
}
|
||||
let mut tokens = HashSet::new();
|
||||
// 全部本地格式检查先于任何可能轮换 RT 的上游请求
|
||||
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)
|
||||
|| !valid_token(&entry.refresh_token)
|
||||
|| !tokens.insert(entry.refresh_token.as_str())
|
||||
@@ -75,14 +96,30 @@ impl CredentialService {
|
||||
}
|
||||
let mut credentials = Vec::with_capacity(file.accounts.len());
|
||||
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 {
|
||||
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
|
||||
.oauth
|
||||
.verify_import(
|
||||
&entry.refresh_token,
|
||||
input.default_outbound_proxy.as_ref(),
|
||||
&profile,
|
||||
profile.as_ref().ok_or_else(|| error(Kind::Internal))?,
|
||||
)
|
||||
.await?;
|
||||
if !subjects.insert(grant.material.subject.clone()) {
|
||||
@@ -106,16 +143,20 @@ impl CredentialService {
|
||||
&self,
|
||||
input: PrepareCredentialRotation,
|
||||
) -> 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));
|
||||
}
|
||||
let account_id =
|
||||
ProviderAccountId::new(input.account.id).map_err(|_| error(Kind::Invalid))?;
|
||||
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));
|
||||
}
|
||||
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(
|
||||
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 accounts = Vec::with_capacity(credentials.len());
|
||||
for input in credentials {
|
||||
if input.account.provider_kind != self.kind
|
||||
|| input.account.authentication_kind != "oauth"
|
||||
{
|
||||
if input.account.provider_kind != self.kind {
|
||||
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));
|
||||
}
|
||||
let material: Material = serde_json::from_value(Value::Object(
|
||||
@@ -158,7 +209,7 @@ impl CredentialService {
|
||||
}
|
||||
account_ids
|
||||
.push(ProviderAccountId::new(input.account.id).map_err(|_| error(Kind::Invalid))?);
|
||||
accounts.push(AccountEntry {
|
||||
accounts.push(Entry::OAuth(AccountEntry {
|
||||
label: input.account.name,
|
||||
refresh_token: material.refresh_token,
|
||||
access_token: Some(material.access_token),
|
||||
@@ -169,7 +220,7 @@ impl CredentialService {
|
||||
plan_type: input.account.plan_type,
|
||||
created_at: Some(input.account.created_at),
|
||||
updated_at: Some(input.account.updated_at),
|
||||
});
|
||||
}));
|
||||
}
|
||||
let Value::Object(document) = serde_json::to_value(AccountFile {
|
||||
provider: self.kind.as_str().to_owned(),
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! OAuth 流程、账号凭据与文件导入导出
|
||||
|
||||
pub(crate) mod api_key;
|
||||
mod authorization;
|
||||
pub(crate) mod catalog;
|
||||
mod documents;
|
||||
@@ -10,4 +11,4 @@ mod refresh;
|
||||
mod service;
|
||||
pub(crate) use authorization::AuthorizationService;
|
||||
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)?
|
||||
.filter(|a| a.provider() == &self.kind)
|
||||
.ok_or_else(|| error(Kind::NotFound))?;
|
||||
if account.authentication_kind() == super::super::api_key::API_KEY {
|
||||
return Ok(ProviderQuota::default());
|
||||
}
|
||||
let observations = self
|
||||
.accounts
|
||||
.get_quotas(std::slice::from_ref(id))
|
||||
@@ -160,6 +163,9 @@ impl QuotaService {
|
||||
|
||||
pub(crate) async fn refresh(&self, id: &ProviderAccountId) -> Result<(), ProviderAdminError> {
|
||||
let current = self.credentials.current(id).await?;
|
||||
if current.account.authentication_kind() != "oauth" {
|
||||
return Err(error(Kind::Unsupported));
|
||||
}
|
||||
let material = self
|
||||
.credentials
|
||||
.material(¤t)
|
||||
@@ -253,7 +259,11 @@ impl QuotaService {
|
||||
accounts: &[ProviderAccount],
|
||||
model: &str,
|
||||
) -> 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 observations = self.accounts.get_quotas(&ids).await.map_err(unavailable)?;
|
||||
let now = SystemTime::now();
|
||||
|
||||
@@ -32,6 +32,26 @@ use serde_json::Value;
|
||||
use std::{sync::Arc, time::SystemTime};
|
||||
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(super) kind: ProviderKind,
|
||||
pub(super) accounts: Arc<dyn ProviderAccountStore>,
|
||||
@@ -72,6 +92,9 @@ impl CredentialService {
|
||||
}
|
||||
}
|
||||
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(
|
||||
current.credential.expose_to_provider().clone(),
|
||||
))
|
||||
@@ -87,6 +110,18 @@ impl CredentialService {
|
||||
}
|
||||
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 {
|
||||
_account: Box<dyn ProviderLeaseGuard>,
|
||||
@@ -123,7 +158,7 @@ impl CredentialService {
|
||||
.with_source(e)
|
||||
})?;
|
||||
if loaded.account.provider() != &self.kind
|
||||
|| loaded.account.authentication_kind() != "oauth"
|
||||
|| !matches!(loaded.account.authentication_kind(), "oauth" | "api_key")
|
||||
{
|
||||
return Err(error(Kind::NotFound));
|
||||
}
|
||||
@@ -231,6 +266,9 @@ impl CredentialService {
|
||||
&self,
|
||||
current: &LoadedCredential,
|
||||
) -> Result<PreparedCredentialRotation, ProviderAdminError> {
|
||||
if current.account.authentication_kind() != "oauth" {
|
||||
return Err(error(Kind::Unsupported));
|
||||
}
|
||||
let guards = self.lock_rotation(¤t.account).await?;
|
||||
let previous: Material = serde_json::from_value(Value::Object(
|
||||
current.credential.expose_to_provider().clone(),
|
||||
|
||||
@@ -17,6 +17,7 @@ use std::{collections::BTreeMap, time::SystemTime};
|
||||
pub(super) enum Project {
|
||||
Catalog(String),
|
||||
Discover,
|
||||
GenAi,
|
||||
}
|
||||
|
||||
pub(super) struct CandidatePool {
|
||||
@@ -32,6 +33,7 @@ impl AntigravityProvider {
|
||||
model: &UpstreamModelId,
|
||||
ctx: &AttemptContext,
|
||||
search: bool,
|
||||
method: &'static str,
|
||||
) -> Result<CandidatePool, ProviderError> {
|
||||
let required = ctx.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))]);
|
||||
(vec![account], projects)
|
||||
} 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();
|
||||
if ids.is_empty() && search {
|
||||
return Err(ProviderError::invalid_request(
|
||||
@@ -136,13 +138,16 @@ impl AntigravityProvider {
|
||||
}
|
||||
let (failure_rate, first_output_latency) =
|
||||
self.feedback.scheduling_signals(&self.kind, account.id());
|
||||
let signals = scheduling
|
||||
let mut signals = scheduling
|
||||
.signals()
|
||||
.get(account.id())
|
||||
.cloned()
|
||||
.ok_or_else(|| unsent(Kind::ProviderInfrastructureUnavailable))?
|
||||
.with_runtime_health(failure_rate, first_output_latency)
|
||||
.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 {
|
||||
account,
|
||||
signals,
|
||||
@@ -179,6 +184,7 @@ impl AntigravityProvider {
|
||||
model: &UpstreamModelId,
|
||||
ctx: &AttemptContext,
|
||||
search: bool,
|
||||
method: &'static str,
|
||||
) -> Result<BTreeMap<ProviderAccountId, (CredentialRevision, Project)>, ProviderError> {
|
||||
let required = ctx.required_account();
|
||||
let mut projects = BTreeMap::new();
|
||||
@@ -188,7 +194,10 @@ impl AntigravityProvider {
|
||||
.web_search_model()
|
||||
.is_some_and(|id| id == model.as_str())
|
||||
} else {
|
||||
catalog.models.contains_key(model.as_str())
|
||||
catalog
|
||||
.models
|
||||
.get(model.as_str())
|
||||
.is_some_and(|model| model.supports_method(method))
|
||||
};
|
||||
if !supports {
|
||||
continue;
|
||||
@@ -204,7 +213,10 @@ impl AntigravityProvider {
|
||||
account_id,
|
||||
(
|
||||
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(
|
||||
operation: Operation,
|
||||
context: &AttemptContext,
|
||||
api_model: Option<&str>,
|
||||
) -> Result<(Operation, Option<Translator>), ProviderError> {
|
||||
let Operation::CountTokens(request) = &operation else {
|
||||
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())
|
||||
.map_err(|error| unsent(ProviderErrorKind::InvalidRequest).with_source(error))?;
|
||||
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);
|
||||
let body = match api_model {
|
||||
Some(model) => api_count_body(body, source, model, context)?,
|
||||
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 translated = source == "token-count";
|
||||
let operation = if translated {
|
||||
@@ -38,6 +45,39 @@ pub(super) fn prepare(
|
||||
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;
|
||||
|
||||
impl NativeResponseTranslator for Translator {
|
||||
|
||||
@@ -18,6 +18,11 @@ use gateway_core::{
|
||||
use gateway_protocol::genai::GENAI_PROTOCOL;
|
||||
use std::{sync::Arc, time::Instant};
|
||||
|
||||
enum Resource {
|
||||
CloudCode(crate::transport::CloudCodeClient),
|
||||
GenAi(crate::transport::GenAiClient),
|
||||
}
|
||||
|
||||
impl AntigravityProvider {
|
||||
pub(super) async fn execute_native(
|
||||
self: Arc<Self>,
|
||||
@@ -43,22 +48,38 @@ impl AntigravityProvider {
|
||||
let affinity =
|
||||
super::affinity::session_key(request.operation(), ctx.client_api_key_ref(), &model);
|
||||
let search = request.candidate().uses_dedicated_web_search();
|
||||
let method = if matches!(request.operation(), Operation::CountTokens(_)) {
|
||||
"countTokens"
|
||||
} else {
|
||||
"generateContent"
|
||||
};
|
||||
let selected = self
|
||||
.select_account(&model, &ctx, affinity.as_ref(), search)
|
||||
.select_account(&model, &ctx, affinity.as_ref(), search, method)
|
||||
.await?;
|
||||
let selection = ProviderSelectionObservation::new(
|
||||
u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX),
|
||||
selected.capacity,
|
||||
);
|
||||
let profile = ctx
|
||||
.request_profile()
|
||||
.map(crate::profile::ClientProfile::from_frozen)
|
||||
.transpose()
|
||||
.map_err(|e| unsent(Kind::ProviderInfrastructureUnavailable).with_source(e))?
|
||||
.unwrap_or_else(|| crate::profile::default_profile(&self.release));
|
||||
let resource = self
|
||||
.clients
|
||||
.client(&self.origin, &selected.account, &profile)?;
|
||||
let resource = match &selected.material {
|
||||
crate::credential::Authentication::OAuth(_) => {
|
||||
let profile = ctx
|
||||
.request_profile()
|
||||
.map(crate::profile::ClientProfile::from_frozen)
|
||||
.transpose()
|
||||
.map_err(|e| unsent(Kind::ProviderInfrastructureUnavailable).with_source(e))?
|
||||
.unwrap_or_else(|| crate::profile::default_profile(&self.release));
|
||||
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(
|
||||
self.kind.clone(),
|
||||
model.clone(),
|
||||
@@ -95,10 +116,10 @@ impl AntigravityProvider {
|
||||
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) = 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)
|
||||
} 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)
|
||||
};
|
||||
let headers = crate::transport::request_headers(&operation, headers, selected.account_switch);
|
||||
@@ -124,7 +145,7 @@ impl AntigravityProvider {
|
||||
Err(unsent(Kind::Timeout))?;
|
||||
}
|
||||
let probe_token = (terminal_context.account_eligibility() == AccountEligibilityPolicy::BypassForDiagnostic)
|
||||
.then(|| selected.material.access_token.clone());
|
||||
.then(|| selected.material.token().to_owned());
|
||||
let record_failure = async |error| {
|
||||
let error = match &probe_token {
|
||||
Some(token) => crate::transport::connection_test_error(error, token),
|
||||
@@ -137,7 +158,14 @@ impl AntigravityProvider {
|
||||
_ = cancellation.cancelled() => Err(ProviderError::new(Kind::Cancelled, UpstreamSendState::Ambiguous)),
|
||||
_ = deadline.wait() => Err(ProviderError::new(Kind::Timeout, UpstreamSendState::Ambiguous)),
|
||||
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 {
|
||||
return resource.count_tokens(token, &body, &headers).await;
|
||||
}
|
||||
@@ -145,6 +173,7 @@ impl AntigravityProvider {
|
||||
Project::Catalog(project) => project,
|
||||
// 固定探测使用该账号实际授权的项目,包括尚无公开目录的停用账号
|
||||
Project::Discover => resource.account_info(token).await?.project,
|
||||
Project::GenAi => return Err(unsent(Kind::ProviderInfrastructureUnavailable)),
|
||||
};
|
||||
let mode = if search {
|
||||
crate::transport::GenerateMode::WebSearch
|
||||
@@ -162,10 +191,12 @@ impl AntigravityProvider {
|
||||
};
|
||||
let context = crate::transport::ResponseContext {
|
||||
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 {
|
||||
Box::pin(crate::transport::count_events(response, context))
|
||||
} else if native_api {
|
||||
Box::pin(crate::transport::genai_events(response, context))
|
||||
} else {
|
||||
Box::pin(crate::transport::events(response, context))
|
||||
};
|
||||
|
||||
@@ -31,6 +31,22 @@ impl AntigravityProvider {
|
||||
let feedback = async {
|
||||
match error.kind() {
|
||||
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 负责
|
||||
self.accounts
|
||||
.expire_access_token(account, SystemTime::now())
|
||||
|
||||
@@ -4,7 +4,7 @@ use super::{
|
||||
AntigravityProvider,
|
||||
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_core::{
|
||||
account::{
|
||||
@@ -29,7 +29,7 @@ use std::time::Duration;
|
||||
pub(super) struct SelectedAccount {
|
||||
pub(super) account: ProviderAccount,
|
||||
pub(super) capacity: Option<AccountCapacitySnapshot>,
|
||||
pub(super) material: Material,
|
||||
pub(super) material: Authentication,
|
||||
pub(super) snapshot: AccountHistorySnapshot,
|
||||
pub(super) project: Project,
|
||||
pub(super) lease: Box<dyn ProviderLeaseGuard>,
|
||||
@@ -51,9 +51,11 @@ impl AntigravityProvider {
|
||||
ctx: &AttemptContext,
|
||||
affinity_key: Option<&ProviderSessionAffinityKey>,
|
||||
search: bool,
|
||||
method: &'static str,
|
||||
) -> Result<SelectedAccount, ProviderError> {
|
||||
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 {
|
||||
Err(SelectionError::Queue(reason)) if ctx.required_account().is_none() => {
|
||||
policy
|
||||
@@ -86,6 +88,7 @@ impl AntigravityProvider {
|
||||
queue: ConcurrencyQueuePolicy,
|
||||
affinity_key: Option<&ProviderSessionAffinityKey>,
|
||||
search: bool,
|
||||
method: &'static str,
|
||||
) -> Result<SelectedAccount, SelectionError> {
|
||||
let mut waiting = CapacityWait::new(
|
||||
&self.waiting,
|
||||
@@ -106,7 +109,7 @@ impl AntigravityProvider {
|
||||
mut projects,
|
||||
mut quotas,
|
||||
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()) {
|
||||
Some(key) => Some(ProviderSessionAffinityState::new(
|
||||
key,
|
||||
@@ -328,7 +331,7 @@ impl AntigravityProvider {
|
||||
&self,
|
||||
account: &ProviderAccount,
|
||||
ctx: &AttemptContext,
|
||||
) -> Result<(ProviderAccount, Material), ProviderError> {
|
||||
) -> Result<(ProviderAccount, Authentication), ProviderError> {
|
||||
let current = self
|
||||
.credentials
|
||||
.current(account.id())
|
||||
@@ -339,7 +342,7 @@ impl AntigravityProvider {
|
||||
{
|
||||
return Err(unsent(Kind::NoEligibleAccount));
|
||||
}
|
||||
let material = self.credentials.material(¤t)?;
|
||||
let material = self.credentials.authentication(¤t)?;
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -24,7 +24,8 @@ const MAX_CONTROL_RESPONSE_BYTES: usize = 8 * 1024 * 1024;
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub(crate) struct Catalog {
|
||||
pub(crate) project: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub(crate) project: Option<String>,
|
||||
pub(crate) models: BTreeMap<String, Model>,
|
||||
#[serde(flatten)]
|
||||
pub(crate) metadata: serde_json::Map<String, serde_json::Value>,
|
||||
@@ -81,10 +82,21 @@ impl Model {
|
||||
pub(crate) fn max_output_tokens(&self) -> Option<u64> {
|
||||
self.0
|
||||
.get("maxOutputTokens")
|
||||
.or_else(|| self.0.get("outputTokenLimit"))
|
||||
.and_then(serde_json::Value::as_u64)
|
||||
.filter(|n| *n > 0)
|
||||
}
|
||||
|
||||
pub(crate) fn supports_method(&self, method: &str) -> bool {
|
||||
self.0
|
||||
.get("supportedGenerationMethods")
|
||||
.is_none_or(|methods| {
|
||||
methods.as_array().is_some_and(|methods| {
|
||||
methods.iter().any(|value| value.as_str() == Some(method))
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn quota(&self) -> Result<Option<super::account::ModelQuota>, serde_json::Error> {
|
||||
self.0
|
||||
.get("quotaInfo")
|
||||
@@ -203,7 +215,7 @@ impl CloudCodeClient {
|
||||
return Err(sent(Kind::Protocol));
|
||||
}
|
||||
Ok(Catalog {
|
||||
project,
|
||||
project: Some(project),
|
||||
models: models.models,
|
||||
metadata: models.metadata,
|
||||
})
|
||||
@@ -244,7 +256,7 @@ impl CloudCodeClient {
|
||||
} else {
|
||||
request
|
||||
};
|
||||
let (send, media) = if matches!(
|
||||
let (request_builder, media) = if matches!(
|
||||
mode,
|
||||
GenerateMode::Stream | GenerateMode::Chat { stream: true }
|
||||
) {
|
||||
@@ -260,8 +272,8 @@ impl CloudCodeClient {
|
||||
"application/json",
|
||||
)
|
||||
};
|
||||
self.send(
|
||||
send.json(&Envelope {
|
||||
send(
|
||||
request_builder.json(&Envelope {
|
||||
project,
|
||||
model,
|
||||
user_agent: "antigravity",
|
||||
@@ -295,7 +307,7 @@ impl CloudCodeClient {
|
||||
struct Envelope<'a> {
|
||||
request: &'a RawValue,
|
||||
}
|
||||
self.send(
|
||||
send(
|
||||
self.post("countTokens", token)
|
||||
.timeout(GENERATION_TIMEOUT)
|
||||
.json(&Envelope { request: &request }),
|
||||
@@ -305,39 +317,37 @@ impl CloudCodeClient {
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn send(
|
||||
&self,
|
||||
mut send: reqwest::RequestBuilder,
|
||||
token: &str,
|
||||
headers: &[MiddlewareHeader],
|
||||
media: &str,
|
||||
) -> Result<Response, ProviderError> {
|
||||
for header in headers {
|
||||
if super::headers::managed_header(header.name()) {
|
||||
continue;
|
||||
}
|
||||
let name = reqwest::header::HeaderName::from_bytes(header.name().as_bytes())
|
||||
.map_err(|e| unsent(Kind::InvalidRequest).with_source(e))?;
|
||||
let value = reqwest::header::HeaderValue::from_bytes(header.value())
|
||||
.map_err(|e| unsent(Kind::InvalidRequest).with_source(e))?;
|
||||
send = send.header(name, value);
|
||||
}
|
||||
let response = send.send().await.map_err(network)?;
|
||||
let response = successful(super::response::decode(response), token).await?;
|
||||
if !response
|
||||
.headers()
|
||||
.get(reqwest::header::CONTENT_TYPE)
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.and_then(|v| v.split(';').next())
|
||||
.is_some_and(|v| v.trim().eq_ignore_ascii_case(media))
|
||||
{
|
||||
return Err(sent(Kind::Protocol));
|
||||
}
|
||||
Ok(response)
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn send(
|
||||
mut send: reqwest::RequestBuilder,
|
||||
token: &str,
|
||||
headers: &[MiddlewareHeader],
|
||||
media: &str,
|
||||
) -> Result<Response, ProviderError> {
|
||||
for header in headers {
|
||||
if super::headers::managed_header(header.name()) {
|
||||
continue;
|
||||
}
|
||||
let name = reqwest::header::HeaderName::from_bytes(header.name().as_bytes())
|
||||
.map_err(|e| unsent(Kind::InvalidRequest).with_source(e))?;
|
||||
let value = reqwest::header::HeaderValue::from_bytes(header.value())
|
||||
.map_err(|e| unsent(Kind::InvalidRequest).with_source(e))?;
|
||||
send = send.header(name, value);
|
||||
}
|
||||
let response = send.send().await.map_err(network)?;
|
||||
let response = successful(super::response::decode(response), token).await?;
|
||||
if !response
|
||||
.headers()
|
||||
.get(reqwest::header::CONTENT_TYPE)
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.and_then(|v| v.split(';').next())
|
||||
.is_some_and(|v| v.trim().eq_ignore_ascii_case(media))
|
||||
{
|
||||
return Err(sent(Kind::Protocol));
|
||||
}
|
||||
Ok(response)
|
||||
}
|
||||
pub(super) async fn control<T: DeserializeOwned>(
|
||||
request: reqwest::RequestBuilder,
|
||||
token: &str,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Cloud Code 上游 HTTP、响应解包与错误事实
|
||||
|
||||
mod api_key;
|
||||
mod client;
|
||||
mod count;
|
||||
mod failure;
|
||||
@@ -10,10 +11,11 @@ mod request;
|
||||
mod response;
|
||||
mod signatures;
|
||||
mod tool_ids;
|
||||
pub(crate) use api_key::GenAiClient;
|
||||
pub(crate) use client::{Catalog, CloudCodeClient, GenerateMode, Model, unwrap_frame};
|
||||
pub(crate) use count::count_events;
|
||||
pub(crate) use failure::{connection_test_error, sent, unsent};
|
||||
pub(crate) use headers::request_headers;
|
||||
pub(crate) use pool::ClientPool;
|
||||
pub(crate) use response::{ResponseContext, events};
|
||||
pub(crate) use response::{ResponseContext, events, genai_events};
|
||||
pub(crate) mod account;
|
||||
|
||||
@@ -9,7 +9,7 @@ use gateway_core::{
|
||||
use reqwest::Client;
|
||||
use url::Url;
|
||||
|
||||
use super::{CloudCodeClient, unsent};
|
||||
use super::{CloudCodeClient, GenAiClient, unsent};
|
||||
use crate::profile::ClientProfile;
|
||||
|
||||
const MAX_CACHED_CLIENTS: usize = 64;
|
||||
@@ -19,7 +19,7 @@ struct Identity {
|
||||
account: ProviderAccountId,
|
||||
revision: CredentialRevision,
|
||||
proxy: Option<OutboundProxy>,
|
||||
user_agent: String,
|
||||
user_agent: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
@@ -34,11 +34,32 @@ impl ClientPool {
|
||||
account: &ProviderAccount,
|
||||
profile: &ClientProfile,
|
||||
) -> Result<CloudCodeClient, ProviderError> {
|
||||
let client = self.http_client(account, Some(profile))?;
|
||||
// 系统提示不缓存,画像只修改提示词时也立即使用本次冻结值
|
||||
CloudCodeClient::with_client(origin, client, profile, account.auto_use_quota_credits())
|
||||
}
|
||||
|
||||
pub(crate) fn genai(
|
||||
&self,
|
||||
base_url: Url,
|
||||
account: &ProviderAccount,
|
||||
) -> Result<GenAiClient, ProviderError> {
|
||||
Ok(GenAiClient::with_client(
|
||||
base_url,
|
||||
self.http_client(account, None)?,
|
||||
))
|
||||
}
|
||||
|
||||
fn http_client(
|
||||
&self,
|
||||
account: &ProviderAccount,
|
||||
profile: Option<&ClientProfile>,
|
||||
) -> Result<Client, ProviderError> {
|
||||
let identity = Identity {
|
||||
account: account.id().clone(),
|
||||
revision: account.revision(),
|
||||
proxy: account.outbound_proxy().cloned(),
|
||||
user_agent: profile.user_agent(),
|
||||
user_agent: profile.map(ClientProfile::user_agent),
|
||||
};
|
||||
let mut clients = self
|
||||
.clients
|
||||
@@ -51,14 +72,16 @@ impl ClientPool {
|
||||
let client = if let Some((_, client)) = existing {
|
||||
client
|
||||
} else {
|
||||
CloudCodeClient::build_client(account.outbound_proxy(), profile)?
|
||||
match profile {
|
||||
Some(profile) => CloudCodeClient::build_client(account.outbound_proxy(), profile)?,
|
||||
None => GenAiClient::build_client(account.outbound_proxy())?,
|
||||
}
|
||||
};
|
||||
clients.push_back((identity, client.clone()));
|
||||
if clients.len() > MAX_CACHED_CLIENTS {
|
||||
clients.pop_front();
|
||||
}
|
||||
drop(clients);
|
||||
// 系统提示不缓存,画像只修改提示词时也立即使用本次冻结值
|
||||
CloudCodeClient::with_client(origin, client, profile, account.auto_use_quota_credits())
|
||||
Ok(client)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -58,8 +58,25 @@ pub(crate) struct ResponseContext {
|
||||
}
|
||||
|
||||
pub(crate) fn events(
|
||||
response: Response,
|
||||
context: ResponseContext,
|
||||
) -> impl Stream<Item = Result<ProviderEvent, ProviderError>> + Send + 'static {
|
||||
response_events(response, context, unwrap_frame)
|
||||
}
|
||||
|
||||
pub(crate) fn genai_events(
|
||||
response: Response,
|
||||
context: ResponseContext,
|
||||
) -> impl Stream<Item = Result<ProviderEvent, ProviderError>> + Send + 'static {
|
||||
response_events(response, context, |data| {
|
||||
Ok(Bytes::copy_from_slice(data.as_bytes()))
|
||||
})
|
||||
}
|
||||
|
||||
fn response_events(
|
||||
mut response: Response,
|
||||
context: ResponseContext,
|
||||
frame_body: fn(&str) -> Result<Bytes, ProviderError>,
|
||||
) -> impl Stream<Item = Result<ProviderEvent, ProviderError>> + Send + 'static {
|
||||
let ResponseContext {
|
||||
stream,
|
||||
@@ -108,7 +125,7 @@ pub(crate) fn events(
|
||||
vec![SseEvent { event: None, data, id: None, retry: None }]
|
||||
};
|
||||
for frame in frames {
|
||||
let inner = unwrap_frame(&frame.data)?;
|
||||
let inner = frame_body(&frame.data)?;
|
||||
let value: Value = serde_json::from_slice(&inner).map_err(|_| sent(Kind::Protocol))?;
|
||||
if value.get("error").is_some_and(Value::is_object) {
|
||||
let status=value.get("error").and_then(|e|e.get("code")).and_then(Value::as_u64).and_then(|code|u16::try_from(code).ok());
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
//! 密钥账号的文件、连接配置和凭据更新不经过 OAuth 身份交换
|
||||
|
||||
use super::documents_tests::{document, fixture, import};
|
||||
use gateway_admin::{
|
||||
model::{
|
||||
Revision,
|
||||
provider_credentials::{PrepareCredentialRotation, ProviderExportCredentialInput},
|
||||
},
|
||||
ports::provider::ProviderAdminErrorKind,
|
||||
};
|
||||
use serde_json::json;
|
||||
|
||||
#[tokio::test]
|
||||
async fn api_key_export_reimports_without_identity_or_refresh() {
|
||||
let (server, credentials, store) = fixture().await;
|
||||
let base = format!("{}/antigravity/v1beta", server.uri());
|
||||
let mut imported = credentials
|
||||
.prepare_import(import(document(json!({
|
||||
"authentication_kind":"api_key","base_url":base,"api_key":"fixture-key","name":"Relay"
|
||||
}))))
|
||||
.await
|
||||
.unwrap();
|
||||
let prepared = imported.credentials.remove(0);
|
||||
assert!(!prepared.has_refresh_token);
|
||||
assert!(prepared.access_token_expires_at.is_none());
|
||||
assert!(prepared.upstream_user_id.is_none());
|
||||
store.use_api_key(&base);
|
||||
let current = store.primary().loaded.lock().unwrap().clone();
|
||||
let material = super::api_key::ApiKeyMaterial::load(¤t).unwrap();
|
||||
let configuration = material.configuration();
|
||||
assert_eq!(
|
||||
configuration.expose_to_provider().expose_to_provider(),
|
||||
json!({"base_url":base}).as_object().unwrap()
|
||||
);
|
||||
assert_eq!(
|
||||
credentials
|
||||
.refresh_current(¤t)
|
||||
.await
|
||||
.unwrap_err()
|
||||
.kind(),
|
||||
ProviderAdminErrorKind::Unsupported
|
||||
);
|
||||
let mut account = crate::support::account_record();
|
||||
account.authentication_kind = "api_key".into();
|
||||
account.name = prepared.name;
|
||||
let exported = credentials
|
||||
.export_credentials(vec![ProviderExportCredentialInput {
|
||||
account,
|
||||
provider_material: prepared.provider_material,
|
||||
}])
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
exported.document.expose_to_provider().expose_to_provider()["accounts"][0]["name"],
|
||||
"Relay"
|
||||
);
|
||||
let reimported = credentials
|
||||
.prepare_import(import(exported.document))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(reimported.credentials[0].authentication_kind, "api_key");
|
||||
assert_eq!(reimported.credentials[0].name, "Relay");
|
||||
assert_ne!(reimported.credentials[0].account_id, prepared.account_id);
|
||||
assert!(server.received_requests().await.unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn connection_update_retains_secret_and_rejects_stale_revision() {
|
||||
let (server, credentials, store) = fixture().await;
|
||||
store.use_api_key(&format!("{}/v1beta", server.uri()));
|
||||
let mut account = crate::support::account_record();
|
||||
account.authentication_kind = "api_key".into();
|
||||
let prepared = credentials
|
||||
.prepare_rotation(PrepareCredentialRotation {
|
||||
account: account.clone(),
|
||||
provider_material: document(
|
||||
json!({"base_url":format!("{}/relay/v1beta/",server.uri())}),
|
||||
),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let (facts, guard) = prepared.into_parts();
|
||||
assert_eq!(
|
||||
facts
|
||||
.provider_material
|
||||
.expose_to_provider()
|
||||
.expose_to_provider()["api_key"],
|
||||
"fixture-key"
|
||||
);
|
||||
assert!(!facts.has_refresh_token);
|
||||
guard.finish();
|
||||
account.credential_revision = Revision::new(2).unwrap();
|
||||
let error = credentials
|
||||
.prepare_rotation(PrepareCredentialRotation {
|
||||
account,
|
||||
provider_material: document(json!({"base_url":server.uri(),"api_key":"new-key"})),
|
||||
})
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(error.kind(), ProviderAdminErrorKind::Conflict);
|
||||
assert_eq!(store.active_leases(), 0);
|
||||
assert!(server.received_requests().await.unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn invalid_connections_fail_before_any_network_request() {
|
||||
let (server, credentials, _) = fixture().await;
|
||||
for base in [
|
||||
"ftp://host/v1beta",
|
||||
"https://user:pass@host/v1beta",
|
||||
"https://host/v1beta?key=bad",
|
||||
"https://host/v1beta#fragment",
|
||||
"https://host/\nv1beta",
|
||||
] {
|
||||
assert_eq!(
|
||||
credentials
|
||||
.prepare_import(import(document(json!({
|
||||
"authentication_kind":"api_key","base_url":base,"api_key":"fixture-key"
|
||||
}))))
|
||||
.await
|
||||
.unwrap_err()
|
||||
.kind(),
|
||||
ProviderAdminErrorKind::Invalid
|
||||
);
|
||||
}
|
||||
for key in ["", "contains space", "line\nbreak"] {
|
||||
assert_eq!(
|
||||
credentials
|
||||
.prepare_import(import(document(json!({
|
||||
"authentication_kind":"api_key","base_url":server.uri(),"api_key":key
|
||||
}))))
|
||||
.await
|
||||
.unwrap_err()
|
||||
.kind(),
|
||||
ProviderAdminErrorKind::Invalid
|
||||
);
|
||||
}
|
||||
assert!(server.received_requests().await.unwrap().is_empty());
|
||||
}
|
||||
@@ -29,7 +29,7 @@ use wiremock::{
|
||||
matchers::{body_string_contains, header, method, path, query_param},
|
||||
};
|
||||
|
||||
async fn fixture() -> (MockServer, CredentialService, Arc<MemoryPorts>) {
|
||||
pub(super) async fn fixture() -> (MockServer, CredentialService, Arc<MemoryPorts>) {
|
||||
let server = MockServer::start().await;
|
||||
let origin = server.uri();
|
||||
let config: OAuthRegistration = serde_json::from_value(json!({
|
||||
@@ -58,11 +58,11 @@ async fn fixture() -> (MockServer, CredentialService, Arc<MemoryPorts>) {
|
||||
(server, credentials, store)
|
||||
}
|
||||
|
||||
fn document(value: Value) -> ProviderDocument {
|
||||
pub(super) fn document(value: Value) -> ProviderDocument {
|
||||
ProviderDocument::new(OpaqueProviderData::new(value.as_object().unwrap().clone()))
|
||||
}
|
||||
|
||||
fn import(document: ProviderDocument) -> PrepareCredentialImport {
|
||||
pub(super) fn import(document: ProviderDocument) -> PrepareCredentialImport {
|
||||
PrepareCredentialImport {
|
||||
default_outbound_proxy: None,
|
||||
document,
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
//! 在凭据模块内验证 OAuth 叶子边界,并复用真实授权与刷新服务
|
||||
|
||||
#[path = "../../src/credential/api_key.rs"]
|
||||
pub(crate) mod api_key;
|
||||
#[path = "api_key.rs"]
|
||||
mod api_key_tests;
|
||||
#[path = "../../src/credential/authorization.rs"]
|
||||
mod authorization;
|
||||
#[path = "../../src/credential/documents.rs"]
|
||||
@@ -14,7 +18,7 @@ mod refresh;
|
||||
mod service;
|
||||
pub(crate) use authorization::AuthorizationService;
|
||||
pub(crate) use oauth::{GoogleOAuth, Material};
|
||||
pub(crate) use service::CredentialService;
|
||||
pub(crate) use service::{Authentication, CredentialService};
|
||||
|
||||
#[path = "documents.rs"]
|
||||
mod documents_tests;
|
||||
|
||||
@@ -0,0 +1,400 @@
|
||||
//! 真实 Provider 的 API Key 目录、原生转发、状态隔离和取消合同
|
||||
|
||||
use crate::support::{Fixture, context, request};
|
||||
use futures::{StreamExt, TryStreamExt};
|
||||
use gateway_core::{
|
||||
account::{CredentialRevision, CredentialState, OpaqueProviderData, ProviderAccount},
|
||||
engine::provider::{Provider, ProviderRequest},
|
||||
error::ProviderErrorKind,
|
||||
event::GatewayEvent,
|
||||
lifecycle::CancellationToken,
|
||||
operation::{GenerateRequest, Operation, ProtocolPayload, RawJsonPayload, TokenCountRequest},
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
use std::{sync::atomic::Ordering, time::Duration};
|
||||
use wiremock::{
|
||||
Mock, MockServer, ResponseTemplate,
|
||||
matchers::{header, method, path, query_param},
|
||||
};
|
||||
|
||||
fn native_request(stream: bool, body: &[u8]) -> ProviderRequest {
|
||||
let payload = ProtocolPayload::from_json_bytes("genai", body.to_vec().into())
|
||||
.unwrap()
|
||||
.with_context(json!({"stream":stream}).as_object().unwrap().clone());
|
||||
ProviderRequest::new(
|
||||
Operation::Generate(GenerateRequest::from_protocol_payload(payload)),
|
||||
request(stream).candidate().clone(),
|
||||
)
|
||||
}
|
||||
|
||||
fn count_request(body: Value) -> ProviderRequest {
|
||||
ProviderRequest::new(
|
||||
Operation::CountTokens(TokenCountRequest::from_raw_json(
|
||||
RawJsonPayload::new("genai", serde_json::to_vec(&body).unwrap().into()).unwrap(),
|
||||
)),
|
||||
request(false).candidate().clone(),
|
||||
)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn json_and_sse_keep_native_bodies_signatures_and_usage() {
|
||||
for streaming in [false, true] {
|
||||
let upstream = MockServer::start().await;
|
||||
let action = if streaming {
|
||||
"streamGenerateContent"
|
||||
} else {
|
||||
"generateContent"
|
||||
};
|
||||
let response = r#"{"responseId":"native","candidates":[{"content":{"parts":[{"functionCall":{"name":"tool","args":{"x":1}},"thoughtSignature":"opaque-response"}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":4,"candidatesTokenCount":2},"unknown":12345678901234567890}"#;
|
||||
let template = if streaming {
|
||||
ResponseTemplate::new(200).set_body_raw(
|
||||
format!("id: event-1\nretry: 1000\ndata: {response}\n\n"),
|
||||
"text/event-stream",
|
||||
)
|
||||
} else {
|
||||
ResponseTemplate::new(200).set_body_raw(response, "application/json")
|
||||
};
|
||||
Mock::given(method("POST"))
|
||||
.and(path(format!("/relay/v1beta/models/fixture-model:{action}")))
|
||||
.and(header("x-goog-api-key", "fixture-key"))
|
||||
.respond_with(template)
|
||||
.expect(1)
|
||||
.mount(&upstream)
|
||||
.await;
|
||||
let fixture = Fixture::new(&upstream.uri());
|
||||
fixture
|
||||
.store
|
||||
.use_api_key(&format!("{}/relay/v1beta/", upstream.uri()));
|
||||
let body = br#"{ "contents":[{"role":"model","parts":[{"functionCall":{"name":"tool","args":{}},"thoughtSignature":"opaque-request"}]}],"systemInstruction":{"parts":[{"text":"caller instructions"}]},"unknown":12345678901234567890 }"#;
|
||||
let stream = fixture
|
||||
.provider
|
||||
.clone()
|
||||
.execute(
|
||||
native_request(streaming, body),
|
||||
context(
|
||||
OpaqueProviderData::new(Default::default()),
|
||||
CancellationToken::new(),
|
||||
),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(upstream.received_requests().await.unwrap().is_empty());
|
||||
let events = stream.try_collect::<Vec<_>>().await.unwrap();
|
||||
let wire = events.iter().find_map(|event| event.wire_event()).unwrap();
|
||||
if streaming {
|
||||
assert_eq!(
|
||||
wire.data()["candidates"][0]["content"]["parts"][0]["thoughtSignature"],
|
||||
"opaque-response"
|
||||
);
|
||||
} else {
|
||||
assert_eq!(wire.raw_json_body().unwrap().as_ref(), response.as_bytes());
|
||||
}
|
||||
assert!(events.iter().flat_map(|event| event.canonical_facts()).any(
|
||||
|event| matches!(event, GatewayEvent::Usage(usage) if usage.input_tokens == Some(4))
|
||||
));
|
||||
let requests = upstream.received_requests().await.unwrap();
|
||||
assert_eq!(requests.len(), 1);
|
||||
assert_eq!(requests[0].body, body);
|
||||
assert_eq!(requests[0].url.query(), streaming.then_some("alt=sse"));
|
||||
for name in [
|
||||
"authorization",
|
||||
"user-agent",
|
||||
"x-goog-user-project",
|
||||
"x-goog-api-client",
|
||||
] {
|
||||
assert!(!requests[0].headers.contains_key(name));
|
||||
}
|
||||
assert_eq!(fixture.store.active_leases(), 0);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn native_count_keeps_generate_content_envelope_without_oauth_prompt() {
|
||||
let upstream = MockServer::start().await;
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/v1beta/models/fixture-model:countTokens"))
|
||||
.and(header("x-goog-api-key", "fixture-key"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({"totalTokens":42})))
|
||||
.expect(1)
|
||||
.mount(&upstream)
|
||||
.await;
|
||||
let fixture = Fixture::new(&upstream.uri());
|
||||
fixture
|
||||
.store
|
||||
.use_api_key(&format!("{}/v1beta", upstream.uri()));
|
||||
let body = json!({"generateContentRequest":{"model":"models/public-alias","contents":[{"parts":[{"text":"hello"}]}],"systemInstruction":{"parts":[{"text":"caller"}]},"tools":[],"toolConfig":{}}});
|
||||
let events = fixture
|
||||
.provider
|
||||
.clone()
|
||||
.execute(
|
||||
count_request(body.clone()),
|
||||
context(
|
||||
OpaqueProviderData::new(Default::default()),
|
||||
CancellationToken::new(),
|
||||
),
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
.try_collect::<Vec<_>>()
|
||||
.await
|
||||
.unwrap();
|
||||
let mut expected = body;
|
||||
expected["generateContentRequest"]["model"] = json!("models/fixture-model");
|
||||
assert_eq!(
|
||||
upstream.received_requests().await.unwrap()[0]
|
||||
.body_json::<Value>()
|
||||
.unwrap(),
|
||||
expected
|
||||
);
|
||||
assert!(
|
||||
events
|
||||
.iter()
|
||||
.flat_map(|event| event.canonical_facts())
|
||||
.all(|event| !matches!(
|
||||
event,
|
||||
GatewayEvent::Usage(_) | GatewayEvent::CalculatedCost(_)
|
||||
))
|
||||
);
|
||||
assert_eq!(fixture.store.active_leases(), 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn model_pages_preserve_native_metadata_and_filter_operation_support() {
|
||||
let upstream = MockServer::start().await;
|
||||
Mock::given(method("GET")).and(path("/antigravity/v1beta/models"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({"models":[
|
||||
{"name":"models/fixture-model","displayName":"Native","outputTokenLimit":8192,"supportedGenerationMethods":["generateContent"],"custom":{"keep":true}},
|
||||
{"name":"models/embedding","supportedGenerationMethods":["embedContent"]}
|
||||
],"nextPageToken":"page-two"}))).expect(1).mount(&upstream).await;
|
||||
Mock::given(method("GET")).and(path("/antigravity/v1beta/models")).and(query_param("pageToken","page-two"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({"models":[{"name":"models/count-only","supportedGenerationMethods":["countTokens"]}]})))
|
||||
.expect(1).with_priority(1).mount(&upstream).await;
|
||||
let fixture = Fixture::new(&upstream.uri());
|
||||
fixture
|
||||
.store
|
||||
.use_api_key(&format!("{}/antigravity/v1beta", upstream.uri()));
|
||||
let id = fixture
|
||||
.store
|
||||
.primary()
|
||||
.loaded
|
||||
.lock()
|
||||
.unwrap()
|
||||
.account
|
||||
.id()
|
||||
.clone();
|
||||
let models = fixture.catalog.account_models(&id, true).await.unwrap();
|
||||
assert_eq!(models.models.len(), 2);
|
||||
let catalog = fixture
|
||||
.catalog
|
||||
.client_model_catalog(&fixture.store.account_scope())
|
||||
.await
|
||||
.unwrap();
|
||||
let native = catalog
|
||||
.into_iter()
|
||||
.find(|entry| entry.model.as_str() == "fixture-model")
|
||||
.unwrap();
|
||||
let gateway_core::routing::ProviderModelContent::Native(payload) = native.content else {
|
||||
panic!("native model")
|
||||
};
|
||||
let value: Value = serde_json::from_slice(payload.body()).unwrap();
|
||||
assert_eq!(value["custom"], json!({"keep":true}));
|
||||
assert_eq!(value["outputTokenLimit"], 8192);
|
||||
let error = fixture
|
||||
.provider
|
||||
.clone()
|
||||
.execute(
|
||||
count_request(json!({"contents":[]})),
|
||||
context(
|
||||
OpaqueProviderData::new(Default::default()),
|
||||
CancellationToken::new(),
|
||||
),
|
||||
)
|
||||
.await
|
||||
.err()
|
||||
.unwrap();
|
||||
assert_eq!(error.kind(), ProviderErrorKind::NoEligibleAccount);
|
||||
let requests = upstream.received_requests().await.unwrap();
|
||||
assert_eq!(requests.len(), 2);
|
||||
assert!(
|
||||
requests
|
||||
.iter()
|
||||
.all(|request| request.headers.get("x-goog-api-key").unwrap() == "fixture-key")
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stale_catalog_cannot_admit_replaced_credentials() {
|
||||
let fixture = Fixture::new("http://127.0.0.1:1");
|
||||
fixture.store.use_api_key("http://127.0.0.1:1/v1beta");
|
||||
{
|
||||
let mut loaded = fixture.store.primary().loaded.lock().unwrap();
|
||||
loaded.account = ProviderAccount::new(
|
||||
loaded.account.id().clone(),
|
||||
loaded.account.provider().clone(),
|
||||
"Relay".into(),
|
||||
None,
|
||||
"api_key".into(),
|
||||
CredentialRevision::new(2).unwrap(),
|
||||
None,
|
||||
);
|
||||
}
|
||||
let result = fixture
|
||||
.provider
|
||||
.clone()
|
||||
.execute(
|
||||
request(false),
|
||||
context(
|
||||
OpaqueProviderData::new(Default::default()),
|
||||
CancellationToken::new(),
|
||||
),
|
||||
)
|
||||
.await;
|
||||
assert!(matches!(result,Err(error) if error.kind()==ProviderErrorKind::NoEligibleAccount));
|
||||
assert_eq!(fixture.store.active_leases(), 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn fixed_account_diagnostic_works_without_catalog_or_google_project() {
|
||||
use gateway_core::{
|
||||
account::{AccountSelectionPolicy, RotationStrategy},
|
||||
engine::{
|
||||
AccountAttemptContext, AttemptContext, ModelRequestId, RequestAttemptContext,
|
||||
probe::AccountProbeTarget,
|
||||
},
|
||||
policy::ClientApiKeyId,
|
||||
};
|
||||
use std::{num::NonZeroU32, time::SystemTime};
|
||||
let upstream = MockServer::start().await;
|
||||
Mock::given(path("/v1beta/models/fixture-model:generateContent"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(
|
||||
json!({"candidates":[{"content":{"parts":[{"text":"ok"}]},"finishReason":"STOP"}]}),
|
||||
))
|
||||
.expect(1)
|
||||
.mount(&upstream)
|
||||
.await;
|
||||
let fixture = Fixture::new(&upstream.uri());
|
||||
fixture
|
||||
.store
|
||||
.use_api_key(&format!("{}/v1beta", upstream.uri()));
|
||||
*fixture.store.primary().catalog.lock().unwrap() = None;
|
||||
let id = fixture
|
||||
.store
|
||||
.primary()
|
||||
.loaded
|
||||
.lock()
|
||||
.unwrap()
|
||||
.account
|
||||
.id()
|
||||
.clone();
|
||||
let attempt = AttemptContext::new(
|
||||
RequestAttemptContext::new(
|
||||
ModelRequestId::new("req_probe").unwrap(),
|
||||
ClientApiKeyId::new("key_probe").unwrap(),
|
||||
),
|
||||
NonZeroU32::MIN,
|
||||
SystemTime::now() + Duration::from_secs(5),
|
||||
AccountSelectionPolicy::new(RotationStrategy::Smart, NonZeroU32::MIN),
|
||||
AccountAttemptContext::diagnostic(
|
||||
Default::default(),
|
||||
AccountProbeTarget::ConnectionTest(id),
|
||||
None,
|
||||
),
|
||||
None,
|
||||
CancellationToken::new(),
|
||||
);
|
||||
let events = fixture
|
||||
.provider
|
||||
.clone()
|
||||
.execute(request(false), attempt)
|
||||
.await
|
||||
.unwrap()
|
||||
.try_collect::<Vec<_>>()
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(events.iter().any(|event| event.has_client_event()));
|
||||
assert_eq!(upstream.received_requests().await.unwrap().len(), 1);
|
||||
assert_eq!(fixture.store.active_leases(), 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn unauthorized_key_is_invalidated_without_expiring_an_oauth_token() {
|
||||
let upstream = MockServer::start().await;
|
||||
Mock::given(path("/v1beta/models/fixture-model:generateContent"))
|
||||
.respond_with(
|
||||
ResponseTemplate::new(401)
|
||||
.set_body_json(json!({"error":{"message":"rejected fixture-key"}})),
|
||||
)
|
||||
.expect(1)
|
||||
.mount(&upstream)
|
||||
.await;
|
||||
let fixture = Fixture::new(&upstream.uri());
|
||||
fixture
|
||||
.store
|
||||
.use_api_key(&format!("{}/v1beta", upstream.uri()));
|
||||
let error = fixture
|
||||
.provider
|
||||
.clone()
|
||||
.execute(
|
||||
request(false),
|
||||
context(
|
||||
OpaqueProviderData::new(Default::default()),
|
||||
CancellationToken::new(),
|
||||
),
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
.try_collect::<Vec<_>>()
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(error.kind(), ProviderErrorKind::Unauthorized);
|
||||
assert!(error.raw_upstream_error().is_none());
|
||||
assert_eq!(
|
||||
fixture
|
||||
.store
|
||||
.primary()
|
||||
.loaded
|
||||
.lock()
|
||||
.unwrap()
|
||||
.account
|
||||
.credential_state(),
|
||||
CredentialState::Invalid
|
||||
);
|
||||
assert!(!fixture.store.expired.load(Ordering::SeqCst));
|
||||
assert_eq!(fixture.store.active_leases(), 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cancellation_releases_the_key_account_lease_without_sending() {
|
||||
let upstream = MockServer::start().await;
|
||||
let fixture = Fixture::new(&upstream.uri());
|
||||
fixture
|
||||
.store
|
||||
.use_api_key(&format!("{}/v1beta", upstream.uri()));
|
||||
let cancellation = CancellationToken::new();
|
||||
let mut stream = fixture
|
||||
.provider
|
||||
.clone()
|
||||
.execute(
|
||||
request(true),
|
||||
context(
|
||||
OpaqueProviderData::new(Default::default()),
|
||||
cancellation.clone(),
|
||||
),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
cancellation.cancel();
|
||||
assert_eq!(
|
||||
stream.next().await.unwrap().unwrap_err().kind(),
|
||||
ProviderErrorKind::Cancelled
|
||||
);
|
||||
drop(stream);
|
||||
tokio::time::timeout(Duration::from_secs(1), async {
|
||||
while fixture.store.active_leases() != 0 {
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(upstream.received_requests().await.unwrap().is_empty());
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Provider 真实执行合同测试
|
||||
|
||||
mod affinity;
|
||||
mod api_key;
|
||||
mod execution;
|
||||
mod headers;
|
||||
mod middleware;
|
||||
|
||||
@@ -76,6 +76,39 @@ pub(crate) struct MemoryAccount {
|
||||
}
|
||||
|
||||
impl MemoryPorts {
|
||||
pub(crate) fn use_api_key(&self, base_url: &str) {
|
||||
let entry = self.primary();
|
||||
let mut loaded = entry.loaded.lock().unwrap();
|
||||
loaded.account = ProviderAccount::new(
|
||||
loaded.account.id().clone(),
|
||||
loaded.account.provider().clone(),
|
||||
"Relay".into(),
|
||||
None,
|
||||
"api_key".into(),
|
||||
loaded.account.revision(),
|
||||
None,
|
||||
)
|
||||
.with_account_facts(
|
||||
true,
|
||||
CredentialState::Ready,
|
||||
QuotaState::unknown(),
|
||||
None,
|
||||
None,
|
||||
);
|
||||
loaded.credential = PlaintextCredential::new(
|
||||
json!({
|
||||
"schema_version":1,"base_url":base_url,"api_key":"fixture-key"
|
||||
})
|
||||
.as_object()
|
||||
.unwrap()
|
||||
.clone(),
|
||||
);
|
||||
let mut catalog = entry.catalog.lock().unwrap();
|
||||
let (observation, body) = catalog.as_mut().unwrap();
|
||||
observation.etag = Some("genai_api_key_v1".into());
|
||||
*body = serde_json::to_vec(&json!({"models":{"fixture-model":{"name":"models/fixture-model","displayName":"Fixture Model","supportedGenerationMethods":["generateContent","countTokens"]}}})).unwrap().into();
|
||||
}
|
||||
|
||||
pub(crate) fn primary(&self) -> &MemoryAccount {
|
||||
&self.accounts[&ProviderAccountId::new(PRIMARY_ACCOUNT).unwrap()]
|
||||
}
|
||||
|
||||
@@ -33,6 +33,7 @@ impl ProviderLeasePort for MemoryPorts {
|
||||
AccountRuntimeSignals {
|
||||
in_flight: self.accounts[id].active_leases.load(Ordering::SeqCst)
|
||||
as u32,
|
||||
recent_requests: 0,
|
||||
last_started_at: None,
|
||||
quota_reset_at: None,
|
||||
quota_reset_windows: None,
|
||||
@@ -622,8 +623,19 @@ impl ProviderAccountStore for MemoryPorts {
|
||||
) -> Result<QuotaWriteOutcome, StoreError> {
|
||||
unreachable!("unused fixture port: ProviderAccountStore::apply_quota_access")
|
||||
}
|
||||
async fn apply_state_change(&self, _change: AccountStateChange) -> Result<(), StoreError> {
|
||||
unreachable!("unused fixture port: ProviderAccountStore::apply_state_change")
|
||||
async fn apply_state_change(&self, change: AccountStateChange) -> Result<(), StoreError> {
|
||||
let entry = &self.accounts[&change.account_id];
|
||||
let mut loaded = entry.loaded.lock().unwrap();
|
||||
if loaded.account.revision() == change.expected_revision {
|
||||
loaded.account = loaded.account.clone().with_account_facts(
|
||||
loaded.account.enabled(),
|
||||
change.credential_state,
|
||||
loaded.account.quota(),
|
||||
change.error_reason,
|
||||
change.message,
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
async fn update_account(&self, _update: ProviderAccountUpdate) -> Result<(), StoreError> {
|
||||
unreachable!("unused fixture port: ProviderAccountStore::update_account")
|
||||
|
||||
@@ -111,7 +111,7 @@ async fn oauth_refresh_and_native_generate_preserve_grant_profile_and_wire_paylo
|
||||
for stream in [false, true] {
|
||||
let res = client
|
||||
.generate(
|
||||
&catalog.project,
|
||||
catalog.project.as_deref().unwrap(),
|
||||
"fixture-model",
|
||||
&access_token,
|
||||
body,
|
||||
|
||||
@@ -1,60 +1,30 @@
|
||||
//! 推理响应携带的额度观察合并与 Provider 快照规范化
|
||||
|
||||
use super::*;
|
||||
use crate::transport::CodexRateLimitObservation;
|
||||
|
||||
impl CodexCredentialQuotaService {
|
||||
/// 把正常推理响应携带的限流事实合并进 Provider 原始 quota JSON
|
||||
pub async fn synchronize_passive_headers(
|
||||
&self,
|
||||
account: &ProviderAccount,
|
||||
headers: &[(String, String)],
|
||||
) -> Result<bool, CodexCredentialQuotaError> {
|
||||
let Some(rate_limits) = parse_rate_limit_headers(headers) else {
|
||||
return Ok(false);
|
||||
};
|
||||
self.synchronize_passive_rate_limits(account, std::slice::from_ref(&rate_limits))
|
||||
.await
|
||||
}
|
||||
|
||||
/// 把成功推理响应中采集的结构化限流观察合并后单次落库
|
||||
pub async fn synchronize_passive_rate_limits(
|
||||
&self,
|
||||
account: &ProviderAccount,
|
||||
rate_limits: &[ParsedRateLimits],
|
||||
observations: &[CodexRateLimitObservation],
|
||||
) -> Result<bool, CodexCredentialQuotaError> {
|
||||
self.synchronize_passive_rate_limits_with_usage(account, rate_limits, true)
|
||||
self.synchronize_passive_rate_limits_with_usage(account, observations, true)
|
||||
.await
|
||||
}
|
||||
|
||||
pub(crate) async fn synchronize_passive_rate_limits_with_usage(
|
||||
&self,
|
||||
account: &ProviderAccount,
|
||||
rate_limits: &[ParsedRateLimits],
|
||||
observations: &[CodexRateLimitObservation],
|
||||
request_used_quota: bool,
|
||||
) -> Result<bool, CodexCredentialQuotaError> {
|
||||
if account.authentication_kind() != crate::credential::CODEX_AUTHENTICATION_KIND_OAUTH
|
||||
|| rate_limits.is_empty()
|
||||
|| observations.is_empty()
|
||||
{
|
||||
return Ok(false);
|
||||
}
|
||||
let has_quota_facts = rate_limits.iter().any(|observation| {
|
||||
observation
|
||||
.limits
|
||||
.values()
|
||||
.any(|details| passive_rate_limit_snapshot(details).is_some())
|
||||
});
|
||||
// 只用本次响应明确携带的套餐更新账号,不能把合并前的旧快照重新当作新证据
|
||||
let observed_plan = rate_limits
|
||||
.iter()
|
||||
.rev()
|
||||
.filter_map(|observation| {
|
||||
observation.plan_type.as_deref().filter(|plan| {
|
||||
!plan.trim().is_empty() && !plan.trim().eq_ignore_ascii_case("unknown")
|
||||
})
|
||||
})
|
||||
.next();
|
||||
// 重读发生冲突的快照时仍用响应到达时间,不能把迟到的用量当成新证据
|
||||
let observed_at = SystemTime::now();
|
||||
for _ in 0..QUOTA_MERGE_ATTEMPTS {
|
||||
let existing = self
|
||||
.store
|
||||
@@ -68,9 +38,36 @@ impl CodexCredentialQuotaService {
|
||||
let merge_base = QuotaMergeBase {
|
||||
observed_at: existing.as_ref().map(|obs| obs.observed_at),
|
||||
};
|
||||
if merge_base.observed_at.is_some_and(|at| at >= observed_at) {
|
||||
// 每条事实按采集时间过滤,后来的具名桶事件不能替旧的通用额度续期
|
||||
// 冲突重读也重新筛选,流结束和落库重试都不产生新的上游观测
|
||||
let fresh: Vec<_> = observations
|
||||
.iter()
|
||||
.filter(|observation| {
|
||||
merge_base
|
||||
.observed_at
|
||||
.is_none_or(|at| observation.observed_at > at)
|
||||
})
|
||||
.collect();
|
||||
let Some(observed_at) = fresh
|
||||
.iter()
|
||||
.map(|observation| observation.observed_at)
|
||||
.max()
|
||||
else {
|
||||
return Ok(false);
|
||||
}
|
||||
};
|
||||
let has_quota_facts = fresh.iter().any(|observation| {
|
||||
observation
|
||||
.rate_limits
|
||||
.limits
|
||||
.values()
|
||||
.any(|details| passive_rate_limit_snapshot(details).is_some())
|
||||
});
|
||||
// 套餐也只取本轮新事实,不能把旧响应里的套餐重新写回账号
|
||||
let observed_plan = fresh.iter().rev().find_map(|observation| {
|
||||
observation.rate_limits.plan_type.as_deref().filter(|plan| {
|
||||
!plan.trim().is_empty() && !plan.trim().eq_ignore_ascii_case("unknown")
|
||||
})
|
||||
});
|
||||
let previous = if account.quota_settings().is_empty() {
|
||||
None
|
||||
} else {
|
||||
@@ -87,8 +84,12 @@ impl CodexCredentialQuotaService {
|
||||
let prior = existing_state.unwrap_or_else(|| account.quota());
|
||||
let (mut quota, updated_default) = merge_passive_quota(
|
||||
existing,
|
||||
rate_limits,
|
||||
request_used_quota.then_some(observed_at),
|
||||
fresh.iter().map(|observation| {
|
||||
(
|
||||
&observation.rate_limits,
|
||||
request_used_quota.then_some(observation.observed_at),
|
||||
)
|
||||
}),
|
||||
);
|
||||
let mut snapshot = parse_account_quota_snapshot(
|
||||
account.id().clone(),
|
||||
@@ -98,7 +99,9 @@ impl CodexCredentialQuotaService {
|
||||
)?;
|
||||
snapshot.retain_limit_evidence(account.quota_settings(), previous.as_ref(), &mut quota);
|
||||
let credit_access = prior.evidence() == Some(QuotaEvidence::CreditsAvailable);
|
||||
let fresh_credits = rate_limits.iter().any(|limits| limits.credits.is_some());
|
||||
let fresh_credits = fresh
|
||||
.iter()
|
||||
.any(|observation| observation.rate_limits.credits.is_some());
|
||||
// 具名桶和元数据不改变套餐结论;点数不能再用时,仍须撤销原先仅凭点数的放行
|
||||
let subscription = if !updated_default
|
||||
|| (snapshot.quota().access() == QuotaAccessState::Unknown
|
||||
@@ -156,21 +159,20 @@ pub(crate) fn observed_quota_window(
|
||||
key: &str,
|
||||
) -> Option<CodexQuotaWindow> {
|
||||
// 只解释本次响应,不借用当前快照补全旧观测或把具名桶镜像当作账号额度
|
||||
let (quota, _) = merge_passive_quota(Map::new(), std::slice::from_ref(parsed), None);
|
||||
let (quota, _) = merge_passive_quota(Map::new(), std::iter::once((parsed, None)));
|
||||
snapshot::quota_windows("a)
|
||||
.ok()?
|
||||
.into_iter()
|
||||
.find(|window| window.key() == key)
|
||||
}
|
||||
|
||||
fn merge_passive_quota(
|
||||
fn merge_passive_quota<'a>(
|
||||
mut quota: Map<String, Value>,
|
||||
observations: &[ParsedRateLimits],
|
||||
used_at: Option<SystemTime>,
|
||||
observations: impl IntoIterator<Item = (&'a ParsedRateLimits, Option<SystemTime>)>,
|
||||
) -> (Map<String, Value>, bool) {
|
||||
let mut updated_default = false;
|
||||
let mut snapshots = RateLimitSnapshotsByLimitId::take_from_document(&mut quota);
|
||||
for rate_limits in observations {
|
||||
for (rate_limits, used_at) in observations {
|
||||
let default_is_named_alias = default_limit_is_named_alias(rate_limits);
|
||||
let mut resolved_limit_ids = BTreeMap::new();
|
||||
for (wire_limit_id, details) in &rate_limits.limits {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! 账号额度窗口预热与完成事件校验
|
||||
|
||||
use super::*;
|
||||
use crate::transport::CodexRateLimitObservation;
|
||||
|
||||
enum WarmupDecision<'a> {
|
||||
Ready,
|
||||
@@ -263,30 +264,38 @@ impl CodexCredentialQuotaService {
|
||||
.await
|
||||
.map_err(|_| "request_rejected")?;
|
||||
let terminal = consume_warmup_sse(&mut response).await;
|
||||
let mut observations = response
|
||||
.diagnostics
|
||||
.headers_observed_at
|
||||
.and_then(|observed_at| {
|
||||
parse_rate_limit_headers(&response.rate_limit_headers).map(|rate_limits| {
|
||||
CodexRateLimitObservation {
|
||||
rate_limits,
|
||||
observed_at,
|
||||
}
|
||||
})
|
||||
})
|
||||
.into_iter()
|
||||
.collect::<Vec<_>>();
|
||||
let rate_limit_updates = match response.rate_limit_updates.as_ref() {
|
||||
Some(updates) => std::mem::take(&mut *updates.lock().await),
|
||||
None => Vec::new(),
|
||||
};
|
||||
Ok::<_, &'static str>((terminal, response.rate_limit_headers, rate_limit_updates))
|
||||
observations.extend(rate_limit_updates);
|
||||
Ok::<_, &'static str>((terminal, observations))
|
||||
})
|
||||
.await;
|
||||
match attempt {
|
||||
Ok(Ok((terminal, headers, rate_limit_updates))) => {
|
||||
Ok(Ok((terminal, observations))) => {
|
||||
match terminal {
|
||||
Ok(()) => {
|
||||
// 被动额度同步会把成功请求的窗口事实标为可用,失败流不能复用该结论
|
||||
if !headers.is_empty()
|
||||
&& let Err(error) =
|
||||
self.synchronize_passive_headers(account, &headers).await
|
||||
{
|
||||
tracing::warn!(account_id = %account.id(), error = %error, "OpenAI warmup rate-limit header sync failed");
|
||||
}
|
||||
if !rate_limit_updates.is_empty()
|
||||
if !observations.is_empty()
|
||||
&& let Err(error) = self
|
||||
.synchronize_passive_rate_limits(account, &rate_limit_updates)
|
||||
.synchronize_passive_rate_limits(account, &observations)
|
||||
.await
|
||||
{
|
||||
tracing::warn!(account_id = %account.id(), error = %error, "OpenAI warmup rate-limit event sync failed");
|
||||
tracing::warn!(account_id = %account.id(), error = %error, "OpenAI warmup rate-limit sync failed");
|
||||
}
|
||||
summary.warmed_up += 1;
|
||||
tracing::info!(
|
||||
|
||||
@@ -1139,12 +1139,13 @@ impl CodexCredentialSelector {
|
||||
model,
|
||||
request.attempt.account_selection_policy().strategy(),
|
||||
);
|
||||
let signals = scheduling
|
||||
let mut signals = scheduling
|
||||
.signals()
|
||||
.get(account.id())
|
||||
.cloned()
|
||||
.unwrap_or(AccountRuntimeSignals {
|
||||
in_flight: 0,
|
||||
recent_requests: 0,
|
||||
last_started_at: None,
|
||||
quota_reset_at: None,
|
||||
quota_reset_windows: None,
|
||||
@@ -1156,6 +1157,11 @@ impl CodexCredentialSelector {
|
||||
.with_provider_quota(quota)
|
||||
.with_rate_limit(rate_limits.get(account.id()).copied())
|
||||
.with_runtime_health(health.0, health.1);
|
||||
signals.recent_requests = self.account_feedback.recent_requests(
|
||||
&self.provider_kind,
|
||||
account.id(),
|
||||
model.model(),
|
||||
);
|
||||
AccountCandidate {
|
||||
account,
|
||||
signals,
|
||||
|
||||
@@ -730,6 +730,7 @@ pub(super) fn cold_json_response_stream(request: ColdJsonResponse) -> EventStrea
|
||||
&request.quota,
|
||||
&active_account,
|
||||
&response.rate_limit_headers,
|
||||
response.diagnostics.headers_observed_at,
|
||||
image_endpoint,
|
||||
true,
|
||||
)
|
||||
@@ -1015,7 +1016,7 @@ pub(super) fn cold_response_stream(response: ColdResponse) -> EventStream {
|
||||
}
|
||||
let failure_rate_limit_headers = response.rate_limit_headers.clone();
|
||||
let mut passive_quota_observation =
|
||||
OpenAiPassiveQuotaObservation::new(response.rate_limit_headers);
|
||||
OpenAiPassiveQuotaObservation::new(response.rate_limit_headers, response.diagnostics.headers_observed_at);
|
||||
let rate_limit_updates = response.rate_limit_updates;
|
||||
let response_metadata_updates = response.response_metadata_updates;
|
||||
// 同协议保留原始帧;canonical 解析只提取计费、续接和状态事实
|
||||
|
||||
@@ -51,6 +51,7 @@ pub(super) struct MappedProviderFailure {
|
||||
pub(super) set_cookie_headers: Vec<String>,
|
||||
pub(super) response_origin: Option<Url>,
|
||||
pub(super) rate_limit_headers: Vec<(String, String)>,
|
||||
pub(super) headers_observed_at: Option<std::time::SystemTime>,
|
||||
pub(super) observation: Option<ProviderResponseObservation>,
|
||||
pub(super) capture_response_cookies: bool,
|
||||
}
|
||||
@@ -67,6 +68,7 @@ impl MappedProviderFailure {
|
||||
set_cookie_headers: Vec::new(),
|
||||
response_origin: None,
|
||||
rate_limit_headers: Vec::new(),
|
||||
headers_observed_at: None,
|
||||
observation: None,
|
||||
capture_response_cookies: false,
|
||||
}
|
||||
@@ -342,6 +344,7 @@ pub(super) async fn apply_failure(
|
||||
context.quota,
|
||||
account,
|
||||
&failure.rate_limit_headers,
|
||||
failure.headers_observed_at,
|
||||
context.image_endpoint,
|
||||
false,
|
||||
)
|
||||
@@ -725,18 +728,7 @@ pub(super) fn continuation_recovery_error(
|
||||
|
||||
let mut headers: Vec<ProviderResponseHeader> = error
|
||||
.client_visible_upstream_response()
|
||||
.map(|response| {
|
||||
response
|
||||
.headers()
|
||||
.iter()
|
||||
// 额度窗口的等待时间不适用于客户端重建历史
|
||||
.filter(|header| {
|
||||
!header.name().eq_ignore_ascii_case("retry-after")
|
||||
&& !header.name().eq_ignore_ascii_case("retry-after-ms")
|
||||
})
|
||||
.cloned()
|
||||
.collect()
|
||||
})
|
||||
.map(|response| response.headers().to_vec())
|
||||
.unwrap_or_default();
|
||||
// 流内拒绝没有原始 HTTP 失败响应,仍需把该次失败的关联 ID 交给 HTTP 客户端
|
||||
if !headers.iter().any(|header| {
|
||||
@@ -751,7 +743,8 @@ pub(super) fn continuation_recovery_error(
|
||||
}
|
||||
// 丢弃仍未交付的前导与额度错误帧,避免原错误覆盖客户端恢复投影
|
||||
// 已交付的 Lite 前导不在此批次内,语义输出后的失败不进入此分支
|
||||
drop(error.take_atomic_client_events());
|
||||
let events = error.take_atomic_client_events();
|
||||
error.extend_client_retry_headers(&mut headers, &events);
|
||||
error
|
||||
.with_continuation_failure(ContinuationFailure::HistoryUnavailable)
|
||||
.with_continuation_recovery_disposition(
|
||||
@@ -1634,6 +1627,7 @@ pub(super) fn map_upstream_failure(
|
||||
set_cookie_headers: failure.set_cookie_headers,
|
||||
response_origin: failure.response_origin,
|
||||
rate_limit_headers: failure.rate_limit_headers,
|
||||
headers_observed_at: failure.headers_observed_at,
|
||||
observation,
|
||||
capture_response_cookies: !matches!(
|
||||
category,
|
||||
|
||||
@@ -46,9 +46,7 @@ use gateway_core::task::{
|
||||
WorkerRunnable, WorkerSchedule, WorkerTaskError,
|
||||
};
|
||||
use gateway_core::upstream::{UpstreamSendState, UpstreamTransport};
|
||||
use gateway_protocol::openai::events::{
|
||||
ParsedRateLimits, parse_rate_limit_headers, rate_limits_to_header_pairs,
|
||||
};
|
||||
use gateway_protocol::openai::events::{parse_rate_limit_headers, rate_limits_to_header_pairs};
|
||||
use gateway_protocol::openai::{CodexGuardianRole, OPENAI_PROTOCOL, codex_guardian_role};
|
||||
use reqwest::{Client, header::HeaderValue};
|
||||
use secrecy::{ExposeSecret, SecretString};
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! OpenAI 请求、响应与 transport 观测事实归一化
|
||||
|
||||
use super::*;
|
||||
use crate::transport::CodexRateLimitObservation;
|
||||
|
||||
pub(super) fn endpoint_requested_model(
|
||||
payload: &gateway_core::operation::RawJsonPayload,
|
||||
@@ -39,21 +40,34 @@ pub(super) struct OpenAiResponseObservationState {
|
||||
}
|
||||
|
||||
pub(super) struct OpenAiPassiveQuotaObservation {
|
||||
rate_limits: Vec<ParsedRateLimits>,
|
||||
rate_limits: Vec<CodexRateLimitObservation>,
|
||||
}
|
||||
|
||||
impl OpenAiPassiveQuotaObservation {
|
||||
pub(super) fn new(headers: Vec<(String, String)>) -> Self {
|
||||
pub(super) fn new(
|
||||
headers: Vec<(String, String)>,
|
||||
observed_at: Option<std::time::SystemTime>,
|
||||
) -> Self {
|
||||
Self {
|
||||
rate_limits: parse_rate_limit_headers(&headers).into_iter().collect(),
|
||||
rate_limits: observed_at
|
||||
.and_then(|observed_at| {
|
||||
parse_rate_limit_headers(&headers).map(|rate_limits| {
|
||||
CodexRateLimitObservation {
|
||||
rate_limits,
|
||||
observed_at,
|
||||
}
|
||||
})
|
||||
})
|
||||
.into_iter()
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn observe(&mut self, updates: &[ParsedRateLimits]) {
|
||||
pub(super) fn observe(&mut self, updates: &[CodexRateLimitObservation]) {
|
||||
self.rate_limits.extend_from_slice(updates);
|
||||
}
|
||||
|
||||
pub(super) fn rate_limits(&self) -> &[ParsedRateLimits] {
|
||||
pub(super) fn rate_limits(&self) -> &[CodexRateLimitObservation] {
|
||||
&self.rate_limits
|
||||
}
|
||||
}
|
||||
@@ -493,17 +507,19 @@ pub(super) fn insert_first_timing(target: &mut Option<u64>, started_at: Instant)
|
||||
|
||||
pub(super) async fn take_rate_limit_updates(
|
||||
updates: Option<&CodexRateLimitUpdates>,
|
||||
) -> Vec<ParsedRateLimits> {
|
||||
) -> Vec<CodexRateLimitObservation> {
|
||||
let Some(updates) = updates else {
|
||||
return Vec::new();
|
||||
};
|
||||
std::mem::take(&mut *updates.lock().await)
|
||||
}
|
||||
|
||||
pub(super) fn rate_limit_update_headers(updates: &[ParsedRateLimits]) -> Vec<(String, String)> {
|
||||
pub(super) fn rate_limit_update_headers(
|
||||
updates: &[CodexRateLimitObservation],
|
||||
) -> Vec<(String, String)> {
|
||||
updates
|
||||
.iter()
|
||||
.flat_map(rate_limits_to_header_pairs)
|
||||
.flat_map(|observation| rate_limits_to_header_pairs(&observation.rate_limits))
|
||||
.collect()
|
||||
}
|
||||
|
||||
@@ -532,7 +548,7 @@ pub(super) fn terminal_response_is_incomplete(events: &[ProviderEvent]) -> bool
|
||||
pub(super) async fn synchronize_passive_quota(
|
||||
quota: &CodexCredentialQuotaService,
|
||||
account: &ProviderAccount,
|
||||
rate_limits: &[ParsedRateLimits],
|
||||
rate_limits: &[CodexRateLimitObservation],
|
||||
request_used_quota: bool,
|
||||
) {
|
||||
if rate_limits.is_empty() {
|
||||
@@ -554,9 +570,13 @@ pub(super) async fn synchronize_passive_quota_headers(
|
||||
quota: &CodexCredentialQuotaService,
|
||||
account: &ProviderAccount,
|
||||
headers: &[(String, String)],
|
||||
observed_at: Option<std::time::SystemTime>,
|
||||
image_endpoint: bool,
|
||||
request_used_quota: bool,
|
||||
) {
|
||||
let Some(observed_at) = observed_at else {
|
||||
return;
|
||||
};
|
||||
let parsed = if image_endpoint {
|
||||
gateway_protocol::openai::events::parse_image_rate_limit_headers(headers)
|
||||
} else {
|
||||
@@ -566,7 +586,10 @@ pub(super) async fn synchronize_passive_quota_headers(
|
||||
synchronize_passive_quota(
|
||||
quota,
|
||||
account,
|
||||
std::slice::from_ref(&rate_limits),
|
||||
&[CodexRateLimitObservation {
|
||||
rate_limits,
|
||||
observed_at,
|
||||
}],
|
||||
request_used_quota,
|
||||
)
|
||||
.await;
|
||||
|
||||
@@ -944,7 +944,10 @@ async fn append_http_sse_rate_limit_updates(
|
||||
let Some(rate_limits) = events::parse_rate_limits_event_raw(&event.data) else {
|
||||
continue;
|
||||
};
|
||||
observations.push(rate_limits);
|
||||
observations.push(crate::transport::CodexRateLimitObservation {
|
||||
rate_limits,
|
||||
observed_at: std::time::SystemTime::now(),
|
||||
});
|
||||
}
|
||||
}
|
||||
if !observations.is_empty() {
|
||||
|
||||
@@ -85,6 +85,7 @@ pub struct CodexUpstreamFailure {
|
||||
pub(crate) response_origin: Option<url::Url>,
|
||||
pub(crate) set_cookie_headers: Vec<String>,
|
||||
pub(crate) rate_limit_headers: Vec<(String, String)>,
|
||||
pub(crate) headers_observed_at: Option<std::time::SystemTime>,
|
||||
pub(crate) send_phase: CodexUpstreamSendPhase,
|
||||
category: CodexFailureCategory,
|
||||
}
|
||||
@@ -132,6 +133,7 @@ impl CodexUpstreamFailure {
|
||||
response_origin: diagnostics.response_origin.clone(),
|
||||
set_cookie_headers: set_cookie_headers.to_vec(),
|
||||
rate_limit_headers: rate_limit_headers.to_vec(),
|
||||
headers_observed_at: diagnostics.headers_observed_at,
|
||||
send_phase,
|
||||
category,
|
||||
}
|
||||
@@ -188,6 +190,7 @@ impl CodexUpstreamFailure {
|
||||
response_origin: diagnostics.response_origin.clone(),
|
||||
set_cookie_headers: set_cookie_headers.to_vec(),
|
||||
rate_limit_headers: rate_limit_headers.to_vec(),
|
||||
headers_observed_at: diagnostics.headers_observed_at,
|
||||
send_phase,
|
||||
category,
|
||||
}
|
||||
@@ -321,6 +324,8 @@ enum UpstreamFailureSource {
|
||||
|
||||
#[derive(Clone, Default, PartialEq, Eq)]
|
||||
pub struct CodexUpstreamDiagnostics {
|
||||
/// 响应头的采集时间,不随正文消费或连接复用推进
|
||||
pub headers_observed_at: Option<std::time::SystemTime>,
|
||||
pub status_code: Option<u16>,
|
||||
pub request_id: Option<String>,
|
||||
pub identity_authorization_error: Option<String>,
|
||||
@@ -381,6 +386,7 @@ impl CodexUpstreamDiagnostics {
|
||||
|
||||
pub fn from_headers(status_code: Option<u16>, headers: &HeaderMap) -> Self {
|
||||
Self {
|
||||
headers_observed_at: Some(std::time::SystemTime::now()),
|
||||
status_code,
|
||||
request_id: first_header(headers, UPSTREAM_REQUEST_ID_HEADERS),
|
||||
identity_authorization_error: header_value(
|
||||
|
||||
@@ -60,7 +60,7 @@ pub use self::{
|
||||
CodexRateLimitResetCredit, CodexRateLimitResetCredits,
|
||||
CodexRateLimitResetCreditsConsumeResult, MAX_CODEX_RESET_CREDITS_BODY_BYTES,
|
||||
},
|
||||
response_meta::CodexResponseMetadata,
|
||||
response_meta::{CodexRateLimitObservation, CodexResponseMetadata},
|
||||
usage::MAX_CODEX_USAGE_BODY_BYTES,
|
||||
websocket::{
|
||||
CodexWebSocketPool, CodexWebSocketPoolConfig, CodexWebSocketPoolKey, WebSocketPoolDecision,
|
||||
|
||||
@@ -1,13 +1,22 @@
|
||||
//! 上游响应元数据提取辅助
|
||||
|
||||
use std::fmt;
|
||||
use std::{fmt, time::SystemTime};
|
||||
|
||||
use bytes::Bytes;
|
||||
use gateway_protocol::openai::events::{is_codex_quota_header_name, is_rate_limit_header_name};
|
||||
use gateway_protocol::openai::events::{
|
||||
ParsedRateLimits, is_codex_quota_header_name, is_rate_limit_header_name,
|
||||
};
|
||||
use reqwest::header::{HeaderMap, SET_COOKIE};
|
||||
|
||||
use super::diagnostics::CodexUpstreamDiagnostics;
|
||||
|
||||
/// 额度事实与采集时间一起跨越流缓冲和持久化等待
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct CodexRateLimitObservation {
|
||||
pub rate_limits: ParsedRateLimits,
|
||||
pub observed_at: SystemTime,
|
||||
}
|
||||
|
||||
/// Codex Responses 上游响应元数据
|
||||
#[derive(Clone, Default, PartialEq, Eq)]
|
||||
pub struct CodexResponseMetadata {
|
||||
|
||||
@@ -8,12 +8,12 @@ use std::{pin::Pin, sync::Arc};
|
||||
|
||||
use bytes::Bytes;
|
||||
use futures::Stream;
|
||||
use gateway_protocol::openai::events::ParsedRateLimits;
|
||||
use tokio::sync::Mutex;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::transport::{
|
||||
diagnostics::CodexUpstreamDiagnostics, response_meta::CodexResponseMetadata,
|
||||
diagnostics::CodexUpstreamDiagnostics,
|
||||
response_meta::{CodexRateLimitObservation, CodexResponseMetadata},
|
||||
};
|
||||
|
||||
use super::error::CodexWebSocketExchangeError;
|
||||
@@ -54,7 +54,7 @@ pub struct CodexWebSocketStreamingExchange {
|
||||
pub type CodexWebSocketTextStream =
|
||||
Pin<Box<dyn Stream<Item = Result<Bytes, CodexWebSocketExchangeError>> + Send + 'static>>;
|
||||
/// live 流中的结构化限流动态更新
|
||||
pub type CodexWebSocketRateLimitUpdates = Arc<Mutex<Vec<ParsedRateLimits>>>;
|
||||
pub type CodexWebSocketRateLimitUpdates = Arc<Mutex<Vec<CodexRateLimitObservation>>>;
|
||||
/// 单次响应的动态 metadata,与连接池保存的握手快照隔离
|
||||
#[derive(Debug, Default)]
|
||||
pub struct CodexWebSocketResponseMetadataUpdate {
|
||||
|
||||
@@ -365,7 +365,11 @@ async fn forward_websocket_response_stream(state: WebSocketStreamForwardState) {
|
||||
}
|
||||
let terminal = match reduced.action {
|
||||
ExchangeAction::RateLimits(rate_limits) => {
|
||||
rate_limit_updates.lock().await.push(rate_limits);
|
||||
let observation = crate::transport::CodexRateLimitObservation {
|
||||
rate_limits,
|
||||
observed_at: std::time::SystemTime::now(),
|
||||
};
|
||||
rate_limit_updates.lock().await.push(observation);
|
||||
continue;
|
||||
}
|
||||
ExchangeAction::Forward { terminal } => terminal,
|
||||
|
||||
@@ -14,6 +14,7 @@ use super::*;
|
||||
fn busy_signal(in_flight: u32) -> AccountRuntimeSignals {
|
||||
AccountRuntimeSignals {
|
||||
in_flight,
|
||||
recent_requests: 0,
|
||||
last_started_at: None,
|
||||
quota_reset_at: None,
|
||||
quota_reset_windows: None,
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
mod capacity;
|
||||
mod cooldown_reads;
|
||||
mod recent_load;
|
||||
mod scheduling_projection;
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
//! 验证近期模型请求量参与新会话选号且不打断可用绑定
|
||||
|
||||
use std::time::Instant;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn smart_new_sessions_prefer_recently_idle_accounts_and_keep_existing_bindings() {
|
||||
let store = Arc::new(MemoryAccountStore::default());
|
||||
create_account(&store, "acct_first", "test-first");
|
||||
create_account(&store, "acct_second", "test-second");
|
||||
let provider = ProviderKind::new("openai").unwrap();
|
||||
let first = ProviderAccountId::new("acct_first").unwrap();
|
||||
let feedback = Arc::new(AccountFeedbackStats::default());
|
||||
let now = Instant::now();
|
||||
for _ in 0..20 {
|
||||
feedback.record_request_at(&provider, &first, "gpt-5.4", now, now);
|
||||
}
|
||||
let affinity = Arc::new(MemorySessionAffinity::default());
|
||||
let key = ProviderSessionAffinityKey::try_new("recent-load-bound").unwrap();
|
||||
affinity
|
||||
.bind(&provider, &key, &first, Duration::from_secs(60))
|
||||
.await
|
||||
.unwrap();
|
||||
let selector = selector_with_runtime(
|
||||
&store,
|
||||
Arc::new(TestLeaseCoordinator::default()),
|
||||
affinity,
|
||||
feedback,
|
||||
Arc::new(MemoryCooldownPort::new()),
|
||||
);
|
||||
let request_url = Url::parse(OFFICIAL_CODEX_BASE_URL).unwrap();
|
||||
let request_attempt = attempt(BTreeSet::new());
|
||||
for (session_affinity_key, expected) in [(None, "acct_second"), (Some(&key), "acct_first")] {
|
||||
let selected = selector
|
||||
.select(&SelectCodexCredential {
|
||||
protocol: gateway_protocol::openai::OPENAI_PROTOCOL,
|
||||
upstream_model: "gpt-5.4",
|
||||
request_url: &request_url,
|
||||
attempt: &request_attempt,
|
||||
session_affinity_key,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(selected.account_id().as_str(), expected);
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user