Compare commits

...
12 Commits
Author SHA1 Message Date
ZyyandCodex 177679a13c chore: bump version to 3.62.1-rc.2
Co-authored-by: Codex <noreply@openai.com>
2026-12-06 02:33:53 +08:00
ZyyandCodex 195c51c06c refactor(db): consolidate unreleased account migrations
Co-authored-by: Codex <noreply@openai.com>
2026-12-06 02:31:55 +08:00
745bd15d3d feat(antigravity): make account query refresh modes configurable (#856)
* feat(antigravity): make account query refresh modes configurable

Co-authored-by: Codex <noreply@openai.com>

* fix(antigravity): release exhausted accounts when quota windows expire

Co-authored-by: Codex <noreply@openai.com>

* fix(antigravity): apply quota exhaustion to upstream model groups

Co-authored-by: Codex <noreply@openai.com>

---------

Co-authored-by: Zyy <zyycn@users.noreply.github.com>
Co-authored-by: Codex <noreply@openai.com>
2026-12-06 02:25:36 +08:00
3170b92d47 feat(accounts): schedule daily shifts for accounts and groups (#855)
* feat(accounts): schedule daily shifts for accounts and groups

Co-authored-by: Codex <noreply@openai.com>

* fix(accounts): keep off-shift sessions on their account by default

Co-authored-by: Codex <noreply@openai.com>

---------

Co-authored-by: Zyy <zyycn@users.noreply.github.com>
Co-authored-by: Codex <noreply@openai.com>
2026-12-05 23:50:08 +08:00
github-actions[bot] 8b40e707fd chore(release): update release channels to 3.62.1-rc.1 2026-12-05 07:59:21 +00:00
ZyyandCodex 15aabfc861 fix(release): restore GitHub release notes with channel-aware baselines
Co-authored-by: Codex <noreply@openai.com>
2026-12-05 15:50:18 +08:00
ZyyandCodex 0ebf6739e2 chore: bump version to 3.62.1-rc.1
Co-authored-by: Codex <noreply@openai.com>
2026-12-05 15:37:36 +08:00
ZyyandCodex b987cca4aa docs(release): base stable version bumps on changes since the last stable release
Co-authored-by: Codex <noreply@openai.com>
2026-12-05 15:36:01 +08:00
ZyyandCodex 72e82c565e fix(openai): clear only recovery feedback observed before success
Confirm the request still uses the current access token before resetting transient feedback across credential revisions. Track the latest 401 independently from Cloudflare streaks so an overlapping failure cannot suppress or be erased by a successful request.

Co-authored-by: Codex <noreply@openai.com>
2026-12-05 15:30:10 +08:00
47ccdeb737 fix(openai): preserve OAuth recovery and token rotation (#853)
* fix(openai): refresh OAuth tokens rejected before expiry

A 401 on a model request marked a refreshable OAuth account Expired when
its access token had not reached its expiry. Expired accounts are left out
of both selection and scheduled refresh, so the account stayed out of
rotation until it was refreshed by hand, even though the refresh token was
still valid.

Expire the rejected access token instead and let the OAuth worker renew
it, as quota refresh already does for token_revoked. A renewed token that
is rejected again before any successful request still marks the account
Expired.

Constraint: Accounts without a refresh token or a known expiry keep the existing Expired outcome
Rejected: Match the "status=503" text inside the 401 body | free-text matching, and other 401s on unexpired tokens would still strand the account
Rejected: Refresh on every 401 without a bound | an account whose renewed tokens keep failing would refresh in a loop
Confidence: high
Scope-risk: narrow
Tested: Rust 1.99.1 fmt --check; clippy -p provider-openai --all-targets --all-features -D warnings; provider-openai tests (1264 passed); the new selector case and the adapter case fail without the selector change
Not-tested: A live upstream 401 against this build; workspace-wide clippy and tests are left to CI

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* fix(openai): preserve OAuth recovery across concurrent feedback

Report success from native endpoints and upstream adapters, and keep stale
responses from clearing the current OAuth recovery bound. Serialize model
401 and Cookie feedback with token refresh through the account lease.
Recheck credential revisions after acquiring scheduled and manual refresh
leases so a queued snapshot cannot resend an already rotated refresh token.

Cookie feedback skips writes while refresh owns the lease; a later response
can capture cookies without discarding successfully exchanged tokens.

Validated: workspace fmt and strict Clippy; 1265 provider-openai tests;
48 gateway architecture and bootstrap tests. Real upstream and store service
integration remain for live verification and CI.

Co-authored-by: Codex <noreply@openai.com>

* fix(openai): retain token recovery across cookie revisions

Use the access token and revision that were sent upstream to recognize a successful OAuth request after a concurrent cookie write. Keep account and quota recovery fenced by revision, and preserve newer rejection records and replies from superseded tokens.

Co-authored-by: Codex <noreply@openai.com>

* fix(openai): preserve account feedback across cookie writes

Reset consecutive Cloudflare failures on a successful request using the current access token. Keep quota and account state fenced by the response revision. A model 401 can shorten expiry while the cookie writer holds the refresh lease; a conflicting write is retried only for the same token.

Co-authored-by: Codex <noreply@openai.com>

* test(openai): separate risk counters from OAuth rejection

Verify that a successful request using the rejected token breaks a path-block streak without allowing a refreshed token to be rejected indefinitely.

Co-authored-by: Codex <noreply@openai.com>

---------

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
Co-authored-by: Zyy <zyycn@users.noreply.github.com>
Co-authored-by: Codex <noreply@openai.com>
2026-12-05 14:00:11 +08:00
ZyyandCodex b20b0e2013 fix(release): freeze complete notes and expose backend validation
Co-authored-by: Codex <noreply@openai.com>
2026-12-05 02:09:06 +08:00
github-actions[bot] 16fc302d46 chore(release): update release channels to 3.62.0 2026-12-04 17:37:26 +00:00
204 changed files with 7848 additions and 721 deletions

No files matched your search

@@ -20,7 +20,7 @@
调用入口前重新核对当前脚本的副作用、目标版本和待推送提交,保留无关工作区内容,不自动清理或暂存用户文件。
先编辑 `release/notes.md`,保留为未提交改动(已暂存或未暂存均可);其他已跟踪文件的改动应先单独提交。
脚本只改 `release/version.yaml` 的顶层 `version`,按[接口弃用规则](../../../../backend/crates/gateway-plugin/sdk/docs/manifest.md#接口弃用)校验并维护 `plugin-api-deprecations.json`,将这些差异与最终工作区中的发布说明一起提交为 `chore: bump version to <version>`。
脚本更新 `release/version.yaml` 的顶层 `version`,按[接口弃用规则](../../../../backend/crates/gateway-plugin/sdk/docs/manifest.md#接口弃用)校验并维护 `plugin-api-deprecations.json`,与手写发布说明一起提交为 `chore: bump version to <version>`。
不要提前单独提交说明或把版本文件改成目标版本;脚本要求说明相对 HEAD 有改动,并自行更新版本号。
本任务需要的提交按[项目约定](../../../../CONTRIBUTING.md#项目约定)保留英文 Conventional Commits 与相应署名。
@@ -31,7 +31,7 @@ release/publish "$release_version"
```
该命令会创建上述版本提交与 annotated tag,原子推送分支和 tag,再从长期分支手动触发 `release.yml`。
只读预检使用 `release/publish --check "$release_version"`。发布工作流读取 tag 中的说明,修改 tag 之后的本地文件不会改变该次构建。
只读预检使用 `release/publish --check "$release_version"`。发布工作流读取 tag 中的手写说明,为常规版本追加安装入口、文档和 GitHub 变更列表。
只调整已发布页面的标题或正文时,编辑对应 GitHub Release 的 `name` 或 `body` 并回读核对;
保持已有 tag、源码提交、附件和预发行状态,不重新执行发布入口。
@@ -60,7 +60,8 @@ release/publish "$release_version"
### 验收
- 发布完成后核对 GitHub Release 的版本、正式版/预发行状态和中文变更正文;对照平台清单与工作流确认归档、校验和及镜像产物。
工作流附加的安装说明和自动提交列表按其当前配置处理,不用它们替代手写的中文变更说明。
手写正文应与 tag 内的说明一致,核对安装入口和 `Full Changelog` 指向目标版本,正式版的比较范围从上一正式版开始
- 核对 `backend-validation` 的结果。复用时检查摘要中的源码提交和成功 CI 链接,确认发行提交仅修改版本与说明;未满足复用条件时检查本次完整后端任务,不能把 `quality / backend` 的跳过单独记为测试通过
- 回读 `main:release/version.yaml` 的 `published`。正式版参与同一大版本四个普通通道的比较;RC 参与 RC、Beta、Alpha,Beta 参与 Beta、Alpha,Alpha 只参与自身。实验版只推进 `exp["X.Y.Z"]`。有通道推进时应有 `chore(release): update release channels to <version>` 提交;重复执行或较旧版本未推进任何通道时无提交
- 正式版提升或恢复后,回读 GitHub Latest 的 tag 与镜像 `latest` 的摘要,核对两者均指向预期正式版
- 保留 v3.42.0 在线升级使用的 `update-index` 页面和 v3.42.1 的 `version.yaml` 附件
@@ -9,12 +9,20 @@
3. 使用用户确定的目标版本,建议版本时说明兼容性、能力或修复依据;同名 tag 先区分重试与新发行,不递增版本掩盖冲突
4. 命名与晋级按[版本命名与升级规则](../../../../deploy/README.md#版本命名与升级规则),实验版另读[实验流程](experimental.md#分支与版本)
对比基线选自已公开且 tag 位于目标提交历史内的 GitHub Release
- 推荐正式版号和编写发布说明时,都核对上一正式版到目标提交的最终差异,覆盖期间全部预发行。对于向后兼容的变更,只要有用户可用的新功能,就从上一正式版递增 minor 并将 patch 归零,仅含修复则递增 patch
- alpha、beta、rc 优先对比同一 `X.Y.Z` 的上一常规预发行,没有时对比上一正式版
- exp 对比同一 `X.Y.Z` 的上一实验版,首次实验对比同号正式版
- 没有前序发行的首次发布从仓库起点核对
## 发布说明
读取当前 [notes.md](../../../../release/notes.md)与[项目约定](../../../../CONTRIBUTING.md#项目约定)中的发布说明条目
- 只在发布说明任务中修改 `release/notes.md`,替换为本次版本内容,首行为目标 tag,正文使用中文
- 常规版本按「新增功能」「优化改进」「问题修复」「升级须知」归类,省略空章节;单一改动可直接写一句。安装命令和文档入口由工作流附加
- 常规版本的手写正文按「新增功能」「优化改进」「问题修复」「升级须知」归类,省略空章节;单一改动可直接写一句
- 常规版本的安装入口、文档链接和 GitHub 变更列表由工作流在发版时追加
- 每条用一句短语讲清一个用户可感知的结果,不加句号,例如「系统更新:确认当前平台有安装包后才提示升级」
- 同一变化只写一次,保留会影响使用或升级的默认值和限制,不展开实现过程、逐条翻译提交或写未经验证的承诺
- 剔除回退、重复及未进入发行范围的内容,升级事项须能追溯到实际迁移、配置或兼容变化
@@ -31,7 +39,7 @@
在上一发行基线到 HEAD 的提交中检查是否已有目标版本的备版提交(`chore: bump version to <version>`;查历史时也匹配 `chore(release): prepare v<version>` 和 `chore(release): v<version>`),即使同名 tag 已不存在也要查。命中时先核对该提交对应的发行状态,按[失败恢复](operations.md#恢复与验收)处理,不在旧提交上再叠一个同名提交
发布说明准备好、其他代码已提交后,执行 `release/publish --check <version>`,检查版本、说明、工作区、远端分支与 tag、工具链和插件兼容窗口。
预检不修改文件、Git 引用或远端状态;远端存在本地未知提交时先同步再检查。它不替代 CI、发行物验证或实际发布授权
预检不修改文件、Git 引用或远端状态;远端存在本地未知提交时,先同步再检查。它不替代 CI、发行物验证或实际发布授权
按[验证要求](../../../../CONTRIBUTING.md#验证)核对目标提交的证据,区分通过、失败、跳过与未执行
数据库变更同时读取[迁移冻结规则](../../../../backend/migrations/README.md#冻结规则):
+25 -6
View File
@@ -91,17 +91,36 @@ module ReleaseMetadata
"#{APP_NAME}_#{version}_#{platform.fetch('os')}_#{platform.fetch('arch')}.#{platform.fetch('archive')}"
end
# 正式版始终对比上一正式版,常规预发行优先对比同一目标版本的上一预发行
def self.previous_tag(value)
return if value.include?('-exp.')
endpoint = "repos/#{ENV.fetch('GITHUB_REPOSITORY')}/releases?per_page=100"
output, status = Open3.capture2('gh', 'api', '--paginate', endpoint, '--jq',
'.[] | select(.draft == false) | [.tag_name, .prerelease] | @tsv')
raise 'Failed to read published releases' unless status.success?
reachable = git('tag', '--list', 'v*', '--merged', 'HEAD').lines.map(&:strip)
candidates = output.each_line.each_with_object([]) do |line, tags|
tag, prerelease = line.chomp.split("\t")
next unless reachable.include?(tag) && tag.delete_prefix('v').match?(SEMVER) && !tag.include?('+')
next unless prerelease?(tag) == (prerelease == 'true') && sort_key(tag) < sort_key(value)
tags << tag
end
if prerelease?(value)
prefix = "v#{value.split('-', 2).first}-"
previous = candidates.select { |tag| tag.start_with?(prefix) && !tag.include?('-exp.') }.max_by { |tag| sort_key(tag) }
return previous if previous
end
candidates.reject { |tag| prerelease?(tag) }.max_by { |tag| sort_key(tag) }
end
def self.outputs(tag)
value = release_version(YAML.load_file('release/version.yaml').fetch('version'))
raise "Release tag #{tag} does not match v#{value}" unless tag == "v#{value}"
validate_notes(value)
entries = platforms
docker, native = entries.partition { |entry| entry['docker'] == true }
previous = git('tag', '--list', 'v*', '--merged', 'HEAD').lines.map(&:strip).filter_map do |candidate|
next unless candidate.delete_prefix('v').match?(SEMVER)
key = sort_key(candidate)
[key, candidate] if key < sort_key(value)
end.max_by(&:first)&.last
{
'tag' => tag,
'version' => value,
@@ -112,7 +131,7 @@ module ReleaseMetadata
'non_docker_matrix' => JSON.generate('include' => native),
'windows_matrix' => JSON.generate('include' => entries.select { |entry| entry['os'] == 'windows' }),
'docker_platforms' => docker.map { |entry| entry['dockerPlatform'] }.join(','),
'previous_tag' => previous,
'previous_tag' => previous_tag(value),
'prerelease' => prerelease?(value),
'build_type' => value.split('+', 2).first.include?('-exp.') ? 'experimental' : 'release'
}
+4 -2
View File
@@ -25,7 +25,7 @@ module ReleaseQuality
rows = capture('gh', 'api', '--paginate', "repos/#{repository}/actions/runs/#{run.fetch('id')}/jobs?per_page=100", '--jq', '.jobs[] | @json')
job = rows.lines.map { |line| JSON.parse(line) }.find { |entry| entry.fetch('name') == 'quality / backend' }
return nil unless job && job.fetch('conclusion') == 'success'
job.fetch('html_url')
{ 'sha' => parent, 'url' => job.fetch('html_url') }
end
end
@@ -37,8 +37,10 @@ if $PROGRAM_NAME == __FILE__
evidence = nil
end
puts "run_backend=#{evidence.nil?}"
puts "backend_source_sha=#{evidence ? evidence.fetch('sha') : ReleaseQuality.capture('git', 'rev-parse', 'HEAD').strip}"
puts "backend_evidence_url=#{evidence ? evidence.fetch('url') : ''}"
if ENV['GITHUB_STEP_SUMMARY']
message = evidence ? "后端质量检查复用版本提交父提交的 [CI 结果](#{evidence});仅版本与发布说明不同" : '未找到可复用的后端 CI 结果,完整检查发行提交'
message = evidence ? "后端质量检查复用 `#{evidence.fetch('sha')}` 的[成功 CI](#{evidence.fetch('url')});仅版本与发布说明不同" : '未找到可复用的后端 CI 结果,完整检查发行提交'
File.open(ENV.fetch('GITHUB_STEP_SUMMARY'), 'a') { |file| file.puts(message) }
end
end
+38 -3
View File
@@ -51,6 +51,8 @@ jobs:
rust: ${{ steps.toolchains.outputs.rust }}
rust_image: ${{ steps.toolchains.outputs.rust_image }}
run_backend: ${{ steps.quality.outputs.run_backend }}
backend_source_sha: ${{ steps.quality.outputs.backend_source_sha }}
backend_evidence_url: ${{ steps.quality.outputs.backend_evidence_url }}
steps:
- name: Checkout
@@ -68,6 +70,7 @@ jobs:
- name: Read release metadata and seal plugin manifest
id: version
env:
GH_TOKEN: ${{ github.token }}
RELEASE_TAG: ${{ inputs.tag }}
run: ruby .github/scripts/release-metadata.rb outputs "$RELEASE_TAG" >> "$GITHUB_OUTPUT"
@@ -97,6 +100,31 @@ jobs:
run_backend: ${{ needs.release-info.outputs.run_backend == 'true' }}
run_frontend: false
backend-validation:
name: backend-validation (${{ needs.release-info.outputs.run_backend == 'true' && 'current release' || 'reused CI' }})
needs: [release-info, quality]
if: ${{ !cancelled() && needs.release-info.result == 'success' }}
runs-on: ubuntu-26.04
timeout-minutes: 5
steps:
- name: Report backend validation evidence
env:
QUALITY_RESULT: ${{ needs.quality.result }}
RUN_BACKEND: ${{ needs.release-info.outputs.run_backend }}
SOURCE_SHA: ${{ needs.release-info.outputs.backend_source_sha }}
EVIDENCE_URL: ${{ needs.release-info.outputs.backend_evidence_url }}
run: |
if [ "$QUALITY_RESULT" != success ]; then
echo "后端质量检查未通过:$QUALITY_RESULT" | tee -a "$GITHUB_STEP_SUMMARY"
exit 1
fi
if [ "$RUN_BACKEND" = true ]; then
echo "后端质量检查已执行并通过,提交:\`$SOURCE_SHA\`" | tee -a "$GITHUB_STEP_SUMMARY"
else
test -n "$EVIDENCE_URL"
echo "后端质量检查复用 \`$SOURCE_SHA\` 的[成功 CI]($EVIDENCE_URL);发行提交仅版本与发布说明不同" | tee -a "$GITHUB_STEP_SUMMARY"
fi
windows:
needs: release-info
name: windows-tests (${{ matrix.arch }})
@@ -411,7 +439,7 @@ jobs:
group: release-publication
queue: max
# 产物准备可与测试重叠,版本标签和 GitHub Release 必须等全部质量与镜像验证通过
needs: [release-info, quality, windows, security, package-assets, build-docker-image]
needs: [release-info, backend-validation, windows, security, package-assets, build-docker-image]
runs-on: ubuntu-26.04
timeout-minutes: 20
permissions:
@@ -522,6 +550,8 @@ jobs:
- name: Prepare release notes
shell: bash
env:
PREVIOUS_TAG: ${{ needs.release-info.outputs.previous_tag }}
RELEASE_TAG: ${{ needs.release-info.outputs.tag }}
BUILD_TYPE: ${{ needs.release-info.outputs.build_type }}
INSTALLATION_NOTES: |
## Linux 一键安装(Docker Compose)
@@ -537,7 +567,12 @@ jobs:
run: |
ruby <<'RUBY'
notes = File.readlines('release/notes.md').drop(1).join.strip
notes += "\n\n#{ENV.fetch('INSTALLATION_NOTES').strip}" unless ENV.fetch('BUILD_TYPE') == 'experimental'
unless ENV.fetch('BUILD_TYPE') == 'experimental'
notes += "\n\n#{ENV.fetch('INSTALLATION_NOTES').strip}"
if ENV.fetch('PREVIOUS_TAG').empty?
notes += "\n\n**Full Changelog**: https://github.com/#{ENV.fetch('GITHUB_REPOSITORY')}/commits/#{ENV.fetch('RELEASE_TAG')}"
end
end
output = File.join(ENV.fetch('RUNNER_TEMP'), 'release-notes.md')
File.write(output, "#{notes}\n")
RUBY
@@ -552,7 +587,7 @@ jobs:
uses: softprops/action-gh-release@8a0cd651e5b2365bd640854a3fa5dfc70e4875f3 # v3.0.4
with:
tag_name: ${{ needs.release-info.outputs.tag }}
generate_release_notes: ${{ needs.release-info.outputs.build_type != 'experimental' }}
generate_release_notes: ${{ needs.release-info.outputs.build_type != 'experimental' && needs.release-info.outputs.previous_tag != '' }}
previous_tag: ${{ needs.release-info.outputs.previous_tag }}
prerelease: ${{ needs.release-info.outputs.prerelease == 'true' }}
# action 保留已公开 Release 的状态,新 Release 上传完成后仍保持草稿
+2 -2
View File
@@ -122,7 +122,7 @@ PR 不接受以下协作规则文件的新增、修改、删除或重命名:
- 业务数据的解析、校验和展示优先复用已有逻辑。新增抽象放在拥有该职责的模块,避免重复事实源或无实际需求的通用层
- 新增代码注释使用中文。提交信息使用英文 Conventional Commits,参考近期历史,按完整功能归并
- AI 参与的提交按实际助手添加 `Co-authored-by: 名称 <邮箱>`,名称与邮箱采用该助手已知的署名身份,并保留其他实际共同作者署名;PR 的 AI 使用披露不替代提交署名
- 发布说明写入 `release/notes.md`,标题首行为目标版本的 `# vX.Y.Z`,章节标题和正文使用中文;命令、配置键、协议名等保留原文。只说明本次版本的实际变化,按影响交代升级事项
- 发布说明写入 `release/notes.md`,标题首行为目标版本的 `# vX.Y.Z`,手写章节标题和正文使用中文;命令、配置键、协议名等保留原文。只说明本次版本的实际变化,按影响交代升级事项。常规版本由发布工作流追加安装入口、文档链接和 GitHub 变更列表,比较基线见[版本与说明准备](.agents/skills/cpr-release/references/preparation.md)
- PR 聚焦目标;无关格式化、重构和依赖升级单独处理
## 文档职责与更新条件
@@ -229,7 +229,7 @@ git diff --check
常规容器检查与发行构建共用二进制构建入口,并复用已检查的前端产物;Dockerfile、工具链、依赖或构建配置变化时执行完整源码镜像构建,定期安全检查也覆盖源码构建。两条路径均验证容器运行、安全扫描与关闭行为
发行构建与质量检查并行,Windows 两种架构的插件与系统更新测试独立运行。仅当发行提交只修改版本与发布说明,且其父提交有本仓库主分支成功的后端 CI 时复用该结果;缺少证据则完整重跑。对外发布等待质量、Windows 测试、依赖审计和镜像验证全部成功,构建耗时与测试报告保留 7 天
发行构建与质量检查并行,Windows 两种架构的插件与系统更新测试独立运行。仅当发行提交只修改版本与发布说明,且其父提交有本仓库主分支成功的后端 CI 时复用该结果;缺少证据则完整重跑。`backend-validation` 明确报告本次执行或复用结果,复用时列出被验证的源码提交和 CI 链接。对外发布等待质量、Windows 测试、依赖审计和镜像验证全部成功,构建耗时与测试报告保留 7 天
新增自动规则优先使用现有工具,要求依据明确、结果稳定、误报可控;无法可靠判定的设计与视觉问题保留审查判断,避免把具体源码写法锁成测试
@@ -135,6 +135,7 @@ async fn execute(
store.admin_ports().settings(),
timezone,
providers.admin.clone(),
core.snapshots(),
core.snapshot_control(),
core.account_probe(),
Some(providers.peer.service()),
+3 -1
View File
@@ -76,7 +76,9 @@ fn core_value_owners_do_not_depend_on_execution_or_routing() {
let reexports = read_root_reexport_owners(&root);
for relative in super::rust_files(&root) {
let allowed: Option<&[&str]> = match relative.to_str().expect("source path") {
"validation.rs" => Some(&[]),
"validation.rs" | "time.rs" => Some(&[]),
// 每日排班使用部署日历换算;时间值模块自身不得依赖路由、执行或其他业务
"account/duty.rs" => Some(&["account", "time"]),
"identity.rs" => Some(&["validation"]),
"upstream.rs" => Some(&["validation"]),
"event.rs" => Some(&["metering", "operation", "upstream", "validation"]),
@@ -99,6 +99,7 @@ async fn initialize_inner(
store.settings(),
timezone,
providers.clone(),
published_snapshot.clone(),
snapshot.clone(),
probe.clone(),
upstream_info.clone(),
@@ -194,6 +195,12 @@ async fn initialize_inner(
)),
auth,
accounts: accounts.clone(),
account_schedules: Arc::new(crate::AccountScheduleService {
timezone,
store: store.account_schedules(),
providers: providers.clone(),
snapshot: snapshot.clone(),
}),
account_groups: Arc::new(DefaultAccountGroupService::new(
upstream_info.clone(),
store.account_groups(),
@@ -304,6 +311,7 @@ pub fn initialize_accounts(
settings: Arc<dyn ports::store::SettingsStore>,
timezone: gateway_core::time::DeploymentTimeZone,
providers: ProviderAdminRegistry,
published: gateway_core::runtime::RuntimeSnapshotHandle,
snapshot: Arc<dyn SnapshotControl>,
probe: Arc<dyn AccountProbe>,
upstream_info: Option<Arc<dyn ports::peer::PeerUpstreamService>>,
@@ -314,6 +322,7 @@ pub fn initialize_accounts(
settings,
timezone,
providers,
published,
snapshot,
probe,
upstream_info,
+7
View File
@@ -26,6 +26,7 @@ pub use use_case::peer_link::{PeerLinkError, PeerLinkService};
pub use use_case::{
account_groups::AccountGroupService,
account_schedules::AccountScheduleService,
accounts::AccountsService,
auth::AuthService,
backup::BackupService,
@@ -209,6 +210,7 @@ pub struct AdminServices {
peer_link: Arc<dyn PeerLinkService>,
accounts: Arc<dyn AccountsService>,
account_groups: Arc<dyn AccountGroupService>,
account_schedules: Arc<AccountScheduleService>,
client_keys: Arc<dyn ClientKeyService>,
client_distribution: Arc<dyn ClientDistributionService>,
observability: Arc<dyn ObservabilityService>,
@@ -272,6 +274,11 @@ impl AdminServices {
self.accounts.as_ref()
}
#[must_use]
pub fn account_schedules(&self) -> &AccountScheduleService {
self.account_schedules.as_ref()
}
#[must_use]
pub fn account_groups(&self) -> &dyn AccountGroupService {
self.account_groups.as_ref()
@@ -0,0 +1,262 @@
//! 账号排班的轻量目录与批量变更合同
use super::AdminError;
use chrono::{DateTime, Offset, TimeDelta, Utc};
use gateway_core::account::duty::{DailyShift, SchedulePolicy};
use gateway_core::time::DeploymentTimeZone;
use serde::{Deserialize, Serialize};
use std::collections::BTreeSet;
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ScheduleAccount {
pub id: String,
pub name: String,
#[serde(skip)]
pub provider_kind: String,
#[serde(skip)]
pub has_cached_quota: bool,
pub authentication_kind: String,
pub plan_type: Option<String>,
pub plan_type_display: Option<String>,
pub group_ids: Vec<String>,
}
#[derive(Debug, Serialize)]
pub struct ScheduleGroup {
pub id: String,
pub name: String,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ScheduleChange {
#[serde(default)]
pub clear: bool,
pub revision: u64,
pub policy: Option<SchedulePolicy>,
pub targets: Vec<TargetChange>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum TargetKind {
Account,
Group,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct TargetChange {
pub kind: TargetKind,
pub id: String,
pub action: ScheduleAction,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum ScheduleAction {
Remove,
Set(Vec<DailyShift>),
}
impl ScheduleChange {
pub fn validate(&self) -> Result<(), AdminError> {
if self.revision == 0
|| !self.clear && self.policy.is_none() && self.targets.is_empty()
|| self
.policy
.is_some_and(|p| !(1..=100).contains(&p.limit_percent))
{
return Err(AdminError::invalid("排班策略或版本无效"));
}
validate_targets(&self.targets)
}
}
fn validate_targets(changes: &[TargetChange]) -> Result<(), AdminError> {
let mut targets = BTreeSet::new();
for target in changes {
if !targets.insert((target.kind, &target.id)) || target.id.is_empty() {
return Err(AdminError::invalid("排班对象重复或无效"));
}
if let ScheduleAction::Set(shifts) = &target.action {
let mut ids = BTreeSet::new();
let mut spans = Vec::new();
for shift in shifts {
if shift.start >= 1440
|| shift.end >= 1440
|| uuid::Uuid::parse_str(&shift.id).is_err()
|| !ids.insert(&shift.id)
{
return Err(AdminError::invalid("班次标识或时间无效"));
}
if shift.start < shift.end {
spans.push((shift.start, shift.end));
} else {
spans.push((shift.start, 1440));
if shift.end > 0 {
spans.push((0, shift.end));
}
}
}
spans.sort_unstable();
if spans.windows(2).any(|w| w[0].1 > w[1].0) {
return Err(AdminError::invalid("同一排班对象的班次时间重叠"));
}
}
}
Ok(())
}
#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub enum ScheduleScope {
Roster,
Account,
Group,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ScheduleQuery {
pub scope: ScheduleScope,
pub page: u32,
pub page_size: u32,
pub revision: Option<u64>,
#[serde(default)]
pub search: String,
#[serde(default)]
pub group_id: String,
#[serde(default)]
pub targets: Vec<TargetChange>,
#[serde(default)]
pub clear: bool,
pub summary_minute: Option<u16>,
#[serde(default)]
pub include_summary: bool,
}
impl ScheduleQuery {
pub fn validate(&self) -> Result<(), AdminError> {
if self.page == 0
|| !(1..=100).contains(&self.page_size)
|| self.summary_minute.is_some_and(|minute| minute >= 1440)
{
return Err(AdminError::invalid("排班查询页码、每页数量或时间无效"));
}
validate_targets(&self.targets)
}
}
#[derive(Debug, Serialize)]
#[serde(tag = "kind", rename_all = "camelCase")]
pub enum ScheduleItem {
Account {
#[serde(flatten)]
account: ScheduleAccount,
shifts: Option<Vec<DailyShift>>,
},
Group {
#[serde(flatten)]
group: ScheduleGroup,
shifts: Option<Vec<DailyShift>>,
},
}
#[derive(Debug, Serialize, Deserialize)]
pub struct ScheduleBand {
pub start: u16,
pub end: u16,
pub count: u64,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ScheduleSummary {
pub target_count: u64,
pub pool_count: u64,
pub available: u64,
pub off_duty: Option<String>,
pub visible: u64,
pub current: u64,
pub bands: Vec<ScheduleBand>,
pub editing: ScheduleEditingBasis,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ScheduleEditingBasis {
pub bands: Vec<ScheduleBand>,
pub available: u64,
pub off_duty: Option<String>,
pub cohorts: Vec<ScheduleCohort>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct ScheduleCohort {
pub targets: Vec<String>,
pub fixed: Vec<(u16, u16)>,
pub count: u64,
pub example: String,
}
#[derive(Debug, Serialize)]
pub struct ScheduleList {
pub revision: u64,
pub policy: SchedulePolicy,
pub items: Vec<ScheduleItem>,
pub total: i64,
#[serde(skip_serializing_if = "Option::is_none")]
pub groups: Option<Vec<ScheduleGroup>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub summary: Option<ScheduleSummary>,
}
#[derive(Debug, Serialize)]
pub struct ScheduleQueryResult {
#[serde(flatten)]
pub page: ScheduleList,
#[serde(skip_serializing_if = "Option::is_none")]
pub clock: Option<ScheduleClock>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ScheduleClock {
pub valid_for_millis: i64,
pub unix_millis: i64,
pub minute: u16,
}
impl ScheduleClock {
#[must_use]
pub fn at(now: DateTime<Utc>, timezone: DeploymentTimeZone) -> Self {
let offset = |minutes| {
timezone
.local(now + TimeDelta::minutes(minutes))
.offset()
.fix()
};
let current = offset(0);
let mut end = 24 * 60;
// 同一偏移下可用经过的分钟推进本地时钟;遇到夏令时跳变就在边界重新采样
if offset(end) != current {
let mut start = 0;
while end - start > 1 {
let mid = (start + end) / 2;
if offset(mid) == current {
start = mid;
} else {
end = mid;
}
}
}
let unix_millis = now.timestamp_millis();
Self {
valid_for_millis: end * 60_000 - unix_millis.rem_euclid(60_000),
unix_millis,
minute: timezone.minute_of_day(now),
}
}
}
@@ -13,6 +13,7 @@ pub enum MutationAuditOperation {
AdminApiKeyChanged { exists: bool },
AccountGroupCreate,
AccountGroupUpdate,
AccountScheduleUpdate,
AccountGroupEnabled { enabled: bool },
AccountGroupDelete,
ClientApiKeyResetBudget,
@@ -73,6 +74,7 @@ impl MutationAuditOperation {
"runtime_settings",
),
Self::AccountGroupCreate => ("create", "account_group"),
Self::AccountScheduleUpdate => ("update", "account_schedule"),
Self::AccountGroupUpdate => ("update", "account_group"),
Self::AccountGroupEnabled { enabled } => {
(if enabled { "enable" } else { "disable" }, "account_group")
@@ -3,6 +3,7 @@
use std::num::{NonZeroU16, NonZeroU64};
pub mod account_groups;
pub mod account_schedules;
pub mod accounts;
pub mod analytics;
pub mod audit;
@@ -78,6 +78,8 @@ impl fmt::Debug for ImportCredentials {
/// 批量导入提交结果
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CredentialImportResult {
/// 本次事务首次创建的账号,同身份重新导入沿用已有账号
pub created_ids: std::collections::BTreeSet<ProviderAccountId>,
pub config_revision: Revision,
pub credential_ids: Vec<ProviderAccountId>,
}
@@ -540,10 +542,18 @@ impl fmt::Debug for AuthorizationReceiptKey {
}
}
/// 凭据事务对账号的实际影响,同身份授权可以更新既有账号
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CredentialChange {
Created,
Updated,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AuthorizationCommitResult {
pub result: CredentialMutationResult,
pub newly_committed: bool,
/// 重放已提交回执时没有新的账号变更
pub change: Option<CredentialChange>,
}
/// OAuth 准备结果拆解后的 Store 命令与两个结算 guard
@@ -698,6 +708,8 @@ pub struct PreparedCredentialRotationFacts {
pub plan_type: Option<String>,
/// Token 刷新保留提交时的资料,不以准备阶段的副本覆盖新套餐
pub preserve_profile: bool,
/// 已核实同一身份续期时,允许把匹配此标识的目录续接至新凭据版本
pub preserve_catalog_etag: Option<String>,
/// 凭据或连接配置更新保留提交时的健康状态与错误事实
pub preserve_credential_state: bool,
pub preserve_access_token_expiry: bool,
@@ -729,6 +741,12 @@ impl PreparedCredentialRotation {
self
}
#[must_use]
pub fn preserving_catalog(mut self, etag: String) -> Self {
self.facts.preserve_catalog_etag = Some(etag);
self
}
#[must_use]
pub const fn facts(&self) -> &PreparedCredentialRotationFacts {
&self.facts
@@ -890,6 +908,8 @@ pub struct ProviderQuotaReadRequest<'a> {
/// Provider 已解析的 quota 结果及其不透明差异字段
#[derive(Debug, Default, Clone, PartialEq)]
pub struct ProviderQuota {
/// 与 Provider 选号使用同一日额度观测,仅在其有效期内提供
pub daily_used_percent: Option<u8>,
pub paused_windows: Vec<String>,
pub upstream: Option<super::upstream_info::ProviderUpstreamInfo>,
/// 上游额度响应明确提供的套餐,可用于补全账号展示
@@ -1319,6 +1339,7 @@ impl fmt::Debug for ProviderExport {
/// 统一账号目录的一行完整结果
#[derive(Debug, Clone, PartialEq)]
pub struct AccountDirectoryItem {
pub schedule_duty: Option<gateway_core::account::duty::ScheduleDuty>,
pub model_cooldowns: Vec<gateway_core::provider_ports::ProviderScopedCooldown>,
pub platform_icon: Option<String>,
pub protection_rules: Vec<gateway_core::account::AccountProtectionMatch>,
@@ -45,6 +45,7 @@ pub use gateway_core::account::RotationStrategy;
/// 运行设置的共同值;版本、Provider 画像更新和数据库秘密由外层类型拥有
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct RuntimeSettingsValues {
pub antigravity_background_refresh: bool,
pub openai_websocket_pool: gateway_core::settings::OpenAiWebSocketPoolSettings,
pub openai_request_settings: gateway_core::settings::OpenAiRequestSettings,
pub codex_privacy_policy: gateway_core::settings::privacy::CodexPrivacyPolicy,
@@ -0,0 +1,18 @@
//! 账号排班的事务存储边界
use super::store::AdminStoreResult;
use crate::model::{
MutationContext, Revision,
account_schedules::{ScheduleChange, ScheduleList, ScheduleQuery},
};
use async_trait::async_trait;
#[async_trait]
pub trait AccountScheduleStore: Send + Sync {
async fn query(&self, query: &ScheduleQuery) -> AdminStoreResult<ScheduleList>;
async fn save(
&self,
change: ScheduleChange,
context: &MutationContext,
) -> AdminStoreResult<Revision>;
}
@@ -1,5 +1,6 @@
//! 管理用例依赖的外部能力端口
pub mod account_schedules;
pub mod backup;
pub mod client_distribution;
pub mod peer;
@@ -1,6 +1,9 @@
//! 原生 Provider 管理能力与启动时注册表
use std::{collections::BTreeMap, sync::Arc};
use std::{
collections::{BTreeMap, BTreeSet},
sync::Arc,
};
use async_trait::async_trait;
use gateway_core::{
@@ -145,6 +148,24 @@ struct ProviderAdminDiagnostic {
source: Option<gateway_core::error::ErrorSource>,
}
/// 区分新账号首查与既有账号变更后的后台观察
#[derive(Clone, Copy)]
pub struct AccountFactsChange<'a> {
pub ids: &'a [ProviderAccountId],
pub created_ids: &'a BTreeSet<ProviderAccountId>,
}
impl<'a> AccountFactsChange<'a> {
#[must_use]
pub const fn updated(ids: &'a [ProviderAccountId]) -> Self {
static EMPTY: BTreeSet<ProviderAccountId> = BTreeSet::new();
Self {
ids,
created_ids: &EMPTY,
}
}
}
/// 一个具体 Provider 对管理控制面提供的解析、验证、上游交互与运行时资源回收能力
///
/// 数据变更由 Provider 返回 prepared facts;config revision、审计与 PostgreSQL 事务
@@ -297,7 +318,12 @@ pub trait ProviderAdmin: Send + Sync {
/// 该通知发生在 Store 事务成功之后、下一份 RuntimeSnapshot 编译之前;通知
/// 不参与已提交事务成败
/// 没有账号派生状态的 Provider 可使用默认空实现
async fn account_facts_changed(&self, _account_ids: &[ProviderAccountId]) {}
async fn account_facts_changed(&self, _change: AccountFactsChange<'_>) {}
/// 既有账号变更后是否主动查额,手动刷新与新账号首查独立执行
async fn background_quota_refresh_enabled(&self) -> Result<bool, ProviderAdminError> {
Ok(true)
}
/// 生成一次连接测试所需的 Provider-owned operation;Core 负责实际执行与落账
async fn connection_test_operation(
@@ -655,6 +655,7 @@ pub struct AdminAccountStorePorts {
accounts: Arc<dyn AccountStore>,
runtime: Arc<dyn AccountRuntimeStore>,
groups: Arc<dyn AccountGroupStore>,
schedules: Arc<dyn super::account_schedules::AccountScheduleStore>,
proxies: Arc<dyn super::proxy::ProxyStore>,
}
@@ -664,12 +665,14 @@ impl AdminAccountStorePorts {
accounts: Arc<dyn AccountStore>,
runtime: Arc<dyn AccountRuntimeStore>,
groups: Arc<dyn AccountGroupStore>,
schedules: Arc<dyn super::account_schedules::AccountScheduleStore>,
proxies: Arc<dyn super::proxy::ProxyStore>,
) -> Self {
Self {
accounts,
runtime,
groups,
schedules,
proxies,
}
}
@@ -755,6 +758,11 @@ impl AdminStorePorts {
self.accounts.runtime.clone()
}
#[must_use]
pub fn account_schedules(&self) -> Arc<dyn super::account_schedules::AccountScheduleStore> {
self.accounts.schedules.clone()
}
#[must_use]
pub fn account_groups(&self) -> Arc<dyn AccountGroupStore> {
self.accounts.groups.clone()
@@ -0,0 +1,98 @@
//! 批量排班校验与已提交配置的发布
use super::{map_store_error, publish_committed};
use crate::{
model::{
AdminError, MutationContext,
account_schedules::{
ScheduleAccount, ScheduleChange, ScheduleClock, ScheduleItem, ScheduleQuery,
ScheduleQueryResult,
},
provider_credentials::ProviderQuotaRequest,
},
ports::{account_schedules::AccountScheduleStore, provider::ProviderAdminRegistry},
};
use futures::{StreamExt, stream};
use gateway_core::{account::ProviderAccountId, routing::ProviderKind, runtime::SnapshotControl};
use std::sync::Arc;
pub struct AccountScheduleService {
pub(crate) timezone: gateway_core::time::DeploymentTimeZone,
pub(crate) providers: ProviderAdminRegistry,
pub(crate) store: Arc<dyn AccountScheduleStore>,
pub(crate) snapshot: Arc<dyn SnapshotControl>,
}
impl AccountScheduleService {
pub async fn query(&self, mut query: ScheduleQuery) -> Result<ScheduleQueryResult, AdminError> {
query.validate()?;
let clock = query.include_summary.then(|| {
let clock = ScheduleClock::at(chrono::Utc::now(), self.timezone);
query.summary_minute.get_or_insert(clock.minute);
clock
});
let mut page = self
.store
.query(&query)
.await
.map_err(|e| map_store_error(e, "账号排班"))?;
stream::iter(page.items.iter_mut().filter_map(|item| match item {
ScheduleItem::Account { account, .. } => Some(account),
ScheduleItem::Group { .. } => None,
}))
.for_each_concurrent(8, |account| self.fill_plan(account))
.await;
Ok(ScheduleQueryResult { page, clock })
}
async fn fill_plan(&self, account: &mut ScheduleAccount) {
account.plan_type_display = self
.providers
.plan_type_display(&account.provider_kind, account.plan_type.as_deref());
// 有些套餐名来自上游额度观测,只在目录缺少展示名时读取已保存的快照
if account.plan_type_display.is_some()
|| !account.has_cached_quota
|| account.authentication_kind == "api_key"
{
return;
}
let (Ok(kind), Ok(account_id)) = (
ProviderKind::new(account.provider_kind.clone()),
ProviderAccountId::new(account.id.clone()),
) else {
return;
};
let Ok(provider) = self.providers.require(&kind) else {
return;
};
if let Ok(quota) = provider
.quota(ProviderQuotaRequest {
account_id,
refresh: false,
rolling_usage: None,
})
.await
{
account.plan_type_display = self.providers.resolve_account_plan(
&account.provider_kind,
&mut account.plan_type,
Some(&quota),
);
}
}
pub async fn save(
&self,
change: ScheduleChange,
context: &MutationContext,
) -> Result<u64, AdminError> {
change.validate()?;
let revision = self
.store
.save(change, context)
.await
.map_err(|e| map_store_error(e, "账号排班"))?;
publish_committed(self.snapshot.as_ref(), revision).await?;
Ok(revision.get())
}
}
@@ -2,6 +2,7 @@
mod reset_credit_automation;
use crate::ports::provider::AccountFactsChange;
use std::{
collections::{BTreeMap, BTreeSet},
sync::Arc,
@@ -197,6 +198,7 @@ pub(crate) struct DefaultAccountsService {
settings: Arc<dyn crate::ports::store::SettingsStore>,
timezone: gateway_core::time::DeploymentTimeZone,
providers: ProviderAdminRegistry,
published: gateway_core::runtime::RuntimeSnapshotHandle,
snapshot: Arc<dyn SnapshotControl>,
probe: Arc<dyn AccountProbe>,
upstream_info: Option<Arc<dyn crate::ports::peer::PeerUpstreamService>>,
@@ -216,6 +218,7 @@ impl DefaultAccountsService {
settings: Arc<dyn crate::ports::store::SettingsStore>,
timezone: gateway_core::time::DeploymentTimeZone,
providers: ProviderAdminRegistry,
published: gateway_core::runtime::RuntimeSnapshotHandle,
snapshot: Arc<dyn SnapshotControl>,
probe: Arc<dyn AccountProbe>,
upstream_info: Option<Arc<dyn crate::ports::peer::PeerUpstreamService>>,
@@ -226,6 +229,7 @@ impl DefaultAccountsService {
settings,
timezone,
providers,
published,
snapshot,
probe,
upstream_info,
@@ -513,6 +517,16 @@ impl DefaultAccountsService {
lookback,
);
Ok(AccountDirectoryItem {
schedule_duty: self
.published
.snapshot_for_diagnostics()
.and_then(|snapshot| {
snapshot.account_schedule_duty(
account_id,
std::time::SystemTime::now(),
quota.daily_used_percent,
)
}),
model_cooldowns: stored.model_cooldowns,
platform_icon: stored.platform_icon,
protection_rules: stored.protection_rules,
@@ -625,6 +639,7 @@ impl AccountsService for DefaultAccountsService {
self.attach_quota_local_usage(&page.items, &mut quotas)
.await?;
let mut api_key_usage = self.load_api_key_usage(&page.items, &quotas).await?;
let published = self.published.snapshot_for_diagnostics();
let items = page
.items
.into_iter()
@@ -649,6 +664,9 @@ impl AccountsService for DefaultAccountsService {
lookback,
);
Ok(AccountDirectoryItem {
schedule_duty: published.as_ref().and_then(|snapshot| {
snapshot.account_schedule_duty(&id, now.into(), quota.daily_used_percent)
}),
model_cooldowns: item.model_cooldowns,
platform_icon: item.platform_icon,
protection_rules: item.protection_rules,
@@ -759,7 +777,7 @@ impl AccountsService for DefaultAccountsService {
super::notify_account_facts_changed(
self.upstream_info.as_deref(),
provider.as_ref(),
std::slice::from_ref(&result.account_id),
AccountFactsChange::updated(std::slice::from_ref(&result.account_id)),
)
.await;
publish_committed(self.snapshot.as_ref(), result.config_revision).await?;
@@ -807,7 +825,7 @@ impl AccountsService for DefaultAccountsService {
super::notify_account_facts_changed(
self.upstream_info.as_deref(),
provider.as_ref(),
std::slice::from_ref(&account_id),
AccountFactsChange::updated(std::slice::from_ref(&account_id)),
)
.await;
publish_committed(self.snapshot.as_ref(), config_revision).await?;
@@ -843,7 +861,7 @@ impl AccountsService for DefaultAccountsService {
super::notify_account_facts_changed(
self.upstream_info.as_deref(),
provider.as_ref(),
std::slice::from_ref(&account_id),
AccountFactsChange::updated(std::slice::from_ref(&account_id)),
)
.await;
publish_committed(self.snapshot.as_ref(), result.config_revision).await?;
@@ -961,7 +979,7 @@ impl AccountsService for DefaultAccountsService {
super::notify_account_facts_changed(
self.upstream_info.as_deref(),
provider.as_ref(),
provider_ids,
AccountFactsChange::updated(provider_ids),
)
.await;
}
@@ -974,7 +992,7 @@ impl AccountsService for DefaultAccountsService {
self.upstream_info.as_ref(),
&provider,
&self.accounts,
&exhausted,
AccountFactsChange::updated(&exhausted),
context.request_id.as_str(),
);
}
@@ -12,7 +12,10 @@ use crate::{
ProviderQuotaRequest, StartAuthorization,
},
},
ports::{provider::ProviderAdmin, store::AccountStore},
ports::{
provider::{AccountFactsChange, ProviderAdmin},
store::AccountStore,
},
};
use gateway_core::{account::ProviderAccountId, routing::ProviderKind, runtime::SnapshotControl};
@@ -24,13 +27,13 @@ pub(super) async fn publish_credentials_and_observe_quota(
accounts: &std::sync::Arc<dyn AccountStore>,
snapshot: &dyn SnapshotControl,
revision: crate::model::Revision,
account_ids: &[ProviderAccountId],
change: AccountFactsChange<'_>,
request_id: &str,
) -> Result<(), AdminError> {
notify_account_facts_changed(peer.map(AsRef::as_ref), provider.as_ref(), account_ids).await;
notify_account_facts_changed(peer.map(AsRef::as_ref), provider.as_ref(), change).await;
publish_committed(snapshot, revision).await?;
observe_account_quotas(peer, provider, accounts, account_ids, request_id);
observe_account_quotas(peer, provider, accounts, change, request_id);
Ok(())
}
@@ -38,16 +41,32 @@ pub(super) fn observe_account_quotas(
peer: Option<&std::sync::Arc<dyn crate::ports::peer::PeerUpstreamService>>,
provider: &std::sync::Arc<dyn ProviderAdmin>,
accounts: &std::sync::Arc<dyn AccountStore>,
account_ids: &[ProviderAccountId],
change: AccountFactsChange<'_>,
request_id: &str,
) {
// 配置已提交,额度查询失败不回滚配置
let provider = provider.clone();
let peer = peer.cloned();
let accounts = accounts.clone();
let account_ids = account_ids.to_vec();
let mut seen = std::collections::BTreeSet::new();
let (initial, updated): (Vec<_>, Vec<_>) = change
.ids
.iter()
.filter(|id| seen.insert(*id))
.cloned()
.partition(|id| change.created_ids.contains(id));
let request_id = request_id.to_owned();
tokio::spawn(async move {
let mut account_ids = initial;
if !updated.is_empty() {
match provider.background_quota_refresh_enabled().await {
Ok(true) => account_ids.extend(updated),
Ok(false) => {}
Err(error) => {
tracing::warn!(request_id, error = %error, "读取后台额度查询设置失败")
}
}
}
for account_id in account_ids {
let request = ProviderQuotaRequest {
account_id: account_id.clone(),
@@ -292,7 +311,7 @@ pub(super) async fn commit_authorization(
match accounts.commit_authorization(command, context).await {
Ok(result) => {
if let Some(guard) = credential_guard
&& result.newly_committed
&& result.change.is_some()
{
guard.finish();
}
@@ -405,7 +424,7 @@ pub(super) async fn delete_credentials(
for account_id in &account_ids {
notify_account_unavailable(peer, provider, account_id).await;
}
notify_account_facts_changed(peer, provider, &account_ids).await;
notify_account_facts_changed(peer, provider, AccountFactsChange::updated(&account_ids)).await;
Ok(CredentialDeletionResult {
config_revision: revision,
account_ids,
@@ -415,11 +434,11 @@ pub(super) async fn delete_credentials(
pub(super) async fn notify_account_facts_changed(
peer: Option<&dyn crate::ports::peer::PeerUpstreamService>,
provider: &dyn ProviderAdmin,
ids: &[ProviderAccountId],
change: AccountFactsChange<'_>,
) {
provider.account_facts_changed(ids).await;
provider.account_facts_changed(change).await;
if let Some(peer) = peer {
for id in ids {
for id in change.ids {
if let Err(error) = peer.account_changed(id).await {
tracing::warn!(account_id = %id, error = %error, "upstream information cache invalidation failed");
}
@@ -9,13 +9,16 @@ use crate::{
AdminError,
provider_credentials::{
AuthorizationCommitResult, AuthorizationReceiptKey, AuthorizationStarted,
CompleteAuthorization, CredentialDeletion, CredentialDeletionResult,
CompleteAuthorization, CredentialChange, CredentialDeletion, CredentialDeletionResult,
CredentialImportCommit, CredentialImportResult, CredentialMutationResult,
ImportCredentials, PrepareCredentialImport, PrepareCredentialRotation,
RotateCredential, StartAuthorization,
},
},
ports::{provider::ProviderAdmin, store::AccountStore},
ports::{
provider::{AccountFactsChange, ProviderAdmin},
store::AccountStore,
},
};
use super::super::{
@@ -97,7 +100,10 @@ impl ProviderCredentials {
&self.accounts,
self.snapshot.as_ref(),
result.config_revision,
&result.credential_ids,
AccountFactsChange {
ids: &result.credential_ids,
created_ids: &result.created_ids,
},
&context.request_id,
)
.await?;
@@ -175,7 +181,7 @@ impl ProviderCredentials {
super::super::notify_account_facts_changed(
self.upstream_info.as_deref(),
self.provider.as_ref(),
std::slice::from_ref(&result.account_id),
AccountFactsChange::updated(std::slice::from_ref(&result.account_id)),
)
.await;
publish_committed(self.snapshot.as_ref(), result.config_revision).await?;
@@ -248,14 +254,23 @@ impl super::CredentialsService {
request_id: &str,
) -> Result<CredentialMutationResult, AdminError> {
let result = outcome.result;
if outcome.newly_committed {
if let Some(change) = outcome.change {
let ids = std::slice::from_ref(&result.account_id);
let created_ids = (change == CredentialChange::Created)
.then(|| result.account_id.clone())
.into_iter()
.collect();
let change = AccountFactsChange {
ids,
created_ids: &created_ids,
};
publish_credentials_and_observe_quota(
self.upstream_info.as_ref(),
provider,
&self.accounts,
self.snapshot.as_ref(),
result.config_revision,
std::slice::from_ref(&result.account_id),
change,
request_id,
)
.await?;
@@ -1,6 +1,7 @@
//! 管理控制面的用例实现
pub mod account_groups;
pub mod account_schedules;
pub mod accounts;
pub mod auth;
pub mod backup;
@@ -320,6 +320,13 @@ fn model_observation(
reset.min(observed_at + TimeDelta::minutes(30))
})
.min(now + TimeDelta::minutes(5));
let expires_at = if let Some(deadline) = account.quota.exhaustion_deadline()
&& account.quota.is_exhausted()
{
expires_at.min(deadline.into())
} else {
expires_at
};
if observed_at > now || expires_at <= now {
return None;
}
@@ -214,6 +214,7 @@ impl PeerInfoService {
}
}
ProviderQuota {
daily_used_percent: None,
paused_windows: Vec::new(),
upstream: Some(info),
plan_type: None,
@@ -172,6 +172,7 @@ impl PeerInfoService {
.and_then(|peer| quota::observe(&peer, started_at, now))
.unwrap_or(QuotaState::unknown());
let observation = QuotaObservation {
merge_base: None,
quota_pause: None,
expected_connection: Some(connection.clone()),
account_id: id.clone(),
@@ -19,6 +19,8 @@ use crate::{
},
};
use crate::ports::provider::AccountFactsChange;
use super::{
map_provider_error, map_store_error, publish_credentials_and_observe_quota,
required_credential, required_plugin_credential, validate_prepared_import,
@@ -218,7 +220,10 @@ impl PluginAccountAccess for DefaultPluginAccountAccess {
&self.accounts,
self.snapshot.as_ref(),
result.config_revision,
std::slice::from_ref(&account_id),
AccountFactsChange {
ids: &result.credential_ids,
created_ids: &result.created_ids,
},
&context.request_id,
)
.await?;
@@ -263,7 +268,7 @@ impl PluginAccountAccess for DefaultPluginAccountAccess {
&self.accounts,
self.snapshot.as_ref(),
result.config_revision,
std::slice::from_ref(&result.account_id),
AccountFactsChange::updated(std::slice::from_ref(&result.account_id)),
&context.request_id,
)
.await?;
@@ -106,6 +106,7 @@ fn provider_document_debug_should_not_expose_opaque_material() {
#[test]
fn representative_quota_should_prefer_short_window_and_highest_usage() {
let quota = ProviderQuota {
daily_used_percent: None,
paused_windows: Vec::new(),
upstream: None,
credits: None,
@@ -131,6 +132,7 @@ fn representative_quota_should_prefer_account_wide_window_over_model_specific_wi
let mut model_specific = quota_window("shortTerm", Some(18_000), Some(64.0));
model_specific.local_usage_attribution = QuotaLocalUsageAttribution::Unavailable;
let quota = ProviderQuota {
daily_used_percent: None,
paused_windows: Vec::new(),
upstream: None,
credits: None,
@@ -152,6 +154,7 @@ fn representative_quota_should_prefer_account_wide_window_over_model_specific_wi
#[test]
fn account_exhaustion_preserves_measured_and_unknown_window_usage() {
let mut quota = ProviderQuota {
daily_used_percent: None,
paused_windows: Vec::new(),
upstream: None,
credits: None,
@@ -183,6 +186,7 @@ fn exhausted_quota_should_preserve_the_provider_identified_reached_window() {
let mut reached = quota_window("monthly", Some(2_592_000), Some(98.0));
reached.limit_reached = true;
let mut quota = ProviderQuota {
daily_used_percent: None,
paused_windows: Vec::new(),
upstream: None,
credits: None,
@@ -0,0 +1,21 @@
//! 排班分钟采样在部署时区的跳时和重复时刻重新对齐
use chrono::{DateTime, TimeDelta, Utc};
use gateway_admin::model::account_schedules::ScheduleClock;
#[test]
fn clock_expires_at_both_dst_boundaries() {
let zone = "America/New_York".parse().unwrap();
for (sample, before, after) in [
("2026-03-08T06:59:44.500Z", 119, 180),
("2026-11-01T05:59:44.500Z", 119, 60),
] {
let at: DateTime<Utc> = sample.parse().unwrap();
let clock = ScheduleClock::at(at, zone);
assert_eq!(clock.minute, before);
assert_eq!(clock.valid_for_millis, 15_500);
let next = ScheduleClock::at(at + TimeDelta::milliseconds(clock.valid_for_millis), zone);
assert_eq!(next.minute, after);
assert_eq!(next.valid_for_millis, 86_400_000);
}
}
@@ -1,6 +1,7 @@
//! 模型模块测试:镜像 src/model/ 中带逻辑的模块
mod account_groups;
mod account_schedules;
mod audit;
mod backup;
mod client_keys;
@@ -116,6 +116,7 @@ fn selected_usage_window(quota: &ProviderQuota) -> Option<(&str, AccountUsagePer
fn usage_quota(windows: Vec<ProviderQuotaWindow>) -> ProviderQuota {
ProviderQuota {
daily_used_percent: None,
paused_windows: Vec::new(),
upstream: None,
credits: None,
@@ -170,6 +171,7 @@ fn usage_window(key: &str, group: &str, seconds: u64) -> ProviderQuotaWindow {
#[test]
fn dashboard_quota_should_preserve_unknown_and_actual_window_facts() {
let mut quota = ProviderQuota {
daily_used_percent: None,
paused_windows: Vec::new(),
upstream: None,
credits: None,
@@ -59,6 +59,7 @@ fn window(key: &str, days: u64) -> ProviderQuotaWindow {
fn quota(windows: Vec<ProviderQuotaWindow>) -> ProviderQuota {
ProviderQuota {
daily_used_percent: None,
paused_windows: Vec::new(),
upstream: None,
credits: None,
@@ -40,7 +40,7 @@ use gateway_admin::{
provider_credentials::{
AuthorizationCommit, AuthorizationCommitGuard, AuthorizationCredentialCommit,
AuthorizationMutationTarget, AuthorizationStarted, CompleteAuthorization,
ConsumeProviderResetCredit, CredentialCommitGuard, CredentialDetails,
ConsumeProviderResetCredit, CredentialChange, CredentialCommitGuard, CredentialDetails,
CredentialImportCommit, CredentialImportResult, CredentialMutationResult,
CredentialRotationCommit, PendingAuthorizationMutation, PrepareCredentialImport,
PrepareCredentialRefresh, PrepareCredentialRotation, PreparedAuthorizationCommit,
@@ -267,6 +267,7 @@ impl FakeProviderAdmin {
email: account.email.clone(),
plan_type: account.plan_type.clone(),
preserve_profile: false,
preserve_catalog_etag: None,
preserve_credential_state: false,
preserve_access_token_expiry: false,
provider_material: document(),
@@ -346,7 +347,10 @@ impl ProviderAdmin for FakeProviderAdmin {
self.record("provider.account_unavailable");
}
async fn account_facts_changed(&self, _: &[ProviderAccountId]) {
async fn account_facts_changed(
&self,
_: gateway_admin::ports::provider::AccountFactsChange<'_>,
) {
self.record("provider.account_facts_changed");
}
@@ -994,6 +998,12 @@ impl AccountStore for FakeAccountStore {
self.record_context(context);
self.require_commit()?;
Ok(CredentialImportResult {
created_ids: command
.prepared
.credentials
.iter()
.map(|c| c.account_id.clone())
.collect(),
config_revision: revision(2),
credential_ids: command
.prepared
@@ -1018,18 +1028,21 @@ impl AccountStore for FakeAccountStore {
return Ok(
gateway_admin::model::provider_credentials::AuthorizationCommitResult {
result,
newly_committed: false,
change: None,
},
);
}
self.record("store.commit_authorization");
self.record_context(context);
self.require_commit()?;
let (account_id, credential_revision) = match command.credential {
AuthorizationCredentialCommit::Create(credential) => (credential.account_id, None),
let (account_id, credential_revision, change) = match command.credential {
AuthorizationCredentialCommit::Create(credential) => {
(credential.account_id, None, CredentialChange::Created)
}
AuthorizationCredentialCommit::Reauthorize(credential) => (
credential.account_id,
Some(revision(credential.expected_credential_revision.get() + 1)),
CredentialChange::Updated,
),
};
let result = CredentialMutationResult {
@@ -1044,7 +1057,7 @@ impl AccountStore for FakeAccountStore {
Ok(
gateway_admin::model::provider_credentials::AuthorizationCommitResult {
result,
newly_committed: true,
change: Some(change),
},
)
}
@@ -1202,6 +1215,7 @@ impl SettingsStore for StaticSettingsStore {
rotation_strategy: RotationStrategy::Smart,
updated_at: Utc::now(),
values: gateway_admin::model::settings::RuntimeSettingsValues {
antigravity_background_refresh: true,
openai_websocket_pool: Default::default(),
openai_request_settings: gateway_core::settings::OpenAiRequestSettings {
oauth_guardian_review_model: false,
@@ -2149,6 +2163,7 @@ async fn accounts_list_should_degrade_quota_failure_to_empty_window_without_drop
let events = events();
let openai = FakeProviderAdmin::new("openai", events.clone());
openai.set_quota(ProviderQuota {
daily_used_percent: None,
paused_windows: Vec::new(),
upstream: None,
credits: None,
@@ -2311,6 +2326,7 @@ async fn accounts_list_should_map_unknown_credential_to_error_not_normal() {
async fn accounts_list_should_not_derive_rate_limited_from_provider_quota_view() {
let provider = FakeProviderAdmin::new("openai", events());
provider.set_quota(ProviderQuota {
daily_used_percent: None,
paused_windows: Vec::new(),
upstream: None,
credits: None,
@@ -2364,6 +2380,7 @@ async fn accounts_list_should_not_derive_rate_limited_from_provider_quota_view()
async fn accounts_list_should_not_derive_exhaustion_from_provider_quota_view() {
let provider = FakeProviderAdmin::new("openai", events());
provider.set_quota(ProviderQuota {
daily_used_percent: None,
paused_windows: Vec::new(),
upstream: None,
credits: None,
@@ -3130,6 +3147,7 @@ async fn accounts_list_should_attach_local_usage_to_quota_windows() {
let provider = FakeProviderAdmin::new("openai", events());
let reset_at = Utc::now() + TimeDelta::hours(1);
provider.set_quota(ProviderQuota {
daily_used_percent: None,
paused_windows: Vec::new(),
upstream: None,
credits: None,
@@ -3296,6 +3314,7 @@ async fn account_windows_attach_only_the_usage_allowed_by_the_provider() {
let provider = FakeProviderAdmin::new("openai", events());
let reset_at = Utc::now() + TimeDelta::days(7);
let mut quota = ProviderQuota {
daily_used_percent: None,
paused_windows: Vec::new(),
upstream: None,
credits: None,
@@ -3619,6 +3638,7 @@ pub(super) fn document() -> ProviderDocument {
fn empty_quota() -> ProviderQuota {
ProviderQuota {
daily_used_percent: None,
paused_windows: Vec::new(),
upstream: None,
credits: None,
@@ -3747,6 +3767,7 @@ fn plugin_rotation_facts(account: &AccountRecord) -> PreparedCredentialRotationF
email: account.email.clone(),
plan_type: account.plan_type.clone(),
preserve_profile: true,
preserve_catalog_etag: None,
preserve_credential_state: false,
preserve_access_token_expiry: false,
provider_material: document(),
@@ -33,6 +33,7 @@ fn runtime_settings(enabled: bool, probe_enabled: bool) -> RuntimeSettings {
rotation_strategy: gateway_admin::model::settings::RotationStrategy::Smart,
updated_at: Utc::now(),
values: gateway_admin::model::settings::RuntimeSettingsValues {
antigravity_background_refresh: true,
openai_websocket_pool: Default::default(),
openai_request_settings: gateway_core::settings::OpenAiRequestSettings {
oauth_guardian_review_model: false,
@@ -283,6 +283,7 @@ impl AdminHarness {
self.accounts,
self.account_runtime,
self.account_groups,
Arc::new(UnavailableStore),
self.proxies,
),
self.auth,
@@ -1381,3 +1382,20 @@ impl gateway_admin::ports::reset_credit_automation::ResetCreditAutomationStore
Err(unavailable("reset-credit automation"))
}
}
#[async_trait::async_trait]
impl gateway_admin::ports::account_schedules::AccountScheduleStore for UnavailableStore {
async fn query(
&self,
_: &gateway_admin::model::account_schedules::ScheduleQuery,
) -> AdminStoreResult<gateway_admin::model::account_schedules::ScheduleList> {
unreachable!()
}
async fn save(
&self,
_: gateway_admin::model::account_schedules::ScheduleChange,
_: &gateway_admin::model::MutationContext,
) -> AdminStoreResult<gateway_admin::model::Revision> {
unreachable!()
}
}
@@ -337,6 +337,7 @@ impl SettingsStore for FixtureSettingsStore {
rotation_strategy: RotationStrategy::Smart,
updated_at: Utc::now(),
values: gateway_admin::model::settings::RuntimeSettingsValues {
antigravity_background_refresh: true,
openai_websocket_pool: Default::default(),
openai_request_settings: gateway_core::settings::OpenAiRequestSettings {
oauth_guardian_review_model: false,
@@ -340,6 +340,7 @@ async fn linked_accounts_share_plan_resolution_and_only_read_cached_quota() {
] {
let provider = FakeProviderAdmin::new(kind, events());
provider.set_quota(ProviderQuota {
daily_used_percent: None,
paused_windows: Vec::new(),
upstream: None,
credits: None,
@@ -349,6 +349,7 @@ async fn settings_should_reject_zero_refresh_margin_before_store_call() {
model_mappings: Default::default(),
rotation_strategy: RotationStrategy::Smart,
values: gateway_admin::model::settings::RuntimeSettingsValues {
antigravity_background_refresh: true,
openai_websocket_pool: Default::default(),
openai_request_settings: Default::default(),
codex_privacy_policy: Default::default(),
@@ -12,6 +12,7 @@ where
S: SessionState + Clone + Send + Sync + 'static,
{
Router::new()
.merge(super::schedules::router::<S>())
.merge(super::import_tasks::router::<S>())
.route("/api/admin/accounts", get(list_accounts::<S>))
.route(
@@ -68,6 +68,7 @@ mod credentials;
mod handlers;
mod import_tasks;
mod presenter;
mod schedules;
mod upstream_info;
mod wire;
@@ -67,6 +67,7 @@ pub(super) fn account_view(
time: crate::time::TimePresenter,
) -> AccountView {
let AccountDirectoryItem {
schedule_duty,
model_cooldowns,
platform_icon,
account,
@@ -124,6 +125,7 @@ pub(super) fn account_view(
})
.collect();
AccountView {
schedule_duty,
platform_icon,
quota_settings: account.quota_settings,
auto_use_quota_credits: account.auto_use_quota_credits,
@@ -0,0 +1,45 @@
//! 管理端账号排班的读取与原子保存
use crate::SessionState;
use crate::admin::{
AdminAuth, AdminEnvelope, AdminError, AdminJson, AdminResponse, wire::map_admin_service_error,
};
use axum::{Router, extract::State, http::StatusCode, response::IntoResponse, routing::post};
use gateway_admin::model::account_schedules::{ScheduleChange, ScheduleQuery};
pub fn router<S: SessionState + Clone + Send + Sync + 'static>() -> Router<S> {
Router::new()
.route("/api/admin/accounts/schedules/query", post(query::<S>))
.route("/api/admin/accounts/schedules/update", post(save::<S>))
}
async fn query<S: SessionState + Send + Sync>(
_auth: AdminAuth,
State(state): State<S>,
AdminJson(query): AdminJson<ScheduleQuery>,
) -> Result<impl IntoResponse, AdminError> {
let page = state
.admin_services()
.account_schedules()
.query(query)
.await
.map_err(map_admin_service_error)?;
Ok(AdminResponse::new(StatusCode::OK, AdminEnvelope::ok(page)))
}
async fn save<S: SessionState + Send + Sync>(
auth: AdminAuth,
State(state): State<S>,
AdminJson(change): AdminJson<ScheduleChange>,
) -> Result<impl IntoResponse, AdminError> {
let revision = state
.admin_services()
.account_schedules()
.save(change, &auth.context().mutation_context())
.await
.map_err(map_admin_service_error)?;
Ok(AdminResponse::new(
StatusCode::OK,
AdminEnvelope::ok(revision),
))
}
@@ -247,6 +247,8 @@ pub struct AccountSummaryView {
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AccountView {
#[serde(skip_serializing_if = "Option::is_none")]
pub schedule_duty: Option<gateway_core::account::duty::ScheduleDuty>,
pub platform_icon: Option<String>,
pub quota_settings: gateway_core::account::AccountQuotaSettings,
pub auto_use_quota_credits: bool,
@@ -36,6 +36,7 @@ pub type ProviderRequestProfileUpdates =
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RuntimeSettingsFields {
pub antigravity_background_refresh: bool,
pub openai_websocket_pool: gateway_core::settings::OpenAiWebSocketPoolSettings,
pub openai_request_settings: gateway_core::settings::OpenAiRequestSettings,
pub codex_privacy_policy: gateway_core::settings::privacy::CodexPrivacyPolicy,
@@ -715,6 +716,7 @@ impl RuntimeSettingsFields {
self,
) -> Result<gateway_admin::model::settings::RuntimeSettingsValues, WireValidationError> {
let values = gateway_admin::model::settings::RuntimeSettingsValues {
antigravity_background_refresh: self.antigravity_background_refresh,
openai_websocket_pool: self.openai_websocket_pool,
openai_request_settings: self.openai_request_settings,
codex_privacy_policy: self.codex_privacy_policy,
@@ -767,6 +769,7 @@ impl RuntimeSettingsFields {
impl From<gateway_admin::model::settings::RuntimeSettingsValues> for RuntimeSettingsFields {
fn from(settings: gateway_admin::model::settings::RuntimeSettingsValues) -> Self {
crate::admin::settings::RuntimeSettingsFields {
antigravity_background_refresh: settings.antigravity_background_refresh,
openai_websocket_pool: settings.openai_websocket_pool,
openai_request_settings: settings.openai_request_settings,
codex_privacy_policy: settings.codex_privacy_policy,
@@ -381,6 +381,7 @@ async fn account_quota_refresh_time_uses_server_clock_and_deployment_timezone()
),
] {
*fixture.provider_quota.lock().unwrap() = Some(ProviderQuota {
daily_used_percent: None,
paused_windows: Vec::new(),
upstream: None,
plan_type: None,
@@ -914,6 +914,7 @@ mod actions {
#[test]
fn account_import_response_should_emit_account_ids() {
let response = AccountImportData::from_result(CredentialImportResult {
created_ids: Default::default(),
config_revision: Revision::new(8).expect("revision"),
credential_ids: vec![ProviderAccountId::new("acct_imported").expect("account ID")],
});
@@ -184,6 +184,7 @@ impl AdminTestFixture {
unused.clone(),
unused.clone(),
account_groups.clone(),
unused.clone(),
Arc::new(proxies::MemoryProxies::default()),
),
auth.clone(),
@@ -1996,6 +1997,7 @@ fn test_runtime_settings() -> RuntimeSettings {
rotation_strategy: RotationStrategy::Smart,
updated_at: Utc::now(),
values: gateway_admin::model::settings::RuntimeSettingsValues {
antigravity_background_refresh: true,
openai_websocket_pool: Default::default(),
openai_request_settings: Default::default(),
codex_privacy_policy: Default::default(),
@@ -2112,3 +2114,20 @@ impl gateway_admin::ports::reset_credit_automation::ResetCreditAutomationStore f
Err(unavailable("reset-credit automation"))
}
}
#[async_trait::async_trait]
impl gateway_admin::ports::account_schedules::AccountScheduleStore for UnusedStore {
async fn query(
&self,
_: &gateway_admin::model::account_schedules::ScheduleQuery,
) -> AdminStoreResult<gateway_admin::model::account_schedules::ScheduleList> {
unreachable!()
}
async fn save(
&self,
_: gateway_admin::model::account_schedules::ScheduleChange,
_: &gateway_admin::model::MutationContext,
) -> AdminStoreResult<gateway_admin::model::Revision> {
unreachable!()
}
}
@@ -84,6 +84,7 @@ fn update_body() -> Value {
"gpt-5.4": "gpt-5.5",
"grok-latest": "grok-4.5"
},
"antigravityBackgroundRefresh": false,
"refreshMarginSeconds": 1800,
"refreshConcurrency": 4,
"maxConcurrentPerAccount": 5,
@@ -637,6 +638,7 @@ fn settings_service_contract_flattens_values_and_rejects_unknown_fields() {
command
);
for field in [
"antigravity_background_refresh",
"openai_request_settings",
"reset_credit_on_low_weekly_quota",
] {
@@ -993,22 +995,30 @@ fn decompression_setting_should_reject_invalid_values() {
}
#[tokio::test]
async fn settings_update_rejects_unknown_fields_without_writing() {
async fn settings_update_rejects_incomplete_and_unknown_fields_without_writing() {
let fixture = AdminTestFixture::new().await;
fixture.auth.insert_session("valid-session");
let app = app(fixture.state());
let initial = fixture.settings.settings.lock().unwrap().clone();
let mut body = update_body();
body["unknownSetting"] = json!(true);
let response = app
.oneshot(request(
Method::POST,
"/api/admin/settings/update",
Some(body),
))
.await
.unwrap();
assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
let mut unknown = update_body();
unknown["unknownSetting"] = json!(true);
let mut incomplete = update_body();
incomplete
.as_object_mut()
.unwrap()
.remove("antigravityBackgroundRefresh");
for body in [unknown, incomplete] {
let response = app
.clone()
.oneshot(request(
Method::POST,
"/api/admin/settings/update",
Some(body),
))
.await
.unwrap();
assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
}
assert_eq!(*fixture.settings.settings.lock().unwrap(), initial);
}
@@ -134,6 +134,7 @@ async fn fixture(sharing: ClientPeerSharing, plaintext: &str) -> (AdminTestFixtu
},
});
*fixture.provider_quota.lock().unwrap() = Some(ProviderQuota {
daily_used_percent: None,
paused_windows: Vec::new(),
upstream: None,
plan_type: Some("pro".into()),
@@ -0,0 +1,105 @@
//! 每日重复的账号班次与接单资格,共享请求冻结的配置快照
use serde::{Deserialize, Serialize};
use std::{collections::BTreeMap, time::SystemTime};
use super::{ProviderAccountId, scope::RuntimeAccount};
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct DailyShift {
pub id: String,
pub start: u16,
pub end: u16,
}
impl DailyShift {
pub fn contains(&self, minute: u16) -> bool {
if self.start < self.end {
(self.start..self.end).contains(&minute)
} else {
minute >= self.start || minute < self.end
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum OffShiftSession {
Rebind,
#[default]
Keep,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct SchedulePolicy {
pub enabled: bool,
pub off_shift_session: OffShiftSession,
pub early_finish: bool,
pub limit_percent: u8,
}
impl Default for SchedulePolicy {
fn default() -> Self {
Self {
enabled: true,
off_shift_session: OffShiftSession::default(),
early_finish: false,
limit_percent: 80,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum ScheduleDuty {
OnDuty,
OffDuty,
QuotaReached,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct AccountSchedules {
pub timezone: crate::time::DeploymentTimeZone,
pub accounts: BTreeMap<String, Vec<DailyShift>>,
pub groups: BTreeMap<String, Vec<DailyShift>>,
pub policy: SchedulePolicy,
}
impl AccountSchedules {
/// 没有任何班表的账号沿用默认调度;个人和所在组有任一有效时段即可在班
pub fn duty(
&self,
id: &ProviderAccountId,
account: &RuntimeAccount,
now: SystemTime,
daily_used_percent: Option<u8>,
) -> Option<ScheduleDuty> {
if !self.policy.enabled || (self.accounts.is_empty() && self.groups.is_empty()) {
return None;
}
let mut sources = self
.accounts
.get(id.as_str())
.into_iter()
.chain(
account
.group_ids()
.iter()
.filter_map(|id| self.groups.get(id.as_str())),
)
.peekable();
sources.peek()?;
let minute = self.timezone.minute_of_day(now.into());
if !sources.any(|shifts| shifts.iter().any(|shift| shift.contains(minute))) {
return Some(ScheduleDuty::OffDuty);
}
if self.policy.early_finish
&& daily_used_percent.is_some_and(|used| used >= self.policy.limit_percent)
{
return Some(ScheduleDuty::QuotaReached);
}
Some(ScheduleDuty::OnDuty)
}
}
@@ -1,5 +1,6 @@
//! Provider 账号领域、持久化端口与同一 target 内的账号选择
pub mod duty;
mod error;
mod error_protection;
pub use error_protection::*;
@@ -407,6 +407,7 @@ pub struct QuotaState {
evidence: Option<QuotaEvidence>,
observed_at: Option<SystemTime>,
reset_at: Option<SystemTime>,
exhaustion_deadline: Option<SystemTime>,
limit_window_minutes: Option<u16>,
}
@@ -424,6 +425,7 @@ impl QuotaState {
evidence: None,
observed_at: None,
reset_at: None,
exhaustion_deadline: None,
limit_window_minutes: None,
}
}
@@ -435,6 +437,7 @@ impl QuotaState {
evidence: None,
observed_at: Some(observed_at),
reset_at: None,
exhaustion_deadline: None,
limit_window_minutes: None,
}
}
@@ -446,6 +449,7 @@ impl QuotaState {
evidence: None,
observed_at: Some(observed_at),
reset_at: None,
exhaustion_deadline: None,
limit_window_minutes: None,
}
}
@@ -461,6 +465,7 @@ impl QuotaState {
evidence: Some(evidence),
observed_at: Some(observed_at),
reset_at,
exhaustion_deadline: None,
limit_window_minutes: None,
}
}
@@ -473,6 +478,7 @@ impl QuotaState {
evidence: Some(QuotaEvidence::CreditsAvailable),
observed_at: Some(observed_at),
reset_at,
exhaustion_deadline: None,
limit_window_minutes: None,
}
}
@@ -501,6 +507,7 @@ impl QuotaState {
evidence,
observed_at,
reset_at,
exhaustion_deadline: None,
limit_window_minutes: None,
})
} else {
@@ -528,6 +535,28 @@ impl QuotaState {
self.reset_at
}
/// 耗尽观测阻止调度的截止时间;上游重置时间仍独立保留
#[must_use]
pub const fn exhaustion_deadline(self) -> Option<SystemTime> {
self.exhaustion_deadline
}
#[must_use]
pub fn with_exhaustion_deadline(mut self, deadline: Option<SystemTime>) -> Self {
if self.is_exhausted() || self.evidence == Some(QuotaEvidence::CreditsAvailable) {
self.exhaustion_deadline = deadline;
}
self
}
#[must_use]
pub fn is_exhausted_at(self, now: SystemTime) -> bool {
self.is_exhausted()
&& self
.exhaustion_deadline
.is_none_or(|deadline| now < deadline)
}
/// 本次上游用量拒绝明确指出的窗口时长
#[must_use]
pub const fn limit_window_minutes(self) -> Option<u16> {
@@ -542,9 +571,7 @@ impl QuotaState {
self
}
/// 返回当前已确认的额度耗尽结论
///
/// `reset_at` 只表示何时应重新向 Provider 求证;时间到期本身不是额度恢复证据
/// 返回最近观测的耗尽结论,选号使用带时间判断的有效状态
#[must_use]
pub fn is_exhausted(self) -> bool {
self.access == QuotaAccessState::Exhausted
@@ -552,13 +579,13 @@ impl QuotaState {
/// 判断已耗尽额度是否到达 Provider 的下一次复核时间
///
/// 有明确 `reset_at` 时严格等待该时刻;没有时由 Provider 传入自己的保守复核周期
/// 优先使用耗尽截止时间,其次使用上游重置时间,缺省时按观测时间和复核周期计算
#[must_use]
pub fn exhaustion_refresh_due(self, now: SystemTime, fallback_interval: Duration) -> bool {
if !self.is_exhausted() {
return false;
}
let due_at = self.reset_at.or_else(|| {
let due_at = self.exhaustion_deadline.or(self.reset_at).or_else(|| {
self.observed_at
.and_then(|observed_at| observed_at.checked_add(fallback_interval))
});
@@ -777,7 +804,7 @@ pub fn resolve_account_status(
cooldown: None,
};
}
if facts.quota.is_exhausted() {
if facts.quota.is_exhausted_at(now) {
return status_projection(AccountStatus::QuotaExhausted);
}
if facts
@@ -1316,6 +1343,7 @@ pub struct CredentialCasUpdateParts {
pub expected_revision: CredentialRevision,
pub profile: ProviderAccountUpdate,
pub preserve_profile: bool,
pub preserve_catalog_etag: Option<String>,
pub preserve_access_token_expiry: bool,
pub credential: PlaintextCredential,
pub has_refresh_token: bool,
@@ -1331,6 +1359,7 @@ pub struct CredentialCasUpdate {
expected_revision: CredentialRevision,
profile: ProviderAccountUpdate,
preserve_profile: bool,
preserve_catalog_etag: Option<String>,
preserve_access_token_expiry: bool,
credential: PlaintextCredential,
has_refresh_token: bool,
@@ -1386,6 +1415,7 @@ impl CredentialCasUpdate {
expected_revision,
profile,
preserve_profile: false,
preserve_catalog_etag: None,
preserve_access_token_expiry: false,
credential,
has_refresh_token,
@@ -1402,6 +1432,13 @@ impl CredentialCasUpdate {
self
}
/// 同一身份续期只续接旧版本、当前套餐和指定标识均匹配的目录
#[must_use]
pub fn with_preserved_catalog_etag(mut self, etag: Option<String>) -> Self {
self.preserve_catalog_etag = etag;
self
}
/// 沿用同一访问令牌时,保留提交时的有效期,避免覆盖在途收到的撤销事实
#[must_use]
pub const fn preserving_access_token_expiry(mut self) -> Self {
@@ -1475,6 +1512,7 @@ impl CredentialCasUpdate {
expected_revision: self.expected_revision,
profile: self.profile,
preserve_profile: self.preserve_profile,
preserve_catalog_etag: self.preserve_catalog_etag,
preserve_access_token_expiry: self.preserve_access_token_expiry,
credential: self.credential,
has_refresh_token: self.has_refresh_token,
@@ -1503,6 +1541,8 @@ pub struct QuotaObservationVersion {
/// Provider quota 的一次完整观察结果
#[derive(Clone, PartialEq)]
pub struct QuotaObservation {
/// 合并旧快照时校验读取的版本,独立观测不需要基准版本
pub merge_base: Option<super::QuotaMergeBase>,
/// 本地阈值决策与观测一起写入,策略已变时拒绝旧结论
pub quota_pause: Option<super::QuotaPauseDecision>,
/// 网络查询可额外校验请求出口与启用状态,避免连接变化后的迟到写入
@@ -94,8 +94,6 @@ pub struct QuotaMergeBase {
/// 此次判断依据的策略,以及是否有通用窗口触发暂停
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct QuotaPauseDecision {
/// 独立观测无需合并,依赖旧快照的判断必须随写入校验版本
pub merge_base: Option<QuotaMergeBase>,
pub limits: AccountQuotaSettings,
pub paused: bool,
}
@@ -104,6 +104,7 @@ impl RuntimeAccount {
/// 全快照共享的账号、Provider 与分组反向索引
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct RuntimeAccountDirectory {
pub schedules: super::duty::AccountSchedules,
accounts: BTreeMap<ProviderAccountId, RuntimeAccount>,
providers_with_accounts: BTreeSet<ProviderKind>,
providers_by_group: BTreeMap<AccountGroupId, BTreeSet<ProviderKind>>,
@@ -126,6 +127,7 @@ impl RuntimeAccountDirectory {
}
}
Self {
schedules: Default::default(),
accounts,
providers_with_accounts,
providers_by_group,
@@ -143,6 +145,12 @@ impl RuntimeAccountDirectory {
self
}
#[must_use]
pub fn with_schedules(mut self, schedules: super::duty::AccountSchedules) -> Self {
self.schedules = schedules;
self
}
#[must_use]
pub fn with_group_fast_modes(mut self, policies: BTreeMap<AccountGroupId, FastMode>) -> Self {
self.group_fast_modes = policies;
@@ -261,6 +261,7 @@ pub struct AccountRuntimeSignals {
pub recent_requests: u64,
pub last_started_at: Option<SystemTime>,
pub quota_reset_at: Option<SystemTime>,
pub daily_used_percent: Option<u8>,
pub quota_reset_windows: Option<Arc<[AccountQuotaResetWindow]>>,
/// Provider 归一化的剩余额度基点:0 耗尽,10_000 全部可用
pub quota_remaining_rank: Option<u64>,
@@ -549,6 +550,7 @@ impl AccountRuntimeSignals {
pub fn with_provider_quota(mut self, quota: Option<AccountQuotaSignals>) -> Self {
if let Some(quota) = quota {
self.quota_reset_at = quota.reset_at;
self.daily_used_percent = quota.daily_used_percent();
self.quota_reset_windows = quota.reset_windows;
self.quota_remaining_rank = quota.remaining_rank;
}
@@ -583,6 +585,7 @@ pub struct AccountQuotaResetWindow {
/// Provider 从私有 quota JSON 投影出的中立调度事实
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AccountQuotaSignals {
daily_used_percent: Option<u8>,
reset_windows: Option<Arc<[AccountQuotaResetWindow]>>,
reset_at: Option<SystemTime>,
remaining_rank: Option<u64>,
@@ -595,10 +598,22 @@ impl AccountQuotaSignals {
Self {
reset_at,
remaining_rank,
daily_used_percent: None,
reset_windows: None,
}
}
#[must_use]
pub const fn daily_used_percent(&self) -> Option<u8> {
self.daily_used_percent
}
#[must_use]
pub const fn with_daily_used_percent(mut self, percent: Option<u8>) -> Self {
self.daily_used_percent = percent;
self
}
#[must_use]
pub fn with_reset_windows(mut self, windows: Vec<AccountQuotaResetWindow>) -> Self {
self.reset_windows = (!windows.is_empty()).then(|| windows.into());
@@ -664,6 +679,8 @@ pub struct AccountSelectionContext {
/// 租约争用或队列让位只阻止立即选号,不排除等待资格
pub busy_accounts: BTreeSet<ProviderAccountId>,
pub preferred_account: Option<ProviderAccountId>,
/// 经会话绑定或原生续接验证的账号,缓存偏好不能作为旧会话凭据
pub bound_session_account: Option<ProviderAccountId>,
/// 优先账号可调度时,是否优先于其它账号的持久权重
pub preferred_account_overrides_weight: bool,
pub round_robin_cursor: u64,
@@ -674,6 +691,50 @@ pub struct AccountSelectionContext {
}
impl AccountSelectionContext {
fn off_shift_policy(
&self,
candidate: &AccountCandidate,
) -> Option<super::duty::OffShiftSession> {
let directory = self.account_scope.as_ref()?.directory();
let id = candidate.account.id();
let schedules = &directory.schedules;
schedules
.duty(
id,
directory.account(id)?,
self.now,
candidate.signals.daily_used_percent,
)
.filter(|duty| *duty != super::duty::ScheduleDuty::OnDuty)
.map(|_| schedules.policy.off_shift_session)
}
pub fn allows_shift(&self, candidate: &AccountCandidate) -> bool {
match self.off_shift_policy(candidate) {
None => true,
Some(super::duty::OffShiftSession::Keep) => {
self.bound_session_account.as_ref() == Some(candidate.account.id())
}
Some(super::duty::OffShiftSession::Rebind) => false,
}
}
/// 下班后选择沿用原账号时,已有绑定优先于一般亲和与权重,健康和并发仍由共用资格判断约束
pub fn prefer_retained_shift_owner(&mut self, candidates: &[AccountCandidate]) {
if self.eligibility.bypasses_local_eligibility() {
return;
}
let Some(id) = &self.bound_session_account else {
return;
};
if let Some(candidate) = candidates.iter().find(|c| c.account.id() == id)
&& self.off_shift_policy(candidate) == Some(super::duty::OffShiftSession::Keep)
{
self.preferred_account = Some(id.clone());
self.preferred_account_overrides_weight = true;
}
}
/// 本请求在该账号上可使用的并发上限;资格判断、租约与策略投影必须共用这一口径
#[must_use]
pub fn concurrency_limit(&self, candidate: &AccountCandidate) -> AccountConcurrency {
@@ -1030,7 +1091,7 @@ impl AccountSelector {
.account
.status_projection(context.now, candidate.signals.cooldown)
.status;
if status != AccountStatus::Normal {
if status != AccountStatus::Normal || !context.allows_shift(candidate) {
return Some(AccountSchedulingBlocker::LocalAvailability);
}
}
@@ -13,6 +13,11 @@ pub trait ProviderRuntimePolicyPort: Send + Sync {
Box::pin(async { Ok(None) })
}
/// 是否允许定时或缓存缺失时自动查询 Antigravity OAuth 账号
fn antigravity_background_refresh(&self) -> BoxFuture<'_, Result<bool, ProviderStoreError>> {
Box::pin(async { Ok(true) })
}
/// 后台 OpenAI 操作读取当前全局请求设置
fn load_openai_request_settings(
&self,
@@ -36,6 +36,9 @@ impl<'a> ProviderSessionAffinityState<'a> {
/// 原生续接的固定账号由调用方优先设置,不以软亲和覆盖
pub fn apply_preference(&self, context: &mut AccountSelectionContext) {
if context.bound_session_account.is_none() {
context.bound_session_account = self.bound_account().cloned();
}
if self.policy.account_affinity() != AccountAffinity::Relaxed
&& context.preferred_account.is_none()
{
@@ -194,6 +194,7 @@ impl SnapshotAccountGroupMemberFacts {
/// 一次一致性读取产生的全部 RuntimeSnapshot 持久事实
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SnapshotFacts {
schedules: crate::account::duty::AccountSchedules,
config_revision: ConfigRevision,
observed_current_revision: ConfigRevision,
settings: SettingsValues,
@@ -217,6 +218,7 @@ impl SnapshotFacts {
Self {
config_revision,
observed_current_revision,
schedules: Default::default(),
settings,
client_policies,
account_groups,
@@ -230,6 +232,12 @@ impl SnapshotFacts {
self.config_revision
}
#[must_use]
pub fn with_schedules(mut self, schedules: crate::account::duty::AccountSchedules) -> Self {
self.schedules = schedules;
self
}
#[must_use]
pub const fn observed_current_revision(&self) -> ConfigRevision {
self.observed_current_revision
@@ -584,6 +592,7 @@ async fn compile_runtime_snapshot(
.collect();
let account_directory = Arc::new(
RuntimeAccountDirectory::new(accounts)
.with_schedules(facts.schedules)
.with_group_model_access(group_model_access)
.with_group_fast_modes(
groups
@@ -897,6 +906,21 @@ impl RuntimeSnapshot {
self
}
#[must_use]
pub fn account_schedule_duty(
&self,
id: &ProviderAccountId,
now: std::time::SystemTime,
daily_used_percent: Option<u8>,
) -> Option<crate::account::duty::ScheduleDuty> {
self.account_directory.schedules.duty(
id,
self.account_directory.account(id)?,
now,
daily_used_percent,
)
}
#[must_use]
pub fn all_account_scope(&self) -> Arc<FrozenAccountScope> {
Arc::new(FrozenAccountScope::new(
+8 -1
View File
@@ -2,7 +2,9 @@
use std::str::FromStr;
use chrono::{DateTime, Days, NaiveDate, NaiveDateTime, Offset as _, TimeZone as _, Utc};
use chrono::{
DateTime, Days, NaiveDate, NaiveDateTime, Offset as _, TimeZone as _, Timelike as _, Utc,
};
use chrono_tz::{GapInfo, Tz};
use serde::{Deserialize, Serialize};
@@ -41,6 +43,11 @@ impl DeploymentTimeZone {
value.with_timezone(&self.0)
}
#[must_use]
pub fn minute_of_day(self, value: DateTime<Utc>) -> u16 {
(self.local(value).num_seconds_from_midnight() / 60) as u16
}
/// 重复本地时刻只取较早时间点,缺失时刻由调用方决定是否跳过
#[must_use]
pub fn resolve_local(self, value: NaiveDateTime) -> Option<DateTime<Utc>> {
@@ -0,0 +1,218 @@
//! 每日排班在内置选号、等待资格和会话绑定上的边界
use super::*;
use gateway_core::account::duty::{
AccountSchedules, DailyShift, OffShiftSession, ScheduleDuty, SchedulePolicy,
};
use gateway_core::routing::AccountGroupId;
fn shift(start: u16, end: u16) -> DailyShift {
DailyShift {
id: "shift".into(),
start,
end,
}
}
#[test]
fn daily_schedule_combines_memberships_and_preserves_default_pool() {
let group = AccountGroupId::new("grp_11111111111111111111111111111111").unwrap();
let provider = ProviderKind::new("openai").unwrap();
let managed = candidate("acct_managed", 0, None);
let unmanaged = candidate("acct_unmanaged", 0, None);
let mut schedules = AccountSchedules::default();
schedules
.accounts
.insert("acct_managed".into(), vec![shift(540, 1020)]);
schedules
.groups
.insert(group.as_str().into(), vec![shift(1290, 405)]);
let directory = RuntimeAccountDirectory::new(BTreeMap::from([
(
managed.account.id().clone(),
RuntimeAccount::new(provider.clone(), BTreeSet::from([group])),
),
(
unmanaged.account.id().clone(),
RuntimeAccount::new(provider, BTreeSet::new()),
),
]))
.with_schedules(schedules);
let mut context = context(RotationStrategy::Smart);
context.account_scope = Some(Arc::new(FrozenAccountScope::new(
Arc::new(directory),
ClientRoutingScope::AllAccounts,
)));
for (minute, expected) in [
(0, true),
(404, true),
(405, false),
(539, false),
(540, true),
(1019, true),
(1020, false),
(1290, true),
] {
context.now =
std::time::UNIX_EPOCH + Duration::from_secs(((minute + 1440 - 480) % 1440) * 60);
assert_eq!(
AccountSelector
.select(std::slice::from_ref(&managed), &context)
.is_some(),
expected
);
assert!(
AccountSelector
.select(std::slice::from_ref(&unmanaged), &context)
.is_some()
);
}
}
#[test]
fn shifts_follow_the_deployment_zone_across_daylight_saving_time() {
let managed = candidate("acct_managed", 0, None);
let account = RuntimeAccount::new(managed.account.provider().clone(), BTreeSet::new());
let id = managed.account.id();
let schedules = AccountSchedules {
timezone: "America/New_York".parse().unwrap(),
accounts: BTreeMap::from([(id.as_str().to_owned(), vec![shift(60, 120)])]),
..Default::default()
};
for (instant, expected) in [
("2026-03-08T06:59:00Z", true),
("2026-03-08T07:00:00Z", false),
("2026-11-01T05:30:00Z", true),
("2026-11-01T06:30:00Z", true),
("2026-11-01T07:00:00Z", false),
] {
let now = instant.parse::<chrono::DateTime<chrono::Utc>>().unwrap();
assert_eq!(
schedules.duty(id, &account, now.into(), None),
Some(if expected {
ScheduleDuty::OnDuty
} else {
ScheduleDuty::OffDuty
})
);
}
}
#[test]
fn disabled_schedule_bypasses_empty_shifts_and_quota_without_removing_them() {
let managed = candidate("acct_managed", 0, None);
let account = RuntimeAccount::new(managed.account.provider().clone(), BTreeSet::new());
let id = managed.account.id();
let mut schedules = AccountSchedules {
accounts: BTreeMap::from([(id.as_str().to_owned(), vec![])]),
policy: SchedulePolicy {
enabled: false,
early_finish: true,
..Default::default()
},
..Default::default()
};
let now = std::time::UNIX_EPOCH;
assert_eq!(schedules.duty(id, &account, now, Some(100)), None);
schedules.policy.enabled = true;
assert_eq!(
schedules.duty(id, &account, now, None),
Some(ScheduleDuty::OffDuty)
);
schedules
.accounts
.get_mut(id.as_str())
.unwrap()
.push(shift(0, 0));
assert_eq!(
schedules.duty(id, &account, now, Some(100)),
Some(ScheduleDuty::QuotaReached)
);
schedules.policy.enabled = false;
assert_eq!(schedules.duty(id, &account, now, Some(100)), None);
}
#[test]
fn daily_quota_and_empty_members_only_restrict_new_work() {
let mut managed = candidate("acct_managed", 0, None);
let mut context = context(RotationStrategy::Smart);
let default_session = SchedulePolicy::default().off_shift_session;
for (shifts, percent, bound, session_policy, expected) in [
(vec![], None, false, default_session, false),
(vec![], None, true, default_session, true),
(vec![], None, true, OffShiftSession::Rebind, false),
(
vec![shift(0, 0)],
None,
false,
OffShiftSession::Rebind,
true,
),
(
vec![shift(0, 0)],
Some(79),
false,
OffShiftSession::Rebind,
true,
),
(
vec![shift(0, 0)],
Some(80),
false,
OffShiftSession::Keep,
false,
),
(
vec![shift(0, 0)],
Some(99),
true,
OffShiftSession::Keep,
true,
),
] {
managed.signals.daily_used_percent = percent;
context.bound_session_account = bound.then(|| managed.account.id().clone());
let retained = bound
&& session_policy == OffShiftSession::Keep
&& (shifts.is_empty() || percent.is_some_and(|p| p >= 80));
let schedules = AccountSchedules {
timezone: Default::default(),
accounts: BTreeMap::from([("acct_managed".into(), shifts)]),
groups: Default::default(),
policy: SchedulePolicy {
enabled: true,
off_shift_session: session_policy,
early_finish: true,
limit_percent: 80,
},
};
let directory = RuntimeAccountDirectory::new(BTreeMap::from([(
managed.account.id().clone(),
RuntimeAccount::new(managed.account.provider().clone(), BTreeSet::new()),
)]))
.with_schedules(schedules);
context.account_scope = Some(Arc::new(FrozenAccountScope::new(
Arc::new(directory),
ClientRoutingScope::AllAccounts,
)));
let pool = std::slice::from_ref(&managed);
context.preferred_account = None;
context.preferred_account_overrides_weight = false;
context.prefer_retained_shift_owner(pool);
assert_eq!(
context.preferred_account.as_ref() == Some(managed.account.id()),
retained
);
assert_eq!(context.preferred_account_overrides_weight, retained);
assert_eq!(AccountSelector.select(pool, &context).is_some(), expected);
context.busy_accounts.insert(managed.account.id().clone());
assert_eq!(
AccountSelector
.wait_candidates(pool, &context)
.contains(managed.account.id()),
expected
);
assert!(AccountSelector.select(pool, &context).is_none());
context.busy_accounts.clear();
}
}
@@ -1,5 +1,6 @@
//! 账号领域测试入口,以及候选账号与调度输入构造辅助
mod duty;
mod location;
mod model_access;
mod proxy;
@@ -60,6 +61,7 @@ fn candidate(id: &str, in_flight: u32, remaining: Option<u64>) -> AccountCandida
recent_requests: 0,
last_started_at: None,
quota_reset_at: None,
daily_used_percent: None,
quota_reset_windows: None,
quota_remaining_rank: remaining,
cooldown: None,
@@ -113,6 +115,7 @@ fn context(strategy: RotationStrategy) -> AccountSelectionContext {
excluded_accounts: BTreeSet::new(),
busy_accounts: Default::default(),
preferred_account: None,
bound_session_account: None,
preferred_account_overrides_weight: false,
round_robin_cursor: 0,
eligibility: AccountEligibilityPolicy::Enforce,
@@ -234,6 +237,7 @@ fn diagnostic_selection_bypasses_all_local_account_eligibility() {
recent_requests: 0,
last_started_at: None,
quota_reset_at: None,
daily_used_percent: None,
quota_reset_windows: None,
quota_remaining_rank: None,
cooldown: None,
@@ -255,6 +259,7 @@ fn diagnostic_selection_bypasses_all_local_account_eligibility() {
recent_requests: 0,
last_started_at: None,
quota_reset_at: None,
daily_used_percent: None,
quota_reset_windows: None,
quota_remaining_rank: None,
cooldown: None,
@@ -651,6 +656,7 @@ fn provider_quota_overlay_should_preserve_store_concurrency_facts() {
recent_requests: 0,
last_started_at: Some(last_started_at),
quota_reset_at: None,
daily_used_percent: None,
quota_reset_windows: None,
quota_remaining_rank: None,
cooldown: None,
@@ -1073,6 +1079,41 @@ fn elapsed_quota_reset_does_not_fabricate_recovery() {
assert_eq!(selected.candidate().account.id().as_str(), "acct_healthy");
}
#[test]
fn quota_deadline_releases_status_and_selection_at_the_same_instant() {
let mut selection = context(RotationStrategy::Smart);
let deadline = selection.now;
let state = QuotaState::exhausted(
QuotaEvidence::UsageLimitReached,
deadline - Duration::from_secs(300),
None,
)
.with_exhaustion_deadline(Some(deadline));
let mut account = candidate("acct_window", 0, Some(100));
account.account =
account
.account
.with_account_facts(true, CredentialState::Ready, state, None, None);
let candidates = [account];
for (time, status) in [
(
deadline - Duration::from_nanos(1),
AccountStatus::QuotaExhausted,
),
(deadline, AccountStatus::Normal),
] {
selection.now = time;
assert_eq!(
candidates[0].account.status_projection(time, None).status,
status
);
assert_eq!(
AccountSelector.select(&candidates, &selection).is_some(),
status == AccountStatus::Normal
);
}
}
#[test]
fn due_probe_freeze_blocks_scheduling_and_remains_visible_as_rate_limited() {
use gateway_core::account::{AccountCooldown, AccountCooldownKind};
@@ -2473,6 +2473,7 @@ impl Provider for PolicySelectingProvider {
recent_requests: 0,
last_started_at: None,
quota_reset_at: None,
daily_used_percent: None,
quota_reset_windows: None,
quota_remaining_rank: None,
cooldown: None,
@@ -2486,6 +2487,7 @@ impl Provider for PolicySelectingProvider {
excluded_accounts: attempt.excluded_accounts().clone(),
busy_accounts: Default::default(),
preferred_account: attempt.required_account().cloned(),
bound_session_account: None,
preferred_account_overrides_weight: true,
round_robin_cursor: 0,
eligibility: AccountEligibilityPolicy::Enforce,
@@ -78,6 +78,7 @@ fn candidate(id: &str) -> AccountCandidate {
recent_requests: 0,
last_started_at: None,
quota_reset_at: None,
daily_used_percent: None,
quota_reset_windows: None,
quota_remaining_rank: None,
cooldown: None,
@@ -113,6 +114,7 @@ fn context() -> AccountSelectionContext {
excluded_accounts: BTreeSet::new(),
busy_accounts: Default::default(),
preferred_account: Some(account_id("acct_a")),
bound_session_account: None,
preferred_account_overrides_weight: true,
round_robin_cursor: 0,
eligibility: AccountEligibilityPolicy::Enforce,
@@ -12,6 +12,7 @@ fn scheduling_state_preserves_provider_neutral_signals() {
recent_requests: 0,
last_started_at: None,
quota_reset_at: None,
daily_used_percent: None,
quota_reset_windows: None,
quota_remaining_rank: Some(7),
cooldown: None,
@@ -40,6 +40,7 @@ fn candidate(id: &str, busy: bool) -> AccountCandidate {
recent_requests: 0,
last_started_at: None,
quota_reset_at: None,
daily_used_percent: None,
quota_reset_windows: None,
quota_remaining_rank: None,
cooldown: None,
@@ -58,6 +59,7 @@ fn context(mode: AccountAffinity) -> AccountSelectionContext {
excluded_accounts: Default::default(),
busy_accounts: Default::default(),
preferred_account: None,
bound_session_account: None,
preferred_account_overrides_weight: false,
round_robin_cursor: 0,
eligibility: AccountEligibilityPolicy::Enforce,
@@ -266,6 +266,7 @@ fn prepare_replace(
email: facts.email,
plan_type: facts.plan_type,
preserve_profile: false,
preserve_catalog_etag: None,
preserve_credential_state: false,
preserve_access_token_expiry: false,
provider_material: ProviderDocument::new(OpaqueProviderData::new(facts.material)),
@@ -158,6 +158,7 @@ impl PluginAccountAccess for Facts {
self.reads.fetch_add(1, Ordering::SeqCst);
assert_eq!(account.as_str(), "acct_facts");
Ok(ProviderQuota {
daily_used_percent: None,
paused_windows: Vec::new(),
upstream: None,
credits: Some(ProviderQuotaCredits {
@@ -631,6 +631,7 @@ fn candidate(id: &str, weight: u16) -> AccountCandidate {
recent_requests: 0,
last_started_at: None,
quota_reset_at: None,
daily_used_percent: None,
quota_reset_windows: None,
quota_remaining_rank: None,
cooldown: None,
@@ -650,6 +651,7 @@ fn selection_context() -> AccountSelectionContext {
excluded_accounts: BTreeSet::new(),
busy_accounts: Default::default(),
preferred_account: None,
bound_session_account: None,
preferred_account_overrides_weight: true,
round_robin_cursor: 0,
eligibility: AccountEligibilityPolicy::Enforce,
@@ -61,6 +61,7 @@ async fn explicit_service_dispatch_composes_once_and_preserves_native_transactio
.unwrap();
let typed: gateway_plugin_sdk::call::services::settings::RuntimeSettings =
serde_json::from_value(through_registry).unwrap();
assert!(typed.antigravity_background_refresh);
assert_eq!(typed.refresh_margin_seconds, 4321);
// 返回层改写不是持久化写入;原 owner 保留真实配置事实
assert_eq!(
@@ -77,6 +78,7 @@ async fn explicit_service_dispatch_composes_once_and_preserves_native_transactio
);
let mut command = ReplaceRuntimeSettings::from(original);
command.values.antigravity_background_refresh = false;
command.values.refresh_margin_seconds = 999;
command
.values
@@ -107,10 +109,11 @@ async fn explicit_service_dispatch_composes_once_and_preserves_native_transactio
)
.await
.unwrap();
let saved: gateway_admin::model::settings::RuntimeSettings =
let saved: gateway_plugin_sdk::call::services::settings::RuntimeSettings =
serde_json::from_value(saved).unwrap();
assert_eq!(saved.values.refresh_margin_seconds, 1234);
assert!(saved.config_revision > command.expected_revision);
assert!(!saved.antigravity_background_refresh);
assert_eq!(saved.refresh_margin_seconds, 1234);
assert!(saved.config_revision.get() > command.expected_revision.get());
let current = environment
.store
.admin_ports()
@@ -118,6 +121,7 @@ async fn explicit_service_dispatch_composes_once_and_preserves_native_transactio
.load_runtime_settings()
.await
.unwrap();
assert!(!current.values.antigravity_background_refresh);
assert_eq!(current.values.refresh_margin_seconds, 1234);
assert!(
!current
@@ -189,6 +189,7 @@ pub struct PrivacyPreviewResult {
#[derive(Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct RuntimeSettings {
pub antigravity_background_refresh: bool,
pub openai_websocket_pool: OpenAiWebSocketPoolSettings,
pub openai_request_settings: OpenAiRequestSettings,
pub codex_privacy_policy: CodexPrivacyPolicy,
@@ -232,6 +233,7 @@ pub struct RuntimeSettings {
#[derive(Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ReplaceRuntimeSettings {
pub antigravity_background_refresh: bool,
pub openai_websocket_pool: OpenAiWebSocketPoolSettings,
pub openai_request_settings: OpenAiRequestSettings,
pub codex_privacy_policy: CodexPrivacyPolicy,
@@ -453,6 +455,7 @@ impl Operation for PreviewClientProfile {
impl From<RuntimeSettings> for ReplaceRuntimeSettings {
fn from(settings: RuntimeSettings) -> Self {
Self {
antigravity_background_refresh: settings.antigravity_background_refresh,
openai_websocket_pool: settings.openai_websocket_pool,
openai_request_settings: settings.openai_request_settings,
codex_privacy_policy: settings.codex_privacy_policy,
@@ -93,6 +93,7 @@ impl SettingsStore for AdminSettingsStoreAdapter {
MutationAuditOperation::RuntimeSettingsReplace,
"1",
vec![
"antigravity_background_refresh".to_owned(),
"provider_request_profiles_json".to_owned(),
"request_location_enabled".to_owned(),
"request_location_json".to_owned(),
+5 -1
View File
@@ -206,6 +206,7 @@ async fn connect(
)
.with_timezone(config.timezone),
),
Arc::new(postgres::account_schedules::PgScheduleStore(pool.clone())),
Arc::new(postgres::PgProxyRepository::new(pool.clone())),
),
Arc::new(AuthStoreAdapter {
@@ -267,7 +268,10 @@ async fn connect(
),
continuation,
(
Arc::new(postgres::PgRuntimeSnapshotRepository::new(pool.clone())),
Arc::new(
postgres::PgRuntimeSnapshotRepository::new(pool.clone())
.with_timezone(config.timezone),
),
Arc::new(redis::RedisRuntimeChangeRepository::new(
redis_client,
REDIS_NAMESPACE,
@@ -245,7 +245,7 @@ impl AccountGroupStore for PgAccountGroupRepository {
account.next_refresh_at, account.enabled, account.quota_settings, account.quota_paused, account.auto_use_quota_credits, account.concurrency_limit,
account.quota_observed_at, account.weight, account.model_access_json, account.credential_state, account.quota_access_state,
account.quota_evidence, account.quota_access_observed_at,
account.quota_reset_at, account.quota_limit_window_minutes, account.last_error_reason,
account.quota_reset_at, account.quota_exhaustion_deadline, account.quota_limit_window_minutes, account.last_error_reason,
account.last_error_message, account.credential_observed_at,
account.created_at, account.updated_at,
settings.max_concurrent_per_account
@@ -0,0 +1,159 @@
//! 每日班表、目录与调度快照的事务读取和写入
mod query;
use super::{append_admin_audit_event_in_transaction, bump_config_revision_in_transaction};
use crate::{StoreResult, admin_revision, admin_store_error, mutation_audit, postgres_unavailable};
use async_trait::async_trait;
use gateway_admin::{
model::{
MutationContext, Revision,
account_schedules::{ScheduleAction, ScheduleChange, TargetKind},
audit::MutationAuditOperation,
},
ports::{
account_schedules::AccountScheduleStore,
store::{AdminStoreError, AdminStoreErrorKind, AdminStoreResult},
},
};
use gateway_core::account::duty::{AccountSchedules, DailyShift, SchedulePolicy};
use sqlx::{PgPool, Postgres, Transaction, types::Json};
pub(crate) struct PgScheduleStore(pub(crate) PgPool);
const ENTITY: &str = "account schedule";
pub(super) async fn load_schedules(
tx: &mut Transaction<'_, Postgres>,
) -> StoreResult<AccountSchedules> {
let Json(policy) = sqlx::query_scalar::<_, Json<SchedulePolicy>>(
"select account_schedule_policy from runtime_settings where id=1",
)
.fetch_one(&mut **tx)
.await
.map_err(|e| postgres_unavailable("load schedule policy", e))?;
let rows = sqlx::query_as::<_, (Option<String>, Option<String>, Json<Vec<DailyShift>>)>(
"select account_id, group_id, shifts from account_schedules",
)
.fetch_all(&mut **tx)
.await
.map_err(|e| postgres_unavailable("load daily shifts", e))?;
let mut schedules = AccountSchedules {
policy,
..Default::default()
};
for (account, group, Json(shifts)) in rows {
if let Some(id) = account {
schedules.accounts.insert(id, shifts);
} else if let Some(id) = group {
schedules.groups.insert(id, shifts);
}
}
Ok(schedules)
}
fn database_error(source: sqlx::Error) -> AdminStoreError {
if source
.as_database_error()
.is_some_and(|e| e.is_foreign_key_violation())
{
return AdminStoreError::new(AdminStoreErrorKind::StaleRevision, ENTITY, "排班对象已删除")
.with_source(source);
}
admin_store_error(
ENTITY,
postgres_unavailable("account schedule storage", source),
)
}
#[async_trait]
impl AccountScheduleStore for PgScheduleStore {
async fn query(
&self,
query: &gateway_admin::model::account_schedules::ScheduleQuery,
) -> AdminStoreResult<gateway_admin::model::account_schedules::ScheduleList> {
query::page(&self.0, query).await
}
async fn save(
&self,
change: ScheduleChange,
context: &MutationContext,
) -> AdminStoreResult<Revision> {
let mut tx = self.0.begin().await.map_err(database_error)?;
let revision = bump_config_revision_in_transaction(&mut tx)
.await
.map_err(|e| admin_store_error(ENTITY, e))?;
if revision.get() - 1 != change.revision {
return Err(AdminStoreError::new(
AdminStoreErrorKind::StaleRevision,
ENTITY,
"配置版本已更新,请重新打开排班表后再保存",
));
}
let mut fields = Vec::new();
if let Some(policy) = change.policy {
sqlx::query("update runtime_settings set account_schedule_policy=$1 where id=1")
.bind(Json(policy))
.execute(&mut *tx)
.await
.map_err(database_error)?;
fields.push("policy".to_owned());
}
if change.clear {
sqlx::query("delete from account_schedules")
.execute(&mut *tx)
.await
.map_err(database_error)?;
}
if change.clear || !change.targets.is_empty() {
fields.push("shifts".to_owned());
}
for kind in [TargetKind::Account, TargetKind::Group] {
let mut remove = Vec::new();
let mut set = serde_json::Map::new();
for target in change.targets.iter().filter(|t| t.kind == kind) {
match &target.action {
ScheduleAction::Remove => remove.push(&target.id),
ScheduleAction::Set(shifts) => {
set.insert(target.id.clone(), serde_json::json!(shifts));
}
}
}
let (delete_sql, set_sql) = match kind {
TargetKind::Account => (
"delete from account_schedules where account_id=any($1)",
"insert into account_schedules (account_id,shifts) select key,value from jsonb_each($1) on conflict(account_id) do update set shifts=excluded.shifts",
),
TargetKind::Group => (
"delete from account_schedules where group_id=any($1)",
"insert into account_schedules (group_id,shifts) select key,value from jsonb_each($1) on conflict(group_id) do update set shifts=excluded.shifts",
),
};
if !remove.is_empty() {
sqlx::query(delete_sql)
.bind(remove)
.execute(&mut *tx)
.await
.map_err(database_error)?;
}
if !set.is_empty() {
sqlx::query(set_sql)
.bind(Json(set))
.execute(&mut *tx)
.await
.map_err(database_error)?;
}
}
let audit = mutation_audit(
context,
MutationAuditOperation::AccountScheduleUpdate,
"daily",
fields,
);
append_admin_audit_event_in_transaction(&mut tx, audit, revision)
.await
.map_err(|e| admin_store_error(ENTITY, e))?;
tx.commit().await.map_err(database_error)?;
admin_revision(revision)
}
}
@@ -0,0 +1,244 @@
//! 排班编辑器的分页目录、草稿投影与跨页覆盖统计
use super::database_error;
use gateway_admin::model::account_schedules::{
ScheduleAccount, ScheduleGroup, ScheduleItem, ScheduleList, ScheduleQuery, ScheduleScope,
ScheduleSummary,
};
use gateway_admin::ports::store::{AdminStoreError, AdminStoreErrorKind, AdminStoreResult};
use gateway_core::account::duty::{DailyShift, SchedulePolicy};
use sqlx::{PgPool, Postgres, Row, postgres::PgArguments, query::Query, types::Json};
// 同一个匹配集合用于总数、当页与全局统计,草稿覆盖只在当前只读事务内生效
const DIRECTORY: &str = r#"
with draft as (
select kind,id,action->'set' as shifts from jsonb_to_recordset($1) as d(kind text,id text,action jsonb)
), enrolled as (
select coalesce(account_id,group_id) id, case when account_id is null then 'group' else 'account' end kind, shifts
from account_schedules
), effective as (
select e.* from enrolled e where not $2 and not exists(select 1 from draft d where (d.kind,d.id)=(e.kind,e.id))
union all select id,kind,shifts from draft where shifts is not null
), directory as (
select 'account' kind,a.id,coalesce(nullif(a.name,''),nullif(a.email,''),a.id) name
from provider_accounts a where $3 <> 'group'
union all select 'group',id,name from account_groups where $3 <> 'account'
), matches as (
select d.* from directory d
where ($3 <> 'roster' or exists(select 1 from effective e where (e.kind,e.id)=(d.kind,d.id)))
and ($4='' or (d.kind='group' and d.id=$4) or (d.kind='account' and exists(
select 1 from account_group_accounts m where m.provider_account_id=d.id and m.account_group_id=$4)))
and ($5='' or strpos(lower(d.name),lower($5))>0 or strpos(lower(d.kind||':'||d.id),lower($5))>0
or (d.kind='account' and exists(select 1 from account_group_accounts m join account_groups g on g.id=m.account_group_id
where m.provider_account_id=d.id and strpos(lower(g.name),lower($5))>0)))
)
"#;
const PAGE: &str = r#"
select p.*,a.provider_kind,a.authentication_kind,a.plan_type,a.quota_observed_at is not null as cached,
array(select account_group_id from account_group_accounts m where m.provider_account_id=a.id order by account_group_id) as group_ids,
e.shifts
from (select * from matches order by kind,name,id limit $6 offset $7) p
left join provider_accounts a on p.kind='account' and a.id=p.id
left join enrolled e on (e.kind,e.id)=(p.kind,p.id)
order by p.kind,p.name,p.id
"#;
// 每个账号的个人与分组班次先取并集,然后仅在区间端点累计人数
const SUMMARY: &str = r#"
, calendars as (
select e.kind,e.id,coalesce(range_agg(span) filter(where span is not null),'{}'::int4multirange) hours
from effective e left join lateral (
select int4range(s.start,case when s.start<s."end" then s."end" else 1440 end,'[)') span
from jsonb_to_recordset(e.shifts) s(start int,"end" int)
union all select int4range(0,s."end",'[)') from jsonb_to_recordset(e.shifts) s(start int,"end" int)
where s.start>=s."end"
) spans on true group by e.kind,e.id
), sources as (
select id as account_id,* from calendars where kind='account'
union all select m.provider_account_id,c.* from calendars c join account_group_accounts m on m.account_group_id=c.id where c.kind='group'
), accounts as (
select s.account_id,range_agg(s.hours) hours,bool_or(m.id is not null) visible,
coalesce(array_agg(p.key order by p.key) filter(where p.key is not null),'{}') targets,
coalesce(range_agg(s.hours) filter(where p.key is null),'{}'::int4multirange) fixed
from sources s left join matches m on (s.kind,s.id)=(m.kind,m.id)
left join unnest($7::text[]) p(key) on p.key=s.kind||':'||s.id
group by s.account_id
), named as (
select m.*,coalesce(nullif(a.name,''),nullif(a.email,''),a.id) name
from accounts m join provider_accounts a on a.id=m.account_id
), cohorts as (
select targets,fixed,count(*) n,min(name) example from named
where cardinality(targets)>0 group by targets,fixed
), spans as (
select unnest(hours) span,fixed_only from accounts cross join (values(false),(true)) v(fixed_only)
where visible and (not fixed_only or cardinality(targets)=0)
), edges as (
select at,0 delta,fixed_only from (values(0),(1440)) a(at) cross join (values(false),(true)) v(fixed_only)
union all select lower(span),1,fixed_only from spans union all select upper(span),-1,fixed_only from spans
), boundaries as (
select fixed_only,at,sum(delta) delta from edges group by fixed_only,at having sum(delta)<>0 or at in (0,1440)
), bands as (
select fixed_only,at as start,lead(at) over w as "end",sum(delta) over w as count from boundaries
window w as (partition by fixed_only order by at)
), series as (
select fixed_only,jsonb_agg(jsonb_build_object('start',start,'end',"end",'count',count) order by start) bands
from bands where "end" is not null group by fixed_only
), totals as (select count(*) pool from provider_accounts)
select jsonb_build_object(
'targetCount',(select count(*) from effective),'poolCount',pool,
'available',pool-(select count(*) from accounts where not hours @> $6::int),
'offDuty',(select min(name) from named where not hours @> $6::int),
'visible',(select count(*) from accounts where visible),
'current',(select count(*) from accounts where visible and hours @> $6::int),
'bands',(select bands from series where not fixed_only),
'editing',jsonb_build_object(
'available',pool-(select count(*) from accounts where cardinality(targets)>0 or not hours @> $6::int),
'offDuty',(select min(name) from named where cardinality(targets)=0 and not hours @> $6::int),
'bands',(select bands from series where fixed_only),
'cohorts',coalesce((select jsonb_agg(jsonb_build_object(
'targets',targets,'count',n,'example',example,
'fixed',array(select array[lower(r),upper(r)] from unnest(fixed) r)
)) from cohorts),'[]'::jsonb)
)
) as summary from totals
"#;
fn bind_query<'a>(suffix: &'static str, q: &'a ScheduleQuery) -> Query<'a, Postgres, PgArguments> {
let scope = match q.scope {
ScheduleScope::Roster => "roster",
ScheduleScope::Account => "account",
ScheduleScope::Group => "group",
};
sqlx::query(sqlx::AssertSqlSafe(format!("{DIRECTORY}{suffix}")))
.bind(Json(&q.targets))
.bind(q.clear)
.bind(scope)
.bind(&q.group_id)
.bind(q.search.trim())
}
pub(super) async fn page(pool: &PgPool, q: &ScheduleQuery) -> AdminStoreResult<ScheduleList> {
let mut tx = pool.begin().await.map_err(database_error)?;
sqlx::query("set transaction isolation level repeatable read read only")
.execute(&mut *tx)
.await
.map_err(database_error)?;
let (revision, Json(policy)) = sqlx::query_as::<_, (i64, Json<SchedulePolicy>)>(
"select config_revision,account_schedule_policy from runtime_settings where id=1",
)
.fetch_one(&mut *tx)
.await
.map_err(database_error)?;
if q.revision.is_some_and(|version| version != revision as u64) {
return Err(AdminStoreError::new(
AdminStoreErrorKind::StaleRevision,
super::ENTITY,
"配置版本已更新,请重新打开排班表",
));
}
let counts = bind_query(
"select (select count(*) from matches) as total, exists (
select 1 from draft d where d.shifts is not null and (
(d.kind='account' and not exists(select 1 from provider_accounts a where a.id=d.id))
or (d.kind='group' and not exists(select 1 from account_groups g where g.id=d.id))
)
) as missing_target",
q,
)
.fetch_one(&mut *tx)
.await
.map_err(database_error)?;
if counts.get("missing_target") {
return Err(AdminStoreError::new(
AdminStoreErrorKind::StaleRevision,
super::ENTITY,
"排班对象已删除",
));
}
let total = counts.get("total");
let rows = bind_query(PAGE, q)
.bind(i64::from(q.page_size))
.bind(i64::from(q.page - 1) * i64::from(q.page_size))
.fetch_all(&mut *tx)
.await
.map_err(database_error)?;
let items: Vec<_> = rows
.into_iter()
.map(|row| {
let shifts = row
.get::<Option<Json<Vec<DailyShift>>>, _>("shifts")
.map(|v| v.0);
let id = row.get("id");
let name = row.get("name");
if row.get::<&str, _>("kind") == "group" {
ScheduleItem::Group {
group: ScheduleGroup { id, name },
shifts,
}
} else {
ScheduleItem::Account {
account: ScheduleAccount {
id,
name,
group_ids: row.get("group_ids"),
provider_kind: row.get("provider_kind"),
authentication_kind: row.get("authentication_kind"),
plan_type: row.get("plan_type"),
has_cached_quota: row.get("cached"),
plan_type_display: None,
},
shifts,
}
}
})
.collect();
let groups = if q.revision.is_none() {
Some(
sqlx::query_as::<_, (String, String)>(
"select id,name from account_groups order by name,id",
)
.fetch_all(&mut *tx)
.await
.map_err(database_error)?
.into_iter()
.map(|(id, name)| ScheduleGroup { id, name })
.collect(),
)
} else {
None
};
let summary = if let Some(minute) = q.summary_minute {
// 只有当前排班页能被就地拖动,其他来源只提供固定覆盖与人数
let editable: Vec<_> = items
.iter()
.filter(|_| q.scope == ScheduleScope::Roster)
.map(|item| match item {
ScheduleItem::Account { account, .. } => format!("account:{}", account.id),
ScheduleItem::Group { group, .. } => format!("group:{}", group.id),
})
.collect();
let row = bind_query(SUMMARY, q)
.bind(i32::from(minute))
.bind(editable)
.fetch_one(&mut *tx)
.await
.map_err(database_error)?;
Some(
row.try_get::<Json<ScheduleSummary>, _>("summary")
.map_err(database_error)?
.0,
)
} else {
None
};
tx.commit().await.map_err(database_error)?;
Ok(ScheduleList {
revision: revision as u64,
policy,
total,
items,
groups,
summary,
})
}
@@ -1,6 +1,7 @@
//! PostgreSQL 业务表、连接与控制面事务的适配入口
mod account_groups;
pub(crate) mod account_schedules;
mod admin_security_audit;
mod admission_recovery;
mod backup;
@@ -996,21 +996,28 @@ pub(super) fn prepare_import(
pub(super) fn import_result(
imported: ProviderAccountAdminImport,
) -> AdminStoreResult<CredentialImportResult> {
let credential_ids = imported
.account_ids
.into_iter()
.map(|id| {
CoreProviderAccountId::new(id).map_err(|_| {
AdminStoreError::new(
AdminStoreErrorKind::Unavailable,
ENTITY,
"provider account import returned an invalid account ID",
)
})
})
.collect::<AdminStoreResult<Vec<_>>>()?;
let created_ids = credential_ids
.iter()
.filter(|id| imported.created_ids.contains(id.as_str()))
.cloned()
.collect();
Ok(CredentialImportResult {
config_revision: admin_revision(imported.config_revision)?,
credential_ids: imported
.account_ids
.into_iter()
.map(|id| {
CoreProviderAccountId::new(id).map_err(|_| {
AdminStoreError::new(
AdminStoreErrorKind::Unavailable,
ENTITY,
"provider account import returned an invalid account ID",
)
})
})
.collect::<AdminStoreResult<_>>()?,
credential_ids,
created_ids,
})
}
@@ -1093,6 +1100,7 @@ pub(super) fn prepare_rotation(
access_token_expires_at: prepared.access_token_expires_at,
next_refresh_at: prepared.next_refresh_at,
preserve_profile: prepared.preserve_profile,
preserve_catalog_etag: prepared.preserve_catalog_etag,
preserve_credential_state: prepared.preserve_credential_state,
preserve_access_token_expiry: prepared.preserve_access_token_expiry,
},
@@ -58,7 +58,8 @@ pub(crate) async fn load_admin_account_page(
when not a.enabled then 'disabled'
when a.credential_state <> 'ready'
or a.access_token_expires_at <= $2 then 'error'
when a.quota_access_state = 'exhausted' then 'quota_exhausted'
when a.quota_access_state = 'exhausted'
and (a.quota_exhaustion_deadline is null or a.quota_exhaustion_deadline > $2) then 'quota_exhausted'
when a.id = any($1::text[]) or exists (
select 1 from unnest($13::text[], $14::bigint[]) as limits(account_id, revision)
where limits.account_id = a.id and limits.revision = a.credential_revision
@@ -116,7 +117,7 @@ pub(crate) async fn load_admin_account_page(
a.credential_revision, a.has_refresh_token, a.access_token_expires_at,
a.next_refresh_at, a.enabled, a.quota_settings, a.quota_paused, a.auto_use_quota_credits, a.concurrency_limit, a.weight, a.model_access_json,
a.credential_state, a.quota_access_state, a.quota_evidence,
a.quota_observed_at, a.quota_access_observed_at, a.quota_reset_at, a.quota_limit_window_minutes, a.last_error_reason,
a.quota_observed_at, a.quota_access_observed_at, a.quota_reset_at, a.quota_exhaustion_deadline, a.quota_limit_window_minutes, a.last_error_reason,
a.last_error_message, a.credential_observed_at, a.created_at, a.updated_at,
filtered_total.filtered_total,
global_summary.summary_total, global_summary.summary_normal,
@@ -2,7 +2,7 @@
use gateway_admin::model::provider_credentials::{
AuthorizationCommitResult, AuthorizationMutationTarget, AuthorizationReceiptKey,
CredentialMutationResult,
CredentialChange, CredentialMutationResult,
};
use serde::{Deserialize, Serialize};
@@ -87,10 +87,10 @@ async fn commit_authorization_in_transaction(
if let Some(result) = load_receipt(&mut **transaction, key).await? {
return Ok(AuthorizationCommitResult {
result,
newly_committed: false,
change: None,
});
}
let result = match (command.pending.target(), command.credential) {
let (result, change) = match (command.pending.target(), command.credential) {
(
AuthorizationMutationTarget::Create { .. },
AuthorizationCredentialCommit::Create(credential),
@@ -120,7 +120,12 @@ async fn commit_authorization_in_transaction(
let result = repository::import_provider_accounts_in_transaction(transaction, prepared)
.await
.map_err(|error| admin_store_error(ENTITY, error))?;
admin_adapter::authorization_import_result(result)?
let change = if result.created_ids.is_empty() {
CredentialChange::Updated
} else {
CredentialChange::Created
};
(admin_adapter::authorization_import_result(result)?, change)
}
(
AuthorizationMutationTarget::Reauthorize { account_id },
@@ -145,7 +150,10 @@ async fn commit_authorization_in_transaction(
)
.await
.map_err(|error| admin_store_error(ENTITY, error))?;
admin_adapter::rotation_result(result, account_id.clone())?
(
admin_adapter::rotation_result(result, account_id.clone())?,
CredentialChange::Updated,
)
}
_ => return Err(invalid_receipt()),
};
@@ -163,7 +171,7 @@ async fn commit_authorization_in_transaction(
.execute(&mut **transaction).await.map_err(|source| unavailable_receipt().with_source(source))?;
Ok(AuthorizationCommitResult {
result,
newly_committed: true,
change: Some(change),
})
}
@@ -232,6 +232,7 @@ impl ProviderAccountStore for PgProviderAccountRepository {
expected_revision,
profile,
preserve_profile,
preserve_catalog_etag,
preserve_access_token_expiry,
credential,
has_refresh_token,
@@ -261,7 +262,8 @@ impl ProviderAccountStore for PgProviderAccountRepository {
let message = account_state
.as_ref()
.and_then(|state| state.message.as_deref());
let next = sqlx::query_scalar::<_, i64>(
let previous = to_i64(expected_revision.get()).map_err(core_store_error)?;
let update = sqlx::query_scalar::<_, i64>(
"update provider_accounts
set name = case when $14 then name else $3 end,
email = case when $14 then email else $4 end,
@@ -290,7 +292,7 @@ impl ProviderAccountStore for PgProviderAccountRepository {
returning credential_revision",
)
.bind(&account_id)
.bind(to_i64(expected_revision.get()).map_err(core_store_error)?)
.bind(previous)
.bind(profile.name)
.bind(profile.email)
.bind(profile.plan_type)
@@ -303,10 +305,24 @@ impl ProviderAccountStore for PgProviderAccountRepository {
.bind(error_reason)
.bind(message)
.bind(preserve_profile)
.bind(preserve_access_token_expiry)
.fetch_optional(&self.pool)
.await
.map_err(|source| CoreStoreError::caused_by(CoreStoreErrorKind::Unavailable, source))?;
.bind(preserve_access_token_expiry);
let unavailable = |e| CoreStoreError::caused_by(CoreStoreErrorKind::Unavailable, e);
let next = if let Some(etag) = preserve_catalog_etag {
let mut tx = self.pool.begin().await.map_err(unavailable)?;
let next = update.fetch_optional(&mut *tx).await.map_err(unavailable)?;
if let Some(next) = next {
Self::carry_model_catalog(&mut tx, &account_id, previous, next, &etag)
.await
.map_err(unavailable)?;
}
tx.commit().await.map_err(unavailable)?;
next
} else {
update
.fetch_optional(&self.pool)
.await
.map_err(unavailable)?
};
match next {
Some(next) => {
let revision = Revision::new(to_u64(next).map_err(core_store_error)?)
@@ -336,7 +352,7 @@ impl ProviderAccountStore for PgProviderAccountRepository {
.collect::<Vec<_>>();
let rows = sqlx::query(
"select id, credential_revision, plan_type, provider_quota_json, quota_observed_at, \
quota_access_state, quota_evidence, quota_access_observed_at, quota_reset_at, quota_limit_window_minutes \
quota_access_state, quota_evidence, quota_access_observed_at, quota_reset_at, quota_exhaustion_deadline, quota_limit_window_minutes \
from provider_accounts \
where id = any($1) and quota_observed_at is not null",
)
@@ -370,6 +386,7 @@ impl ProviderAccountStore for PgProviderAccountRepository {
})?;
let state = rows::quota_state_from_row(&row).map_err(core_store_error)?;
Ok(QuotaObservation {
merge_base: None,
quota_pause: None,
expected_connection: None,
plan_type: row.try_get("plan_type").map_err(|source| {
@@ -7,6 +7,29 @@ use super::{
use gateway_core::account::{AccountCatalogObservation, StoredAccountCatalog};
impl PgProviderAccountRepository {
pub(super) async fn carry_model_catalog(
transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>,
account_id: &str,
previous_revision: i64,
revision: i64,
etag: &str,
) -> Result<(), sqlx::Error> {
// 取得账号 CAS 行锁后用新语句读目录,覆盖刚刚在锁前提交的首次观测
sqlx::query(
"update provider_account_model_catalogs c set credential_revision = a.credential_revision
from provider_accounts a where a.id = $1 and c.account_id = a.id
and c.credential_revision = $2 and a.credential_revision = $3
and c.etag = $4 and c.plan_type is not distinct from a.plan_type",
)
.bind(account_id)
.bind(previous_revision)
.bind(revision)
.bind(etag)
.execute(&mut **transaction)
.await?;
Ok(())
}
pub(super) async fn load_model_catalogs(
&self,
provider: &ProviderKind,
@@ -111,7 +111,7 @@ impl PgProviderAccountRepository {
upstream_account_id, plan_type, authentication_kind, credential_revision, has_refresh_token,
access_token_expires_at, next_refresh_at, enabled, quota_settings, quota_paused, auto_use_quota_credits, concurrency_limit, weight, model_access_json, credential_state,
credential_observed_at, quota_access_state, quota_evidence,
quota_access_observed_at, quota_reset_at, quota_limit_window_minutes,
quota_access_observed_at, quota_reset_at, quota_exhaustion_deadline, quota_limit_window_minutes,
quota_observed_at, last_error_reason, last_error_message, created_at, updated_at
from provider_accounts
left join (select id as location_proxy_id, enabled as proxy_enabled, max_websocket_connections, auto_location, detected_location_json, location_country, location_region, location_city, location_timezone from outbound_proxies) proxy_location
@@ -209,7 +209,7 @@ impl ProviderAccountRepository for PgProviderAccountRepository {
upstream_account_id, plan_type, authentication_kind, credential_revision, has_refresh_token,
access_token_expires_at, next_refresh_at, enabled, quota_settings, quota_paused, auto_use_quota_credits, concurrency_limit, weight, model_access_json, credential_state,
credential_observed_at, quota_access_state, quota_evidence,
quota_access_observed_at, quota_reset_at, quota_limit_window_minutes,
quota_access_observed_at, quota_reset_at, quota_exhaustion_deadline, quota_limit_window_minutes,
quota_observed_at, last_error_reason, last_error_message, created_at, updated_at
from provider_accounts
left join (select id as location_proxy_id, enabled as proxy_enabled, max_websocket_connections, auto_location, detected_location_json, location_country, location_region, location_city, location_timezone from outbound_proxies) proxy_location
@@ -620,6 +620,7 @@ impl ProviderAccountAdminRepository for PgProviderAccountRepository {
quota_evidence = null,
quota_access_observed_at = now(),
quota_reset_at = null,
quota_exhaustion_deadline = null,
quota_limit_window_minutes = null,
last_error_reason = null,
last_error_message = null,
@@ -812,6 +813,7 @@ pub(crate) async fn upsert_provider_account_in_transaction(
quota_evidence = null,
quota_access_observed_at = null,
quota_reset_at = null,
quota_exhaustion_deadline = null,
quota_limit_window_minutes = null,
credential_observed_at = excluded.credential_observed_at,
quota_observed_at = null,
@@ -881,6 +883,7 @@ pub(crate) async fn rotate_provider_account_in_transaction(
let upstream_account_id =
replacement_identity.and_then(ProviderAccountIdentity::upstream_account_id);
// 事务时间可能早于应用写入的额度观测,保留既有时间下界,避免轮换破坏时间约束
let previous = to_i64(update.expected_revision.get())?;
let next = sqlx::query_scalar::<_, i64>(
"update provider_accounts
set name = case when $14 or $16 then name else $4 end,
@@ -895,6 +898,7 @@ pub(crate) async fn rotate_provider_account_in_transaction(
quota_evidence = case when $11 then null else quota_evidence end,
quota_access_observed_at = case when $11 then null else quota_access_observed_at end,
quota_reset_at = case when $11 then null else quota_reset_at end,
quota_exhaustion_deadline = case when $11 then null else quota_exhaustion_deadline end,
quota_limit_window_minutes = case when $11 then null else quota_limit_window_minutes end,
provider_credentials_json = $7,
credential_revision = credential_revision + 1,
@@ -921,7 +925,7 @@ pub(crate) async fn rotate_provider_account_in_transaction(
)
.bind(&update.account_id)
.bind(&scope.provider_kind)
.bind(to_i64(update.expected_revision.get())?)
.bind(previous)
.bind(&profile.name)
.bind(&profile.email)
.bind(&profile.plan_type)
@@ -960,6 +964,20 @@ pub(crate) async fn rotate_provider_account_in_transaction(
id: update.account_id.clone(),
kind: ConflictKind::StaleRevision,
})?;
if let Some(etag) = update.preserve_catalog_etag.as_deref()
&& !replace_identity
&& !reauthorization
{
PgProviderAccountRepository::carry_model_catalog(
transaction,
&update.account_id,
previous,
next,
etag,
)
.await
.map_err(|error| postgres_unavailable("carry account model catalog", error))?;
}
Revision::new(to_u64(next)?)
}
@@ -1153,8 +1171,12 @@ pub(super) async fn import_provider_accounts_in_transaction(
}
let mut account_ids = Vec::with_capacity(command.accounts.len());
let mut credential_revisions = std::collections::BTreeMap::new();
let mut created_ids = BTreeSet::new();
for account in &command.accounts {
let (id, revision) = upsert_provider_account_in_transaction(transaction, account).await?;
if revision.get() == 1 {
created_ids.insert(id.clone());
}
credential_revisions.insert(id.clone(), revision);
account_ids.push(id);
}
@@ -1197,6 +1219,7 @@ pub(super) async fn import_provider_accounts_in_transaction(
}
append_admin_audit_event_in_transaction(transaction, command.audit, revision).await?;
Ok(ProviderAccountAdminImport {
created_ids,
config_revision: revision,
account_ids,
credential_revisions,
@@ -1286,7 +1309,7 @@ impl PgProviderAccountRepository {
upstream_account_id, plan_type, authentication_kind, credential_revision, has_refresh_token,
access_token_expires_at, next_refresh_at, enabled, quota_settings, quota_paused, auto_use_quota_credits, concurrency_limit, weight, model_access_json, credential_state,
credential_observed_at, quota_access_state, quota_evidence,
quota_access_observed_at, quota_reset_at, quota_limit_window_minutes,
quota_access_observed_at, quota_reset_at, quota_exhaustion_deadline, quota_limit_window_minutes,
quota_observed_at, last_error_reason, last_error_message, created_at, updated_at
from provider_accounts
left join (select id as location_proxy_id, enabled as proxy_enabled, max_websocket_connections, auto_location, detected_location_json, location_country, location_region, location_city, location_timezone from outbound_proxies) proxy_location
@@ -1325,7 +1348,7 @@ where
let result = sqlx::query(
"update provider_accounts
set quota_access_observed_at = $3, quota_access_state = $4,
quota_evidence = $5, quota_reset_at = $6, quota_limit_window_minutes = $7,
quota_evidence = $5, quota_reset_at = $6, quota_limit_window_minutes = $7, quota_exhaustion_deadline = $8,
updated_at = greatest(now(), updated_at, $3)
where id = $1 and credential_revision = $2
and (quota_access_observed_at is null or quota_access_observed_at <= $3)",
@@ -1337,6 +1360,7 @@ where
.bind(state.evidence().map(QuotaEvidence::as_str))
.bind(state.reset_at().map(DateTime::<Utc>::from))
.bind(state.limit_window_minutes().map(i32::from))
.bind(state.exhaustion_deadline().map(DateTime::<Utc>::from))
.execute(executor)
.await
.map_err(|source| postgres_unavailable("apply provider quota access", source))?;
@@ -1358,7 +1382,7 @@ where
let state = observation.state;
let observed_at = DateTime::<Utc>::from(observation.observed_at);
let access_observed_at = state.observed_at().map(DateTime::<Utc>::from);
let merge_base = observation.quota_pause.as_ref().and_then(|d| d.merge_base);
let merge_base = observation.merge_base;
let result = sqlx::query(
"update provider_accounts
set provider_quota_json = $3, quota_observed_at = $4,
@@ -1380,6 +1404,10 @@ where
when $7::timestamptz is not null
and (quota_access_observed_at is null or quota_access_observed_at <= $7)
then $8 else quota_reset_at end,
quota_exhaustion_deadline = case
when $7::timestamptz is not null
and (quota_access_observed_at is null or quota_access_observed_at <= $7)
then $15 else quota_exhaustion_deadline end,
quota_limit_window_minutes = case
when $7::timestamptz is not null
and (quota_access_observed_at is null or quota_access_observed_at <= $7)
@@ -1388,7 +1416,7 @@ where
where id = $1 and credential_revision = $2
and (quota_observed_at is null or quota_observed_at <= $4)
and ($11::jsonb is null or (quota_settings = $11 and quota_observed_at is distinct from $4))
and (not $12 or quota_observed_at is not distinct from $13)",
and (not $12 or (quota_observed_at is not distinct from $13 and quota_observed_at is distinct from $4))",
)
.bind(account_id)
.bind(to_i64(expected_revision.get())?)
@@ -1409,6 +1437,7 @@ where
.bind(merge_base.is_some())
.bind(merge_base.and_then(|base| base.observed_at).map(DateTime::<Utc>::from))
.bind(state.limit_window_minutes().map(i32::from))
.bind(state.exhaustion_deadline().map(DateTime::<Utc>::from))
.execute(executor)
.await
.map_err(|source| postgres_unavailable("compare and swap provider quota", source))?;
@@ -175,6 +175,7 @@ pub struct ImportProviderAccounts {
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProviderAccountAdminImport {
pub created_ids: std::collections::BTreeSet<String>,
pub config_revision: Revision,
pub account_ids: Vec<String>,
/// 与导入同一事务返回的最终凭据版本,避免提交后再查到另一轮写入
@@ -296,6 +297,8 @@ pub struct ProviderCredentialUpdate {
pub access_token_expires_at: Option<DateTime<Utc>>,
pub next_refresh_at: Option<DateTime<Utc>>,
pub preserve_profile: bool,
/// 已核实同一身份续期时,允许把匹配此标识的目录续接至新凭据版本
pub preserve_catalog_etag: Option<String>,
pub preserve_credential_state: bool,
pub preserve_access_token_expiry: bool,
}
@@ -331,7 +334,7 @@ impl ProviderAccountStateUpdate {
pub(crate) const ACCOUNT_SELECT: &str = "select coalesce(proxy_enabled, true) as outbound_proxy_enabled, coalesce(max_websocket_connections, 0) as outbound_proxy_max_websocket_connections, auto_location, detected_location_json, location_country, location_region, location_city, location_timezone, outbound_proxy_id, outbound_proxy_url, id, provider_kind, name, notes, email, upstream_user_id,
upstream_account_id, plan_type, authentication_kind, provider_credentials_json, credential_revision,
has_refresh_token, access_token_expires_at, next_refresh_at, enabled, quota_settings, quota_paused, auto_use_quota_credits, concurrency_limit, weight, model_access_json, credential_state,
quota_access_state, quota_evidence, quota_access_observed_at, quota_reset_at, quota_limit_window_minutes,
quota_access_state, quota_evidence, quota_access_observed_at, quota_reset_at, quota_exhaustion_deadline, quota_limit_window_minutes,
last_error_reason, last_error_message,
credential_observed_at, quota_observed_at, created_at, updated_at
from provider_accounts
@@ -342,7 +345,7 @@ pub(crate) const ACCOUNT_SELECT: &str = "select coalesce(proxy_enabled, true) as
pub(crate) const ACCOUNT_SELECT_BY_IDS: &str = "select coalesce(proxy_enabled, true) as outbound_proxy_enabled, coalesce(max_websocket_connections, 0) as outbound_proxy_max_websocket_connections, auto_location, detected_location_json, location_country, location_region, location_city, location_timezone, outbound_proxy_id, outbound_proxy_url, id, provider_kind, name, notes, email, upstream_user_id,
upstream_account_id, plan_type, authentication_kind, provider_credentials_json, credential_revision,
has_refresh_token, access_token_expires_at, next_refresh_at, enabled, quota_settings, quota_paused, auto_use_quota_credits, concurrency_limit, weight, model_access_json, credential_state,
quota_access_state, quota_evidence, quota_access_observed_at, quota_reset_at, quota_limit_window_minutes,
quota_access_state, quota_evidence, quota_access_observed_at, quota_reset_at, quota_exhaustion_deadline, quota_limit_window_minutes,
last_error_reason, last_error_message,
credential_observed_at, quota_observed_at, created_at, updated_at
from provider_accounts
@@ -354,7 +357,7 @@ pub(crate) const ACCOUNT_SELECT_BY_IDS: &str = "select coalesce(proxy_enabled, t
pub(crate) const REFRESH_CANDIDATES_SELECT: &str = "select coalesce(proxy_enabled, true) as outbound_proxy_enabled, coalesce(max_websocket_connections, 0) as outbound_proxy_max_websocket_connections, auto_location, detected_location_json, location_country, location_region, location_city, location_timezone, outbound_proxy_id, outbound_proxy_url, id, provider_kind, name, notes, email, upstream_user_id,
upstream_account_id, plan_type, authentication_kind, provider_credentials_json, credential_revision,
has_refresh_token, access_token_expires_at, next_refresh_at, enabled, quota_settings, quota_paused, auto_use_quota_credits, concurrency_limit, weight, model_access_json, credential_state,
quota_access_state, quota_evidence, quota_access_observed_at, quota_reset_at, quota_limit_window_minutes,
quota_access_state, quota_evidence, quota_access_observed_at, quota_reset_at, quota_exhaustion_deadline, quota_limit_window_minutes,
last_error_reason, last_error_message,
credential_observed_at, quota_observed_at, created_at, updated_at
from provider_accounts
@@ -600,6 +603,7 @@ pub(super) fn quota_state_from_row(row: &sqlx::postgres::PgRow) -> StoreResult<Q
let quota_access_state = parse_quota_access_state(&get::<String>(row, "quota_access_state")?)?;
let quota_evidence = parse_quota_evidence(get(row, "quota_evidence")?)?;
let quota_access_observed_at = get::<Option<DateTime<Utc>>>(row, "quota_access_observed_at")?;
let deadline = get::<Option<DateTime<Utc>>>(row, "quota_exhaustion_deadline")?;
let quota_reset_at = get::<Option<DateTime<Utc>>>(row, "quota_reset_at")?;
let minutes = get::<Option<i32>>(row, "quota_limit_window_minutes")?
.map(u16::try_from)
@@ -611,6 +615,10 @@ pub(super) fn quota_state_from_row(row: &sqlx::postgres::PgRow) -> StoreResult<Q
quota_access_observed_at.map(Into::into),
quota_reset_at.map(Into::into),
)
.map(|state| state.with_limit_window_minutes(minutes))
.map(|state| {
state
.with_limit_window_minutes(minutes)
.with_exhaustion_deadline(deadline.map(Into::into))
})
.ok_or_else(|| invalid("invalid persisted quota fact"))
}
@@ -109,7 +109,7 @@ pub(crate) async fn load_account_statuses<'e, E: sqlx::Executor<'e, Database = s
use super::rows::{account_status_facts_from_row, get};
let rows = sqlx::query(
"select id, enabled, quota_paused, concurrency_limit, credential_revision, quota_observed_at, credential_state, access_token_expires_at,
quota_access_state, quota_evidence, quota_access_observed_at, quota_reset_at, quota_limit_window_minutes,
quota_access_state, quota_evidence, quota_access_observed_at, quota_reset_at, quota_exhaustion_deadline, quota_limit_window_minutes,
last_error_reason, last_error_message
from provider_accounts",
)
@@ -152,7 +152,7 @@ impl RuntimeSettingsRepository for PgRuntimeSettingsRepository {
pub(crate) async fn load_runtime_settings_from_pool(pool: &PgPool) -> StoreResult<RuntimeSettings> {
let row = sqlx::query_as::<_, RuntimeSettingsRow>(
"select provider_request_profiles_json, config_revision, admin_api_key, refresh_margin_seconds, request_location_json, request_location_enabled, codex_privacy_policy_json,
"select antigravity_background_refresh, provider_request_profiles_json, config_revision, admin_api_key, refresh_margin_seconds, request_location_json, request_location_enabled, codex_privacy_policy_json,
refresh_concurrency, max_concurrent_per_account,
rotation_strategy, smart_scheduling_json, quota_reset_window_weights_json, model_mappings_json, usage_retention_days, ops_event_retention_days,
audit_retention_days, min_codex_desktop_version,
@@ -173,6 +173,21 @@ pub(crate) async fn load_runtime_settings_from_pool(pool: &PgPool) -> StoreResul
}
impl ProviderRuntimePolicyPort for PgRuntimeSettingsRepository {
fn antigravity_background_refresh(
&self,
) -> futures::future::BoxFuture<'_, Result<bool, ProviderStoreError>> {
Box::pin(async move {
sqlx::query_scalar(
"select antigravity_background_refresh from runtime_settings where id = 1",
)
.fetch_one(&self.pool)
.await
.map_err(|source| {
crate::provider_unavailable("load Antigravity background refresh", source)
})
})
}
fn load_openai_request_settings(
&self,
) -> futures::future::BoxFuture<
@@ -355,7 +370,7 @@ pub(crate) async fn load_runtime_settings_in_transaction(
transaction: &mut Transaction<'_, Postgres>,
) -> StoreResult<RuntimeSettings> {
let row = sqlx::query_as::<_, RuntimeSettingsRow>(
"select provider_request_profiles_json, config_revision, admin_api_key, refresh_margin_seconds, request_location_json, request_location_enabled, codex_privacy_policy_json,
"select antigravity_background_refresh, provider_request_profiles_json, config_revision, admin_api_key, refresh_margin_seconds, request_location_json, request_location_enabled, codex_privacy_policy_json,
refresh_concurrency, max_concurrent_per_account,
rotation_strategy, smart_scheduling_json, quota_reset_window_weights_json, model_mappings_json, usage_retention_days, ops_event_retention_days,
audit_retention_days, min_codex_desktop_version,
@@ -447,6 +462,7 @@ pub(crate) async fn update_runtime_settings_in_transaction(
openai_request_settings_json = $36,
openai_websocket_pool_json = $37,
prompt_rewrite_rules_json = $38,
antigravity_background_refresh = $39,
updated_at = now()
where id = 1
returning config_revision",
@@ -497,6 +513,7 @@ pub(crate) async fn update_runtime_settings_in_transaction(
.bind(sqlx::types::Json(&update.values.openai_request_settings))
.bind(sqlx::types::Json(&update.values.openai_websocket_pool))
.bind(sqlx::types::Json(&update.values.prompt_rewrite_rules))
.bind(update.values.antigravity_background_refresh)
.fetch_optional(&mut **transaction)
.await
.map_err(|source| postgres_unavailable("update runtime settings in transaction", source))?
@@ -561,6 +578,7 @@ pub(crate) async fn update_admin_api_key_in_transaction(
#[derive(sqlx::FromRow)]
struct RuntimeSettingsRow {
antigravity_background_refresh: bool,
provider_request_profiles_json: sqlx::types::Json<
std::collections::BTreeMap<String, serde_json::Map<String, serde_json::Value>>,
>,
@@ -634,6 +652,7 @@ fn runtime_settings_from_row(row: RuntimeSettingsRow) -> StoreResult<RuntimeSett
model_mappings: row.model_mappings_json.0,
updated_at: row.updated_at,
values: gateway_admin::model::settings::RuntimeSettingsValues {
antigravity_background_refresh: row.antigravity_background_refresh,
openai_websocket_pool: row.openai_websocket_pool_json.0,
openai_request_settings: row.openai_request_settings_json.0,
refresh_margin_seconds: to_u64(row.refresh_margin_seconds)?,
@@ -20,6 +20,7 @@ use super::ClientApiKeySnapshot;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RuntimeSnapshotData {
pub schedules: gateway_core::account::duty::AccountSchedules,
pub config_revision: Revision,
pub observed_current_revision: Revision,
pub settings: SettingsValues,
@@ -63,12 +64,22 @@ pub trait RuntimeSnapshotRepository: Send + Sync {
#[derive(Clone)]
pub struct PgRuntimeSnapshotRepository {
pool: PgPool,
timezone: gateway_core::time::DeploymentTimeZone,
}
impl PgRuntimeSnapshotRepository {
#[must_use]
pub const fn new(pool: PgPool) -> Self {
Self { pool }
pub fn new(pool: PgPool) -> Self {
Self {
pool,
timezone: Default::default(),
}
}
#[must_use]
pub fn with_timezone(mut self, timezone: gateway_core::time::DeploymentTimeZone) -> Self {
self.timezone = timezone;
self
}
}
@@ -91,6 +102,8 @@ impl RuntimeSnapshotRepository for PgRuntimeSnapshotRepository {
let client_api_keys = load_client_keys(&mut transaction).await?;
let account_groups = load_account_groups(&mut transaction).await?;
let provider_accounts = load_provider_accounts(&mut transaction).await?;
let mut schedules = super::account_schedules::load_schedules(&mut transaction).await?;
schedules.timezone = self.timezone;
let group_memberships = load_group_memberships(&mut transaction).await?;
transaction
.commit()
@@ -100,6 +113,7 @@ impl RuntimeSnapshotRepository for PgRuntimeSnapshotRepository {
let observed_current_revision =
RuntimeSnapshotRepository::current_config_revision(self).await?;
Ok(RuntimeSnapshotData {
schedules,
config_revision,
observed_current_revision,
settings,
@@ -197,7 +211,8 @@ impl SnapshotStorePort for PgRuntimeSnapshotRepository {
account_groups,
provider_accounts,
group_memberships,
))
)
.with_schedules(data.schedules))
})
}
@@ -677,6 +677,7 @@ impl RedisProviderLeaseCoordinator {
recent_requests: 0,
last_started_at: signal.last_started_at.map(Into::into),
quota_reset_at: None,
daily_used_percent: None,
quota_reset_windows: None,
quota_remaining_rank: None,
cooldown: None,
@@ -2,6 +2,70 @@
use super::*;
#[tokio::test]
async fn quota_deadline_agrees_across_account_filters_summary_and_detail() {
let Some(database) = TestDatabase::create("quota_deadline").await else {
return;
};
let repository = PgProviderAccountRepository::new(database.pool.clone());
let store = admin_account_store(&database.pool);
let now = SystemTime::now();
let observed = now - Duration::from_secs(300);
let id = "acct_quota_window";
repository
.insert_provider_account(account(id, id))
.await
.unwrap();
for (deadline, status) in [
(now + Duration::from_secs(60), AccountStatus::QuotaExhausted),
(now, AccountStatus::Normal),
] {
repository
.apply_quota_access(QuotaAccessChange {
account_id: ProviderAccountId::new(id).unwrap(),
expected_revision: CredentialRevision::new(1).unwrap(),
state: QuotaState::exhausted(QuotaEvidence::UsageLimitReached, observed, None)
.with_exhaustion_deadline(Some(deadline)),
})
.await
.unwrap();
let page = store
.list_accounts(
AccountListQuery {
page: 1,
page_size: PageSize::new(20).unwrap(),
provider_kind: None,
group_filter: None,
search: None,
status: Some(status),
sort: None,
},
Default::default(),
)
.await
.unwrap();
assert_eq!(page.total, 1);
assert_eq!(
page.summary.normal,
u64::from(status == AccountStatus::Normal)
);
assert_eq!(
page.summary.quota_exhausted,
u64::from(status == AccountStatus::QuotaExhausted)
);
assert_eq!(page.items[0].projection.status, status);
let detail = store
.load_account(id, Default::default())
.await
.unwrap()
.unwrap();
assert_eq!(detail.projection.status, status);
assert!(detail.account.quota.is_exhausted());
assert!(detail.account.quota.reset_at().is_none());
}
database.close().await;
}
#[tokio::test]
async fn model_cooldown_status_filter_and_details_share_revision_and_expiry_rules() {
use gateway_core::provider_ports::{ProviderCooldownScope, ProviderScopedCooldown};
@@ -1,6 +1,7 @@
//! 验证账号授权回执的并发幂等、事务回滚与过期清理
use chrono::SubsecRound;
use gateway_admin::model::provider_credentials::CredentialChange;
use gateway_admin::model::provider_credentials::{
AuthorizationReceiptKey, PreparedCredentialRotationFacts,
};
@@ -178,7 +179,10 @@ async fn concurrent_authorization_retries_share_one_account_write_and_one_receip
);
let (first, second) = (first.unwrap(), second.unwrap());
assert_eq!(first.result, second.result);
assert_ne!(first.newly_committed, second.newly_committed);
assert!(matches!(
(first.change, second.change),
(Some(CredentialChange::Created), None) | (None, Some(CredentialChange::Created))
));
assert_eq!(first.result.credential_revision.unwrap().get(), 1);
let counts: (i64, i64, i64) = sqlx::query_as("select (select count(*) from provider_accounts), (select count(*) from admin_audit_events where action='authorize'), (select count(*) from provider_authorization_receipts)")
.fetch_one(&database.pool).await.unwrap();
@@ -249,7 +253,8 @@ async fn a_receipt_failure_rolls_back_accounts_audit_and_config_revision() {
.commit_authorization(command, &context)
.await
.unwrap()
.newly_committed
.change
.is_some()
);
database.close().await;
}
@@ -309,6 +314,7 @@ fn reauthorization(
email: Some("new@example.com".into()),
plan_type: Some("plus".into()),
preserve_profile: false,
preserve_catalog_etag: None,
preserve_credential_state: false,
preserve_access_token_expiry: false,
provider_material: ProviderDocument::new(OpaqueProviderData::new(
@@ -363,6 +369,7 @@ async fn reauthorization_keeps_disabled_account_quota_only_for_the_same_identity
observed_at,
state: QuotaState::allowed(observed_at),
expected_connection: None,
merge_base: None,
quota_pause: None,
plan_type: None,
};
@@ -471,7 +478,7 @@ async fn reauthorization_replay_keeps_the_committed_revision_and_later_profile_e
.commit_authorization(command.clone(), &context)
.await
.unwrap();
assert!(!replayed.newly_committed);
assert!(replayed.change.is_none());
assert_eq!(replayed.result, committed.result);
let account: (String, i64) =
sqlx::query_as("select name, credential_revision from provider_accounts where id=$1")
@@ -206,6 +206,7 @@ async fn core_quota_batch_reads_only_observed_accounts_in_one_contract_call() {
let observed_at = SystemTime::now();
let outcome = repository
.compare_and_swap_quota(QuotaObservation {
merge_base: None,
quota_pause: None,
expected_connection: None,
plan_type: None,
@@ -284,6 +285,7 @@ async fn quota_observation_touch_preserves_quota_state_and_advances_account_upda
assert_eq!(
repository
.compare_and_swap_quota(QuotaObservation {
merge_base: None,
quota_pause: None,
expected_connection: None,
plan_type: None,
@@ -385,6 +387,7 @@ async fn delayed_provider_observations_cannot_overwrite_newer_state_or_quota() {
.expect("older observation time");
let quota = |marker: &str, observed_at| QuotaObservation {
merge_base: None,
quota_pause: None,
expected_connection: None,
plan_type: Some(if marker == "newer" { "pro" } else { "plus" }.to_owned()),
@@ -466,6 +469,7 @@ async fn profile_changes_survive_inflight_background_and_manual_token_refresh()
let repository = PgProviderAccountRepository::new(database.pool.clone());
let id = ProviderAccountId::new("acct_plan_refresh").unwrap();
let mut seed = account(id.as_str(), "user-plan-refresh");
seed.provider_kind = "antigravity".into();
seed.plan_type = Some("plus".to_owned());
repository.insert_provider_account(seed).await.unwrap();
let original = repository.get_account(&id).await.unwrap().unwrap();
@@ -493,6 +497,7 @@ async fn profile_changes_survive_inflight_background_and_manual_token_refresh()
let config_revision = current_revision(&database.pool).await;
let observed_at = SystemTime::now();
let observation = QuotaObservation {
merge_base: None,
quota_pause: None,
expected_connection: None,
account_id: id.clone(),
@@ -518,6 +523,22 @@ async fn profile_changes_survive_inflight_background_and_manual_token_refresh()
.await
.unwrap();
let catalog = gateway_core::account::AccountCatalogObservation {
account_id: id.clone(),
revision: original.revision(),
plan: Some("pro".into()),
etag: Some("registration".into()),
observed_at: SystemTime::UNIX_EPOCH + Duration::from_secs(100),
};
// 首次目录写持有账号共享锁,续期不能漏掉等待 CAS 期间刚提交的正文
let mut publishing = database.pool.begin().await.unwrap();
let publisher: i32 =
sqlx::query_scalar("select pg_backend_pid() from provider_accounts where id=$1 for share")
.bind(id.as_str())
.fetch_one(&mut *publishing)
.await
.unwrap();
// 刷新已准备好旧资料,CAS 提交仍须保留数据库中的新名称和套餐
let refresh = CredentialCasUpdate::new(
id.clone(),
@@ -539,12 +560,31 @@ async fn profile_changes_survive_inflight_background_and_manual_token_refresh()
None,
)
.unwrap()
.preserving_profile();
assert!(matches!(
repository
.preserving_profile()
.with_preserved_catalog_etag(Some("registration".into()));
let pool = database.pool.clone();
let renewing = tokio::spawn(async move {
PgProviderAccountRepository::new(pool)
.compare_and_swap_credential(refresh)
.await
.unwrap(),
.unwrap()
});
tokio::time::timeout(Duration::from_secs(5), async {
loop {
let waiting: bool = sqlx::query_scalar("select exists(select 1 from pg_stat_activity where $1 = any(pg_blocking_pids(pid)))")
.bind(publisher).fetch_one(&database.admin).await.unwrap();
if waiting { break; }
tokio::task::yield_now().await;
}
}).await.unwrap();
sqlx::query("insert into provider_account_model_catalogs (account_id, credential_revision, plan_type, etag, observed_at, document)
values ($1, $2, $3, $4, $5, $6)")
.bind(id.as_str()).bind(i64::try_from(catalog.revision.get()).unwrap())
.bind(&catalog.plan).bind(&catalog.etag).bind(chrono::DateTime::<Utc>::from(catalog.observed_at))
.bind(b"catalog".as_slice()).execute(&mut *publishing).await.unwrap();
publishing.commit().await.unwrap();
assert!(matches!(
renewing.await.unwrap(),
CredentialCasOutcome::Updated(_)
));
let current = repository.get_account(&id).await.unwrap().unwrap();
@@ -559,6 +599,7 @@ async fn profile_changes_survive_inflight_background_and_manual_token_refresh()
saved_quota
);
let stale = QuotaObservation {
merge_base: None,
quota_pause: None,
expected_connection: None,
plan_type: Some("free".to_owned()),
@@ -572,11 +613,12 @@ async fn profile_changes_survive_inflight_background_and_manual_token_refresh()
let mut credential =
credential_update(id.as_str(), current.revision().get(), "manual-refreshed");
credential.preserve_profile = true;
credential.preserve_catalog_etag = catalog.etag.clone();
repository
.rotate_provider_account(RotateProviderAccount {
settings: None,
scope: ProviderAccountAdminScope {
provider_kind: "openai".to_owned(),
provider_kind: "antigravity".to_owned(),
},
profile: profile(id.as_str(), "stale profile"),
replacement_identity: None,
@@ -589,6 +631,20 @@ async fn profile_changes_survive_inflight_background_and_manual_token_refresh()
assert_eq!(refreshed.plan_type(), Some("pro"));
assert_eq!(refreshed.name(), "renamed team");
assert_eq!(refreshed.email(), original.email());
let catalogs = repository
.load_account_catalogs(original.provider())
.await
.unwrap();
assert_eq!(catalogs.len(), 1);
assert_eq!(catalogs[0].accounts[0].revision, refreshed.revision());
assert_eq!(catalogs[0].accounts[0].observed_at, catalog.observed_at);
assert_eq!(catalogs[0].document.as_ref(), b"catalog");
assert!(
!repository
.save_account_catalog(&catalog, b"late")
.await
.unwrap()
);
saved_quota[0].expected_revision = refreshed.revision();
assert_eq!(
repository
@@ -600,6 +656,7 @@ async fn profile_changes_survive_inflight_background_and_manual_token_refresh()
let observed_at = SystemTime::now();
repository
.compare_and_swap_quota(QuotaObservation {
merge_base: None,
quota_pause: None,
expected_connection: None,
account_id: id.clone(),
@@ -628,6 +685,70 @@ async fn profile_changes_survive_inflight_background_and_manual_token_refresh()
database.close().await;
}
#[tokio::test]
async fn catalog_carry_rejects_a_different_revision_plan_registration_or_identity() {
let Some(database) = TestDatabase::create("catalog_carry_fences").await else {
return;
};
let repository = PgProviderAccountRepository::new(database.pool.clone());
let provider = ProviderKind::new("antigravity").unwrap();
for case in ["revision", "plan", "registration", "identity", "explicit"] {
let id = ProviderAccountId::new(format!("acct_{case}")).unwrap();
let mut seed = account(id.as_str(), case);
seed.provider_kind = provider.as_str().into();
repository.insert_provider_account(seed).await.unwrap();
let original = repository.get_account(&id).await.unwrap().unwrap();
let observation = gateway_core::account::AccountCatalogObservation {
account_id: id.clone(),
revision: original.revision(),
plan: original.plan_type().map(str::to_owned),
etag: Some("registration".into()),
observed_at: SystemTime::now(),
};
assert!(
repository
.save_account_catalog(&observation, b"previous")
.await
.unwrap()
);
if case == "revision" {
sqlx::query("update provider_accounts set credential_revision=credential_revision+1 where id=$1")
.bind(id.as_str()).execute(&database.pool).await.unwrap();
}
let current = repository.get_account(&id).await.unwrap().unwrap();
let mut credential = credential_update(id.as_str(), current.revision().get(), "renewed");
credential.preserve_profile = case != "plan";
credential.preserve_catalog_etag = match case {
"registration" => Some("new-registration".into()),
"explicit" => None,
_ => observation.etag,
};
repository
.rotate_provider_account(RotateProviderAccount {
settings: None,
scope: ProviderAccountAdminScope {
provider_kind: provider.as_str().into(),
},
profile: profile(id.as_str(), "updated"),
replacement_identity: (case == "identity")
.then(|| ProviderAccountIdentity::new("replacement".into(), None)),
credential,
audit: audit(&format!("audit_{case}"), "refresh", id.as_str()),
})
.await
.unwrap();
assert!(
repository
.load_account_catalogs(&provider)
.await
.unwrap()
.is_empty(),
"{case}"
);
}
database.close().await;
}
#[tokio::test]
async fn credential_error_message_is_persisted_and_cleared_on_recovery() {
let Some(database) = TestDatabase::create("provider_account_state_message").await else {
@@ -1811,6 +1932,7 @@ async fn account_enable_preserves_facts_and_explicit_recovery_clears_them() {
let observed_at = SystemTime::now();
repository
.compare_and_swap_quota(QuotaObservation {
merge_base: None,
quota_pause: None,
expected_connection: None,
plan_type: None,
@@ -2154,6 +2276,7 @@ async fn admin_import_updates_the_same_verified_identity_without_rebinding_it()
.await
.expect("create imported account");
assert_eq!(imported.account_ids, ["acct_admin_upsert"]);
assert!(imported.created_ids.contains("acct_admin_upsert"));
sqlx::query(
"update provider_accounts
set provider_quota_json = '{}'::jsonb, quota_observed_at = now(),
@@ -2179,6 +2302,7 @@ async fn admin_import_updates_the_same_verified_identity_without_rebinding_it()
.await
.expect("update the same imported identity");
assert_eq!(imported.account_ids, ["acct_admin_upsert"]);
assert!(imported.created_ids.is_empty());
let revision = imported.config_revision;
assert_eq!(revision.get(), 3);
let row: (
@@ -3469,6 +3593,7 @@ pub(super) fn account(id: &str, upstream_user_id: &str) -> NewProviderAccount {
fn credential_update(account_id: &str, revision: u64, marker: &str) -> ProviderCredentialUpdate {
ProviderCredentialUpdate {
preserve_profile: false,
preserve_catalog_etag: None,
preserve_credential_state: false,
preserve_access_token_expiry: false,
account_id: account_id.to_owned(),
@@ -4018,6 +4143,7 @@ async fn disabling_quota_credits_revokes_credit_only_access_even_with_a_late_obs
};
let observe = async |state: QuotaState| {
let observation = QuotaObservation {
merge_base: None,
quota_pause: None,
expected_connection: None,
plan_type: None,
@@ -16,6 +16,7 @@ async fn connection_changes_reject_in_flight_quota_writes() {
let id = ProviderAccountId::new("acct_peer").unwrap();
let current = repository.get_account(&id).await.unwrap().unwrap();
let observation = QuotaObservation {
merge_base: None,
quota_pause: None,
expected_connection: Some(UpstreamConnection::for_account(&current)),
account_id: id.clone(),
@@ -66,6 +67,7 @@ async fn large_quota_uses_shared_snapshot_and_cannot_reappear_after_revocation()
let current = repository.get_account(&id).await.unwrap().unwrap();
let now = SystemTime::now();
let observation = QuotaObservation {
merge_base: None,
quota_pause: None,
expected_connection: Some(UpstreamConnection::for_account(&current)),
account_id: id.clone(),
@@ -158,10 +160,10 @@ async fn quota_merge_can_only_replace_the_snapshot_it_read() {
let start = SystemTime::UNIX_EPOCH + Duration::from_secs(1_800_000_000);
let later = start + Duration::from_secs(1);
let observed = |base, observed_at, paused| QuotaObservation {
merge_base: Some(QuotaMergeBase { observed_at: base }),
quota_pause: Some(QuotaPauseDecision {
limits: limits.clone(),
paused,
merge_base: Some(QuotaMergeBase { observed_at: base }),
}),
expected_connection: None,
account_id: id.clone(),
@@ -223,6 +225,7 @@ async fn snapshot_commit_preserves_newer_quota_failure() {
let id = ProviderAccountId::new("acct_peer").unwrap();
let current = repository.get_account(&id).await.unwrap().unwrap();
let now = SystemTime::now();
let deadline = SystemTime::UNIX_EPOCH + Duration::from_secs(4_000_000_000);
repository
.apply_quota_access(QuotaAccessChange {
account_id: id.clone(),
@@ -232,11 +235,13 @@ async fn snapshot_commit_preserves_newer_quota_failure() {
now + Duration::from_secs(1),
None,
)
.with_limit_window_minutes(Some(10080)),
.with_limit_window_minutes(Some(10080))
.with_exhaustion_deadline(Some(deadline)),
})
.await
.unwrap();
let observation = QuotaObservation {
merge_base: None,
quota_pause: None,
expected_connection: Some(UpstreamConnection::for_account(&current)),
account_id: id.clone(),
@@ -255,6 +260,7 @@ async fn snapshot_commit_preserves_newer_quota_failure() {
);
let account = repository.get_account(&id).await.unwrap().unwrap();
assert!(account.quota().is_exhausted());
assert_eq!(account.quota().exhaustion_deadline(), Some(deadline));
assert_eq!(account.quota().limit_window_minutes(), Some(10080));
let persisted = repository
.get_quotas(std::slice::from_ref(&id))
@@ -307,6 +313,7 @@ async fn managed_proxy_changes_clear_snapshots_and_reject_old_connections() {
for change in ["url", "disabled"] {
let current = repository.get_account(&id).await.unwrap().unwrap();
let observation = QuotaObservation {
merge_base: None,
quota_pause: None,
expected_connection: Some(UpstreamConnection::for_account(&current)),
account_id: id.clone(),
@@ -375,6 +382,7 @@ async fn managed_proxy_changes_clear_snapshots_and_reject_old_connections() {
// 模拟代理更新持有账号锁,额度查询已经开始但必须等待提交的交错
let current = repository.get_account(&id).await.unwrap().unwrap();
let observation = QuotaObservation {
merge_base: None,
quota_pause: None,
expected_connection: Some(UpstreamConnection::for_account(&current)),
account_id: id.clone(),
@@ -419,3 +427,68 @@ async fn managed_proxy_changes_clear_snapshots_and_reject_old_connections() {
assert!(repository.get_quotas(&[id]).await.unwrap().is_empty());
database.close().await;
}
#[tokio::test]
async fn concurrent_quota_merges_require_the_current_document_even_without_pause_settings() {
use gateway_core::account::QuotaMergeBase;
let Some(db) = TestDatabase::create("quota_merge_concurrency").await else {
return;
};
let repo = PgProviderAccountRepository::new(db.pool.clone());
repo.insert_provider_account(account("acct_peer", "fixture"))
.await
.unwrap();
let id = ProviderAccountId::new("acct_peer").unwrap();
let current = repo.get_account(&id).await.unwrap().unwrap();
let now = SystemTime::UNIX_EPOCH + Duration::from_secs(2_000_000_000);
let observation = |base, at, value| QuotaObservation {
merge_base: Some(QuotaMergeBase { observed_at: base }),
quota_pause: None,
expected_connection: Some(UpstreamConnection::for_account(&current)),
account_id: id.clone(),
expected_revision: current.revision(),
observed_at: at,
quota: OpaqueProviderData::new(json!({"groups":value}).as_object().unwrap().clone()),
plan_type: None,
state: QuotaState::allowed(at),
};
assert_eq!(
repo.compare_and_swap_quota(observation(None, now, 0))
.await
.unwrap(),
QuotaWriteOutcome::Updated
);
assert_eq!(
repo.compare_and_swap_quota(observation(Some(now), now, 3))
.await
.unwrap(),
QuotaWriteOutcome::Conflict
);
let later = now + Duration::from_micros(1);
let (a, b) = tokio::join!(
repo.compare_and_swap_quota(observation(Some(now), later, 1)),
repo.compare_and_swap_quota(observation(Some(now), later, 2))
);
assert!(matches!(
(a.unwrap(), b.unwrap()),
(QuotaWriteOutcome::Updated, QuotaWriteOutcome::Conflict)
| (QuotaWriteOutcome::Conflict, QuotaWriteOutcome::Updated)
));
assert_eq!(
repo.compare_and_swap_quota(observation(
Some(later),
later + Duration::from_micros(1),
3
))
.await
.unwrap(),
QuotaWriteOutcome::Updated
);
assert_eq!(
repo.get_quotas(&[id]).await.unwrap()[0]
.quota
.expose_to_provider()["groups"],
3
);
db.close().await;
}
@@ -21,6 +21,7 @@ async fn cross_kind_observations_preserve_time_bounds_and_stale_observation_fenc
let revision = CredentialRevision::new(1).expect("revision");
let quota_at = SystemTime::from(anchor - TimeDelta::milliseconds(400));
let observation = QuotaObservation {
merge_base: None,
quota_pause: None,
expected_connection: None,
plan_type: None,
@@ -22,6 +22,7 @@ pub(super) fn settings_with_margin(refresh_margin_seconds: u64) -> RuntimeSettin
("grok-latest".to_owned(), "grok-4.5".to_owned()),
]),
values: gateway_admin::model::settings::RuntimeSettingsValues {
antigravity_background_refresh: true,
openai_websocket_pool: Default::default(),
openai_request_settings: Default::default(),
codex_privacy_policy: Default::default(),
@@ -218,6 +219,37 @@ fn runtime_settings_require_model_when_warmup_is_enabled() {
assert!(settings.validate().is_err());
}
#[tokio::test]
async fn antigravity_refresh_defaults_to_scheduled_and_round_trips() {
let Some(database) = TestDatabase::create("antigravity_refresh").await else {
return;
};
let repository = PgRuntimeSettingsRepository::new(database.pool.clone());
assert!(
repository
.load_runtime_settings()
.await
.unwrap()
.values
.antigravity_background_refresh
);
for value in [false, true] {
let mut update = settings_with_margin(3600);
update.values.antigravity_background_refresh = value;
repository.update_runtime_settings(update).await.unwrap();
assert_eq!(
repository
.load_runtime_settings()
.await
.unwrap()
.values
.antigravity_background_refresh,
value
);
}
database.close().await;
}
#[tokio::test]
async fn warmup_settings_round_trip_with_database_constraint() {
let Some(database) = TestDatabase::create("warmup_settings").await else {
@@ -1,11 +1,13 @@
//! 管理端账号操作与客户端画像的适配入口
use crate::credential::catalog::CatalogQuery;
use crate::credential::catalog::CatalogService;
use crate::{
credential::{AuthorizationService, CredentialService, oauth::error},
profile::ReleaseService,
};
use async_trait::async_trait;
use gateway_admin::ports::provider::AccountFactsChange;
use gateway_admin::{
model::{
observability::{CalculatedBillingBreakdown, DashboardWireProfile, ProviderBillingInput},
@@ -108,10 +110,16 @@ impl ProviderAdmin for AntigravityAdmin {
async fn account_unavailable(&self, _: &ProviderAccountId) {
self.catalog.invalidate();
}
async fn account_facts_changed(&self, ids: &[ProviderAccountId]) {
async fn background_quota_refresh_enabled(&self) -> Result<bool, ProviderAdminError> {
self.credentials.background_refresh_enabled().await
}
async fn account_facts_changed(&self, change: AccountFactsChange<'_>) {
self.catalog.invalidate();
for id in ids {
let _ = self.catalog.account_models(id, false).await;
for id in change.ids {
let _ = self
.catalog
.account_changed(id, change.created_ids.contains(id))
.await;
}
}
fn dashboard_wire_profile(&self) -> Option<DashboardWireProfile> {
@@ -192,7 +200,12 @@ impl ProviderAdmin for AntigravityAdmin {
id: &ProviderAccountId,
refresh: bool,
) -> Result<ProviderModels, ProviderAdminError> {
self.catalog.account_models(id, refresh).await
let query = if refresh {
CatalogQuery::Refresh
} else {
CatalogQuery::Read
};
self.catalog.account_models(id, query).await
}
async fn account_configuration(
&self,
@@ -206,6 +206,7 @@ impl CredentialService {
email: None,
plan_type: None,
preserve_profile: false,
preserve_catalog_etag: None,
preserve_credential_state: false,
preserve_access_token_expiry: false,
provider_material: material.document()?,
@@ -26,6 +26,12 @@ use std::{
time::{Duration, SystemTime},
};
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum CatalogQuery {
Read,
Refresh,
}
pub(crate) struct CatalogService {
credentials: Arc<CredentialService>,
kind: gateway_core::routing::ProviderKind,
@@ -38,72 +44,7 @@ pub(crate) struct CatalogService {
refresh_cursor: AtomicUsize,
}
pub(crate) struct RefreshCatalog {
observation: AccountCatalogObservation,
document: bytes::Bytes,
}
impl CatalogService {
pub(crate) async fn capture_refresh_catalogs(
&self,
candidates: &[gateway_core::account::LoadedCredential],
) -> Result<BTreeMap<ProviderAccountId, RefreshCatalog>, ProviderAdminError> {
let candidates: BTreeMap<_, _> = candidates
.iter()
.map(|loaded| (loaded.account.id(), &loaded.account))
.collect();
let stored = self
.accounts
.load_account_catalogs(&self.kind)
.await
.map_err(|e| error(AdminKind::Unavailable).with_source(e))?;
let mut snapshots = BTreeMap::new();
for catalog in stored {
for observation in catalog.accounts {
if candidates
.get(&observation.account_id)
.is_some_and(|account| {
account.revision() == observation.revision
&& account.plan_type() == observation.plan.as_deref()
&& observation.etag.as_ref() == Some(&self.registration)
})
{
snapshots.insert(
observation.account_id.clone(),
RefreshCatalog {
observation,
document: catalog.document.clone(),
},
);
}
}
}
Ok(snapshots)
}
pub(crate) async fn after_credential_refresh(
&self,
account_id: &ProviderAccountId,
revision: gateway_core::account::CredentialRevision,
snapshot: Option<RefreshCatalog>,
) -> Result<(), ProviderAdminError> {
if let Some(mut snapshot) = snapshot {
// OAuth 续期已核对同一身份;沿用观测时间,存储仍校验新 revision 和原套餐
snapshot.observation.revision = revision;
if self
.accounts
.save_account_catalog(&snapshot.observation, &snapshot.document)
.await
.map_err(|e| error(AdminKind::Unavailable).with_source(e))?
{
self.invalidate();
return Ok(());
}
}
// 401 过期账号不会进入旧目录读取;新 AT 提交后立即尝试恢复,失败再由目录任务重试
self.account_models(account_id, false).await.map(|_| ())
}
pub(crate) fn new(
kind: gateway_core::routing::ProviderKind,
accounts: Arc<dyn gateway_core::account::ProviderAccountStore>,
@@ -288,13 +229,34 @@ impl CatalogService {
.collect()
}
pub(crate) async fn account_changed(
&self,
id: &ProviderAccountId,
created: bool,
) -> Result<(), ProviderAdminError> {
// 新 OAuth 账号的首次额度观测同时获取目录,API Key 仍需独立发现模型
if created
&& self
.accounts
.get_account(id)
.await
.map_err(|e| error(AdminKind::Unavailable).with_source(e))?
.is_some_and(|account| account.authentication_kind() == "oauth")
{
return Ok(());
}
self.account_models(id, CatalogQuery::Read)
.await
.map(|_| ())
}
pub(crate) async fn account_models(
&self,
id: &ProviderAccountId,
refresh: bool,
query: CatalogQuery,
) -> Result<ProviderModels, ProviderAdminError> {
let current = self.credentials.current(id).await?;
if !refresh {
if query != CatalogQuery::Refresh {
for (accounts, cat) in self
.catalogs()
.await
@@ -307,18 +269,18 @@ impl CatalogService {
return admin_models(cat, a.observed_at);
}
}
}
if !refresh
&& matches!(
if matches!(
current.account.credential_state(),
gateway_core::account::CredentialState::Invalid
| gateway_core::account::CredentialState::Banned
)
{
return Ok(ProviderModels {
models: Vec::new(),
observed_at: None,
});
) || (current.account.authentication_kind() == "oauth"
&& !self.credentials.background_refresh_enabled().await?)
{
return Ok(ProviderModels {
models: Vec::new(),
observed_at: None,
});
}
}
if current.account.authentication_kind() == super::api_key::API_KEY {
let material = super::api_key::ApiKeyMaterial::load(&current)?;
@@ -479,6 +441,7 @@ impl CatalogService {
async fn refresh_due_accounts(&self) -> Result<(), gateway_core::task::WorkerTaskError> {
use futures::{StreamExt, stream};
use gateway_core::task::WorkerTaskError;
// 每个实例都要从共享观测同步目录代次,查询模式只控制发往上游的刷新
let catalogs = self
.catalogs()
.await
@@ -505,18 +468,37 @@ impl CatalogService {
>= Duration::from_secs(3600)
})
});
if due.is_empty() {
return Ok(());
let mut first_error = None;
if due
.iter()
.any(|account| account.authentication_kind() == "oauth")
{
let scheduled = self
.credentials
.background_refresh_enabled()
.await
.unwrap_or_else(|error| {
first_error = Some(error);
false
});
if !scheduled {
due.retain(|account| account.authentication_kind() != "oauth");
}
}
due.sort_by(|a, b| a.id().cmp(b.id()));
// 固定大小轮转批次,持续失败的账号不能阻塞后面的目录修复
let offset = self.refresh_cursor.fetch_add(32, Ordering::Relaxed) % due.len();
due.rotate_left(offset);
due.truncate(32);
// 超出单批上限时轮转,持续失败的账号不能阻塞后面的目录修复
if due.len() > 32 {
let offset = self.refresh_cursor.fetch_add(32, Ordering::Relaxed) % due.len();
due.rotate_left(offset);
due.truncate(32);
}
let mut updates = stream::iter(due)
.map(|account| async move { self.account_models(account.id(), true).await })
.map(|account| async move {
self.account_models(account.id(), CatalogQuery::Refresh)
.await
})
.buffer_unordered(4);
let mut first_error = None;
while let Some(result) = updates.next().await {
if let Err(error) = result
&& !matches!(
@@ -2,7 +2,7 @@
use crate::transport::{
Catalog,
account::{Credit, ModelQuota, QuotaGroup, QuotaSummary, Tier},
account::{AccountInfo, Credit, ModelQuota, QuotaGroup, QuotaSummary, Tier},
};
use chrono::{DateTime, Utc};
use gateway_admin::model::provider_credentials::{
@@ -15,8 +15,12 @@ use std::{
time::{Duration, SystemTime},
};
#[derive(Serialize, Deserialize)]
#[derive(Clone, Serialize, Deserialize)]
pub(super) struct Document {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(super) sampled_at: Option<SystemTime>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub(super) group_denials: BTreeMap<String, super::groups::GroupDenial>,
pub(super) tier: Option<Tier>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(super) plan_description: Option<String>,
@@ -90,13 +94,61 @@ impl ModelQuota {
.filter(|v| v.is_finite() && (0.0..=1.0).contains(v))
}
fn current(&self, now: SystemTime) -> bool {
pub(super) fn current(&self, now: SystemTime) -> bool {
self.reset_time
.is_none_or(|reset| SystemTime::from(reset) > now)
}
fn exhaustion_deadline(&self, observed: SystemTime) -> Option<SystemTime> {
self.reset_time
.map(SystemTime::from)
.or_else(|| observed.checked_add(super::QUOTA_RETRY_FALLBACK))
}
fn valid_until(&self, observed: SystemTime) -> Option<SystemTime> {
let fresh_until = observed.checked_add(Duration::from_secs(600))?;
let until = if self.remaining() == Some(0.0) {
self.exhaustion_deadline(observed)
} else {
self.reset_time.map(SystemTime::from)
};
Some(until.map_or(fresh_until, |until| until.min(fresh_until)))
}
}
impl Document {
pub(super) fn from_upstream(
info: AccountInfo,
catalog: &Catalog,
summary: QuotaSummary,
) -> Result<Self, serde_json::Error> {
let (tier, plan_description) = match info.paid_tier {
Some(paid) => (Some(paid.tier), paid.description),
None => (info.current_tier, None),
};
Ok(Self {
sampled_at: None,
group_denials: BTreeMap::new(),
tier,
plan_description,
bucket_models: bucket_models(&summary, catalog),
summary,
models: catalog
.models
.iter()
.map(|(id, model)| {
Ok((
id.clone(),
model.quota()?.unwrap_or(ModelQuota {
remaining_fraction: None,
reset_time: None,
}),
))
})
.collect::<Result<_, serde_json::Error>>()?,
})
}
fn credit(&self) -> Option<&Credit> {
self.tier
.as_ref()?
@@ -105,6 +157,10 @@ impl Document {
.find(|c| c.is_google_one())
}
pub(super) fn can_use_credits(&self, enabled: bool) -> bool {
enabled && self.credit().is_some_and(Credit::usable)
}
pub(super) fn access_with_credits(
&self,
state: QuotaState,
@@ -113,6 +169,7 @@ impl Document {
) -> QuotaState {
if enabled && state.is_exhausted() && self.credit().is_some_and(Credit::usable) {
QuotaState::credits_only(observed, state.reset_at())
.with_exhaustion_deadline(state.exhaustion_deadline())
} else {
state
}
@@ -124,12 +181,25 @@ impl Document {
observed_at: SystemTime,
now: SystemTime,
) -> Option<gateway_admin::ports::provider::ProviderPeerModelQuota> {
let sampled = self.sampled_at(observed_at);
if let Some(raw) = self.model_group_block(model, sampled, now, false) {
let credits = self.can_use_credits(use_credits);
let denial = credits
.then(|| self.model_group_block(model, sampled, now, true))
.flatten();
let block = denial.unwrap_or(raw);
return Some(gateway_admin::ports::provider::ProviderPeerModelQuota {
state: self.access_with_credits(
block.state(observed_at),
credits && denial.is_none(),
observed_at,
),
valid_until: block.until,
});
}
let observed_at = sampled;
let quota = self.models.get(model)?;
let valid_until = observed_at.checked_add(Duration::from_secs(600))?;
let valid_until = quota
.reset_time
.map(SystemTime::from)
.map_or(valid_until, |reset| reset.min(valid_until));
let valid_until = quota.valid_until(observed_at)?;
if observed_at > now || valid_until <= now {
return None;
}
@@ -139,6 +209,7 @@ impl Document {
observed_at,
quota.reset_time.map(SystemTime::from),
)
.with_exhaustion_deadline(quota.exhaustion_deadline(observed_at))
} else {
QuotaState::allowed(observed_at)
};
@@ -161,8 +232,8 @@ impl Document {
.map(str::to_owned)
}
pub(super) fn access(&self, now: SystemTime) -> QuotaState {
// 独立模型桶不能直接升级为整个账号耗尽,只有全部已知模型都明确耗尽才阻断账号
pub(super) fn ungrouped_account_state(&self, now: SystemTime) -> QuotaState {
// 上游没有分组时,只能根据目录中所有模型的额度决定整号状态
if self
.models
.values()
@@ -183,6 +254,12 @@ impl Document {
.filter_map(|q| q.reset_time.map(SystemTime::from))
.min(),
)
.with_exhaustion_deadline(
self.models
.values()
.filter_map(|q| q.exhaustion_deadline(now))
.min(),
)
} else {
QuotaState::observed_unknown(now)
}
@@ -195,11 +272,17 @@ impl Document {
observed: SystemTime,
now: SystemTime,
) -> (bool, Option<AccountQuotaSignals>) {
// 过时或已过重置点的百分比交回上游判定,避免旧快照永久挡住可用模型
if now.duration_since(observed).unwrap_or_default() > Duration::from_secs(600) {
return (false, None);
let observed = self.sampled_at(observed);
if self
.model_group_block(model, observed, now, self.can_use_credits(use_credits))
.is_some()
{
return (true, None);
}
let Some(quota) = self.models.get(model).filter(|q| q.current(now)) else {
// 过时或已过重置点的百分比交回上游判定,避免旧快照永久挡住可用模型
let Some(quota) = self.models.get(model).filter(|q| {
observed <= now && q.valid_until(observed).is_some_and(|until| now < until)
}) else {
return (false, None);
};
let remaining = quota.remaining();
@@ -214,6 +297,7 @@ impl Document {
}
pub(super) fn project(&self, observed: SystemTime) -> ProviderQuota {
let now = SystemTime::now();
let mut windows = Vec::new();
for group in &self.summary.groups {
let group_id = group.buckets.first().map(|b| {
@@ -258,10 +342,12 @@ impl Document {
unlimited: false,
balance: credit.balance().map(|v| v.to_string()),
}),
limit_reached: self.access(observed).is_exhausted(),
limit_reached: self
.account_state(observed, now, false)
.is_exhausted_at(now),
plan_type: self.plan_type(),
plan_type_display: self.plan_display().map(str::to_owned),
observed_at: Some(DateTime::<Utc>::from(observed)),
observed_at: Some(DateTime::<Utc>::from(self.sampled_at(observed))),
windows,
..Default::default()
}
@@ -0,0 +1,194 @@
//! 按上游额度组归集窗口、模型快照和实际请求的额度拒绝
use super::document::Document;
use crate::transport::account::{ModelQuota, QuotaGroup};
use gateway_core::account::{QuotaEvidence, QuotaState};
use serde::{Deserialize, Serialize};
use std::time::SystemTime;
#[derive(Clone, Copy, Serialize, Deserialize)]
pub(super) struct GroupDenial {
at: SystemTime,
until: SystemTime,
}
#[derive(Clone, Copy)]
pub(super) struct GroupBlock {
pub(super) until: SystemTime,
reset: Option<SystemTime>,
}
impl GroupBlock {
fn from_window(quota: &ModelQuota, sampled: SystemTime, now: SystemTime) -> Option<Self> {
let reset = quota.reset_time.map(SystemTime::from);
let until = reset.or_else(|| sampled.checked_add(super::QUOTA_RETRY_FALLBACK))?;
(sampled <= now && quota.remaining() == Some(0.0) && until > now)
.then_some(Self { until, reset })
}
pub(super) fn state(self, at: SystemTime) -> QuotaState {
QuotaState::exhausted(QuotaEvidence::UsageLimitReached, at, self.reset)
.with_exhaustion_deadline(Some(self.until))
}
}
impl Document {
pub(super) fn sampled_at(&self, version: SystemTime) -> SystemTime {
self.sampled_at.unwrap_or(version)
}
// 同组的窗口使用同一份成员名单,用固定窗口 ID 标识组,不依赖显示名和返回顺序
fn key(group: &QuotaGroup) -> Option<&str> {
group.buckets.iter().map(|b| b.bucket_id.as_str()).min()
}
fn group_for(&self, model: &str) -> Option<&QuotaGroup> {
let mut matches = self.summary.groups.iter().filter(|g| {
Self::key(g)
.and_then(|k| self.bucket_models.get(k))
.is_some_and(|ids| ids.contains(model))
});
let group = matches.next()?;
matches.next().is_none().then_some(group)
}
pub(super) fn record_rejection(
&mut self,
model: &str,
at: SystemTime,
until: SystemTime,
) -> bool {
let Some(key) = self.group_for(model).and_then(Self::key) else {
return false;
};
let key = key.to_owned();
let entry = self
.group_denials
.entry(key)
.or_insert(GroupDenial { at, until });
entry.at = entry.at.max(at);
entry.until = entry.until.max(until);
true
}
pub(super) fn retain_newer_denials(&mut self, old: &Self, sampled: SystemTime) {
for group in &self.summary.groups {
let Some(key) = Self::key(group) else {
continue;
};
if let Some(denial) = old
.group_denials
.get(key)
.filter(|r| r.at > sampled && r.until > sampled)
&& self
.bucket_models
.get(key)
.is_some_and(|ids| Some(ids) == old.bucket_models.get(key))
{
self.group_denials.insert(key.to_owned(), *denial);
}
}
}
fn group_block(
&self,
group: &QuotaGroup,
sampled: SystemTime,
now: SystemTime,
allow_credits: bool,
) -> Option<GroupBlock> {
let key = Self::key(group)?;
let denial = self
.group_denials
.get(key)
.filter(|r| r.at <= now && r.until > now)
.map(|r| GroupBlock {
until: r.until,
reset: None,
});
if allow_credits {
return denial;
}
let windows = group
.buckets
.iter()
.filter_map(|b| GroupBlock::from_window(&b.quota, sampled, now));
let members = self
.bucket_models
.get(key)
.into_iter()
.flatten()
.filter_map(|id| {
let block = GroupBlock::from_window(self.models.get(id)?, sampled, now)?;
std::ptr::eq(self.group_for(id)?, group).then_some(block)
});
windows
.chain(members)
.chain(denial)
.max_by_key(|b| (b.until, b.reset.is_some()))
}
pub(super) fn model_group_block(
&self,
model: &str,
sampled: SystemTime,
now: SystemTime,
allow_credits: bool,
) -> Option<GroupBlock> {
self.group_block(self.group_for(model)?, sampled, now, allow_credits)
}
fn first_group_to_recover(
&self,
sampled: SystemTime,
now: SystemTime,
allow_credits: bool,
) -> Option<GroupBlock> {
let mut first: Option<GroupBlock> = None;
for group in &self.summary.groups {
let block = self.group_block(group, sampled, now, allow_credits)?;
if first.is_none_or(|earliest| block.until < earliest.until) {
first = Some(block);
}
}
first
}
pub(super) fn account_state(
&self,
version: SystemTime,
now: SystemTime,
use_credits: bool,
) -> QuotaState {
let sampled = self.sampled_at(version);
if self.summary.groups.is_empty() {
return self.access_with_credits(
self.ungrouped_account_state(sampled),
use_credits,
now,
);
}
// 整号在首个组恢复时放行,每个组须等所有已耗尽窗口恢复
if let Some(block) = self.first_group_to_recover(sampled, now, false) {
if self.can_use_credits(use_credits) {
if let Some(denied) = self.first_group_to_recover(sampled, now, true) {
return denied.state(now);
}
return QuotaState::credits_only(now, block.reset)
.with_exhaustion_deadline(Some(block.until));
}
return block.state(now);
}
if self.summary.groups.iter().any(|g| {
!g.buckets.is_empty()
&& g.buckets
.iter()
.all(|b| b.quota.remaining().is_some_and(|v| v > 0.0) && b.quota.current(now))
&& self.group_block(g, sampled, now, false).is_none()
}) {
QuotaState::allowed(now)
} else {
QuotaState::observed_unknown(now)
}
}
}
@@ -1,6 +1,10 @@
//! Antigravity 账号额度文档、刷新与调度投影入口
mod document;
mod groups;
mod service;
pub(crate) use service::{CandidateQuota, QuotaService, QuotaTask};
/// 上游确认耗尽但未提供重置时刻时,本地最多等待五分钟再放行尝试
pub(crate) const QUOTA_RETRY_FALLBACK: std::time::Duration = std::time::Duration::from_secs(300);
Loaded 100 of 204 files, more files were not shown because too many files have changed in this diff. Show more