Compare commits

..
Author SHA1 Message Date
ZyyandCodex 8176f5027d feat(antigravity): add protocol conversion and configurable identity
Support Responses, Chat Completions and Messages through the native GenAI transport, preserving signed tool history, tail usage and terminal events.

Add an editable built-in system prompt to AGY profiles and align Cloud Code HTTP/1.1, gzip and request identity behavior. Keep TLS and header layout limitations explicit.

Co-authored-by: Codex <noreply@openai.com>
2026-11-24 22:41:00 +08:00
ZyyandCodex 830f362bba feat(gateway): integrate Antigravity and reorganize settings
Separate client protocols from provider routing, align backend and frontend module ownership, and refine account quota displays.

Reorganize settings forms and navigation, protect stored backup credentials, and scope edit conflicts to the settings being saved.

Co-authored-by: Codex <noreply@openai.com>
2026-11-24 19:58:18 +08:00
ZyyandCodex c99bf1ac35 chore: bump version to 3.54.4
Co-authored-by: Codex <noreply@openai.com>
2026-11-23 12:19:49 +08:00
e41fdfc1c5 fix(accounts): set API key account names once during import (#770)
Use the optional name from account settings and default unnamed key accounts to 密钥账号. Keep connection fields independent of naming.

Co-authored-by: Zyy <zyycn@users.noreply.github.com>
Co-authored-by: Codex <noreply@openai.com>
2026-11-23 12:16:40 +08:00
5fced665bf fix(openai): preserve session bindings during image account fallback (#769)
Co-authored-by: Zyy <zyycn@users.noreply.github.com>
Co-authored-by: Codex <noreply@openai.com>
2026-11-23 11:53:40 +08:00
7ff77413c8 fix(openai): respect response exclusions when reusing WebSockets (#768)
Co-authored-by: Zyy <zyycn@users.noreply.github.com>
Co-authored-by: Codex <noreply@openai.com>
2026-11-23 11:45:03 +08:00
1ee67cd6b2 fix(openai): handle WebSocket size rejections during uploads (#767)
Co-authored-by: Zyy <zyycn@users.noreply.github.com>
Co-authored-by: Codex <noreply@openai.com>
2026-11-23 11:12:23 +08:00
dependabot[bot] baf9992f99 chore(deps): bump the minor-and-patch group in /frontend with 3 updates (#765)
Bumps the minor-and-patch group in /frontend with 3 updates: [@lucide/vue](https://github.com/lucide-icons/lucide/tree/HEAD/packages/vue), [vue](https://github.com/vuejs/core) and [vue-i18n](https://github.com/intlify/vue-i18n/tree/HEAD/packages/vue-i18n).


Updates `@lucide/vue` from 1.73.0 to 1.77.0
- [Release notes](https://github.com/lucide-icons/lucide/releases)
- [Commits](https://github.com/lucide-icons/lucide/commits/1.77.0/packages/vue)

Updates `vue` from 3.5.45 to 3.5.46
- [Release notes](https://github.com/vuejs/core/releases)
- [Changelog](https://github.com/vuejs/core/blob/main/CHANGELOG.md)
- [Commits](https://github.com/vuejs/core/compare/v3.5.45...v3.5.46)

Updates `vue-i18n` from 11.4.20 to 11.4.23
- [Release notes](https://github.com/intlify/vue-i18n/releases)
- [Changelog](https://github.com/intlify/vue-i18n/blob/v11.4.23/CHANGELOG.md)
- [Commits](https://github.com/intlify/vue-i18n/commits/v11.4.23/packages/vue-i18n)

---
updated-dependencies:
- dependency-name: "@lucide/vue"
  dependency-version: 1.77.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-and-patch
- dependency-name: vue
  dependency-version: 3.5.46
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-and-patch
- dependency-name: vue-i18n
  dependency-version: 11.4.23
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-and-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-11-23 10:58:14 +08:00
dependabot[bot] 5f7e50a031 chore(deps): bump taiki-e/install-action (#762)
Bumps the minor-and-patch group with 1 update: [taiki-e/install-action](https://github.com/taiki-e/install-action).


Updates `taiki-e/install-action` from 2.90.3 to 2.90.6
- [Release notes](https://github.com/taiki-e/install-action/releases)
- [Changelog](https://github.com/taiki-e/install-action/blob/main/CHANGELOG.md)
- [Commits](https://github.com/taiki-e/install-action/compare/cfdb7ed4ccc7c7dce37759eae89dc5674b469b39...75a7c0f87bd666af3cdb75c5b9e9d03ab6044e6f)

---
updated-dependencies:
- dependency-name: taiki-e/install-action
  dependency-version: 2.90.6
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-and-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-11-23 10:58:09 +08:00
dependabot[bot]andCodex 939ae78c8c chore(deps): upgrade jsonwebtoken to 12.0.0 (#764)
Upgrade jsonwebtoken to 12.0.0 and adapt the xAI OIDC test fixture
to the fallible HMAC key constructor.

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Codex <noreply@openai.com>
2026-11-23 10:58:03 +08:00
dependabot[bot]andCodex 3039709f36 chore(deps): update backend dependencies and patch url (#763)
Update the backend dependency group, migrate the stale-lock fixture to
std::fs::set_times, and lock url 2.5.9 to resolve RUSTSEC-2026-0592.

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Codex <noreply@openai.com>
2026-11-23 10:57:45 +08:00
github-actions[bot] 6900da36ee chore(release): update release channels to 3.54.3 2026-11-22 06:52:21 +00:00
ZyyandCodex e9a5ee7e3b chore: bump version to 3.54.3
Co-authored-by: Codex <noreply@openai.com>
2026-11-22 14:25:49 +08:00
ZyyandCodex 58cbb60750 fix(accounts): move CPR link detection to the quota card
Co-authored-by: Codex <noreply@openai.com>
2026-11-22 01:02:28 +08:00
ZyyandCodex b85f944c52 fix(accounts): show only account-wide quota in the detail panel
Co-authored-by: Codex <noreply@openai.com>
2026-11-22 00:45:55 +08:00
Wei HUandCodex d1be306f03 test(api): isolate virtual time from idle WebSocket I/O (#761)
The idle expiry test reads a real TCP socket with a Tokio timeout while
the clock is paused. Auto-advance can reach the read deadline while the
socket is still waiting for readiness.

Follow the adjacent connection lifecycle test and pause only for the
60-minute jump. Use a running clock for the handshake and frame read.
Keep the exact limit error and zero-execution assertions.

Co-authored-by: Codex <noreply@openai.com>
2026-11-21 22:51:47 +08:00
aa34d5291d fix(accounts): preserve quota forecast totals through reset time jitter (#760)
* fix(accounts): preserve quota forecast totals through reset time jitter

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

* fix(accounts): confirm quota cycle changes before trimming usage

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

---------

Co-authored-by: Zyy <zyycn@users.noreply.github.com>
Co-authored-by: Codex <noreply@openai.com>
2026-11-21 21:52:12 +08:00
github-actions[bot] 56d3078ee8 chore(release): update release channels to 3.54.2 2026-11-21 12:52:38 +00:00
ZyyandCodex 8b69fa4882 chore: bump version to 3.54.2
Co-authored-by: Codex <noreply@openai.com>
2026-11-21 20:35:59 +08:00
ZyyandCodex d05d38718e feat(frontend): show CPR wordmark and repository link in the browser console
Co-authored-by: Codex <noreply@openai.com>
2026-11-21 19:23:03 +08:00
Zyy a1954c4746 fix(openai): limit request country overrides to Codex OAuth
Preserve the incoming request country on API key routes. Show quota refresh only for supported accounts and keep peer discovery in the account menu.

Clarify the policy scope in settings and tighten shared help icon spacing.

Refs #758
2026-11-21 18:37:59 +08:00
github-actions[bot] 636a3d2a26 chore(release): update release channels to 3.54.1 2026-11-21 04:18:44 +00:00
ZyyandCodex e9627168a7 chore: bump version to 3.54.1
Co-authored-by: Codex <noreply@openai.com>
2026-11-21 12:02:26 +08:00
Zyy 5a4f49036b feat(frontend): share model access controls and separate request country settings
Let accounts and groups manage model lists with the same editor, including custom IDs and common image models. Tighten spacing in the group form and give the request country policy its own settings card.
2026-11-21 11:52:45 +08:00
ZyyandCodex 8041ddab65 refactor(frontend): consolidate chart, form, icon and proxy display rules
Co-authored-by: Codex <noreply@openai.com>
2026-11-21 10:55:06 +08:00
ZyyandCodex e645d6d4c9 fix(usage): unify timestamp columns across record tables
Co-authored-by: Codex <noreply@openai.com>
2026-11-21 10:55:01 +08:00
ZyyandCodex 5079700190 fix(ui): update shared UI to v0.13.1 for WebKit tables
Co-authored-by: Codex <noreply@openai.com>
2026-11-21 10:38:38 +08:00
ZyyandCodex 4db65d8e12 chore(deploy): update PostgreSQL to 18.7 and Redis to 8.10.3
Co-authored-by: Codex <noreply@openai.com>
2026-11-20 23:25:43 +08:00
github-actions[bot] da866de2c7 chore(release): update release channels to 3.54.0 2026-11-20 14:45:41 +00:00
ZyyandCodex a770419818 chore: bump version to 3.54.0
Co-authored-by: Codex <noreply@openai.com>
2026-11-20 22:28:03 +08:00
ZyyandCodex 5b37b574e6 refactor(store): consolidate unreleased database migrations
Co-authored-by: Codex <noreply@openai.com>
2026-11-20 22:27:41 +08:00
0df6c40091 fix(openai): require replay for HTTP continuations after SSE fallback (#756)
Co-authored-by: Zyy <zyycn@users.noreply.github.com>
Co-authored-by: Codex <noreply@openai.com>
2026-11-20 22:20:56 +08:00
ZyyandCodex 4b5443d2f2 fix(settings): separate the dedicated review model from model mapping
Co-authored-by: Codex <noreply@openai.com>
2026-11-20 21:55:48 +08:00
ZyyandCodex b02f13c9cc refactor(admin)!: remove legacy management API fields
Use provider profile maps, saved proxy IDs, and structured dashboard metrics across the admin API and UI. Require the quota reset mode on full settings updates.

Migrate existing Redis freezes atomically with cooldown writes and reuse validated OpenAI credentials during runtime decoding.

Co-authored-by: Codex <noreply@openai.com>
2026-11-20 21:38:58 +08:00
ZyyandCodex 878d2858e8 fix(settings)!: require Guardian model and request country on updates
Plugins and admin HTTP clients must send both OpenAI settings on every replacement. Reject incomplete writes before changing the stored revision.

Co-authored-by: Codex <noreply@openai.com>
2026-11-20 21:04:35 +08:00
ZyyandCodex 369f17d654 fix(openai): preserve account and Guardian header precedence
Co-authored-by: Codex <noreply@openai.com>
2026-11-20 21:02:57 +08:00
Zyy 3709ed2484 feat(openai): align Codex Guardian routing and request country (#754) 2026-11-20 20:14:00 +08:00
Zyy 48a5c9d690 fix(openai): preserve credential errors during model catalog refresh 2026-11-20 17:30:24 +08:00
Zyy 6fc6283f3a fix(gateway): link successful replays to incomplete continuations 2026-11-20 17:30:24 +08:00
ZyyandCodex 605b60e58f refactor(ui): use canonical Tailwind classes
Co-authored-by: Codex <noreply@openai.com>
2026-11-20 17:12:03 +08:00
1bf948a24f feat(keys): add usage statistics and manual budget window alignment (#752)
* feat(keys): add usage statistics and manual budget window alignment

* fix(keys): retain dialog focus when retrying usage statistics

* fix(store): exclude pricing scenarios from missing cost detection

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

---------

Co-authored-by: Zyy <zyycn@users.noreply.github.com>
Co-authored-by: Codex <noreply@openai.com>
2026-11-20 17:04:16 +08:00
Zyy d90b9d129e fix(openai): omit unreferenced item IDs from replayed text messages 2026-11-20 15:42:02 +08:00
ZyyandCodex 4b1cae89b2 feat(admin): add image model shortcut to account allowlists
Co-authored-by: Codex <noreply@openai.com>
2026-11-20 14:46:28 +08:00
ZyyandCodex 6cfe7ce2fc feat(admin): add account group policies and bulk API key editing (#751)
Co-authored-by: Codex <noreply@openai.com>
2026-11-20 14:39:30 +08:00
ZyyandCodex 1427dfc64a feat(openai): set request country from the configured location
Co-authored-by: Codex <noreply@openai.com>
2026-11-20 12:25:27 +08:00
ZyyandCodex 9996fae5b6 fix(ui): distinguish scheduled and quota reset warmup
Co-authored-by: Codex <noreply@openai.com>
2026-11-20 12:20:33 +08:00
6420d86aa6 fix(openai): expire access tokens revoked during quota refresh (#750)
Co-authored-by: Zyy <zyycn@users.noreply.github.com>
Co-authored-by: Codex <noreply@openai.com>
2026-11-20 11:02:57 +08:00
ZyyandCodex f8fa386a7e fix(admin): simplify account error messages
Co-authored-by: Codex <noreply@openai.com>
2026-11-20 10:43:53 +08:00
github-actions[bot] 7c2c532b44 chore(release): update release channels to 3.53.1 2026-11-19 10:57:51 +00:00
ZyyandCodex 188a6817d1 chore: bump version to 3.53.1
Co-authored-by: Codex <noreply@openai.com>
2026-11-19 18:41:20 +08:00
ZyyandCodex d44bc64d1a fix(usage): improve request record layout and error summaries
Co-authored-by: Codex <noreply@openai.com>
2026-11-19 18:10:51 +08:00
github-actions[bot] 6006cc8394 chore(release): update release channels to 3.53.0 2026-11-19 09:36:04 +00:00
ZyyandCodex e7f8b5a354 chore: bump version to 3.53.0
Co-authored-by: Codex <noreply@openai.com>
2026-11-19 17:18:26 +08:00
d62868b692 feat(openai): make the WebSocket fast-path budget configurable (#747)
Co-authored-by: Zyy <zyycn@users.noreply.github.com>
Co-authored-by: Codex <noreply@openai.com>
2026-11-19 17:10:41 +08:00
0922f3486c fix(responses): return HTTP 400 for early WebSocket request errors (#746)
Co-authored-by: Zyy <zyycn@users.noreply.github.com>
Co-authored-by: Codex <noreply@openai.com>
2026-11-19 16:59:11 +08:00
ZyyandCodex f4058c1d2e test: align backend coverage with current behavior
Remove obsolete field assertions and the ignored Codex binary TLS comparison. Keep coverage for request validation, compatibility, and local TLS handshakes.

Co-authored-by: Codex <noreply@openai.com>
2026-11-19 15:56:12 +08:00
Zyy 8253fbc497 fix(errors): show specific causes in admin feedback and request records 2026-11-19 15:41:32 +08:00
ZyyandCodex 193e83f9f3 fix(accounts): keep stale connection tests from closing a new stream
Co-authored-by: Codex <noreply@openai.com>
2026-11-19 15:06:20 +08:00
ZyyandCodex a9e8fa8a44 refactor(openai): simplify account selection and session admission
Co-authored-by: Codex <noreply@openai.com>
2026-11-19 15:06:20 +08:00
ZyyandCodex 437322ee4b refactor(core): centralize attempt preparation failure handling
Co-authored-by: Codex <noreply@openai.com>
2026-11-19 15:06:19 +08:00
Zyy 843e1367bd docs: streamline guides and clarify current behavior 2026-11-19 14:49:42 +08:00
ZyyandCodex ab1bf4372c fix(api): apply the CLI version gate to Desktop-hosted TUI clients
Co-authored-by: Codex <noreply@openai.com>
2026-11-19 14:15:35 +08:00
dca9806961 feat(usage): filter request errors by origin and focus the detail table (#743)
* feat(usage): filter request errors by origin and focus the detail table

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

* fix(usage): preserve request columns and fill the error table

Keep reasoning effort separate and use the success table's column order. Let the error summary fill the space left by hidden columns and reuse the decoded upstream body when filtering saved errors.

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

---------

Co-authored-by: Codex <noreply@openai.com>
Co-authored-by: Zyy <zyycn@users.noreply.github.com>
2026-11-19 13:40:05 +08:00
ZyyandCodex 15ed54d452 fix(ui): refine subscription badge colors and table spacing
Co-authored-by: Codex <noreply@openai.com>
2026-11-19 13:08:31 +08:00
ZyyandCodex 050214860e docs(readme): streamline setup and highlight project support and activity
Co-authored-by: Codex <noreply@openai.com>
2026-11-19 12:08:36 +08:00
github-actions[bot] d917f948cf chore(release): update release channels to 3.52.2 2026-11-19 01:40:04 +00:00
1031 changed files with 48742 additions and 26117 deletions
+6 -3
View File
@@ -31,7 +31,8 @@ description: Codex Proxy RS 的需求评估、排障、开发、代码审查与
| 开发、排查或审查服务端接口、路由、调度、账号与用量规则、持久化、后台任务或协议行为;目标是 `backend/` 中的实现、配置、迁移,或 Rust 源码 | [Workspace 边界](../../../docs/architecture.md#3-workspace-边界)的模块与依赖规则、所属模块及[后端自审](../../../docs/architecture.md#后端自审);Rust 使用 `$rust-best-practices` 和下方后端注释要求,宿主 Rust 同时读取 [Rust 模块组织约定](../../../docs/architecture.md#32-rust-模块组织约定) |
| 修改页面接口调用,或开发、排查、审查面向管理端或模型客户端的 HTTP/WS API 合同 | [API](../../../docs/api.md)对应章节;优先复用已有接口,核对调用方 → 服务端解析 → 实际查询或执行,不能只凭前端类型认定参数生效;按实际改动叠加前后端规范 |
| 新增、修改或审查客户端可见错误、失败提示、后台任务状态文案 | 下方[错误文案](#错误文案),并按实际出口核对[错误与诊断三层边界](../../../docs/architecture.md#错误与诊断三层边界) |
| 模块或调用链变更 | [Workspace 边界](../../../docs/architecture.md#3-workspace-边界)及所属模块章节,不通读整份架构 |
| 模块或调用链变更,包括目录整理 | [Workspace 边界](../../../docs/architecture.md#3-workspace-边界)及所属模块章节;并排核对任务范围内同类实现的职责归属、公开入口与依赖方向,再决定目录与共享合同的位置 |
| 新增内置 Provider、接入客户端协议,或让已有入口支持另一种实现 | 对照[Provider 与协议边界](../../../docs/architecture.md#5-provider-与协议边界),并排追踪新旧实现从入口到执行的路径。沿用目录或类型前,确认名称仍能描述扩展后的职责。共享层按厂商分支时,核实哪个接口合同指定了上游。按能力选择时,核对谁声明能力、谁匹配候选,用同名模型支持不同协议等场景验证。涉及选号时,对照已有实现的满载与取消行为 |
| 新增、调整、清理或审查测试 | 下方[测试维护](#测试维护),按当前行为、职责归属与已有覆盖判断保留、合并或删除 |
| 修改部署行为、`deploy/` 配置或数据库迁移 | 按范围读取[部署](../../../deploy/README.md)、[迁移](../../../backend/migrations/README.md)对应章节 |
| 修改或审查文档;实现或审查用法、公开合同、职责、约束或运维操作的变化 | [文档检查](references/documentation.md),按最终行为核对是否漏更;纯文档任务只补读核实所述事实需要的领域条款 |
@@ -42,7 +43,7 @@ description: Codex Proxy RS 的需求评估、排障、开发、代码审查与
1. 遵守已提供的 [AGENTS.md](../../../AGENTS.md),按其 CodeGraph 约定定位代码;确认工作区、任务范围与已有改动,找到事实归属、同类实现和调用链,补齐上表命中规范及[项目约定](../../../CONTRIBUTING.md#项目约定)对应条目后再修改
2. 以最终差异重新匹配上表,补齐新增领域的规范并检查实际实现,再处理本次引入的职责越界、重复规则、冗余状态与无依据分支;删除或替换功能时一并清理失效的配置、类型、调用、测试与文档,已部署数据和公开合同仍遵守所属迁移及兼容规则;仅审查时报告,不自行修复
3. 在本任务内同步受影响的文档、示例和引用
3. 模块移动或重命名时,同步核对源码、测试、公开导出及配置、脚本中的名称和路径引用;在本任务内更新受影响的文档、示例和引用
4. 按变更范围执行[验证](../../../CONTRIBUTING.md#验证)及其停止条件,后端命令见[验证命令](../../../docs/architecture.md#验证命令);复用仍适用的验证证据与用户已确定的验收分工,区分通过、失败、跳过与未执行
5. 交付前按[首要写作要求](#首要写作要求言简意赅)通读本次新增或修改的文字。交代实际结果与验证缺口;前端按[前端流程](references/frontend.md)核对运行证据,后端按上表检查生命周期,不把构建通过当作行为验收
6. 按授权完成提交与交付;提交前按[提交约定](../../../CONTRIBUTING.md#项目约定)准备提交信息与实际共同作者署名,提交后核对实际提交消息,PR 的 AI 披露不能替代提交署名
@@ -50,9 +51,11 @@ description: Codex Proxy RS 的需求评估、排障、开发、代码审查与
## 测试维护
- 测试随当前功能维护,名称、夹具和断言描述当前输入、行为与结果;功能变更时优先更新所属模块的现有用例,不为每次改动叠加一组记录变更经过的测试
- 移动或重命名测试时,核对受影响的场景覆盖是否保留;涉及子进程调用或名称过滤时,同步更新调用入口并实际运行,确认目标用例确实执行且行为断言通过
- 清理只证明旧字段、旧路由或旧实现已经消失的用例与附带断言;未知字段校验使用合法请求基线加无业务含义的未知字段,避免因缺少必填项等其他错误而误通过
- 同一层对同一行为的重复覆盖合并为清晰的场景矩阵,复用相邻测试夹具;跨层测试确有不同职责或失败路径时保留,不为统一而扩大测试辅助抽象
- 断言可观察的行为与业务不变量,避免复述结构体赋值、罗列表列或字段清单、匹配 SQL 文本与源码布局;项目明确要求的架构边界检查继续维护
- 断言可观察的行为与业务不变量,避免复述结构体赋值、罗列表列或字段清单、匹配 SQL 文本与源码布局
- 维护项目明确要求的架构边界检查;发现漏检时,对照规则核实扫描范围、排除项与被检查的依赖关系,优先补齐现有检查中能稳定判定的缺口
- 当前协议兼容、数据读取兼容、安全边界、并发和资源生命周期仍需覆盖,不按 `old`、`legacy` 等名称机械删除,也不能用改名代替无效用例清理
- 不在仓库中新增或保留迁移 SQL 专项测试,包括迁移文本、schema 演变与指定版本升级用例;需要验证迁移执行、数据保留或回滚时,在临时目录编写一次性验证并使用隔离数据库,测试通过即可,临时脚本不纳入维护测试集
- 持久化功能测试使用当前完整 schema,验证现行读写、事务与数据约束;插件运行时状态迁移等业务能力按当前功能测试,不归为迁移 SQL 专项测试
@@ -35,6 +35,8 @@
- **核对位置与对齐**时,结合周围内容查看实际页面或 PR 截图,确认操作归属一眼可辨,对照相邻行列检查边缘、文字基线和组间留白。发现错位时指出具体控件、对齐参照和受影响的状态
- **精简文案**,删去重复说明,压短必要提示,检查自写文案中的句号和分号
- **样式与状态**:是否使用对应 Token 与 utility,局部样式是否符合适用边界,受影响的主题、窄屏及交互状态是否正确
- **模块归属**从调用方核对公开入口。页面或多文件组件通过 `index.vue` 提供界面,其他页面复用整页时引用所属模块的布局入口,独立复用的业务组件按领域放置
- **Provider 边界**涉及账号操作、身份配置或定价时,沿接口响应、控件和提交载荷追踪同一条规则。服务端决定的能力使用接口字段,Provider 专属表单解释自己的字段,多个页面共用的编辑流程只维护一份。按[前端职责](../../../../docs/architecture.md#34-前端模块职责)核对归属
- **查询与动作**:区分首次加载、刷新、分页、单行与批量操作,核对 loading、禁用状态的影响范围;沿用请求层错误处理,不在页面叠加同一错误的提示
- **运行证据**:按界面验证核对截图与实际交互,证据对应当前实现;页面 PR 的可访问图片和 Draft 条件按该节执行
+3 -3
View File
@@ -35,7 +35,7 @@ jobs:
CPR_TEST_REDIS_URL: redis://127.0.0.1:6379
services:
postgres:
image: postgres:18-bookworm@sha256:bbf83594798e144bff365a9c191c5d779f181fb3135902064ab8ff11918020fc
image: postgres:18-bookworm@sha256:194e55feb2597b1465dbee81cc9fd8d204566cd2eb42c8d22fd6c931a38781b1
env:
POSTGRES_DB: codex_proxy
POSTGRES_USER: codex_proxy
@@ -49,7 +49,7 @@ jobs:
--health-timeout 5s
--health-retries 10
redis:
image: redis:8-alpine@sha256:0bf6577d7774e592b29d093e3ac9390eb91e13d72c21e506afce736de5e0eeb0
image: redis:8-alpine@sha256:7958cfbb9d152f87dadfbc89f1b0b15938f0b81ff8982feb327476f4911935c3
ports:
- 6379:6379
options: >-
@@ -125,7 +125,7 @@ jobs:
run: cargo clippy --all-targets --all-features --locked -- -D warnings
- name: Setup nextest
uses: taiki-e/install-action@cfdb7ed4ccc7c7dce37759eae89dc5674b469b39 # v2.90.3
uses: taiki-e/install-action@75a7c0f87bd666af3cdb75c5b9e9d03ab6044e6f # v2.90.6
with:
tool: cargo-nextest@0.9.143
fallback: none
+1 -1
View File
@@ -115,7 +115,7 @@ jobs:
cache-bin: false
save-if: ${{ github.event_name != 'pull_request' }}
- name: Setup nextest
uses: taiki-e/install-action@cfdb7ed4ccc7c7dce37759eae89dc5674b469b39 # v2.90.3
uses: taiki-e/install-action@75a7c0f87bd666af3cdb75c5b9e9d03ab6044e6f # v2.90.6
with:
tool: cargo-nextest@0.9.143
fallback: none
+1 -1
View File
@@ -34,7 +34,7 @@ jobs:
ref: ${{ inputs.ref || github.event.pull_request.head.sha || github.sha }}
- name: Install cargo-audit
uses: taiki-e/install-action@cfdb7ed4ccc7c7dce37759eae89dc5674b469b39 # v2.90.3
uses: taiki-e/install-action@75a7c0f87bd666af3cdb75c5b9e9d03ab6044e6f # v2.90.6
with:
tool: cargo-audit@0.22.2
fallback: none
+28 -83
View File
@@ -12,7 +12,7 @@
[![GHCR](https://img.shields.io/badge/GHCR-codex--proxy--rs-2496ED?logo=docker&logoColor=white&style=flat-square)](https://github.com/zyycn/codex-proxy-rs/pkgs/container/codex-proxy-rs)
[![License: Apache 2.0](https://img.shields.io/badge/License-Apache%202.0-blue.svg?style=flat-square)](LICENSE)
[快速预览](#快速预览) · [快速开始](#快速开始) · [客户端接入](#客户端接入) · [文档](#文档) · [社区](#社区) · [许可证](#许可证)
[快速预览](#快速预览) · [快速开始](#快速开始) · [文档](#文档) · [社区](#社区) · [贡献者](#贡献者) · [Star History](#star-history) · [支持项目](#支持项目) · [许可证](#许可证)
</div>
@@ -21,105 +21,28 @@
## 快速预览
无需部署即可体验管理端的系统概览、账号分组、代理管理与用量统计:
| 登录信息 | 默认值 |
| --- | --- |
| 地址 | <https://codex-proxy-rs.ainz.cc> |
| 登录身份 | 管理员 |
| 账号 | `admin@cpr.local` |
| 密码 | `039c18de2aeac46d23ead7766bb07bbbe3747233c66a128e` |
预览服务运行已发布版本,展示的账号、代理与使用记录均为模拟数据,每天北京时间 `00:00` 自动生成当天数据
这是公开共享的功能预览环境,不提供真实模型调用;请勿导入真实账号、密钥或其他敏感信息
## 快速开始
使用 Docker Compose 部署版本固定的发布镜像,同时启动 PostgreSQL 和 Redis
以下命令适用于 Linux amd64/arm64,需要 Docker Engine、Docker Compose Plugin、curl 和 OpenSSL
macOS 从[发行页](https://github.com/zyycn/codex-proxy-rs/releases)下载对应的归档:Intel 机型选 `darwin_amd64`,Apple Silicon 机型选 `darwin_arm64`。
Windows x64 / ARM64 的安装步骤见 [Windows 二进制部署](deploy/README.md#windows-二进制部署)
已有部署请先看 [升级说明](deploy/README.md#镜像升级与源码构建),不要覆盖原配置
### 一键安装
请确保当前用户能访问 Docker,并可通过 `sudo` 或 root 设置目录权限
在已安装 Docker Engine、Docker Compose Plugin、curl 和 OpenSSL 的 Linux amd64/arm64 主机上运行
```bash
curl -fsSL https://raw.githubusercontent.com/zyycn/codex-proxy-rs/main/deploy/install.sh -o install.sh && bash install.sh
```
[安装脚本](deploy/install.sh) 默认安装到当前目录下的 `codex-proxy-rs/`,下载同一正式 Release 的部署文件,
自动生成密码、设置目录权限并启动服务
完成后保存显示的访问地址和管理员密码,再[登录管理端](#登录管理端)并[添加账号与客户端密钥](#添加账号与客户端密钥)
可在执行 `bash install.sh` 时传入环境变量:
| 变量 | 用途 | 默认值 |
| --- | --- | --- |
| `INSTALL_DIR` | 安装目录,建议使用绝对路径 | 当前目录下的 `codex-proxy-rs/` |
| `CPR_RELEASE_TAG` | 指定发布标签 | 最新正式版本 |
| `ADMIN_PASSWORD` | 管理员初始密码,至少 12 位,不能包含 `$`,不能使用常见弱口令 | 随机生成 |
例如,自定义安装目录:
```bash
INSTALL_DIR="$HOME/services/codex-proxy-rs" bash install.sh
```
重复运行时请使用同一安装目录,检测到 `deploy/config.yaml` 后,脚本保留现有配置和部署文件,
忽略传入的管理员密码,也不执行版本升级
### 手动安装
自行下载部署文件、配置密码和启动服务的完整步骤见 [部署文档](deploy/README.md#手动安装)
### 登录管理端
部署完成后,打开 `http://127.0.0.1:8080`,使用 `admin@cpr.local` 和管理员密码登录
API Key 持有者可在登录页切换身份,查看自己的用量与额度,并通过「密钥配置」复制 Codex 配置或导入 CC Switch
默认地址只能在服务器本机访问,从其他设备使用时,需要配置
[HTTPS 反向代理](deploy/README.md#公网访问)
### 添加账号与客户端密钥
1. 在「账号」中添加账号,完成授权或导入
2. 按需建立账号分组,再创建客户端密钥并选择可用分组,**不选分组表示可使用全部账号**
3. [连接客户端](#客户端接入)
## 客户端接入
**Codex CLI / 桌面端**:在「使用密钥」中按操作系统复制配置,合并配置后重启 Codex;也可通过「导入到」把服务连接与密钥添加到 CC Switch
完整步骤、生图配置与排障见[客户端配置](deploy/README.md#客户端配置)
**其他 API 客户端**:API Key 填写管理端创建的客户端密钥。按客户端自动追加的请求路径填写 Base URL;远程接入时将本机地址换成服务器的 HTTPS 地址
| 客户端自动追加的路径 | Base URL(本机部署) |
| --- | --- |
| OpenAI Responses:`/responses`;Chat Completions:`/chat/completions` | `http://127.0.0.1:8080/v1` |
| Anthropic Messages:`/v1/messages` | `http://127.0.0.1:8080` |
查询该密钥可见的模型目录:
```bash
curl http://127.0.0.1:8080/v1/models \
-H 'Authorization: Bearer <client-api-key>'
```
[安装脚本选项](deploy/README.md#安装脚本选项) · [macOS 发行包](https://github.com/zyycn/codex-proxy-rs/releases) · [Windows 安装](deploy/README.md#windows-二进制部署) · [已有部署升级](deploy/README.md#镜像升级与源码构建)
## 文档
| 任务 | 文档 |
| 主题 | 文档 |
| --- | --- |
| 部署与使用 | [部署、备份与恢复](deploy/README.md) · [客户端接入与生图](deploy/README.md#客户端配置) |
| 接口集成 | [API 参考](docs/api.md) · [模型定价](docs/api.md#模型定价) |
| 部署与使用 | [部署、备份与恢复](deploy/README.md) · [客户端接入](deploy/README.md#客户端配置) |
| 接口集成 | [API 参考](docs/api.md) · [模型目录](docs/api.md#模型目录) · [模型定价](docs/api.md#模型定价) |
| 使用插件 | [安装、配置与使用](docs/plugins.md) |
| 开发插件 | [SDK 与合同](backend/crates/gateway-plugin/sdk/README.md) · [打包工具](backend/apps/plugin-cli/README.md) · [官方示例](https://github.com/zyycn/codex-proxy-plugins/blob/main/README.md) |
| 开发共用组件 | [组件库说明](https://github.com/zyycn/codex-proxy-ui/blob/main/README.md) · [组件参考](https://github.com/zyycn/codex-proxy-ui/blob/main/playground/components/index.md) · [Playground](https://zyycn.github.io/codex-proxy-ui/) |
@@ -132,6 +55,28 @@ curl http://127.0.0.1:8080/v1/models \
感谢 [LINUX DO](https://linux.do) 社区提供开放、友善的技术交流平台
## 贡献者
[<img src="https://contrib.rocks/image?repo=zyycn/codex-proxy-rs&amp;columns=10" alt="查看 GitHub 贡献者列表" width="480">](https://github.com/zyycn/codex-proxy-rs/graphs/contributors)
## Star History
<a href="https://simrepo.dera.page/#zyycn/codex-proxy-rs&amp;Date">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://simrepo.dera.page/svg?repos=zyycn/codex-proxy-rs&amp;type=Date&amp;theme=dark">
<img src="https://simrepo.dera.page/svg?repos=zyycn/codex-proxy-rs&amp;type=Date" alt="Codex Proxy RS 的 GitHub Star 增长趋势" width="560">
</picture>
</a>
## 支持项目
如果 Codex Proxy RS 帮助到你了,欢迎请我喝杯咖啡 ☕
[![Support me on Ko-fi](docs/donations/ko-fi.svg)](https://ko-fi.com/zyycn)
[<img src="docs/donations/wechat-tips.png" alt="WeChat appreciation code" width="138">](docs/donations/wechat-tips.png)&nbsp;
[<img src="docs/donations/alipay.png" alt="Alipay QR code" width="138">](docs/donations/alipay.png)
## 许可证
本项目基于 [Apache License 2.0](LICENSE) 开源
+77 -54
View File
@@ -292,9 +292,9 @@ dependencies = [
[[package]]
name = "aws-sdk-s3"
version = "1.159.0"
version = "1.161.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8d5c431c5db2f1f6f536c2a19425575e28273859c6ab399d9ac957f73678c7db"
checksum = "d9c63e3ca6e56670513469e992759f4a51041603fde329471b29c5c1f5eaeefe"
dependencies = [
"arc-swap",
"aws-credential-types",
@@ -328,9 +328,9 @@ dependencies = [
[[package]]
name = "aws-sigv4"
version = "1.6.5"
version = "1.6.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "57a4393e6addc3380632887b0998d06ad5f099ab5c478be0a3eeedecf8604161"
checksum = "6c5aa04c533733a77879294f1854c27b3715cc50ea71756d1f6a958702b1a9fb"
dependencies = [
"aws-credential-types",
"aws-smithy-eventstream",
@@ -414,9 +414,9 @@ dependencies = [
[[package]]
name = "aws-smithy-http-client"
version = "1.5.2"
version = "1.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "859a81364f8185349c584fb41cd8765a400cf982f447adada590cf008a9f3b85"
checksum = "203e36a754ced29dab0d710dab8c4fecf181d78f229e90fa6e75c6406ecb55a3"
dependencies = [
"aws-smithy-async",
"aws-smithy-runtime-api",
@@ -460,9 +460,9 @@ dependencies = [
[[package]]
name = "aws-smithy-runtime"
version = "1.16.3"
version = "1.16.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5bc688673e282f42d3152dcd9cacc1a9a75734d7cd39d02e58989276fc750f3c"
checksum = "7ed38b842f93dd8220cc8816750c72ce914b22c6eb3df02beb9632333ccb366d"
dependencies = [
"aws-smithy-async",
"aws-smithy-http",
@@ -483,9 +483,9 @@ dependencies = [
[[package]]
name = "aws-smithy-runtime-api"
version = "1.21.0"
version = "1.22.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0467a2414e84b1b01e37452896fb3562b93926e81c619eba6ecf27ce9e682a0e"
checksum = "c0b79dbb5331ccd297686df811d50ab3f39db171f5c765372a69272a0990b014"
dependencies = [
"aws-smithy-async",
"aws-smithy-runtime-api-macros",
@@ -766,9 +766,9 @@ checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495"
[[package]]
name = "bytes"
version = "1.12.1"
version = "1.12.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"
checksum = "776dfebd015e2d8732c684a2c71003674ccb49457b539b9e82151ba38e96dd7c"
[[package]]
name = "bytes-utils"
@@ -842,9 +842,9 @@ dependencies = [
[[package]]
name = "clap"
version = "4.6.7"
version = "4.6.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946"
checksum = "ac230478587d0269d8d6998b82ae69ea51509d55df66d9e92edd1f986904cd4a"
dependencies = [
"clap_builder",
"clap_derive",
@@ -864,9 +864,9 @@ dependencies = [
[[package]]
name = "clap_derive"
version = "4.6.7"
version = "4.6.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0"
checksum = "895c9d8d2ac2dd8b8a29f3724a14e72aaaa6debcf8c38c82f97305c6a172767a"
dependencies = [
"heck",
"proc-macro2",
@@ -921,6 +921,7 @@ dependencies = [
"gateway-host",
"gateway-plugin-runtime",
"gateway-store",
"provider-antigravity",
"provider-openai",
"provider-xai",
"serde",
@@ -1362,7 +1363,7 @@ dependencies = [
"digest 0.11.3",
"elliptic-curve",
"rfc6979",
"signature 3.0.0",
"signature",
"spki",
"zeroize",
]
@@ -1516,9 +1517,9 @@ dependencies = [
[[package]]
name = "filetime"
version = "0.2.29"
version = "0.2.30"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c287a33c7f0a620c38e641e7f60827713987b3c0f26e8ddc9462cc69cf75759"
checksum = "e1255e7a9f1902190d4c10a75f2f7f495d3d3ce13e9ba26e6c48683a0f4dbed7"
dependencies = [
"cfg-if",
"libc",
@@ -1592,9 +1593,9 @@ checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b"
[[package]]
name = "form_urlencoded"
version = "1.2.2"
version = "1.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"
checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e"
dependencies = [
"percent-encoding",
]
@@ -1849,7 +1850,6 @@ dependencies = [
"bytes",
"chrono",
"config",
"filetime",
"flate2",
"futures",
"gateway-admin",
@@ -2601,17 +2601,17 @@ dependencies = [
[[package]]
name = "jsonwebtoken"
version = "11.1.0"
version = "12.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e75fe14a82d81e5f5af639997db37d8b96045938a7ac6ab18cdbe1c7467e05e1"
checksum = "f347a975eb5fa8f5c4eadce6c1152c11c326cf32cf839fb64ff12d5cb8f4ce8b"
dependencies = [
"aws-lc-rs",
"base64 0.22.1",
"getrandom 0.2.17",
"base64 0.23.1",
"getrandom 0.4.3",
"js-sys",
"serde",
"serde_json",
"signature 2.2.0",
"signature",
"zeroize",
]
@@ -3370,13 +3370,44 @@ dependencies = [
[[package]]
name = "proc-macro2"
version = "1.0.106"
version = "1.0.107"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
dependencies = [
"unicode-ident",
]
[[package]]
name = "provider-antigravity"
version = "0.0.0"
dependencies = [
"async-compression",
"async-stream",
"async-trait",
"base64 0.23.1",
"bytes",
"chrono",
"futures",
"gateway-admin",
"gateway-core",
"gateway-egress",
"gateway-protocol",
"getrandom 0.4.3",
"http",
"http-body-util",
"reqwest",
"serde",
"serde_json",
"sha2",
"thiserror",
"tokio",
"tokio-util",
"tracing",
"url",
"uuid",
"wiremock",
]
[[package]]
name = "provider-openai"
version = "0.0.0"
@@ -3652,9 +3683,9 @@ dependencies = [
[[package]]
name = "redis"
version = "1.8.1"
version = "1.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "db7f3d75b5a3301746bff39a767bf4c5c42506b08513527308b3875bfb64a031"
checksum = "4bef8fa589dd53a8a379a7856de1365d0a1be50c6b8aebb5c01c1ec441a2c509"
dependencies = [
"arc-swap",
"arcstr",
@@ -3725,9 +3756,9 @@ dependencies = [
[[package]]
name = "regex"
version = "1.13.1"
version = "1.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d"
checksum = "9807af0e638c12e753aa1b4e601791bf2a8f71274023c8bbeec12fc149950857"
dependencies = [
"aho-corasick",
"memchr",
@@ -3737,9 +3768,9 @@ dependencies = [
[[package]]
name = "regex-automata"
version = "0.4.18"
version = "0.4.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2"
checksum = "41d60ef07df457506a0a1a2073112eb4aae5733dbd2813c3da77d1b0fd441158"
dependencies = [
"aho-corasick",
"memchr",
@@ -3754,9 +3785,9 @@ checksum = "cab834c73d247e67f4fae452806d17d3c7501756d98c8808d7c9c7aa7d18f973"
[[package]]
name = "regex-syntax"
version = "0.8.11"
version = "0.8.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6"
[[package]]
name = "reqwest"
@@ -4207,15 +4238,6 @@ dependencies = [
"libc",
]
[[package]]
name = "signature"
version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de"
dependencies = [
"rand_core 0.6.4",
]
[[package]]
name = "signature"
version = "3.0.0"
@@ -5110,14 +5132,15 @@ checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
[[package]]
name = "url"
version = "2.5.8"
version = "2.5.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed"
checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a"
dependencies = [
"form_urlencoded",
"idna",
"percent-encoding",
"serde",
"serde_derive",
]
[[package]]
@@ -5140,9 +5163,9 @@ checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
[[package]]
name = "uuid"
version = "1.29.2"
version = "1.29.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bed99139f7dac9b5cfe5f17be4d66dc7079a34dee1d74bcc77217119240e267c"
checksum = "3c14b15dffa2f4bd712103e857140aa04a4f2ff6e955c77d7eb8e53ee02a3b64"
dependencies = [
"getrandom 0.4.3",
"js-sys",
@@ -5692,9 +5715,9 @@ dependencies = [
[[package]]
name = "zeroize"
version = "1.9.1"
version = "1.9.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879"
checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa"
dependencies = [
"zeroize_derive",
]
@@ -5745,9 +5768,9 @@ dependencies = [
[[package]]
name = "zip"
version = "9.5.1"
version = "9.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3476fd497ac8af5b1ec7b51acab7bef380f7e8dd8e0487595bafd839417a302"
checksum = "721c8158b9503b2660291ad3056a20f722deaeed21bb908a9a363d7e17b34f0e"
dependencies = [
"constant_time_eq",
"crc32fast",
+1
View File
@@ -11,6 +11,7 @@ members = [
"crates/gateway-plugin/sdk",
"crates/gateway-protocol",
"crates/gateway-store",
"crates/providers/antigravity",
"crates/providers/openai",
"crates/providers/xai",
]
+1
View File
@@ -18,6 +18,7 @@ gateway-core = { path = "../../crates/gateway-core" }
gateway-host = { path = "../../crates/gateway-host" }
gateway-plugin-runtime = { path = "../../crates/gateway-plugin/runtime" }
gateway-store = { path = "../../crates/gateway-store" }
provider-antigravity = { path = "../../crates/providers/antigravity" }
provider-openai = { path = "../../crates/providers/openai" }
provider-xai = { path = "../../crates/providers/xai" }
serde = { version = "1.0.228", features = ["derive"] }
@@ -32,6 +32,8 @@ pub enum BootstrapError {
#[error(transparent)]
Xai(#[from] provider_xai::XaiInitializeError),
#[error(transparent)]
Antigravity(#[from] provider_antigravity::ConfigError),
#[error(transparent)]
Registry(#[from] gateway_core::engine::provider::RegistryError),
#[error(transparent)]
Core(#[from] gateway_core::CoreError),
+1 -2
View File
@@ -174,8 +174,7 @@ pub async fn run() -> Result<(), BootstrapError> {
gateway_host::retention::worker(store.retention())
));
plan.extend(core.take_worker_contributions());
plan.extend(providers.openai.take_worker_contributions());
plan.extend(providers.xai.take_worker_contributions());
plan.extend(providers.workers);
plan.extend(admin.take_worker_contributions());
plan.extend(providers.peer.take_worker_contributions());
plan.push(or_shutdown!(
+15 -7
View File
@@ -59,8 +59,7 @@ impl Environment {
}
pub(super) struct Providers {
pub(super) openai: provider_openai::ProviderBundle,
pub(super) xai: provider_xai::ProviderBundle,
pub(super) workers: Vec<gateway_core::task::WorkerContribution>,
pub(super) core: ProviderRegistry,
pub(super) admin: ProviderAdminRegistry,
pub(super) peer: gateway_admin::PeerUpstreamBundle,
@@ -80,11 +79,21 @@ impl Providers {
)
.await?;
environment.host.report_startup_ready("OpenAI Provider");
let antigravity = provider_antigravity::initialize(ports.clone())?;
environment
.host
.report_startup_ready("Antigravity Provider");
let xai = provider_xai::initialize(ports).await?;
environment.host.report_startup_ready("xAI Provider");
let core = ProviderRegistry::new([openai.core_provider(), xai.core_provider()])?;
let admin = ProviderAdminRegistry::new([openai.admin_provider(), xai.admin_provider()])
.map_err(|_| gateway_admin::model::AdminError::invalid("Provider 管理身份冲突"))?;
let bundles = [openai, xai, antigravity];
let core = ProviderRegistry::new(bundles.iter().map(|bundle| bundle.core.clone()))?;
let admin =
ProviderAdminRegistry::new(bundles.iter().map(|bundle| bundle.admin.clone()))
.map_err(|_| gateway_admin::model::AdminError::invalid("Provider 管理身份冲突"))?;
let workers = bundles
.into_iter()
.flat_map(|bundle| bundle.workers)
.collect();
let peer = gateway_admin::initialize_peer_upstream(
environment.store.provider_ports().accounts(),
&admin,
@@ -98,8 +107,7 @@ impl Providers {
.map_err(|_| gateway_admin::model::AdminError::invalid("互联观测端口重复绑定"))?;
Ok(Self {
peer,
openai,
xai,
workers,
core,
admin,
})
+131 -25
View File
@@ -22,6 +22,7 @@ pub(super) const WORKSPACE_MEMBERS: &[&str] = &[
"crates/gateway-plugin/sdk",
"crates/gateway-protocol",
"crates/gateway-store",
"crates/providers/antigravity",
"crates/providers/openai",
"crates/providers/xai",
];
@@ -62,6 +63,7 @@ fn gateway_core_depends_on_no_http_db_redis_or_provider_crate() {
"redis",
"gateway-host",
"gateway-store",
"provider-antigravity",
"provider-openai",
"provider-xai",
],
@@ -115,17 +117,50 @@ fn core_value_owners_do_not_depend_on_execution_or_routing() {
#[test]
fn domain_owner_paths_form_a_dag() {
for member in ["crates/gateway-core", "crates/gateway-admin"] {
assert_owner_paths_form_a_dag(member);
let cycles = WORKSPACE_MEMBERS
.iter()
.flat_map(|member| owner_dependency_cycles(member))
.collect::<Vec<_>>();
assert!(
cycles.is_empty(),
"owner dependency cycles:\n{}",
cycles.join("\n")
);
}
#[test]
fn provider_shared_owners_use_consistent_directories() {
for member in provider_members() {
let root = backend_root().join(member).join("src");
for owner in [
"admin",
"billing",
"credential",
"profile",
"provider",
"transport",
] {
assert!(
root.join(owner).join("mod.rs").is_file(),
"{member} must place its {owner} owner in {owner}/mod.rs",
);
}
}
}
fn assert_owner_paths_form_a_dag(member: &str) {
fn provider_members() -> impl Iterator<Item = &'static str> {
WORKSPACE_MEMBERS
.iter()
.copied()
.filter(|member| member.starts_with("crates/providers/"))
}
fn owner_dependency_cycles(member: &str) -> Vec<String> {
let root = backend_root().join(member).join("src");
let reexports = read_root_reexport_owners(&root);
let mut graph = BTreeMap::<String, BTreeSet<String>>::new();
for relative in super::rust_files(&root) {
if relative == Path::new("lib.rs") {
if relative == Path::new("lib.rs") || relative == Path::new("main.rs") {
continue;
}
let mut references = CrateReferences::in_module(&relative).with_root_reexports(&reexports);
@@ -135,35 +170,52 @@ fn assert_owner_paths_form_a_dag(member: &str) {
references.owners.remove(&owner);
graph.entry(owner).or_default().extend(references.owners);
}
let mut cycles = Vec::new();
for owner in graph.keys() {
let mut pending = graph[owner].iter().cloned().collect::<Vec<_>>();
let mut pending = graph[owner]
.iter()
.map(|dependency| (dependency.clone(), vec![owner.clone()]))
.collect::<Vec<_>>();
let mut visited = BTreeSet::new();
while let Some(dependency) = pending.pop() {
assert_ne!(
&dependency, owner,
"{member} owner dependency cycle reaches {owner}"
);
while let Some((dependency, mut path)) = pending.pop() {
path.push(dependency.clone());
if &dependency == owner {
cycles.push(format!("{member}: {}", path.join(" -> ")));
break;
}
if visited.insert(dependency.clone())
&& let Some(next) = graph.get(&dependency)
{
pending.extend(next.iter().cloned());
pending.extend(
next.iter()
.map(|dependency| (dependency.clone(), path.clone())),
);
}
}
}
cycles
}
#[test]
fn shared_owners_do_not_depend_on_their_callers() {
let boundaries: &[(&str, &str, &[&str])] = &[
("crates/providers/xai", "transport", &["credential"]),
("crates/providers/openai", "transport", &["provider"]),
(
"crates/providers/xai",
"transport",
&["credential", "provider"],
),
(
"crates/providers/openai",
"transport",
&["credential", "provider"],
),
("crates/gateway-api", "time", &["admin"]),
(
"crates/gateway-api",
"client_error",
&["admin", "openai", "middleware"],
&["admin", "data_plane", "middleware"],
),
("crates/gateway-api", "middleware", &["openai"]),
("crates/gateway-api", "middleware", &["data_plane"]),
("crates/gateway-host", "system_update", &["config"]),
("crates/gateway-plugin/runtime", "package", &["callback"]),
];
@@ -189,6 +241,39 @@ fn shared_owners_do_not_depend_on_their_callers() {
}
}
#[test]
fn provider_billing_is_private_and_independent_of_other_provider_owners() {
for member in provider_members() {
let root = backend_root().join(member).join("src");
let source = fs::read_to_string(root.join("lib.rs")).expect("read provider root");
let syntax = syn::parse_file(&source).expect("parse provider root");
assert!(
syntax.items.iter().any(|item| matches!(item,
Item::Mod(module) if module.ident == "billing"
&& matches!(module.vis, syn::Visibility::Inherited)
)),
"{member} must keep billing behind a private owner",
);
let reexports = read_root_reexport_owners(&root);
for relative in super::rust_files(&root) {
let mut references =
CrateReferences::in_module(&relative).with_root_reexports(&reexports);
if references.module_path.first().map(String::as_str) != Some("billing") {
continue;
}
let source = fs::read_to_string(root.join(&relative)).expect("read billing source");
references.visit_file(&syn::parse_file(&source).expect("parse billing source"));
references.owners.remove("billing");
assert!(
references.owners.is_empty(),
"{member}/src/{} billing must consume explicit facts, not depend on {:?}",
relative.display(),
references.owners,
);
}
}
}
#[test]
fn owner_reference_scan_resolves_groups_reexports_and_relative_paths() {
let syntax = syn::parse_file(
@@ -252,7 +337,12 @@ fn owner_reference_scan_resolves_crate_root_reexports() {
}
fn read_root_reexport_owners(root: &Path) -> BTreeMap<String, String> {
let source = fs::read_to_string(root.join("lib.rs")).expect("read crate root");
let root_file = if root.join("lib.rs").is_file() {
root.join("lib.rs")
} else {
root.join("main.rs")
};
let source = fs::read_to_string(root_file).expect("read crate root");
root_reexport_owners(&syn::parse_file(&source).expect("parse crate root"))
}
@@ -430,8 +520,18 @@ fn plugin_sdk_has_no_workspace_dependencies() {
#[test]
fn provider_crates_do_not_depend_on_each_other() {
assert_no_dependency("crates/providers/openai", &["provider-xai"]);
assert_no_dependency("crates/providers/xai", &["provider-openai"]);
let providers = PACKAGE_TO_MEMBER
.iter()
.filter(|(_, member)| member.starts_with("crates/providers/"))
.collect::<Vec<_>>();
for (package, member) in &providers {
let forbidden = providers
.iter()
.filter(|(other, _)| other != package)
.map(|(other, _)| *other)
.collect::<Vec<_>>();
assert_no_dependency(member, &forbidden);
}
}
#[test]
@@ -455,6 +555,7 @@ const PACKAGE_TO_MEMBER: &[(&str, &str)] = &[
("gateway-plugin-sdk", "crates/gateway-plugin/sdk"),
("gateway-protocol", "crates/gateway-protocol"),
("gateway-store", "crates/gateway-store"),
("provider-antigravity", "crates/providers/antigravity"),
("provider-openai", "crates/providers/openai"),
("provider-xai", "crates/providers/xai"),
];
@@ -463,7 +564,7 @@ const PACKAGE_TO_MEMBER: &[(&str, &str)] = &[
const ADAPTER_PUBLIC_MODULES: &[(&str, &[&str])] = &[
("crates/gateway-plugin/sdk", &["call", "client"]),
("crates/gateway-plugin/runtime", &[]),
("crates/gateway-api", &["admin", "auth", "openai"]),
("crates/gateway-api", &["admin", "auth", "data_plane"]),
(
"crates/gateway-host",
&[
@@ -485,9 +586,10 @@ const ADAPTER_PUBLIC_MODULES: &[(&str, &[&str])] = &[
("crates/gateway-store", &["backup", "postgres", "redis"]),
(
"crates/providers/openai",
&["config", "credential", "transport"],
&["config", "credential", "profile", "transport"],
),
("crates/providers/xai", &["transport"]),
("crates/providers/antigravity", &[]),
("crates/providers/xai", &["profile", "transport"]),
];
/// 不对应单一生产模块、而是校验 crate/workspace 整体契约的根级测试场景
@@ -505,6 +607,7 @@ const ALLOWED_INTERNAL_EDGES: &[(&str, &str)] = &[
("codex-proxy-rs", "gateway-host"),
("codex-proxy-rs", "gateway-plugin-runtime"),
("codex-proxy-rs", "gateway-store"),
("codex-proxy-rs", "provider-antigravity"),
("codex-proxy-rs", "provider-openai"),
("codex-proxy-rs", "provider-xai"),
("gateway-admin", "gateway-core"),
@@ -525,6 +628,10 @@ const ALLOWED_INTERNAL_EDGES: &[(&str, &str)] = &[
("gateway-plugin-runtime", "gateway-protocol"),
("gateway-store", "gateway-admin"),
("gateway-store", "gateway-core"),
("provider-antigravity", "gateway-admin"),
("provider-antigravity", "gateway-core"),
("provider-antigravity", "gateway-egress"),
("provider-antigravity", "gateway-protocol"),
("provider-openai", "gateway-admin"),
("provider-openai", "gateway-core"),
("provider-openai", "gateway-egress"),
@@ -646,10 +753,9 @@ fn workspace_modules_follow_conventional_file_layout() {
let tests = member_root.join("tests");
if tests.is_dir() {
let roots = targets.get(&tests).expect("Cargo test source roots");
assert_module_tree(
&tests,
&roots.iter().map(String::as_str).collect::<Vec<_>>(),
);
let roots = roots.iter().map(String::as_str).collect::<Vec<_>>();
assert_module_tree(&tests, &roots);
assert_directory_modules_have_children(&tests, &roots);
}
}
}
+8 -13
View File
@@ -1,7 +1,6 @@
# Codex Proxy Plugin CLI
`cpr-plugin` 校验并规范化作者清单、收集声明的资源,生成可安装归档及 SHA-256 校验文件。
输出合同与 [SDK 版本](../../crates/gateway-plugin/sdk/README.md)一致
`cpr-plugin` 按 [SDK 合同](../../crates/gateway-plugin/sdk/README.md)校验清单,将插件可执行文件与声明的资源打包,并输出 SHA-256 校验文件
## 安装
@@ -11,7 +10,7 @@
cargo +1.99.1 install --locked --path backend/apps/plugin-cli --root /path/to/local-tools
```
将 `/path/to/local-tools/bin` 加入 `PATH`,或使用可执行文件的完整路径;工具链与宿主 [验证命令](../../../docs/architecture.md#验证命令)一致
将 `/path/to/local-tools/bin` 加入 `PATH`,或使用可执行文件的完整路径
## 打包
@@ -26,24 +25,20 @@ cpr-plugin package \
--output-dir /path/to/output
```
`--resource-map web=web/dist` 将包内 `web/` 前缀映射到作者清单所在目录下的 `web/dist/`。
可重复传入不同前缀,源目录必须位于项目内;没有对应资源时省略该参数,未使用的映射会被拒绝。
未映射的资源按清单中的相对路径读取,只收集 `resources` 声明的文件
资源文件须在 `resources` 中声明,默认从清单所在目录按相对路径读取。
`--resource-map web=web/dist` 从项目内的 `web/dist/` 读取包内 `web/` 资源。可为不同前缀重复传参,未匹配任何资源的映射会报错
输出为 `<插件 ID>-<版本>-<目标 triple>.tar.gz` 及同名 `.tar.gz.sha256`;归档根目录直接包含 `plugin.json`、可执行文件和声明资源。
输出为 `<插件 ID>-<版本>-<目标 triple>.tar.gz` 及对应的 `.tar.gz.sha256`。归档根目录包含 `plugin.json`、可执行文件和声明资源。
输入清单及生成后的清单均不得超过 64 KiB,压缩包上限为 32 MiB,展开归档上限为 128 MiB
作者清单不填写 `package`;字段省略规则、能力版本和挂载阶段见 [SDK 扩展项声明](../../crates/gateway-plugin/sdk/docs/manifest.md#扩展项简写)。
CLI 生成规范化后的 `plugin.json`,补入协议版本、目标平台和文件摘要。打包成功只证明输入符合包合同,实际启动与能力仍需在目标宿主验证
作者清单须省略 `package`。CLI 将协议版本、目标平台和文件摘要写入 `plugin.json`。可省略的声明字段见 [SDK 扩展项声明](../../crates/gateway-plugin/sdk/docs/manifest.md#扩展项简写)
支持 `x86_64-unknown-linux-gnu`、`aarch64-unknown-linux-gnu` 和 `aarch64-apple-darwin`。
完整开发示例在独立仓库 `codex-proxy-plugins` 的 `examples/workbench`,可通过[子模块](../../../docs/development.md#源码联调)检出;本工具不负责源码构建、上传或启用插件
打包后在目标宿主验证启动和插件功能。完整示例见插件[子模块](../../../docs/development.md#源码联调)的 `examples/workbench`
### 图标资源
在作者清单的 `icon` 中指定图标,并在 `resources` 中登记对应路径与 MIME 类型,配置方式见
[SDK 插件图标](../../crates/gateway-plugin/sdk/docs/manifest.md#插件图标)。图标与其他声明资源一样参与打包和摘要计算,
无需额外命令参数;工具保留文件原始内容,宿主安装时验证图标内容与资源限制
按 [SDK 插件图标](../../crates/gateway-plugin/sdk/docs/manifest.md#插件图标)填写 `icon` 和 `resources`。CLI 自动打包原文件并计算摘要,宿主在安装时校验
## 开发
@@ -117,12 +117,10 @@ async fn initialize_inner(
backup_ports.object_store(),
)
.with_timezone(timezone);
let system_preflight = Arc::new(
use_case::system_preflight::PluginSystemUpdatePreflight::new(
store.plugins(),
plugin_inspector.clone(),
),
);
let system_preflight = Arc::new(use_case::system::PluginSystemUpdatePreflight::new(
store.plugins(),
plugin_inspector.clone(),
));
let system = Arc::new(DefaultSystemService::new(system, system_preflight));
let observations: Arc<dyn ports::store::ObservabilityStore> = Arc::new(
use_case::observability::CachedObservabilityStore::new(store.observability()),
@@ -183,7 +181,7 @@ async fn initialize_inner(
PluginDistributionPorts::new(plugin_distribution, store.proxies()),
snapshot.clone(),
plugin_preparation,
published_snapshot,
published_snapshot.clone(),
store.plugin_state(),
)),
key_usage,
@@ -201,6 +199,7 @@ async fn initialize_inner(
store.account_groups(),
store.account_runtime(),
snapshot.clone(),
published_snapshot,
)),
client_keys: Arc::new(DefaultClientKeyService::new(
store.client_keys(),
@@ -4,7 +4,7 @@ use std::collections::BTreeMap;
use chrono::{DateTime, Utc};
use gateway_core::{
account::{AccountStatusFacts, FastMode},
account::{AccountModelAccess, AccountStatusFacts, FastMode},
routing::AccountGroupId,
};
@@ -14,15 +14,25 @@ use super::{PageSize, Revision, observability::DecimalAmount};
pub fn validate_group_fields(
name: &str,
description: Option<&str>,
) -> Result<(), super::AdminModelError> {
if name.trim() != name
|| name.is_empty()
|| name.chars().count() > 100
|| name.chars().any(char::is_control)
|| description
.is_some_and(|value| value.len() > 4096 || value.chars().any(char::is_control))
{
return Err(super::AdminModelError::InvalidAccountGroupFields);
) -> Result<(), super::AdminError> {
if name.trim().is_empty() {
return Err(super::AdminError::invalid("请输入账号组名称"));
}
if name.chars().count() > 100 {
return Err(super::AdminError::invalid("账号组名称最多 100 个字符"));
}
if name.trim() != name || name.chars().any(char::is_control) {
return Err(super::AdminError::invalid(
"账号组名称不能包含首尾空白或控制字符",
));
}
if let Some(description) = description {
if description.len() > 4096 {
return Err(super::AdminError::invalid("账号组描述最多 4096 字节"));
}
if description.chars().any(char::is_control) {
return Err(super::AdminError::invalid("账号组描述不能包含控制字符"));
}
}
Ok(())
}
@@ -102,6 +112,8 @@ pub struct AccountGroupListQuery {
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AccountGroupRecord {
pub allow_image_generation: bool,
pub allow_subagents: bool,
pub model_access: AccountModelAccess,
pub fast_mode: FastMode,
pub id: AccountGroupId,
pub name: String,
@@ -142,6 +154,8 @@ pub struct AccountGroupOptionsPage {
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CreateAccountGroup {
pub allow_image_generation: bool,
pub allow_subagents: bool,
pub model_access: AccountModelAccess,
pub fast_mode: FastMode,
pub name: String,
pub description: Option<String>,
@@ -152,6 +166,8 @@ pub struct CreateAccountGroup {
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NewAccountGroup {
pub allow_image_generation: bool,
pub allow_subagents: bool,
pub model_access: AccountModelAccess,
pub fast_mode: FastMode,
pub id: AccountGroupId,
pub name: String,
@@ -163,6 +179,8 @@ pub struct NewAccountGroup {
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UpdateAccountGroup {
pub allow_image_generation: Option<bool>,
pub allow_subagents: Option<bool>,
pub model_access: Option<AccountModelAccess>,
pub fast_mode: Option<FastMode>,
pub id: AccountGroupId,
pub name: String,
@@ -21,6 +21,10 @@ pub use gateway_core::account::{
/// 账号可用的管理操作
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct ProviderAccountCapabilities {
pub credential_refresh: bool,
pub reauthorize: bool,
pub credential_export: bool,
pub model_catalog_download: bool,
pub quota_settings_supported: bool,
pub quota_credits: bool,
pub quota: bool,
@@ -36,6 +36,7 @@ pub enum MutationAuditOperation {
PluginSourceCredentialCreate,
PluginSourceCredentialDelete,
ClientApiKeyUpdateBudgetLimits,
ClientApiKeyBatchUpdate,
ClientApiKeyCreate,
ClientApiKeyUpdate,
ClientApiKeyEnabled { enabled: bool },
@@ -97,6 +98,7 @@ impl MutationAuditOperation {
Self::PluginSourceCredentialCreate => ("create", "plugin_source_credential"),
Self::PluginSourceCredentialDelete => ("delete", "plugin_source_credential"),
Self::ClientApiKeyUpdateBudgetLimits => ("update_budget_limits", "client_api_key"),
Self::ClientApiKeyBatchUpdate => ("batch_update", "client_api_key"),
Self::ClientApiKeyCreate => ("create", "client_api_key"),
Self::ClientApiKeyUpdate => ("update", "client_api_key"),
Self::ClientApiKeyEnabled { enabled } => {
@@ -156,6 +156,7 @@ impl BackupStatusTransition {
/// S3 存储配置更新命令;`secret_access_key` 为 `None` 表示保留旧值
#[derive(Clone)]
pub struct UpdateBackupStorageCommand {
pub storage_revision: u64,
pub endpoint: String,
pub region: String,
pub bucket: String,
@@ -183,6 +184,7 @@ impl fmt::Debug for UpdateBackupStorageCommand {
/// 调度配置更新命令
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UpdateBackupScheduleCommand {
pub storage_revision: u64,
pub schedule_enabled: bool,
pub cron_expression: String,
pub retention_days: u32,
@@ -218,6 +218,66 @@ pub struct UpdateClientKey {
pub weekly_limit_usd: Option<gateway_core::metering::Decimal>,
}
/// 批量编辑只覆盖明确选择的互联选项
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ClientPeerSharingPatch {
pub enabled: Option<bool>,
pub share_pool: Option<bool>,
pub share_quota: Option<bool>,
pub share_plans: Option<bool>,
}
impl ClientPeerSharingPatch {
#[must_use]
pub fn is_empty(self) -> bool {
self == Self::default()
}
#[must_use]
pub fn apply(
self,
current: gateway_core::policy::ClientPeerSharing,
) -> gateway_core::policy::ClientPeerSharing {
gateway_core::policy::ClientPeerSharing {
enabled: self.enabled.unwrap_or(current.enabled),
share_pool: self.share_pool.unwrap_or(current.share_pool),
share_quota: self.share_quota.unwrap_or(current.share_quota),
share_plans: self.share_plans.unwrap_or(current.share_plans),
}
}
}
/// 对各个密钥独立应用同一份局部设置
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct BatchUpdateClientKeys {
pub ids: Vec<ClientApiKeyId>,
pub group_ids: Option<Vec<AccountGroupId>>,
pub enabled: Option<bool>,
pub max_concurrency: Option<u64>,
pub requests_per_minute: Option<u64>,
pub daily_limit_usd: Option<gateway_core::metering::Decimal>,
pub weekly_limit_usd: Option<gateway_core::metering::Decimal>,
pub peer_sharing: ClientPeerSharingPatch,
pub request_profile_override_updates: ProviderRequestProfileOverrideUpdates,
pub installation_seed: Option<uuid::Uuid>,
}
impl BatchUpdateClientKeys {
#[must_use]
pub fn has_changes(&self) -> bool {
self.group_ids.is_some()
|| self.enabled.is_some()
|| self.max_concurrency.is_some()
|| self.requests_per_minute.is_some()
|| self.daily_limit_usd.is_some()
|| self.weekly_limit_usd.is_some()
|| !self.peer_sharing.is_empty()
|| !self.request_profile_override_updates.is_empty()
|| self.installation_seed.is_some()
}
}
/// 修改 Client Key 启用状态
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SetClientKeyEnabled {
@@ -257,9 +317,69 @@ impl ClientKeyBudgetWindowPeriod {
}
}
/// 手动对齐只需要账号身份,列表不读取凭据、额度或用量
#[derive(serde::Serialize, Debug)]
pub struct BudgetReferenceAccount {
pub id: String,
pub name: String,
pub email: Option<String>,
pub provider: String,
}
#[derive(serde::Serialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct BudgetReferenceAccountPage {
pub items: Vec<BudgetReferenceAccount>,
pub next_cursor: Option<String>,
}
/// 管理员可预览的账号窗口保留 Provider 的稳定标识
pub struct ClientKeyBudgetReference {
pub key: String,
pub label: String,
pub period: ClientKeyBudgetWindowPeriod,
pub bounds: ExplicitClientKeyBudgetWindow,
}
impl ClientKeyBudgetReference {
/// 只取整账号当前的日/周窗口,对齐结束后恢复密钥自身周期
pub fn from_current_window(
window: super::provider_credentials::ProviderQuotaWindow,
now: DateTime<Utc>,
) -> Option<Self> {
use super::provider_credentials::QuotaLocalUsageAttribution;
if window.local_usage_attribution != QuotaLocalUsageAttribution::AccountWide
|| window
.upstream
.as_ref()
.is_some_and(|upstream| upstream.stale)
{
return None;
}
let period = match window.window_seconds? {
86_400 => ClientKeyBudgetWindowPeriod::Daily,
604_800 => ClientKeyBudgetWindowPeriod::Weekly,
_ => return None,
};
let (starts_at, ends_at) = window.observed_bounds()?;
(starts_at..ends_at).contains(&now).then_some(Self {
key: window.key,
label: window.label,
period,
bounds: ExplicitClientKeyBudgetWindow {
starts_at,
ends_at,
resume_calendar: true,
},
})
}
}
/// 按请求完成时间归属的左闭右开预算窗口
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ExplicitClientKeyBudgetWindow {
/// 一次性对齐的窗口到期后恢复原生滚动
pub resume_calendar: bool,
pub starts_at: DateTime<Utc>,
pub ends_at: DateTime<Utc>,
}
@@ -22,7 +22,6 @@ pub mod pricing;
pub mod provider_credentials;
pub mod proxies;
pub mod quota_forecast;
pub mod quota_forecast_sampling;
pub mod quota_history;
pub mod reset_credit_automation;
pub mod retention;
@@ -236,8 +235,6 @@ pub enum AdminModelError {
InvalidPageSize(u16),
#[error("observability page size {0} is outside 1..=100")]
InvalidObservabilityPageSize(u16),
#[error("account group name or description is invalid")]
InvalidAccountGroupFields,
#[error("client key group IDs are duplicated or exceed 1000 entries")]
InvalidClientKeyGroups,
#[error("client key page size must be inside 1..=65535")]
@@ -180,7 +180,7 @@ pub struct UsageFilter {
pub enum UsageRecordStatus {
#[default]
Success,
Error,
Error(Option<UsageErrorOrigin>),
All,
}
@@ -648,6 +648,56 @@ pub struct AttemptMetrics {
pub costs: Vec<CurrencyCost>,
}
/// 管理员按当前指标排列模型与趋势,值只来自固定的聚合列
#[derive(Debug, Clone, Copy, Default, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum KeyUsageMetric {
#[default]
CostUsd,
Tokens,
Requests,
}
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct KeyUsageTotals {
pub requests: u64,
pub tokens: Option<u64>,
pub cost_usd: Option<String>,
pub has_missing_cost: bool,
pub has_estimated_cost: bool,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct KeyModelRow {
pub model: String,
pub totals: KeyUsageTotals,
pub peak_requests: u64,
pub active_days: u32,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct KeyTrendPoint {
pub date: chrono::NaiveDate,
pub value: Option<String>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct KeyTrendSeries {
/// 空字符串表示未记录模型,None 表示合并的其他模型
pub model: Option<String>,
pub points: Vec<KeyTrendPoint>,
}
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
pub struct KeyStatisticsOverview {
pub totals: KeyUsageTotals,
pub series: Vec<KeyTrendSeries>,
#[serde(rename = "modelCount")]
pub model_count: u64,
}
/// 时间序列粒度
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Granularity {
@@ -814,6 +864,17 @@ pub enum UsageErrorOrigin {
Unknown,
}
/// 来源规则所依赖的已保存事实,供内存投影与持久层分页查询共同解释
#[derive(Clone, Copy)]
pub enum UsageErrorEvidence {
ProviderErrorCode,
UpstreamStatusAtLeast(u16),
SavedUpstreamErrorOrClose,
ErrorKind(&'static [&'static str]),
Continuation(&'static [&'static str]),
ConnectionExit(&'static [&'static str]),
}
impl UsageErrorOrigin {
#[must_use]
pub const fn as_str(self) -> &'static str {
@@ -5,6 +5,7 @@ use std::collections::{BTreeMap, BTreeSet};
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct PricingCatalog {
pub supported_bands: BTreeMap<String, Vec<String>>,
pub defaults: PricingOverrides,
pub overrides: PricingOverrides,
pub synced: PricingOverrides,
@@ -700,6 +700,7 @@ pub struct PreparedCredentialRotationFacts {
pub preserve_profile: bool,
/// 连接配置变更保留当前凭据健康状态与错误事实
pub preserve_credential_state: bool,
pub preserve_access_token_expiry: bool,
pub provider_material: ProviderDocument,
pub has_refresh_token: bool,
pub access_token_expires_at: Option<DateTime<Utc>>,
@@ -819,7 +820,15 @@ pub struct ProviderQuotaWindow {
pub provider_data: Option<ProviderDocument>,
}
/// 账号用量统计周期,完整周/月额度优先,随后使用 Provider 提供的本地滚动日统计
impl ProviderQuotaWindow {
pub(crate) fn observed_bounds(&self) -> Option<(DateTime<Utc>, DateTime<Utc>)> {
let ends_at = self.reset_at?;
let duration = chrono::Duration::try_seconds(i64::try_from(self.window_seconds?).ok()?)?;
Some((ends_at.checked_sub_signed(duration)?, ends_at))
}
}
/// 账号用量统计周期,完整周/月额度优先,缺少可归属窗口时使用本地滚动日统计
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum AccountUsagePeriod {
Weekly,
@@ -1297,6 +1306,8 @@ pub struct AccountDirectoryItem {
pub plan_type_display: Option<String>,
pub projection: gateway_core::account::AccountStatusProjection,
pub usage: Option<super::accounts::AccountUsage>,
/// Admin 选择的本地统计周期,不要求存在对应的上游额度窗口
pub usage_period: Option<AccountUsagePeriod>,
pub quota: ProviderQuota,
}
@@ -9,7 +9,6 @@ use super::{PageSize, Revision, account_groups::AccountGroupRef};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AccountProxySelection {
Direct,
Url(OutboundProxy),
Saved(String),
}
@@ -0,0 +1,14 @@
//! 额度预测投影与历史采样的模块门面
mod projection;
mod sampling;
pub(crate) use projection::quota_forecast_source_window;
pub use projection::{
AccountQuotaForecast, AccountQuotaForecastReport, QuotaForecastSource, account_quota_forecasts,
};
pub use sampling::{
MAX_FORECAST_HISTORY_POINTS, QuotaForecastHistory, QuotaForecastHistoryPoint,
QuotaForecastMethod, QuotaForecastObservation, QuotaForecastPoint, QuotaForecastSample,
QuotaForecastUsage, select_forecast_sample,
};
@@ -2,8 +2,8 @@
use chrono::{DateTime, Duration, Utc};
use super::provider_credentials::{AccountUsagePeriod, ProviderQuota, ProviderQuotaWindow};
use super::quota_forecast_sampling::{QuotaForecastMethod, QuotaForecastSample};
use super::super::provider_credentials::{AccountUsagePeriod, ProviderQuota, ProviderQuotaWindow};
use super::sampling::{QuotaForecastMethod, QuotaForecastSample};
const DAY_SECONDS: u64 = 86_400;
const MIN_USED_PERCENT: f64 = 5.0;
@@ -73,7 +73,7 @@ pub fn account_quota_forecasts(
target_seconds,
extrapolated: false,
source: None,
unavailable_reason: Some("缺少周/月额度窗口,请刷新账号额度"),
unavailable_reason: Some("缺少可归属整个账号的周/月额度窗口"),
low_sample: false,
incomplete_cost: false,
incomplete_tokens: false,
@@ -2,12 +2,13 @@
use chrono::{DateTime, Utc};
use super::provider_credentials::ProviderDocument;
use super::super::provider_credentials::ProviderDocument;
/// 限制带 Provider 文档的历史点数量;累计用量仍覆盖整个查询区间
pub const MAX_FORECAST_HISTORY_POINTS: usize = 128;
const MIN_BLOCK_PERCENT: f64 = 5.0;
const RECENT_BLOCKS: usize = 3;
const MAX_PERCENT_REVERSAL: f64 = 1.0;
#[derive(Debug, Clone, Default, PartialEq)]
pub struct QuotaForecastUsage {
@@ -80,11 +81,55 @@ pub struct QuotaForecastObservation {
#[derive(Debug, Clone)]
pub struct QuotaForecastPoint {
pub started_at: DateTime<Utc>,
pub observed_at: DateTime<Utc>,
pub reset_at: DateTime<Utc>,
pub used_percent: f64,
pub usage: QuotaForecastUsage,
}
impl QuotaForecastPoint {
fn follows(&self, previous: &Self) -> bool {
previous.observed_at <= self.started_at && previous.observed_at < self.observed_at
}
}
/// 当前窗口内仍有旧周期记录时,只在旧读数已到期、用量回落且新读数得到印证后重设累计
fn cycle_boundary(
history: &[QuotaForecastPoint],
current: &QuotaForecastPoint,
) -> (Option<usize>, bool) {
let mut boundary = None;
let mut awaiting_confirmation = false;
for (index, pair) in history.windows(2).enumerate() {
let (older, previous) = (&pair[0], &pair[1]);
let first_index = index + 2;
let first = history.get(first_index).unwrap_or(current);
let before_reset = older.used_percent.min(previous.used_percent);
if !previous.follows(older)
|| !first.follows(previous)
|| older.reset_at <= previous.observed_at
|| older.reset_at > first.started_at
|| previous.reset_at > first.started_at
|| before_reset - first.used_percent <= MAX_PERCENT_REVERSAL
{
continue;
}
// 快照可能复用请求读数;只有另一条在新窗口内独立完成的请求能确认换段
let confirmation = history
.get(first_index + 1..)
.and_then(|later| later.iter().find(|next| next.follows(first)));
awaiting_confirmation = confirmation.is_none();
if confirmation.is_some_and(|next| {
next.observed_at < first.reset_at
&& before_reset - next.used_percent > MAX_PERCENT_REVERSAL
}) {
boundary = Some(first_index);
}
}
(boundary, awaiting_confirmation)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum QuotaForecastMethod {
Cumulative,
@@ -117,7 +162,7 @@ pub fn select_forecast_sample(
current: QuotaForecastPoint,
mut history: Vec<QuotaForecastPoint>,
pending_request_count: u64,
interrupted: bool,
plan_changed: bool,
) -> QuotaForecastSample {
history.retain(|point| {
start_at <= point.observed_at
@@ -126,6 +171,9 @@ pub fn select_forecast_sample(
&& (0.0..=100.0).contains(&point.used_percent)
});
history.sort_by_key(|point| point.observed_at);
let (boundary, awaiting_confirmation) = cycle_boundary(&history, &current);
let history = &history[boundary.unwrap_or(0)..];
let interrupted = plan_changed || boundary.is_some();
let mut sample = QuotaForecastSample {
key,
method: QuotaForecastMethod::Cumulative,
@@ -136,23 +184,35 @@ pub fn select_forecast_sample(
block_count: 0,
observation_count: history.len(),
pending_request_count,
discontinuous: interrupted,
discontinuous: interrupted || awaiting_confirmation,
cycle_usage: current.usage.clone(),
usage: current.usage.clone(),
};
history.push(current);
// 重置边界不在查询起点时,从首个新观测重新计数,避免把旧周期累计带入总量
let cycle_baseline = interrupted.then(|| &history[0]);
if interrupted {
let baseline = history.first().unwrap_or(&current);
let Some(usage) = current.usage.difference(&baseline.usage) else {
return sample;
};
sample.cycle_usage = usage;
}
if awaiting_confirmation {
return sample;
}
let mut anchors: Vec<&QuotaForecastPoint> = Vec::new();
let mut high_water: Option<&QuotaForecastPoint> = None;
for point in &history {
for point in history.iter().chain(std::iter::once(&current)) {
// 截至快照已过期的读数不能用于预测剩余量,窗口累计仍由上面的周期证据决定
if point.reset_at <= current.observed_at {
sample.discontinuous = true;
continue;
}
if let Some(previous) = high_water {
if point.observed_at <= previous.observed_at {
continue;
}
if point.used_percent < previous.used_percent {
// 一个百分点内的回落可能是量化/并发乱序;更大的回落不能跨越
if previous.used_percent - point.used_percent <= 1.0 {
if previous.used_percent - point.used_percent <= MAX_PERCENT_REVERSAL {
continue;
}
// 同窗口回落不能证明周期重置,只重建采样并保留已记录累计
@@ -168,16 +228,6 @@ pub fn select_forecast_sample(
anchors.push(point);
}
}
let Some(current) = history.last() else {
return sample;
};
if let Some(baseline) = cycle_baseline {
let Some(usage) = current.usage.difference(&baseline.usage) else {
sample.discontinuous = true;
return sample;
};
sample.cycle_usage = usage;
}
if anchors.len() < 2 {
return sample;
}
@@ -45,6 +45,8 @@ pub use gateway_core::account::RotationStrategy;
/// 运行设置的共同值;版本、Provider 画像更新和数据库秘密由外层类型拥有
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct RuntimeSettingsValues {
pub openai_oauth_guardian_review_model: bool,
pub openai_request_country: gateway_core::account::OpenAiRequestCountry,
pub codex_privacy_policy: gateway_core::settings::privacy::CodexPrivacyPolicy,
pub request_location_enabled: bool,
pub request_location: gateway_core::account::RequestLocation,
@@ -73,7 +75,6 @@ pub struct RuntimeSettingsValues {
pub account_warmup_enabled: bool,
pub account_warmup_cron: String,
pub account_warmup_model: Option<String>,
#[serde(default)]
pub reset_credit_on_low_weekly_quota: bool,
pub reset_credit_lead_minutes: u32,
pub reset_credit_max_weekly_remaining_percent: Option<u32>,
@@ -200,6 +201,9 @@ impl RuntimeSettingsValues {
{
return Err("reset_credit_max_weekly_remaining_percent");
}
self.openai_request_country
.validate()
.map_err(|_| "openai_request_country")?;
self.request_location
.validate()
.map_err(|_| "request_location")?;
@@ -2,8 +2,94 @@
use crate::model::{AdminError, pricing::PricingSyncPreview};
use async_trait::async_trait;
use std::collections::{BTreeMap, BTreeSet};
/// Provider 明确登记的外部参考模型,不按名称前缀猜测不同产品的对应关系
pub struct PricingSourceModel {
pub provider: String,
pub model: String,
}
/// 同名外部目录可直接同步,跨平台模型只采用 Provider 登记的参考价
pub enum PricingCatalogSource {
Direct,
References(BTreeMap<String, PricingSourceModel>),
}
/// 同一次同步用相同的来源声明选择外部目录并映射网关模型
pub struct PricingSourceScope {
pub catalogs: BTreeMap<String, PricingCatalogSource>,
}
impl PricingSourceScope {
pub fn vendors(&self) -> BTreeSet<&str> {
let mut vendors = BTreeSet::new();
for (kind, source) in &self.catalogs {
match source {
PricingCatalogSource::Direct => {
vendors.insert(kind.as_str());
}
PricingCatalogSource::References(models) => {
vendors.extend(models.values().map(|model| model.provider.as_str()))
}
}
}
vendors
}
pub fn requires_catalog(&self, vendor: &str) -> bool {
matches!(
self.catalogs.get(vendor),
Some(PricingCatalogSource::Direct)
)
}
pub(crate) fn project(self, source: PricingSyncPreview) -> PricingSyncPreview {
let mut result = PricingSyncPreview {
prices: BTreeMap::new(),
skipped: Vec::new(),
};
for (kind, catalog) in self.catalogs {
let prices = match catalog {
PricingCatalogSource::Direct => {
let prefix = format!("{kind}/");
result.skipped.extend(
source
.skipped
.iter()
.filter(|id| id.starts_with(&prefix))
.cloned(),
);
source.prices.get(&kind).cloned().unwrap_or_default()
}
PricingCatalogSource::References(models) => {
let mut prices = BTreeMap::new();
for (model, reference) in models {
match source
.prices
.get(&reference.provider)
.and_then(|models| models.get(&reference.model))
{
Some(price) => {
prices.insert(model, price.clone());
}
None => result.skipped.push(format!("{kind}/{model}")),
}
}
prices
}
};
if !prices.is_empty() {
result.prices.insert(kind, prices);
}
}
result.skipped.sort();
result.skipped.dedup();
result
}
}
#[async_trait]
pub trait PricingSource: Send + Sync {
async fn fetch(&self) -> Result<PricingSyncPreview, AdminError>;
async fn fetch(&self, scope: &PricingSourceScope) -> Result<PricingSyncPreview, AdminError>;
}
@@ -24,7 +24,7 @@ use crate::model::provider_credentials::{
};
use crate::model::{
provider_credentials::{ProviderDocument, ProviderQuotaWindow},
quota_forecast_sampling::QuotaForecastObservation,
quota_forecast::QuotaForecastObservation,
};
/// 按原生 Token 口径计算的报价输入,额外费用由调用方处理
@@ -35,6 +35,19 @@ pub struct ProviderUsagePricingInput {
pub usage: gateway_core::metering::Usage,
}
/// 账号目录中的模型与独立额度观测,缺少观测不能解释为可用
#[derive(Debug, Clone)]
pub struct ProviderPeerAccountModels {
pub credential_revision: gateway_core::account::CredentialRevision,
pub models: BTreeMap<String, Option<ProviderPeerModelQuota>>,
}
#[derive(Debug, Clone, Copy)]
pub struct ProviderPeerModelQuota {
pub state: gateway_core::account::QuotaState,
pub valid_until: std::time::SystemTime,
}
/// Provider 管理失败的稳定分类
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ProviderAdminErrorKind {
@@ -165,11 +178,21 @@ pub trait ProviderAdmin: Send + Sync {
})
}
/// 只读内置价目;没有本地计价能力的 Provider 返回空目录
/// 管理端允许为当前 Provider 覆盖的计费档位
fn supported_pricing_bands(&self) -> &'static [&'static str] {
&["standard"]
}
/// 只读内置价目,没有本地计价能力时返回空目录
fn pricing_catalog(&self) -> crate::model::pricing::ProviderPricingCatalog {
Default::default()
}
/// 外部参考价到本 Provider 上游模型的对应关系,与内置价共用登记
fn pricing_source(&self) -> crate::ports::pricing::PricingCatalogSource {
crate::ports::pricing::PricingCatalogSource::Direct
}
fn evaluate_usage_pricing(
&self,
_input: &ProviderUsagePricingInput,
@@ -193,6 +216,14 @@ pub trait ProviderAdmin: Send + Sync {
None
}
/// 批量读取已授权账号的原生模型事实,不访问上游;None 沿用整号额度合同
async fn peer_model_facts(
&self,
_accounts: &[crate::model::accounts::AccountRecord],
) -> Result<Option<BTreeMap<String, ProviderPeerAccountModels>>, ProviderAdminError> {
Ok(None)
}
/// 只读取原生 Provider 能力及账号类型,不执行网络或数据库查询
fn account_capabilities(
&self,
@@ -231,6 +262,19 @@ pub trait ProviderAdmin: Send + Sync {
self.preview_client_profile(key)
}
/// 在批量更新中合并本地身份;缺省、清除和替换分别保留各自语义,不能执行 I/O
fn merge_batch_key_profile(
&self,
current: Option<&gateway_core::account::OpaqueProviderData>,
update: Option<&Option<gateway_core::account::OpaqueProviderData>>,
installation_seed: Option<uuid::Uuid>,
) -> Result<Option<gateway_core::account::OpaqueProviderData>, ProviderAdminError> {
if installation_seed.is_some() {
return Err(ProviderAdminError::new(ProviderAdminErrorKind::Unsupported));
}
Ok(update.map_or_else(|| current.cloned(), Clone::clone))
}
/// 提供最终套餐展示名称;未覆盖时采用通用的大驼峰格式
fn plan_type_display(&self, plan_type: &str) -> String {
default_plan_type_display(plan_type)
@@ -423,6 +467,13 @@ pub trait ProviderAdmin: Send + Sync {
) -> Result<ProviderExport, ProviderAdminError>;
}
/// 内置 Provider 在启动时一次交付数据面、管理面与后台任务
pub struct ProviderBundle {
pub core: Arc<dyn gateway_core::engine::provider::Provider>,
pub admin: Arc<dyn ProviderAdmin>,
pub workers: Vec<gateway_core::task::WorkerContribution>,
}
/// 启动时注册原生 Provider,按 ProviderKind 查找管理能力
#[derive(Clone)]
pub struct ProviderAdminRegistry {
@@ -430,10 +481,34 @@ pub struct ProviderAdminRegistry {
}
impl ProviderAdminRegistry {
pub(crate) fn pricing_source_scope(&self) -> crate::ports::pricing::PricingSourceScope {
crate::ports::pricing::PricingSourceScope {
catalogs: self
.providers
.iter()
.map(|(kind, provider)| (kind.to_string(), provider.pricing_source()))
.collect(),
}
}
pub(crate) fn registered(&self) -> BTreeMap<ProviderKind, Arc<dyn ProviderAdmin>> {
self.providers.as_ref().clone()
}
pub(crate) fn supported_pricing_bands(&self) -> BTreeMap<String, Vec<String>> {
self.providers
.iter()
.map(|(kind, provider)| {
let bands = provider
.supported_pricing_bands()
.iter()
.map(|&band| band.to_owned())
.collect();
(kind.to_string(), bands)
})
.collect()
}
pub fn pricing_catalog(&self) -> gateway_core::metering::PricingOverrides {
self.providers
.iter()
@@ -22,10 +22,11 @@ use crate::model::{
},
auth::{AdminAuditEvent, AuthSession},
client_keys::{
ClientKeyBudgetMutationOrigin, ClientKeyBudgetWindow, ClientKeyBudgetWindowPeriod,
ClientKeyListQuery, ClientKeyPage, ClientKeyRecord, ClientKeySecret, DeleteClientKey,
NewClientKey, ResetClientKeyBudget, SetClientKeyBudgetWindow, SetClientKeyEnabled,
UpdateClientKey, UpdateClientKeyBudgetLimits,
BatchUpdateClientKeys, BudgetReferenceAccountPage, ClientKeyBudgetMutationOrigin,
ClientKeyBudgetWindow, ClientKeyBudgetWindowPeriod, ClientKeyListQuery, ClientKeyPage,
ClientKeyRecord, ClientKeySecret, DeleteClientKey, NewClientKey, ResetClientKeyBudget,
SetClientKeyBudgetWindow, SetClientKeyEnabled, UpdateClientKey,
UpdateClientKeyBudgetLimits,
},
observability::{
DashboardObservation, DashboardQuery, DiagnosticDimension, DiagnosticsObservation,
@@ -39,7 +40,7 @@ use crate::model::{
CredentialMutationResult, CredentialRotationCommit, PluginAccountListQuery,
PluginAccountPage, ProviderExportCredentialInput,
},
quota_forecast_sampling::QuotaForecastHistory,
quota_forecast::QuotaForecastHistory,
settings::{AdminApiKey, AdminApiKeyMutation, ReplaceRuntimeSettings, RuntimeSettings},
};
@@ -109,6 +110,13 @@ impl AdminStoreError {
pub type AdminStoreResult<T> = Result<T, AdminStoreError>;
/// 在持有密钥行锁时用 Provider 准备好的纯合并操作更新原有画像
pub type BatchClientKeyProfileMerger = Box<
dyn Fn(&mut crate::model::client_keys::ProviderRequestProfileOverrides) -> AdminStoreResult<()>
+ Send
+ Sync,
>;
/// 账号目录与公共账号写操作
#[async_trait]
pub trait AccountStore:
@@ -377,6 +385,18 @@ pub trait AuthStore: Send + Sync {
/// Client API Key 资料读取与管理写入
#[async_trait]
pub trait ClientKeyStore: Send + Sync {
async fn client_key_budget(
&self,
id: &gateway_core::policy::ClientApiKeyId,
) -> AdminStoreResult<Option<gateway_core::engine::budget::ClientBudgetStatus>>;
async fn budget_reference_accounts(
&self,
id: &gateway_core::policy::ClientApiKeyId,
search: &str,
after: &str,
) -> AdminStoreResult<BudgetReferenceAccountPage>;
async fn client_key_budget_window(
&self,
id: &gateway_core::policy::ClientApiKeyId,
@@ -415,6 +435,13 @@ pub trait ClientKeyStore: Send + Sync {
context: &MutationContext,
) -> AdminStoreResult<(Revision, ClientKeyRecord)>;
async fn batch_update_client_keys(
&self,
command: BatchUpdateClientKeys,
merge_profiles: BatchClientKeyProfileMerger,
context: &MutationContext,
) -> AdminStoreResult<Revision>;
async fn set_client_key_enabled(
&self,
command: SetClientKeyEnabled,
@@ -480,6 +507,7 @@ pub trait AccountGroupStore: Send + Sync {
context: &MutationContext,
) -> AdminStoreResult<AccountGroupMutation>;
/// 仍有 API Key 引用分组时返回 Conflict
async fn delete_account_group(
&self,
command: DeleteAccountGroup,
@@ -517,6 +545,19 @@ pub trait ObservabilityStore: Send + Sync {
granularity: Granularity,
) -> AdminStoreResult<Vec<RequestMetricPoint>>;
async fn client_key_statistics(
&self,
range: TimeRange,
id: &gateway_core::policy::ClientApiKeyId,
query: crate::model::observability::KeyUsageMetric,
) -> AdminStoreResult<crate::model::observability::KeyStatisticsOverview>;
async fn client_key_models(
&self,
range: TimeRange,
id: &gateway_core::policy::ClientApiKeyId,
) -> AdminStoreResult<Vec<crate::model::observability::KeyModelRow>>;
async fn usage_trend(
&self,
range: TimeRange,
@@ -9,8 +9,8 @@ use std::{
use async_trait::async_trait;
use gateway_core::{
account::{AccountStatus, resolve_account_status},
routing::AccountGroupId,
runtime::SnapshotControl,
routing::{AccountGroupId, UpstreamModelId},
runtime::{RuntimeSnapshotHandle, SnapshotControl},
};
use uuid::Uuid;
@@ -24,7 +24,7 @@ use crate::{
NewAccountGroup, SetAccountGroupEnabled, UpdateAccountGroup,
},
},
ports::store::{AccountGroupStore, AccountRuntimeStore},
ports::store::{AccountGroupStore, AccountRuntimeStore, AdminStoreErrorKind},
};
use super::{map_store_error, publish_committed};
@@ -32,6 +32,7 @@ use super::{map_store_error, publish_committed};
/// 面向 API 的账号分组管理服务
#[async_trait]
pub trait AccountGroupService: Send + Sync {
fn models(&self, group: &AccountGroupId) -> Result<Vec<UpstreamModelId>, AdminError>;
async fn list(&self, query: AccountGroupListQuery) -> Result<AccountGroupPage, AdminError>;
async fn list_options(
&self,
@@ -64,6 +65,7 @@ pub(crate) struct DefaultAccountGroupService {
store: Arc<dyn AccountGroupStore>,
runtime: Arc<dyn AccountRuntimeStore>,
snapshot: Arc<dyn SnapshotControl>,
published_snapshot: RuntimeSnapshotHandle,
}
impl DefaultAccountGroupService {
@@ -73,12 +75,14 @@ impl DefaultAccountGroupService {
store: Arc<dyn AccountGroupStore>,
runtime: Arc<dyn AccountRuntimeStore>,
snapshot: Arc<dyn SnapshotControl>,
published_snapshot: RuntimeSnapshotHandle,
) -> Self {
Self {
upstream_info,
store,
runtime,
snapshot,
published_snapshot,
}
}
@@ -131,6 +135,14 @@ impl DefaultAccountGroupService {
#[async_trait]
impl AccountGroupService for DefaultAccountGroupService {
fn models(&self, group: &AccountGroupId) -> Result<Vec<UpstreamModelId>, AdminError> {
let snapshot = self
.published_snapshot
.acquire()
.map_err(|_| AdminError::unavailable("模型目录尚未就绪"))?;
Ok(snapshot.upstream_models_for_group(group))
}
async fn list(&self, query: AccountGroupListQuery) -> Result<AccountGroupPage, AdminError> {
let mut page = self
.store
@@ -159,8 +171,7 @@ impl AccountGroupService for DefaultAccountGroupService {
crate::model::account_groups::validate_group_fields(
&command.name,
command.description.as_deref(),
)
.map_err(|_| AdminError::invalid("账号组请求不合法"))?;
)?;
let id = AccountGroupId::new(format!("grp_{}", Uuid::now_v7().simple()))
.map_err(|_| AdminError::internal("创建账号组 ID 失败"))?;
self.publish(
@@ -168,6 +179,8 @@ impl AccountGroupService for DefaultAccountGroupService {
.create_account_group(
NewAccountGroup {
allow_image_generation: command.allow_image_generation,
allow_subagents: command.allow_subagents,
model_access: command.model_access,
id,
name: command.name,
description: command.description,
@@ -189,8 +202,7 @@ impl AccountGroupService for DefaultAccountGroupService {
crate::model::account_groups::validate_group_fields(
&command.name,
command.description.as_deref(),
)
.map_err(|_| AdminError::invalid("账号组请求不合法"))?;
)?;
self.publish(self.store.update_account_group(command, context).await)
.await
}
@@ -209,8 +221,12 @@ impl AccountGroupService for DefaultAccountGroupService {
context: &MutationContext,
command: DeleteAccountGroup,
) -> Result<AccountGroupMutation, AdminError> {
self.publish(self.store.delete_account_group(command, context).await)
.await
match self.store.delete_account_group(command, context).await {
Err(error) if error.kind() == AdminStoreErrorKind::Conflict => {
Err(AdminError::conflict("分组仍绑定 API Key,请先解除绑定").with_source(error))
}
result => self.publish(result).await,
}
}
}
@@ -20,11 +20,13 @@ use gateway_core::{
use crate::{
model::{
AdminError, MutationContext,
account_groups::AccountGroupRef,
accounts::{
AccountConnectionTestEvent, AccountConnectionTestEventStream, AccountListQuery,
AccountPageItem, AccountUpdateResult, AccountUsage, AccountUsageWindowQuery,
AccountsUpdateResult, BatchUpdateAccounts, UpdateAccount,
},
client_keys::ClientKeyBudgetReference,
observability::TimeRange,
provider_credentials::{
AccountDirectoryItem, AccountDirectoryPage, AccountExportBundle, AccountPersonalInfo,
@@ -37,7 +39,7 @@ use crate::{
quota_forecast::{
AccountQuotaForecastReport, account_quota_forecasts, quota_forecast_source_window,
},
quota_forecast_sampling::{QuotaForecastPoint, select_forecast_sample},
quota_forecast::{QuotaForecastPoint, select_forecast_sample},
},
ports::{
provider::ProviderAdminRegistry,
@@ -107,6 +109,12 @@ pub trait AccountsService: Send + Sync {
refresh: bool,
) -> Result<AccountDirectoryItem, AdminError>;
async fn key_budget_references(
&self,
account_id: &ProviderAccountId,
key_groups: &[AccountGroupRef],
) -> Result<Vec<ClientKeyBudgetReference>, AdminError>;
async fn quota_forecast(
&self,
account_id: &ProviderAccountId,
@@ -493,15 +501,16 @@ impl DefaultAccountsService {
std::slice::from_mut(&mut quota),
)
.await?;
let usage = self
let api_key_usage = self
.load_api_key_usage(std::slice::from_ref(&stored), std::slice::from_ref(&quota))
.await?
.remove(&stored.account.id)
.or_else(|| {
quota
.usage_window()
.and_then(|(window, _)| window.local_usage.clone())
});
.remove(&stored.account.id);
let (usage, usage_period) = resolve_account_usage(
&stored.account.authentication_kind,
&quota,
rolling_usage,
api_key_usage,
);
Ok(AccountDirectoryItem {
protection_rules: stored.protection_rules,
capacity: super::peer_link::upstream::account_capacity(
@@ -518,6 +527,7 @@ impl DefaultAccountsService {
),
projection: stored.projection,
usage,
usage_period,
account: stored.account,
quota,
})
@@ -590,7 +600,7 @@ impl AccountsService for DefaultAccountsService {
.load_account_usage(rolling_range, &ids)
.await
.map_err(|error| map_store_error(error, "rolling account usage"))?;
let rolling_usage = rolling_usage
let mut rolling_usage = rolling_usage
.into_iter()
.map(|usage| (usage.account_id.clone(), usage))
.collect::<BTreeMap<_, _>>();
@@ -611,11 +621,12 @@ impl AccountsService for DefaultAccountsService {
provider.account_capabilities(&id, &item.account.authentication_kind)
})
.unwrap_or_default();
let usage = api_key_usage.remove(&item.account.id).or_else(|| {
quota
.usage_window()
.and_then(|(window, _)| window.local_usage.clone())
});
let (usage, usage_period) = resolve_account_usage(
&item.account.authentication_kind,
&quota,
rolling_usage.remove(&item.account.id),
api_key_usage.remove(&item.account.id),
);
Ok(AccountDirectoryItem {
protection_rules: item.protection_rules,
capacity: crate::model::accounts::AccountCapacity {
@@ -635,6 +646,7 @@ impl AccountsService for DefaultAccountsService {
Some(&quota),
),
usage,
usage_period,
account: item.account,
projection: item.projection,
quota,
@@ -654,37 +666,30 @@ impl AccountsService for DefaultAccountsService {
context: &MutationContext,
account_ids: Vec<ProviderAccountId>,
) -> Result<AccountExportBundle, AdminError> {
let providers = &self.providers;
if account_ids.is_empty() || account_ids.len() > 200 {
return Err(AdminError::invalid("账号导出数量必须在 1 到 200 之间"));
}
let exported_ids = account_ids.clone();
let mut grouped = BTreeMap::<ProviderKind, Vec<ProviderAccountId>>::new();
for account_id in account_ids {
let account = self.load_account(&account_id).await?;
grouped
.entry(account.account.provider_kind)
.or_default()
.push(account_id);
let mut grouped = BTreeMap::new();
// 混选时先检查每个账号的导出能力,再读取任何一组明文凭据
for id in account_ids {
let (item, provider) = self.provider_for_account(&id).await?;
if !provider
.account_capabilities(&id, &item.account.authentication_kind)
.credential_export
{
return Err(AdminError::invalid("所选账号不支持导出"));
}
let (_, ids) = grouped
.entry(item.account.provider_kind)
.or_insert_with(|| (provider, Vec::new()));
if ids.contains(&id) {
return Err(AdminError::invalid("账号导出列表包含重复 ID"));
}
ids.push(id);
}
if grouped.values().any(|ids| {
let unique = ids.iter().collect::<std::collections::BTreeSet<_>>();
unique.len() != ids.len()
}) {
return Err(AdminError::invalid("账号导出列表包含重复 ID"));
}
// 混选时先确认全部 Provider 已注册,拒绝路径不读取任何一组明文凭据
let export_groups = grouped
.into_iter()
.map(|(provider_kind, ids)| {
let provider = providers
.require(&provider_kind)
.map_err(|error| map_provider_error(error, "provider account export"))?;
Ok((provider_kind, provider, ids))
})
.collect::<Result<Vec<_>, AdminError>>()?;
let mut documents = Vec::with_capacity(export_groups.len());
for (provider_kind, provider, ids) in export_groups {
let mut documents = Vec::with_capacity(grouped.len());
for (provider_kind, (provider, ids)) in grouped {
let credentials = self
.accounts
.load_credentials_for_export(&provider_kind, &ids)
@@ -972,6 +977,48 @@ impl AccountsService for DefaultAccountsService {
self.load_directory_item(account_id, refresh).await
}
async fn key_budget_references(
&self,
account_id: &ProviderAccountId,
key_groups: &[AccountGroupRef],
) -> Result<Vec<ClientKeyBudgetReference>, AdminError> {
let (stored, provider) = self.provider_for_account(account_id).await?;
if !key_groups.is_empty()
&& !stored.account.groups.iter().any(|account_group| {
account_group.enabled && key_groups.iter().any(|group| group.id == account_group.id)
})
{
return Err(AdminError::bad_request("参考账号不在此密钥的账号范围内"));
}
// 只取已观测的额度边界,预览与确认都不触发上游刷新或账号用量聚合
let quota = match super::peer_link::upstream::read_quota(
self.upstream_info.as_deref(),
provider.as_ref(),
&stored.account,
ProviderQuotaRequest {
account_id: account_id.clone(),
refresh: false,
rolling_usage: None,
},
)
.await
{
Ok(quota) => quota,
Err(error)
if error.kind() == crate::ports::provider::ProviderAdminErrorKind::Unsupported =>
{
return Ok(Vec::new());
}
Err(error) => return Err(map_provider_error(error, "provider quota")),
};
let now = Utc::now();
Ok(quota
.windows
.into_iter()
.filter_map(|window| ClientKeyBudgetReference::from_current_window(window, now))
.collect())
}
async fn quota_forecast(
&self,
account_id: &ProviderAccountId,
@@ -1007,6 +1054,8 @@ impl AccountsService for DefaultAccountsService {
) else {
continue;
};
let reset_at = query.range.end;
let window_duration = reset_at - query.range.start;
query.range.start = query.range.start.max(stored.account.created_at);
if query.range.start >= observed
|| observed > now
@@ -1016,7 +1065,6 @@ impl AccountsService for DefaultAccountsService {
{
continue;
}
let reset_at = query.range.end;
query.range.end = observed;
let history = self
.accounts
@@ -1024,27 +1072,37 @@ impl AccountsService for DefaultAccountsService {
.await
.map_err(|error| map_store_error(error, "forecast paired usage"))?;
let mut points = Vec::new();
let mut interrupted = false;
let mut plan_changed = false;
for point in history.points {
let Some(fact) =
provider.quota_forecast_observation(&point.provider_observation, window)
else {
continue;
};
let same_plan = quota
.plan_type
.as_deref()
.zip(fact.plan_type.as_deref())
.is_some_and(|(current, previous)| current.eq_ignore_ascii_case(previous));
// 仅容纳已观测到的秒级量化抖动,不用宽时间容差合并实际重置
// 不匹配的段截断基线;之后的有效观测可以重新积累
if !same_plan || (fact.reset_at - reset_at).abs() > Duration::seconds(2) {
let (Some(current_plan), Some(previous_plan)) =
(quota.plan_type.as_deref(), fact.plan_type.as_deref())
else {
continue;
};
let Some(start) = fact.reset_at.checked_sub_signed(window_duration) else {
continue;
};
if point.completed_at >= observed
|| point.started_at < query.range.start
|| point.completed_at < start
|| point.completed_at >= fact.reset_at
{
continue;
}
if !current_plan.eq_ignore_ascii_case(previous_plan) {
points.clear();
interrupted = true;
plan_changed = true;
continue;
}
points.push(QuotaForecastPoint {
started_at: point.started_at,
observed_at: point.completed_at,
reset_at: fact.reset_at,
used_percent: fact.used_percent,
usage: point.usage,
});
@@ -1053,13 +1111,15 @@ impl AccountsService for DefaultAccountsService {
window.key.clone(),
query.range.start,
QuotaForecastPoint {
started_at: observed,
observed_at: observed,
reset_at,
used_percent: percent,
usage: history.usage,
},
points,
history.pending_request_count,
interrupted,
plan_changed,
);
samples.push(sample);
}
@@ -1283,6 +1343,22 @@ impl AccountsService for DefaultAccountsService {
}
}
fn resolve_account_usage(
authentication_kind: &str,
quota: &ProviderQuota,
rolling_usage: Option<AccountUsage>,
api_key_usage: Option<AccountUsage>,
) -> (Option<AccountUsage>, Option<AccountUsagePeriod>) {
if authentication_kind == "api_key" {
return (api_key_usage, None);
}
if let Some((window, period)) = quota.usage_window() {
return (window.local_usage.clone(), Some(period));
}
// 模型分组额度无法归属整号用量,本地统计独立回退,不能为此合成上游额度桶
(rolling_usage, Some(AccountUsagePeriod::Daily))
}
fn map_reset_credits_error_after_refresh(
error: crate::ports::provider::ProviderAdminError,
) -> AdminError {
@@ -1304,9 +1380,7 @@ fn quota_usage_window(
if window.local_usage_attribution != QuotaLocalUsageAttribution::AccountWide {
return None;
}
let reset_at = window.reset_at?;
let seconds = i64::try_from(window.window_seconds?).ok()?;
let start = reset_at.checked_sub_signed(Duration::try_seconds(seconds)?)?;
let (start, reset_at) = window.observed_bounds()?;
let range = TimeRange::new(start, reset_at).ok()?;
// 上游百分比以该 reset 边界定义;以当前时间回推会让本地 Token 属于另一窗口
Some(AccountUsageWindowQuery {
@@ -48,6 +48,7 @@ pub trait BackupService: Send + Sync {
async fn test_connection(
&self,
context: &MutationContext,
storage_revision: u64,
) -> Result<ConnectionTestResult, AdminError>;
async fn create_backup(
@@ -151,12 +152,17 @@ impl BackupService for DefaultBackupService {
async fn test_connection(
&self,
context: &MutationContext,
storage_revision: u64,
) -> Result<ConnectionTestResult, AdminError> {
let settings = self
.repository
.load_settings()
.await
.map_err(|error| map_store_error(error, "backup settings"))?;
let stale = || AdminError::conflict("备份存储配置已更改,请刷新后重新测试");
if settings.storage_revision != storage_revision {
return Err(stale());
}
let Some(config) = BackupStorageConfig::from_settings(&settings) else {
return Ok(ConnectionTestResult {
ok: false,
@@ -170,12 +176,14 @@ impl BackupService for DefaultBackupService {
.test_connection(&config)
.await
.map_err(map_backup_error)?;
if result.ok {
let _ = self
if result.ok
&& !self
.repository
.record_verification(config.storage_revision, Utc::now())
.await
.map_err(|error| map_store_error(error, "backup settings"))?;
.map_err(|error| map_store_error(error, "backup settings"))?
{
return Err(stale());
}
self.append_audit(
context,
@@ -1,11 +1,12 @@
//! Client API Key 管理用例
use std::sync::Arc;
use std::{collections::BTreeSet, sync::Arc};
use async_trait::async_trait;
use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
use gateway_core::{
engine::budget::ClientBudgetStatus, policy::ClientApiKeyId, runtime::SnapshotControl,
account::OpaqueProviderData, engine::budget::ClientBudgetStatus, policy::ClientApiKeyId,
routing::ProviderKind, runtime::SnapshotControl,
};
use rand_core::{OsRng, RngCore as _};
use uuid::Uuid;
@@ -14,15 +15,17 @@ use crate::{
model::{
AdminError, MutationContext,
client_keys::{
ClientKeyBudgetMutationOrigin, ClientKeyBudgetWindow, ClientKeyBudgetWindowPeriod,
ClientKeyCursorValue, ClientKeyListQuery, ClientKeyMutation, ClientKeyPage,
ClientKeyRecord, ClientKeySecret, ClientKeySortField, CreateClientKey,
CreatedClientKey, DeleteClientKey, NewClientKey, ResetClientKeyBudget,
SetClientKeyBudgetWindow, SetClientKeyEnabled, UpdateClientKey,
BatchUpdateClientKeys, BudgetReferenceAccountPage, ClientKeyBudgetMutationOrigin,
ClientKeyBudgetWindow, ClientKeyBudgetWindowPeriod, ClientKeyCursorValue,
ClientKeyListQuery, ClientKeyMutation, ClientKeyPage, ClientKeyRecord, ClientKeySecret,
ClientKeySortField, CreateClientKey, CreatedClientKey, DeleteClientKey, NewClientKey,
ResetClientKeyBudget, SetClientKeyBudgetWindow, SetClientKeyEnabled, UpdateClientKey,
UpdateClientKeyBudgetLimits,
},
},
ports::store::{AdminStoreError, AdminStoreErrorKind, ClientKeyStore},
ports::store::{
AdminStoreError, AdminStoreErrorKind, BatchClientKeyProfileMerger, ClientKeyStore,
},
};
use super::{map_store_error, publish_committed};
@@ -30,6 +33,13 @@ use super::{map_store_error, publish_committed};
/// API 消费的 Client Key 管理服务
#[async_trait]
pub trait ClientKeyService: Send + Sync {
async fn budget_reference_accounts(
&self,
id: &gateway_core::policy::ClientApiKeyId,
search: &str,
after: &str,
) -> Result<BudgetReferenceAccountPage, AdminError>;
async fn budget_window(
&self,
id: &ClientApiKeyId,
@@ -55,6 +65,11 @@ pub trait ClientKeyService: Send + Sync {
context: &MutationContext,
command: UpdateClientKey,
) -> Result<ClientKeyMutation, AdminError>;
async fn batch_update(
&self,
context: &MutationContext,
command: BatchUpdateClientKeys,
) -> Result<crate::model::Revision, AdminError>;
async fn set_enabled(
&self,
context: &MutationContext,
@@ -99,10 +114,128 @@ impl DefaultClientKeyService {
providers,
}
}
fn validate_profile(
&self,
kind: &ProviderKind,
profile: Option<&OpaqueProviderData>,
) -> Result<(), AdminError> {
let provider = self
.providers
.require(kind)
.map_err(|error| super::map_provider_error(error, "client profile"))?;
if let Some(profile) = profile {
provider
.preview_key_client_profile(profile, None)
.map_err(|error| super::map_provider_error(error, "client profile"))?;
}
Ok(())
}
fn batch_profile_merger(
&self,
command: &BatchUpdateClientKeys,
) -> Result<BatchClientKeyProfileMerger, AdminError> {
let mut kinds = command
.request_profile_override_updates
.keys()
.cloned()
.collect::<BTreeSet<_>>();
let seed_kind = ProviderKind::new("openai").expect("static Provider kind is valid");
if command.installation_seed.is_some() {
kinds.insert(seed_kind.clone());
}
let mut changes = Vec::with_capacity(kinds.len());
for kind in kinds {
let provider = self
.providers
.require(&kind)
.map_err(|error| super::map_provider_error(error, "client profile"))?;
let update = command.request_profile_override_updates.get(&kind).cloned();
let seed = if kind == seed_kind {
command.installation_seed
} else {
None
};
// 先校验输入,行锁内只依据各把密钥的现值完成合并
if let Some(Some(profile)) = update.as_ref() {
provider
.merge_batch_key_profile(None, update.as_ref(), seed)
.and_then(|_| provider.preview_key_client_profile(profile, None))
.map_err(|error| super::map_provider_error(error, "client profile"))?;
}
changes.push((kind, provider, update, seed));
}
Ok(Box::new(move |profiles| {
for (kind, provider, update, seed) in &changes {
let next = provider
.merge_batch_key_profile(profiles.get(kind), update.as_ref(), *seed)
.map_err(|error| {
AdminStoreError::new(
AdminStoreErrorKind::Invalid,
"client profile",
"invalid stored client profile",
)
.with_source(error)
})?;
if let Some(profile) = next {
profiles.insert(kind.clone(), profile);
} else {
profiles.remove(kind);
}
}
Ok(())
}))
}
}
#[async_trait]
impl ClientKeyService for DefaultClientKeyService {
async fn batch_update(
&self,
context: &MutationContext,
command: BatchUpdateClientKeys,
) -> Result<crate::model::Revision, AdminError> {
if command.ids.is_empty()
|| command.ids.len() > 1000
|| command
.ids
.iter()
.collect::<std::collections::BTreeSet<_>>()
.len()
!= command.ids.len()
{
return Err(AdminError::invalid("请选择 1 至 1000 个不同的 API Key"));
}
if !command.has_changes() {
return Err(AdminError::invalid("请至少选择一项要修改的密钥设置"));
}
if let Some(groups) = &command.group_ids {
crate::model::client_keys::validate_group_ids(groups)
.map_err(|_| AdminError::invalid("API Key 分组不合法"))?;
}
let merge_profiles = self.batch_profile_merger(&command)?;
let revision = self
.store
.batch_update_client_keys(command, merge_profiles, context)
.await
.map_err(|error| map_store_error(error, "client API key"))?;
publish_committed(self.snapshot.as_ref(), revision).await?;
Ok(revision)
}
async fn budget_reference_accounts(
&self,
id: &gateway_core::policy::ClientApiKeyId,
search: &str,
after: &str,
) -> Result<BudgetReferenceAccountPage, AdminError> {
self.store
.budget_reference_accounts(id, search.trim(), after)
.await
.map_err(|error| map_store_error(error, "client API key"))
}
async fn budget_window(
&self,
id: &ClientApiKeyId,
@@ -141,7 +274,11 @@ impl ClientKeyService for DefaultClientKeyService {
}
async fn budget(&self, id: &ClientApiKeyId) -> Result<ClientBudgetStatus, AdminError> {
self.get(id).await.map(|key| key.budget)
self.store
.client_key_budget(id)
.await
.map_err(|error| map_store_error(error, "client API key"))?
.ok_or_else(|| AdminError::not_found("API Key 不存在"))
}
async fn update_budget_limits(
@@ -203,10 +340,7 @@ impl ClientKeyService for DefaultClientKeyService {
crate::model::client_keys::validate_group_ids(&command.group_ids)
.map_err(|_| AdminError::invalid("API Key 分组不合法"))?;
for (provider, profile) in &command.request_profile_overrides {
self.providers
.require(provider)
.and_then(|provider| provider.preview_key_client_profile(profile, None))
.map_err(|error| super::map_provider_error(error, "client profile"))?;
self.validate_profile(provider, Some(profile))?;
}
validate_peer_sharing(command.peer_sharing, &command.group_ids)?;
let id = ClientApiKeyId::new(format!("key_{}", Uuid::now_v7().simple()))
@@ -249,12 +383,7 @@ impl ClientKeyService for DefaultClientKeyService {
crate::model::client_keys::validate_group_ids(&command.group_ids)
.map_err(|_| AdminError::invalid("API Key 分组不合法"))?;
for (provider, profile) in &command.request_profile_override_updates {
if let Some(profile) = profile {
self.providers
.require(provider)
.and_then(|provider| provider.preview_key_client_profile(profile, None))
.map_err(|error| super::map_provider_error(error, "client profile"))?;
}
self.validate_profile(provider, profile.as_ref())?;
}
if let Some(sharing) = command.peer_sharing {
validate_peer_sharing(sharing, &command.group_ids)?;
@@ -314,7 +443,6 @@ impl ClientKeyService for DefaultClientKeyService {
fn map_client_key_write_error(error: AdminStoreError) -> AdminError {
match error.kind() {
AdminStoreErrorKind::DuplicateName => AdminError::conflict("名称已存在"),
AdminStoreErrorKind::Conflict => AdminError::conflict("API Key 已存在,请使用其他密钥"),
_ => map_store_error(error, "client API key"),
}
@@ -150,7 +150,6 @@ pub(super) async fn pending_authorization(
None => {
use crate::model::proxies::AccountProxySelection;
proxy = match &command.outbound_proxy {
Some(AccountProxySelection::Url(value)) => Some(value.clone()),
Some(AccountProxySelection::Saved(id)) => {
let record = proxies
.get(id)
@@ -4,20 +4,15 @@ use crate::model::{AdminError, AdminErrorKind};
use crate::ports::store::{AdminStoreError, AdminStoreErrorKind};
pub(super) fn map_store_error(error: AdminStoreError, resource: &'static str) -> AdminError {
let kind = match error.kind() {
AdminStoreErrorKind::Invalid => AdminErrorKind::Invalid,
AdminStoreErrorKind::NotFound => AdminErrorKind::NotFound,
AdminStoreErrorKind::StaleRevision
| AdminStoreErrorKind::DuplicateName
| AdminStoreErrorKind::Conflict => AdminErrorKind::Conflict,
AdminStoreErrorKind::Unavailable => AdminErrorKind::Unavailable,
};
let message = match kind {
AdminErrorKind::Invalid => "请求参数不合法",
AdminErrorKind::NotFound => "请求的资源不存在",
AdminErrorKind::Conflict => "当前资源状态冲突,请刷新后重试",
AdminErrorKind::Unavailable => "依赖服务暂不可用",
_ => "服务内部错误",
let (kind, message) = match error.kind() {
AdminStoreErrorKind::Invalid => (AdminErrorKind::Invalid, "请求参数不合法"),
AdminStoreErrorKind::NotFound => (AdminErrorKind::NotFound, "请求的资源不存在"),
AdminStoreErrorKind::StaleRevision => {
(AdminErrorKind::Conflict, "数据已更新,请刷新后再操作")
}
AdminStoreErrorKind::DuplicateName => (AdminErrorKind::Conflict, "名称已存在"),
AdminStoreErrorKind::Conflict => (AdminErrorKind::Conflict, "当前资源状态不允许此操作"),
AdminStoreErrorKind::Unavailable => (AdminErrorKind::Unavailable, "存储服务暂不可用"),
};
AdminError::new(kind, message).with_source(OperationFailure {
operation: resource,
@@ -49,9 +44,8 @@ pub(super) fn map_provider_error(
ProviderAdminErrorKind::Conflict => "服务商资源状态冲突,请刷新后重试",
ProviderAdminErrorKind::BadGateway => "上游服务请求失败",
ProviderAdminErrorKind::Ambiguous => "上游执行结果未知,请刷新状态后再决定是否重试",
ProviderAdminErrorKind::Unavailable | ProviderAdminErrorKind::CredentialRefreshRequired => {
"服务商暂不可用"
}
ProviderAdminErrorKind::Unavailable => "服务商暂不可用",
ProviderAdminErrorKind::CredentialRefreshRequired => "账号凭据需要刷新",
ProviderAdminErrorKind::Internal => "服务内部错误",
};
AdminError::new(kind, error.public_message().unwrap_or(message)).with_source(OperationFailure {
@@ -225,7 +225,7 @@ impl KeyUsageService for DefaultKeyUsageService {
.list_usage_records(UsageQuery {
status: match query.kind {
KeyUsageRecordKind::Success => UsageRecordStatus::Success,
KeyUsageRecordKind::Error => UsageRecordStatus::Error,
KeyUsageRecordKind::Error => UsageRecordStatus::Error(None),
KeyUsageRecordKind::All => UsageRecordStatus::All,
},
range: query.usage.range,
@@ -18,7 +18,6 @@ pub mod plugins;
pub mod proxies;
pub mod settings;
pub mod system;
pub(crate) mod system_preflight;
pub mod usage_data;
mod credential_mutation;
@@ -0,0 +1,145 @@
//! 历史费用场景的 Provider 计价投影
use crate::model::AdminError;
use crate::model::observability::{
CurrencyCost, DecimalAmount, ProviderBillingInput, UsageBillingProjection,
UsageCalculatedBillingFact,
};
use crate::ports::provider::{ProviderAdminErrorKind, ProviderAdminRegistry};
use crate::ports::store::UsageBillingProjector;
use crate::use_case::map_provider_error;
use gateway_core::routing::ProviderKind;
use std::str::FromStr;
/// 在后台投影时恢复费用场景,查询不再逐请求读取计费快照
pub struct ProviderUsageBillingProjector {
providers: ProviderAdminRegistry,
}
impl ProviderUsageBillingProjector {
#[must_use]
pub fn new(providers: ProviderAdminRegistry) -> Self {
Self { providers }
}
}
impl UsageBillingProjector for ProviderUsageBillingProjector {
fn project(
&self,
fact: &UsageCalculatedBillingFact,
) -> Result<UsageBillingProjection, AdminError> {
let Ok(provider_kind) = ProviderKind::new(fact.provider_kind.clone()) else {
return Ok(UsageBillingProjection::default());
};
let input = ProviderBillingInput {
upstream_model_id: fact.upstream_model_id.clone(),
service_tier: fact.service_tier.clone(),
input_tokens: fact.input_tokens,
output_tokens: fact.output_tokens,
cached_input_tokens: fact.cached_input_tokens,
cache_write_input_tokens: fact.cache_write_input_tokens,
total: fact.total.clone(),
};
let breakdown = match fact
.breakdown
.as_ref()
.filter(|breakdown| breakdown.total_amount == input.total)
.cloned()
.map_or_else(
|| self.providers.calculated_billing(&provider_kind, &input),
|breakdown| Ok(Some(breakdown)),
) {
Ok(breakdown) => breakdown,
Err(error) if error.kind() == ProviderAdminErrorKind::Unsupported => {
return Ok(UsageBillingProjection::default());
}
Err(error) => return Err(map_provider_error(error, "usage billing")),
};
let Some(breakdown) = breakdown else {
return Ok(UsageBillingProjection::default());
};
if !breakdown
.standard_amount
.currency
.eq_ignore_ascii_case("USD")
{
return Ok(UsageBillingProjection::default());
}
Ok(UsageBillingProjection {
standard_amount: Some(breakdown.standard_amount.amount.clone()),
no_cache_amount: no_cache_cost(fact, &breakdown),
})
}
}
fn no_cache_cost(
fact: &UsageCalculatedBillingFact,
breakdown: &crate::model::observability::CalculatedBillingBreakdown,
) -> Option<DecimalAmount> {
let image = breakdown.image.as_ref();
let input_tokens = fact
.input_tokens?
.checked_sub(image.map_or(0, |i| i.input_tokens))?;
let cached_input_tokens = fact
.cached_input_tokens
.unwrap_or_default()
.checked_sub(image.map_or(0, |i| i.cached_input_tokens))?
.min(input_tokens);
let cache_write_input_tokens = fact
.cache_write_input_tokens
.unwrap_or_default()
.min(input_tokens.saturating_sub(cached_input_tokens));
let input_rate = decimal(&breakdown.input_price_per_million.amount)?;
let replaced_input_amount = input_rate
.scaled()
.checked_mul(u128::from(
cached_input_tokens.saturating_add(cache_write_input_tokens),
))?
.checked_div(1_000_000)?;
let mut total = decimal(&breakdown.total_amount.amount)?
.scaled()
.checked_sub(decimal(&breakdown.cache_read_amount.amount)?.scaled())?
.checked_sub(decimal(&breakdown.cache_write_amount.amount)?.scaled())?
.checked_add(replaced_input_amount)?;
if let Some(image) = image {
let image_no_cache = decimal(&image.input_price_per_million.amount)?
.scaled()
.checked_mul(u128::from(image.cached_input_tokens))?
.checked_div(1_000_000)?;
total = total
.checked_sub(decimal(&image.cache_read_amount.amount)?.scaled())?
.checked_add(image_no_cache)?;
}
DecimalAmount::from_str(
&gateway_core::metering::Decimal::from_scaled(total)
.ok()?
.canonical(),
)
.ok()
}
pub(super) fn amount_difference(
larger: Option<&DecimalAmount>,
smaller: Option<&DecimalAmount>,
) -> Option<DecimalAmount> {
let difference = decimal(larger?)?
.scaled()
.checked_sub(decimal(smaller?)?.scaled())?;
DecimalAmount::from_str(
&gateway_core::metering::Decimal::from_scaled(difference)
.ok()?
.canonical(),
)
.ok()
}
fn decimal(value: &DecimalAmount) -> Option<gateway_core::metering::Decimal> {
value.as_str().parse().ok()
}
pub(super) fn usd_cost(costs: &[CurrencyCost]) -> Option<DecimalAmount> {
costs
.iter()
.find(|cost| cost.currency.eq_ignore_ascii_case("USD"))
.map(|cost| cost.amount.clone())
}
@@ -0,0 +1,295 @@
//! 仪表盘趋势、健康时间桶与期间指标
use super::metrics::{average, rate_or_zero, ratio};
use crate::model::AdminError;
use crate::model::observability::{
CostCoverage, CurrencyCost, DashboardPeriodMetrics, DecimalAmount, HealthStatus,
HealthTimeline, HealthTimelinePoint, RequestHealth, RequestMetricPoint, RequestMetrics, Trend,
TrendKind, TrendPoint, TrendSummary,
};
use chrono::{DateTime, Duration, Utc};
use std::collections::BTreeMap;
const HEALTH_TIMELINE_SLOT_MINUTES: i64 = 15;
const HEALTH_TIMELINE_MIN_SAMPLE_SIZE: u64 = 10;
const HEALTH_TIMELINE_UNAVAILABLE_FAILURE_THRESHOLD: u64 = 3;
const HEALTH_TIMELINE_STABLE_RELIABILITY: f64 = 95.0;
/// 按部署时区的自然日计算 15 分钟健康桶,桶数随夏令时变化
pub(in crate::use_case) fn health_timeline_at(
records: &[RequestMetricPoint],
now: DateTime<Utc>,
timezone: gateway_core::time::DeploymentTimeZone,
) -> Result<HealthTimeline, AdminError> {
let start = timezone
.day_start(now)
.ok_or_else(|| AdminError::internal("时间超出支持范围"))?;
let end = timezone
.days_after(now, 1)
.ok_or_else(|| AdminError::internal("时间超出支持范围"))?;
let current_slot = start
+ Duration::minutes(
(now - start)
.num_minutes()
.div_euclid(HEALTH_TIMELINE_SLOT_MINUTES)
* HEALTH_TIMELINE_SLOT_MINUTES,
);
let slots = ((end - start).num_minutes() + HEALTH_TIMELINE_SLOT_MINUTES - 1)
/ HEALTH_TIMELINE_SLOT_MINUTES;
let mut buckets = (0..slots)
.map(|index| {
(
start + Duration::minutes(HEALTH_TIMELINE_SLOT_MINUTES * index),
RequestHealth::default(),
)
})
.collect::<Vec<_>>();
for record in records {
if record.bucket_start < start || record.bucket_start > now {
continue;
}
let record_slot = start
+ Duration::minutes(
(record.bucket_start - start)
.num_minutes()
.div_euclid(HEALTH_TIMELINE_SLOT_MINUTES)
* HEALTH_TIMELINE_SLOT_MINUTES,
);
if let Some((_, bucket)) = buckets
.iter_mut()
.find(|(bucket_start, _)| *bucket_start == record_slot)
{
bucket.add_metrics(&record.metrics);
}
}
let totals = buckets
.iter()
.filter(|(bucket_start, _)| *bucket_start <= current_slot)
.fold(RequestHealth::default(), |mut totals, (_, bucket)| {
totals.add_window(*bucket);
totals
});
Ok(HealthTimeline {
reliability_percent: health_reliability(totals),
status: health_status(totals, false),
success_requests: totals.success_requests,
failed_requests: totals.failed_requests,
cancelled_requests: totals.cancelled_requests,
incomplete_requests: totals.incomplete_requests,
caller_error_requests: totals.caller_error_requests,
points: buckets
.into_iter()
.map(|(bucket_start, bucket)| HealthTimelinePoint {
bucket_start,
status: health_status(bucket, bucket_start > current_slot),
reliability_percent: health_reliability(bucket),
success_requests: bucket.success_requests,
failed_requests: bucket.failed_requests,
cancelled_requests: bucket.cancelled_requests,
incomplete_requests: bucket.incomplete_requests,
caller_error_requests: bucket.caller_error_requests,
})
.collect(),
})
}
pub(super) fn trend(
kind: TrendKind,
points: Vec<RequestMetricPoint>,
analytics: crate::model::analytics::AnalyticsMetadata,
) -> Result<Trend, AdminError> {
let mut metrics = RequestMetrics::default();
let mut coverage = CostCoverage::default();
let mut costs = BTreeMap::<String, DecimalAmount>::new();
for point in &points {
add_request_metrics(&mut metrics, &point.metrics);
coverage.provider_reported_count = coverage
.provider_reported_count
.saturating_add(point.cost_coverage.provider_reported_count);
coverage.calculated_count = coverage
.calculated_count
.saturating_add(point.cost_coverage.calculated_count);
coverage.partial_count = coverage
.partial_count
.saturating_add(point.cost_coverage.partial_count);
coverage.unavailable_count = coverage
.unavailable_count
.saturating_add(point.cost_coverage.unavailable_count);
coverage.not_billable_count = coverage
.not_billable_count
.saturating_add(point.cost_coverage.not_billable_count);
for cost in &point.costs {
if let Some(amount) = costs.get_mut(&cost.currency) {
*amount = amount
.checked_add(&cost.amount)
.ok_or_else(|| AdminError::internal("成本聚合结果超出数值范围"))?;
} else {
costs.insert(cost.currency.clone(), cost.amount.clone());
}
}
}
let average_latency_ms = average(metrics.latency_sum_ms, metrics.latency_count);
let health = RequestHealth::from_metrics(&metrics);
let error_count = health.non_success_requests();
let success_rate = health.success_ratio();
let cache_hit_request_rate = ratio(
metrics.cache_hit_request_count,
metrics.cache_eligible_request_count,
);
let peak_first_token_p95_ms = points
.iter()
.filter_map(|point| point.metrics.first_token_latency_percentiles.p95_ms)
.map(|value| value.as_f64())
.reduce(f64::max);
let peak_latency_p95_ms = points
.iter()
.filter_map(|point| point.metrics.latency_percentiles.p95_ms)
.map(|value| value.as_f64())
.reduce(f64::max);
let minimum_output_throughput_p50 = points
.iter()
.filter_map(|point| point.metrics.output_throughput_p50)
.min();
Ok(Trend {
analytics,
kind,
points: points.into_iter().map(trend_point).collect(),
summary: TrendSummary {
request_count: metrics.request_count,
input_tokens: metrics.input_tokens,
output_tokens: metrics.output_tokens,
cached_input_tokens: metrics.cached_input_tokens,
total_tokens: metrics.total_tokens,
error_count,
average_latency_ms,
max_latency_ms: metrics.max_latency_ms,
min_latency_ms: metrics.min_latency_ms,
peak_first_token_p95_ms,
peak_latency_p95_ms,
minimum_output_throughput_p50,
success_rate,
cache_hit_request_rate,
costs: costs
.into_iter()
.map(|(currency, amount)| CurrencyCost { currency, amount })
.collect(),
cost_coverage: coverage,
},
})
}
fn trend_point(point: RequestMetricPoint) -> TrendPoint {
let health = RequestHealth::from_metrics(&point.metrics);
TrendPoint {
bucket_start: point.bucket_start,
granularity: point.granularity,
error_count: health.non_success_requests(),
average_latency_ms: average(point.metrics.latency_sum_ms, point.metrics.latency_count),
average_first_token_latency_ms: average(
point.metrics.first_token_latency_sum_ms,
point.metrics.first_token_latency_count,
),
cached_token_rate: rate_or_zero(
point.metrics.cached_input_tokens,
point.metrics.input_tokens,
),
cache_hit_request_rate: ratio(
point.metrics.cache_hit_request_count,
point.metrics.cache_eligible_request_count,
),
success_rate: health.success_ratio(),
metrics: point.metrics,
cost_coverage: point.cost_coverage,
costs: point.costs,
}
}
pub(super) fn dashboard_period_metrics<'a>(
metrics: impl IntoIterator<Item = &'a RequestMetrics>,
) -> DashboardPeriodMetrics {
let mut result = DashboardPeriodMetrics::default();
for metrics in metrics {
result.request_count = result.request_count.saturating_add(metrics.request_count);
result.input_tokens = result.input_tokens.saturating_add(metrics.input_tokens);
result.output_tokens = result.output_tokens.saturating_add(metrics.output_tokens);
result.cached_input_tokens = result
.cached_input_tokens
.saturating_add(metrics.cached_input_tokens);
result.total_tokens = result.total_tokens.saturating_add(metrics.total_tokens);
}
result.cached_token_rate = rate_or_zero(result.cached_input_tokens, result.input_tokens);
result.observed_cached_token_rate = ratio(result.cached_input_tokens, result.input_tokens);
result
}
fn add_request_metrics(total: &mut RequestMetrics, value: &RequestMetrics) {
total.request_count = total.request_count.saturating_add(value.request_count);
total.success_count = total.success_count.saturating_add(value.success_count);
total.failure_count = total.failure_count.saturating_add(value.failure_count);
total.cancelled_count = total.cancelled_count.saturating_add(value.cancelled_count);
total.incomplete_count = total
.incomplete_count
.saturating_add(value.incomplete_count);
total.caller_error_count = total
.caller_error_count
.saturating_add(value.caller_error_count);
total.input_tokens = total.input_tokens.saturating_add(value.input_tokens);
total.output_tokens = total.output_tokens.saturating_add(value.output_tokens);
total.cached_input_tokens = total
.cached_input_tokens
.saturating_add(value.cached_input_tokens);
total.cache_write_input_tokens = total
.cache_write_input_tokens
.saturating_add(value.cache_write_input_tokens);
total.reasoning_output_tokens = total
.reasoning_output_tokens
.saturating_add(value.reasoning_output_tokens);
total.total_tokens = total.total_tokens.saturating_add(value.total_tokens);
total.first_token_latency_sum_ms = total
.first_token_latency_sum_ms
.saturating_add(value.first_token_latency_sum_ms);
total.first_token_latency_count = total
.first_token_latency_count
.saturating_add(value.first_token_latency_count);
total.latency_sum_ms = total.latency_sum_ms.saturating_add(value.latency_sum_ms);
total.latency_count = total.latency_count.saturating_add(value.latency_count);
total.min_latency_ms = match (total.min_latency_ms, value.min_latency_ms) {
(Some(left), Some(right)) => Some(left.min(right)),
(left, right) => left.or(right),
};
total.max_latency_ms = match (total.max_latency_ms, value.max_latency_ms) {
(Some(left), Some(right)) => Some(left.max(right)),
(left, right) => left.or(right),
};
total.cache_eligible_request_count = total
.cache_eligible_request_count
.saturating_add(value.cache_eligible_request_count);
total.cache_hit_request_count = total
.cache_hit_request_count
.saturating_add(value.cache_hit_request_count);
}
fn health_status(bucket: RequestHealth, is_future: bool) -> HealthStatus {
let eligible_requests = bucket.eligible_requests();
if is_future {
HealthStatus::Future
} else if eligible_requests == 0 {
HealthStatus::NoData
} else if bucket.success_requests == 0
&& bucket.non_success_requests() >= HEALTH_TIMELINE_UNAVAILABLE_FAILURE_THRESHOLD
{
HealthStatus::Unavailable
} else if eligible_requests < HEALTH_TIMELINE_MIN_SAMPLE_SIZE {
HealthStatus::LowSample
} else if health_reliability(bucket)
.is_some_and(|reliability| reliability < HEALTH_TIMELINE_STABLE_RELIABILITY)
{
HealthStatus::Unstable
} else {
HealthStatus::Stable
}
}
fn health_reliability(bucket: RequestHealth) -> Option<f64> {
bucket.success_rate()
}
@@ -1,6 +1,8 @@
//! 从已保存的错误事实投影管理端来源,不参与执行错误分类或重试
use crate::model::observability::{UsageErrorOrigin, UsageListRecord, UsageRecord};
use crate::model::observability::{
UsageErrorEvidence, UsageErrorOrigin, UsageListRecord, UsageRecord,
};
impl UsageListRecord {
#[must_use]
@@ -47,107 +49,124 @@ fn error_origin(
continuation_reason: Option<&str>,
connection_exit_reason: Option<&str>,
) -> UsageErrorOrigin {
if has_upstream_error
|| upstream_code.is_some_and(|code| !code.is_empty())
|| websocket_close_code.is_some()
|| upstream_status_code.is_some_and(|status| status >= 400)
|| matches!(
continuation_reason,
Some("upstream_rejected" | "quota_exhausted")
)
|| matches!(
error_kind,
// 这里匹配内部 errorKind;message_too_big 只由收到的上游 close 1009 产生
Some("permission_denied" | "message_too_big" | "upstream_capacity_unavailable")
)
{
return UsageErrorOrigin::Upstream;
}
if matches!(
continuation_reason,
Some(
"scope_unavailable"
| "pool_unavailable"
| "fresh_connection_required"
| "connection_busy"
| "latest_response_mismatch"
| "reused_connection_lost"
| "transport_payload_too_large"
)
) || matches!(
error_kind,
Some(
"process_interrupted"
| "process_terminated"
| "internal_error"
| "model_not_found"
| "no_available_provider"
| "no_eligible_account"
| "account_capacity_unavailable"
| "middleware_capacity_unavailable"
| "concurrency_queue_full"
| "concurrency_queue_timeout"
| "provider_infrastructure_unavailable"
| "session_policy_restricted"
| "request_policy_denied"
| "policy_denied"
| "budget_exhausted"
)
) || matches!(
connection_exit_reason,
Some(
"command_channel_closed"
| "local_close"
| "message_receiver_closed"
| "client_cancelled"
| "downstream_send_failed"
| "downstream_connection_closed"
| "downstream_rebound"
| "pool_shutdown"
| "max_age_expired"
| "idle_timeout_expired"
| "proxy_capacity_evicted"
| "search_activation_required"
)
) {
return UsageErrorOrigin::Proxy;
}
if matches!(
connection_exit_reason,
Some(
"upstream_close"
| "normal_close"
| "unexpected_binary_event"
| "incomplete_response"
| "failed_response"
)
) {
return UsageErrorOrigin::Upstream;
}
if error_kind == Some("transport")
|| matches!(
connection_exit_reason,
Some(
"eof"
| "unexpected_eof"
| "transport_error"
| "connection_reset"
| "connection_aborted"
| "broken_pipe"
| "tcp_reset"
| "reset_without_closing_handshake"
| "transport_timeout"
| "outbound_transport_error"
| "receive_idle_timeout"
| "pong_timeout"
| "ping_write_timeout"
| "pong_write_timeout"
)
)
{
return UsageErrorOrigin::Connection;
}
// invalid_request、protocol、rate_limited 等分类同时用于本地和上游失败
// 发送状态与笼统的连接退出摘要也不能替代缺失的来源事实
UsageErrorOrigin::Unknown
use UsageErrorEvidence::*;
UsageErrorOrigin::RULES
.iter()
.find(|(evidence, _)| match evidence {
ProviderErrorCode => upstream_code.is_some_and(|code| !code.is_empty()),
UpstreamStatusAtLeast(min) => upstream_status_code.is_some_and(|status| status >= *min),
SavedUpstreamErrorOrClose => has_upstream_error || websocket_close_code.is_some(),
ErrorKind(values) => error_kind.is_some_and(|value| values.contains(&value)),
Continuation(values) => {
continuation_reason.is_some_and(|value| values.contains(&value))
}
ConnectionExit(values) => {
connection_exit_reason.is_some_and(|value| values.contains(&value))
}
})
.map_or(UsageErrorOrigin::Unknown, |(_, origin)| *origin)
}
impl UsageErrorOrigin {
/// 第一条命中的规则决定来源;含义不唯一的分类在缺少其他证据时保留 unknown
pub const RULES: &'static [(UsageErrorEvidence, Self)] = {
use UsageErrorEvidence::*;
&[
(ProviderErrorCode, Self::Upstream),
(UpstreamStatusAtLeast(400), Self::Upstream),
(
Continuation(&["upstream_rejected", "quota_exhausted"]),
Self::Upstream,
),
// message_too_big 只由收到的上游 close 1009 产生
(
ErrorKind(&[
"permission_denied",
"message_too_big",
"upstream_capacity_unavailable",
]),
Self::Upstream,
),
(SavedUpstreamErrorOrClose, Self::Upstream),
(
Continuation(&[
"scope_unavailable",
"pool_unavailable",
"fresh_connection_required",
"connection_busy",
"latest_response_mismatch",
"reused_connection_lost",
"transport_payload_too_large",
]),
Self::Proxy,
),
(
ErrorKind(&[
"process_interrupted",
"process_terminated",
"internal_error",
"model_not_found",
"no_available_provider",
"no_eligible_account",
"account_capacity_unavailable",
"middleware_capacity_unavailable",
"concurrency_queue_full",
"concurrency_queue_timeout",
"provider_infrastructure_unavailable",
"session_policy_restricted",
"request_policy_denied",
"policy_denied",
"budget_exhausted",
]),
Self::Proxy,
),
(
ConnectionExit(&[
"command_channel_closed",
"local_close",
"message_receiver_closed",
"client_cancelled",
"downstream_send_failed",
"downstream_connection_closed",
"downstream_rebound",
"pool_shutdown",
"max_age_expired",
"idle_timeout_expired",
"proxy_capacity_evicted",
"search_activation_required",
]),
Self::Proxy,
),
(
ConnectionExit(&[
"upstream_close",
"normal_close",
"unexpected_binary_event",
"incomplete_response",
"failed_response",
]),
Self::Upstream,
),
(ErrorKind(&["transport"]), Self::Connection),
(
ConnectionExit(&[
"eof",
"unexpected_eof",
"transport_error",
"connection_reset",
"connection_aborted",
"broken_pipe",
"tcp_reset",
"reset_without_closing_handshake",
"transport_timeout",
"outbound_transport_error",
"receive_idle_timeout",
"pong_timeout",
"ping_write_timeout",
"pong_write_timeout",
]),
Self::Connection,
),
]
};
}
@@ -9,12 +9,13 @@ use tokio::time::{Instant, timeout_at};
mod availability;
use super::{DefaultObservabilityService, map_store_error};
use super::DefaultObservabilityService;
use crate::model::{
AdminError, AdminErrorKind,
diagnostics::{DiagnosticBundle, DiagnosticGap, DiagnosticRequest, DiagnosticTarget},
observability::OpsError,
};
use crate::use_case::map_store_error;
const MAX_REQUESTS: usize = 8;
const MAX_ERRORS: u16 = 128;
@@ -0,0 +1,393 @@
//! 用量洞察与费用场景的纯聚合
use super::billing::{amount_difference, usd_cost};
use super::metrics::{rate_or_zero, ratio};
use crate::model::AdminError;
use crate::model::observability::{
DecimalAmount, RequestHealth, RequestMetricPoint, UsageCacheEfficiency, UsageConcurrencyPoint,
UsageCostComparison, UsageCostSummary, UsageInsight, UsageInsightData, UsageInsightMetric,
UsageInsights, UsageInsightsCost, UsageInsightsCostPoint, UsageInsightsHealth,
UsageInsightsHealthPoint, UsageInsightsLoad, UsageInsightsObservation,
UsageInsightsPerformance, UsageInsightsPerformancePoint, UsageMetricPoint, UsageMetricSeries,
UsageOverview, UsageThroughputPercentiles,
};
use chrono::{DateTime, Utc};
use std::collections::BTreeMap;
use std::collections::btree_map::Entry;
pub(super) fn insights_from_observation(
observation: UsageInsightsObservation,
) -> Result<UsageInsights, AdminError> {
let mut standard_costs = UsageCostScenarios::default();
for point in observation.costs {
if let Some(amount) = point.standard_amount {
standard_costs.standard.add(point.bucket_start, amount)?;
}
if let Some(amount) = point.no_cache_amount {
standard_costs.no_cache.add(point.bucket_start, amount)?;
}
}
let overview = observation.overview;
let trend = observation.trend;
build_usage_insights(overview, trend, standard_costs, observation.concurrency)
}
pub(super) fn select_usage_metric(
insights: UsageInsights,
metric: UsageInsightMetric,
) -> UsageInsight {
let activity = insights
.health
.points
.iter()
.map(|point| (point.bucket_start, point.total_requests))
.collect::<BTreeMap<_, _>>();
let data = match metric {
UsageInsightMetric::Health => UsageInsightData::Health(insights.health),
UsageInsightMetric::Latency => UsageInsightData::Latency(metric_series(
insights.performance.latency_percentiles,
insights
.performance
.points
.into_iter()
.map(|point| (point.bucket_start, point.latency_percentiles)),
&activity,
)),
UsageInsightMetric::FirstToken => UsageInsightData::FirstToken(metric_series(
insights.performance.first_token_latency_percentiles,
insights
.performance
.points
.into_iter()
.map(|point| (point.bucket_start, point.first_token_latency_percentiles)),
&activity,
)),
UsageInsightMetric::Throughput => UsageInsightData::Throughput(metric_series(
UsageThroughputPercentiles {
p10: insights.performance.output_throughput_p10,
p50: insights.performance.output_throughput_p50,
p90: insights.performance.output_throughput_p90,
},
insights.performance.points.into_iter().map(|point| {
(
point.bucket_start,
UsageThroughputPercentiles {
p10: point.output_throughput_p10,
p50: point.output_throughput_p50,
p90: point.output_throughput_p90,
},
)
}),
&activity,
)),
UsageInsightMetric::Load => UsageInsightData::Load(metric_series(
insights.performance.load,
insights
.performance
.points
.into_iter()
.map(|point| (point.bucket_start, point.load)),
&activity,
)),
UsageInsightMetric::Cost => UsageInsightData::Cost(metric_series(
cost_summary(&insights.cost),
insights.cost.points.into_iter().map(|point| {
(
point.bucket_start,
UsageCostComparison {
estimated_cost: point.estimated_cost,
no_cache_cost: point.no_cache_cost,
},
)
}),
&activity,
)),
UsageInsightMetric::Savings => UsageInsightData::Savings(metric_series(
cost_summary(&insights.cost),
insights
.cost
.points
.into_iter()
.map(|point| (point.bucket_start, point.cache_savings)),
&activity,
)),
UsageInsightMetric::Cache => UsageInsightData::Cache(metric_series(
cost_summary(&insights.cost),
insights.cost.points.into_iter().map(|point| {
(
point.bucket_start,
UsageCacheEfficiency {
input_tokens: point.input_tokens,
cached_token_rate: point.cached_token_rate,
cache_hit_request_rate: point.cache_hit_request_rate,
},
)
}),
&activity,
)),
};
UsageInsight {
analytics: insights.analytics,
granularity: insights.granularity,
data,
}
}
fn cost_summary(cost: &UsageInsightsCost) -> UsageCostSummary {
UsageCostSummary {
estimated_cost: cost.estimated_cost.clone(),
cache_savings: cost.cache_savings.clone(),
tier_premium: cost.tier_premium.clone(),
cost_per_successful_request: cost.cost_per_successful_request.clone(),
coverage: cost.coverage.clone(),
}
}
fn metric_series<S, P>(
summary: S,
points: impl Iterator<Item = (DateTime<Utc>, P)>,
activity: &BTreeMap<DateTime<Utc>, u64>,
) -> UsageMetricSeries<S, P> {
UsageMetricSeries {
summary,
points: points
.map(|(bucket_start, value)| UsageMetricPoint {
bucket_start,
request_count: activity.get(&bucket_start).copied().unwrap_or_default(),
value,
})
.collect(),
}
}
fn build_usage_insights(
overview: UsageOverview,
trend: Vec<RequestMetricPoint>,
standard_costs: UsageCostScenarios,
concurrency: Vec<UsageConcurrencyPoint>,
) -> Result<UsageInsights, AdminError> {
let granularity = trend.first().map_or(
crate::model::observability::Granularity::FifteenMinutes,
|point| point.granularity,
);
if trend.iter().any(|point| point.granularity != granularity) {
return Err(AdminError::internal("用量洞察趋势包含不一致的时间粒度"));
}
let requests = &overview.requests;
let health_window = RequestHealth::from_metrics(requests);
let failed_requests = health_window.failed_requests;
let health = UsageInsightsHealth {
total_requests: requests.request_count,
success_requests: requests.success_count,
failed_requests,
cancelled_requests: requests.cancelled_count,
incomplete_requests: requests.incomplete_count,
caller_error_requests: requests.caller_error_count,
success_rate: health_window.success_ratio(),
completion_rate: rate_or_zero(
requests
.success_count
.saturating_add(requests.failure_count),
requests.request_count,
),
points: trend
.iter()
.map(|point| {
let health_window = RequestHealth::from_metrics(&point.metrics);
UsageInsightsHealthPoint {
total_requests: point.metrics.request_count,
bucket_start: point.bucket_start,
success_requests: point.metrics.success_count,
failed_requests: health_window.failed_requests,
cancelled_requests: point.metrics.cancelled_count,
incomplete_requests: point.metrics.incomplete_count,
caller_error_requests: point.metrics.caller_error_count,
error_rate: health_window.error_ratio(),
}
})
.collect(),
};
let concurrency_by_bucket = concurrency
.iter()
.map(|point| (point.bucket_start, point))
.collect::<BTreeMap<_, _>>();
let mut weighted_concurrency_micros = 0.0;
let mut effective_micros = 0_i64;
for (index, point) in concurrency.iter().enumerate() {
let start = point.bucket_start.max(overview.range.start);
let end = concurrency
.get(index + 1)
.map_or(overview.range.end, |next| next.bucket_start)
.min(overview.range.end);
let micros = (end - start).num_microseconds().unwrap_or(0).max(0);
effective_micros = effective_micros.saturating_add(micros);
weighted_concurrency_micros += point.average_concurrency * micros as f64;
}
let average_concurrency = if effective_micros > 0 {
weighted_concurrency_micros / effective_micros as f64
} else {
0.0
};
let peak_concurrency = concurrency
.iter()
.map(|point| point.peak_concurrency)
.max()
.unwrap_or(0);
let performance = UsageInsightsPerformance {
latency_percentiles: requests.latency_percentiles,
first_token_latency_percentiles: requests.first_token_latency_percentiles,
output_throughput_p10: requests.output_throughput_p10,
output_throughput_p50: requests.output_throughput_p50,
output_throughput_p90: requests.output_throughput_p90,
load: UsageInsightsLoad {
average_concurrency,
peak_concurrency,
admission_decision_p95_ms: requests.admission_decision_percentiles.p95_ms,
account_selection_wait_p95_ms: requests.account_selection_wait_percentiles.p95_ms,
},
points: trend
.iter()
.map(|point| {
let concurrency = concurrency_by_bucket.get(&point.bucket_start);
UsageInsightsPerformancePoint {
bucket_start: point.bucket_start,
latency_percentiles: point.metrics.latency_percentiles,
first_token_latency_percentiles: point.metrics.first_token_latency_percentiles,
output_throughput_p10: point.metrics.output_throughput_p10,
output_throughput_p50: point.metrics.output_throughput_p50,
output_throughput_p90: point.metrics.output_throughput_p90,
load: UsageInsightsLoad {
average_concurrency: concurrency
.map_or(0.0, |point| point.average_concurrency),
peak_concurrency: concurrency.map_or(0, |point| point.peak_concurrency),
admission_decision_p95_ms: point
.metrics
.admission_decision_percentiles
.p95_ms,
account_selection_wait_p95_ms: point
.metrics
.account_selection_wait_percentiles
.p95_ms,
},
}
})
.collect(),
};
let estimated_cost = usd_cost(&overview.attempts.costs);
let UsageCostScenarios {
standard:
ScenarioCosts {
total: standard_cost,
by_bucket: standard_costs_by_bucket,
},
no_cache:
ScenarioCosts {
total: no_cache_cost,
by_bucket: no_cache_costs_by_bucket,
},
} = standard_costs;
let cache_savings = amount_difference(no_cache_cost.as_ref(), estimated_cost.as_ref());
let tier_premium = amount_difference(estimated_cost.as_ref(), standard_cost.as_ref());
let cost_per_request = estimated_cost
.as_ref()
.and_then(|cost| cost.checked_div_u64(requests.request_count));
let cost_per_successful_request = estimated_cost
.as_ref()
.and_then(|cost| cost.checked_div_u64(requests.success_count));
let cost = UsageInsightsCost {
cost_per_request,
estimated_cost,
standard_cost,
no_cache_cost,
cache_savings,
tier_premium,
tokens_per_request: rate_or_zero(requests.total_tokens, requests.request_count),
cost_per_successful_request,
cached_token_rate: rate_or_zero(requests.cached_input_tokens, requests.input_tokens),
cache_hit_request_rate: ratio(
requests.cache_hit_request_count,
requests.cache_eligible_request_count,
),
input_tokens: requests.input_tokens,
output_tokens: requests.output_tokens,
cached_input_tokens: requests.cached_input_tokens,
total_tokens: requests.total_tokens,
points: trend
.iter()
.map(|point| UsageInsightsCostPoint {
bucket_start: point.bucket_start,
input_tokens: point.metrics.input_tokens,
output_tokens: point.metrics.output_tokens,
cached_input_tokens: point.metrics.cached_input_tokens,
total_tokens: point.metrics.total_tokens,
estimated_cost: usd_cost(&point.costs),
standard_cost: standard_costs_by_bucket.get(&point.bucket_start).cloned(),
no_cache_cost: no_cache_costs_by_bucket.get(&point.bucket_start).cloned(),
cache_savings: amount_difference(
no_cache_costs_by_bucket.get(&point.bucket_start),
usd_cost(&point.costs).as_ref(),
),
cached_token_rate: rate_or_zero(
point.metrics.cached_input_tokens,
point.metrics.input_tokens,
),
cache_hit_request_rate: ratio(
point.metrics.cache_hit_request_count,
point.metrics.cache_eligible_request_count,
),
})
.collect(),
costs: overview.attempts.costs.clone(),
coverage: overview.attempts.cost_coverage.clone(),
};
Ok(UsageInsights {
analytics: overview.analytics,
granularity,
health,
performance,
cost,
attempts: overview.attempts,
providers: overview.providers,
})
}
#[derive(Debug, Default)]
struct ScenarioCosts {
total: Option<DecimalAmount>,
by_bucket: BTreeMap<DateTime<Utc>, DecimalAmount>,
}
impl ScenarioCosts {
fn add(
&mut self,
bucket_start: DateTime<Utc>,
amount: DecimalAmount,
) -> Result<(), AdminError> {
self.total = Some(match self.total.take() {
Some(current) => current
.checked_add(&amount)
.ok_or_else(|| AdminError::internal("用量标准成本超出数值范围"))?,
None => amount.clone(),
});
match self.by_bucket.entry(bucket_start) {
Entry::Occupied(mut entry) => {
let sum = entry
.get()
.checked_add(&amount)
.ok_or_else(|| AdminError::internal("用量标准成本超出数值范围"))?;
entry.insert(sum);
}
Entry::Vacant(entry) => {
entry.insert(amount);
}
}
Ok(())
}
}
#[derive(Debug, Default)]
struct UsageCostScenarios {
standard: ScenarioCosts,
no_cache: ScenarioCosts,
}
@@ -0,0 +1,13 @@
//! 观测指标的均值与比率计算
pub(super) fn average(sum: u64, count: u64) -> Option<u64> {
(count > 0).then(|| sum / count)
}
pub(super) fn ratio(numerator: u64, denominator: u64) -> Option<f64> {
(denominator > 0).then(|| numerator as f64 / denominator as f64)
}
pub(super) fn rate_or_zero(numerator: u64, denominator: u64) -> f64 {
ratio(numerator, denominator).unwrap_or(0.0)
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,610 @@
//! 观测查询与账号信息补充的用例协调
use super::billing::usd_cost;
use super::dashboard::{dashboard_period_metrics, health_timeline_at, trend};
use super::insights::{insights_from_observation, select_usage_metric};
use super::metrics::{average, rate_or_zero};
use crate::model::AdminError;
use crate::model::observability::{
DashboardAccountUsage, DashboardCapacity, DashboardQuery, DashboardResult, DiagnosticDimension,
DiagnosticsItem, DiagnosticsResult, Granularity, OpsErrorPage, OpsErrorQuery,
ProviderBillingInput, RequestHealth, TimeRange, Trend, TrendKind, UsageBilling, UsageDetail,
UsageFilter, UsageInsight, UsageInsightMetric, UsageInsights, UsagePage, UsageQuery,
UsageSummary,
};
use crate::model::provider_credentials::ProviderQuotaRequest;
use crate::ports::provider::ProviderAdminRegistry;
use crate::ports::store::{AccountStore, ObservabilityStore, SettingsStore};
use crate::use_case::map_store_error;
use async_trait::async_trait;
use chrono::{Duration, Utc};
use futures::StreamExt as _;
use gateway_core::account::ProviderAccountId;
use gateway_core::routing::ProviderKind;
use std::collections::HashMap;
use std::sync::Arc;
/// API 消费的观测控制面服务
#[async_trait]
pub trait ObservabilityService: Send + Sync {
async fn dashboard_summary(
&self,
range: TimeRange,
kind: TrendKind,
) -> Result<DashboardResult, AdminError>;
async fn dashboard_trend(&self, range: TimeRange, kind: TrendKind)
-> Result<Trend, AdminError>;
async fn usage_records(&self, query: UsageQuery) -> Result<UsagePage, AdminError>;
async fn usage_record_detail(&self, request_id: &str) -> Result<UsageDetail, AdminError>;
async fn client_key_statistics(
&self,
range: TimeRange,
id: &gateway_core::policy::ClientApiKeyId,
query: crate::model::observability::KeyUsageMetric,
) -> Result<crate::model::observability::KeyStatisticsOverview, AdminError>;
async fn client_key_models(
&self,
range: TimeRange,
id: &gateway_core::policy::ClientApiKeyId,
) -> Result<Vec<crate::model::observability::KeyModelRow>, AdminError>;
async fn usage_summary(
&self,
range: TimeRange,
filter: UsageFilter,
) -> Result<UsageSummary, AdminError>;
async fn usage_insights(
&self,
range: TimeRange,
filter: UsageFilter,
) -> Result<UsageInsights, AdminError>;
async fn usage_metric(
&self,
range: TimeRange,
filter: UsageFilter,
metric: UsageInsightMetric,
) -> Result<UsageInsight, AdminError>;
async fn diagnostics(
&self,
range: TimeRange,
filter: UsageFilter,
dimension: DiagnosticDimension,
) -> Result<DiagnosticsResult, AdminError>;
async fn ops_errors(&self, query: OpsErrorQuery) -> Result<OpsErrorPage, AdminError>;
async fn export_diagnostics(
&self,
target: crate::model::diagnostics::DiagnosticTarget,
) -> Result<crate::model::diagnostics::DiagnosticBundle, AdminError>;
}
pub(crate) struct DefaultObservabilityService {
pub(super) timezone: gateway_core::time::DeploymentTimeZone,
pub(super) store: Arc<dyn ObservabilityStore>,
pub(super) accounts: Arc<dyn AccountStore>,
pub(super) settings: Arc<dyn SettingsStore>,
pub(super) providers: ProviderAdminRegistry,
pub(super) system: Arc<dyn crate::use_case::system::SystemService>,
pub(super) upstream_info: Option<Arc<dyn crate::ports::peer::PeerUpstreamService>>,
}
impl DefaultObservabilityService {
#[must_use]
pub(crate) fn new(
store: Arc<dyn ObservabilityStore>,
accounts: Arc<dyn AccountStore>,
settings: Arc<dyn SettingsStore>,
providers: ProviderAdminRegistry,
timezone: gateway_core::time::DeploymentTimeZone,
system: Arc<dyn crate::use_case::system::SystemService>,
upstream_info: Option<Arc<dyn crate::ports::peer::PeerUpstreamService>>,
) -> Self {
Self {
timezone,
store,
accounts,
settings,
providers,
system,
upstream_info,
}
}
async fn load_dashboard_summary(
&self,
range: TimeRange,
) -> Result<DashboardResult, AdminError> {
let observed_at = Utc::now();
let query = DashboardQuery::new(range, self.timezone)
.map_err(|_| AdminError::internal("时间超出支持范围"))?;
let today_start = query.yesterday_range.end;
let (mut observation, settings) = futures::try_join!(
self.store.dashboard_summary(query, observed_at),
self.settings.load_runtime_settings(),
)
.map_err(|error| map_store_error(error, "dashboard"))?;
let runtime_slots = observation.runtime_slots.as_ref();
self.enrich_list_records(&mut observation.recent_requests)
.await;
self.enrich_dashboard_quotas(&mut observation.account_usage)
.await;
for account in &mut observation.account_usage {
account.plan_type_display = self
.providers
.plan_type_display(&account.provider_kind, account.plan_type.as_deref());
}
let today = dashboard_period_metrics(
observation
.trend
.iter()
.filter(|point| {
point.bucket_start >= today_start && point.bucket_start < observation.range.end
})
.map(|point| &point.metrics),
);
let yesterday = dashboard_period_metrics(std::iter::once(&observation.yesterday));
let total_billing_usd = observation.totals.billing_usd.clone();
let total_cached_token_rate = rate_or_zero(
observation.totals.cached_input_tokens,
observation.totals.input_tokens,
);
let (first_token_latency_sum_ms, first_token_latency_count) = observation
.trend
.iter()
.fold((0_u64, 0_u64), |(sum, count), point| {
(
sum.saturating_add(point.metrics.first_token_latency_sum_ms),
count.saturating_add(point.metrics.first_token_latency_count),
)
});
let average_first_token_latency_ms =
average(first_token_latency_sum_ms, first_token_latency_count);
let trend = trend(
TrendKind::Usage,
observation.trend.clone(),
observation.analytics.clone(),
)?;
let health_timeline =
health_timeline_at(&observation.trend, observation.range.end, self.timezone)?;
let wire_profiles = self
.providers
.dashboard_wire_profiles(&settings.request_profiles);
let max_concurrent_per_account = u64::from(settings.values.max_concurrent_per_account);
let (mut inherited_accounts, mut overridden_slots) = runtime_slots
.map_or((observation.provider_accounts.normal, 0), |slots| {
(slots.inherited_accounts, slots.overridden_slots)
});
if let (Some(peer), Some(slots)) = (&self.upstream_info, runtime_slots) {
let now = std::time::SystemTime::now();
for version in &slots.inherited_versions {
if let Some(limit) = peer.observed_concurrency_limit(version, now) {
inherited_accounts -= 1;
overridden_slots = overridden_slots.saturating_add(u64::from(limit.get()));
}
}
}
let total_slots = (max_concurrent_per_account > 0 || inherited_accounts == 0).then(|| {
inherited_accounts
.saturating_mul(max_concurrent_per_account)
.saturating_add(overridden_slots)
});
let used_slots = runtime_slots.and_then(|slots| slots.used_slots);
Ok(DashboardResult {
capacity: DashboardCapacity {
max_concurrent_per_account,
total_slots,
used_slots,
available_slots: used_slots
.zip(total_slots)
.map(|(used, total)| total.saturating_sub(used)),
},
rotation_strategy: settings.rotation_strategy,
observation,
today,
yesterday,
total_billing_usd,
total_cached_token_rate,
average_first_token_latency_ms,
trend,
health_timeline,
wire_profiles,
})
}
}
#[async_trait]
impl ObservabilityService for DefaultObservabilityService {
async fn export_diagnostics(
&self,
target: crate::model::diagnostics::DiagnosticTarget,
) -> Result<crate::model::diagnostics::DiagnosticBundle, AdminError> {
self.collect_diagnostics(target).await
}
async fn dashboard_summary(
&self,
range: TimeRange,
kind: TrendKind,
) -> Result<DashboardResult, AdminError> {
let mut result = self.load_dashboard_summary(range).await?;
result.trend = trend(
kind,
result.observation.trend.clone(),
result.observation.analytics.clone(),
)?;
Ok(result)
}
async fn dashboard_trend(
&self,
range: TimeRange,
kind: TrendKind,
) -> Result<Trend, AdminError> {
let observation = self
.store
.usage_insights_observation(
range,
UsageFilter::default(),
Granularity::for_range(range),
false,
)
.await
.map_err(|error| map_store_error(error, "dashboard trend"))?;
trend(kind, observation.trend, observation.overview.analytics)
}
async fn usage_records(&self, query: UsageQuery) -> Result<UsagePage, AdminError> {
let mut page = self
.store
.list_usage_records(query)
.await
.map_err(|error| map_store_error(error, "usage records"))?;
self.enrich_list_records(&mut page.items).await;
Ok(page)
}
async fn usage_record_detail(&self, request_id: &str) -> Result<UsageDetail, AdminError> {
if request_id.trim().is_empty() {
return Err(AdminError::invalid("用量记录 ID 不能为空"));
}
let mut detail = self
.store
.usage_record_detail(request_id)
.await
.map_err(|error| map_store_error(error, "usage record"))?;
self.enrich_detail_billing(std::slice::from_mut(&mut detail.request));
Ok(detail)
}
async fn client_key_statistics(
&self,
range: TimeRange,
id: &gateway_core::policy::ClientApiKeyId,
query: crate::model::observability::KeyUsageMetric,
) -> Result<crate::model::observability::KeyStatisticsOverview, AdminError> {
self.store
.client_key_statistics(range, id, query)
.await
.map_err(|error| map_store_error(error, "client key statistics"))
}
async fn client_key_models(
&self,
range: TimeRange,
id: &gateway_core::policy::ClientApiKeyId,
) -> Result<Vec<crate::model::observability::KeyModelRow>, AdminError> {
self.store
.client_key_models(range, id)
.await
.map_err(|error| map_store_error(error, "client key statistics"))
}
async fn usage_summary(
&self,
range: TimeRange,
filter: UsageFilter,
) -> Result<UsageSummary, AdminError> {
let observation = self
.store
.usage_summary(range, filter)
.await
.map_err(|error| map_store_error(error, "usage summary"))?;
let average_latency_ms = average(
observation.requests.latency_sum_ms,
observation.requests.latency_count,
);
Ok(UsageSummary {
observation,
average_latency_ms,
})
}
async fn usage_insights(
&self,
range: TimeRange,
filter: UsageFilter,
) -> Result<UsageInsights, AdminError> {
let granularity = Granularity::for_range(range);
let observation = self
.store
.usage_insights_observation(range, filter, granularity, true)
.await
.map_err(|error| map_store_error(error, "usage insights"))?;
insights_from_observation(observation)
}
async fn usage_metric(
&self,
range: TimeRange,
filter: UsageFilter,
metric: UsageInsightMetric,
) -> Result<UsageInsight, AdminError> {
let observation = self
.store
.usage_metric_observation(range, filter, Granularity::for_range(range), metric)
.await
.map_err(|error| map_store_error(error, "usage metric"))?;
let insights = insights_from_observation(observation)?;
Ok(select_usage_metric(insights, metric))
}
async fn diagnostics(
&self,
range: TimeRange,
filter: UsageFilter,
dimension: DiagnosticDimension,
) -> Result<DiagnosticsResult, AdminError> {
let observation = self
.store
.usage_diagnostics(range, filter, dimension, 100)
.await
.map_err(|error| map_store_error(error, "usage diagnostics"))?;
let peers = if dimension == DiagnosticDimension::Account {
self.current_upstream_peers(observation.items.iter().map(|item| item.key.as_str()))
.await
} else {
HashMap::new()
};
let items = observation
.items
.into_iter()
.map(|item| {
let health = RequestHealth::from_counts(
item.success_count,
item.failure_count,
item.cancelled_count,
item.incomplete_count,
item.caller_error_count,
);
let non_completion_count =
item.cancelled_count.saturating_add(item.incomplete_count);
let non_completion_rate = rate_or_zero(non_completion_count, item.request_count);
let retry_rate = rate_or_zero(item.retried_request_count, item.request_count);
DiagnosticsItem {
account_upstream_peer: peers.get(&item.key).copied(),
key: item.key,
name: item.name,
account_authentication_kind: item.account_authentication_kind,
account_plan_type_display: item.account_provider_kind.as_deref().and_then(
|provider| {
self.providers
.plan_type_display(provider, item.account_plan_type.as_deref())
},
),
account_plan_type: item.account_plan_type,
request_count: item.request_count,
success_count: item.success_count,
error_count: health.non_success_requests(),
error_rate: health.error_ratio(),
request_share: rate_or_zero(
item.request_count,
observation.total_request_count,
),
average_latency_ms: item.average_latency_ms,
latency_p95_ms: item.latency_p95_ms,
first_token_p95_ms: item.first_token_p95_ms,
non_completion_count,
non_completion_rate,
retry_count: item.retry_count,
retry_rate,
estimated_cost: usd_cost(&item.costs),
attempt_count: item.attempt_count,
total_tokens: item.total_tokens,
}
})
.collect::<Vec<_>>();
Ok(DiagnosticsResult {
analytics: observation.analytics,
dimension,
items,
})
}
async fn ops_errors(&self, query: OpsErrorQuery) -> Result<OpsErrorPage, AdminError> {
let mut page = self
.store
.list_ops_errors(query)
.await
.map_err(|error| map_store_error(error, "operations errors"))?;
for error in &mut page.items {
error.provider_account_plan_type_display =
error.provider_kind.as_deref().and_then(|provider| {
self.providers
.plan_type_display(provider, error.provider_account_plan_type.as_deref())
});
}
Ok(page)
}
}
impl DefaultObservabilityService {
async fn current_upstream_peers<'a>(
&self,
ids: impl Iterator<Item = &'a str>,
) -> HashMap<String, bool> {
let Some(peer) = self.upstream_info.as_deref() else {
return HashMap::new();
};
let ids = ids
.map(str::to_owned)
.collect::<std::collections::BTreeSet<_>>();
// 同一页重复账号只读取一次摘要,单个账号不存在或读取失败不阻断历史记录
futures::stream::iter(ids)
.map(|id: String| async move {
let account_id = ProviderAccountId::new(id.clone()).ok()?;
let upstream = peer.read_summary(&account_id).await.ok()??.upstream?;
Some((id, upstream.discovered && upstream.observed_at.is_some()))
})
.buffer_unordered(8)
.filter_map(|value| async move { value })
.collect()
.await
}
async fn enrich_dashboard_quotas(&self, accounts: &mut [DashboardAccountUsage]) {
if accounts.is_empty() {
return;
}
let now = Utc::now();
let ids = accounts
.iter()
.map(|account| account.account_id.clone())
.collect::<Vec<_>>();
let mut rolling_usage = self
.accounts
.load_account_usage(
TimeRange {
start: now - Duration::hours(24),
end: now,
},
&ids,
)
.await
.unwrap_or_default()
.into_iter()
.map(|usage| (usage.account_id.clone(), usage))
.collect::<HashMap<_, _>>();
let providers = self.providers.clone();
let peer = self.upstream_info.as_deref();
let quota_reads = accounts.iter().map(|account| {
let rolling_usage = rolling_usage.remove(&account.account_id);
let account_id = ProviderAccountId::new(account.account_id.clone()).ok();
let provider = ProviderKind::new(account.provider_kind.clone())
.ok()
.and_then(|kind| providers.require(&kind).ok());
async move {
let (Some(account_id), Some(provider)) = (account_id, provider) else {
return None;
};
if let Some(peer) = peer
&& let Ok(Some(quota)) = peer.read_summary(&account_id).await
{
return Some(quota);
}
provider
.quota(ProviderQuotaRequest {
account_id,
refresh: false,
rolling_usage,
})
.await
.ok()
}
});
let quotas = futures::future::join_all(quota_reads).await;
for (account, quota) in accounts.iter_mut().zip(quotas) {
if let Some(mut quota) = quota {
quota.fill_missing_plan_type(&mut account.plan_type);
quota.apply_limit_reached_display();
account.quota_used_percent = quota.representative_used_percent();
account.quota_window = quota.representative_window().cloned();
account.upstream = quota.upstream;
}
}
}
/// 补充当前套餐展示名称,逐条尽力把可校验的总额升级为完整分解;单条脏数据(非法 Provider kind、
/// 不支持的来源或费用规则失败)只保留该条已存的总额,不影响整页返回
async fn enrich_list_records(
&self,
records: &mut [crate::model::observability::UsageListRecord],
) {
let peers = self
.current_upstream_peers(
records
.iter()
.filter_map(|record| record.provider_account_ref.as_deref()),
)
.await;
for record in records {
record.provider_account_upstream_peer = record
.provider_account_ref
.as_ref()
.and_then(|id| peers.get(id).copied());
record.provider_account_plan_type_display =
record.provider_kind.as_deref().and_then(|provider| {
self.providers
.plan_type_display(provider, record.provider_account_plan_type.as_deref())
});
let Some(UsageBilling::Total { source, total }) = record.billing.as_ref() else {
continue;
};
if !matches!(source.as_str(), "calculated" | "provider_reported") {
continue;
}
let (Some(provider), Some(upstream_model_id)) = (
record.provider_kind.as_deref(),
record.upstream_model_id.as_ref(),
) else {
continue;
};
let Ok(provider_kind) = ProviderKind::new(provider.to_owned()) else {
continue;
};
let input = ProviderBillingInput {
upstream_model_id: upstream_model_id.clone(),
service_tier: record.service_tier.clone(),
input_tokens: record.input_tokens,
output_tokens: record.output_tokens,
cached_input_tokens: record.cached_input_tokens,
cache_write_input_tokens: record.cache_write_input_tokens,
total: total.clone(),
};
if let Ok(Some(breakdown)) = self.providers.calculated_billing(&provider_kind, &input) {
record.billing = Some(UsageBilling::Calculated(Box::new(breakdown)));
}
}
}
fn enrich_detail_billing(&self, records: &mut [crate::model::observability::UsageRecord]) {
for record in records {
let Some(UsageBilling::Total { source, total }) = record.billing.as_ref() else {
continue;
};
if !matches!(source.as_str(), "calculated" | "provider_reported") {
continue;
}
let (Some(provider), Some(upstream_model_id)) = (
record.provider_kind.as_deref(),
record.upstream_model_id.as_ref(),
) else {
continue;
};
let Ok(provider_kind) = ProviderKind::new(provider.to_owned()) else {
continue;
};
let input = ProviderBillingInput {
upstream_model_id: upstream_model_id.clone(),
service_tier: record.service_tier.clone(),
input_tokens: record.input_tokens,
output_tokens: record.output_tokens,
cached_input_tokens: record.cached_input_tokens,
cache_write_input_tokens: record.cache_write_input_tokens,
total: total.clone(),
};
if let Ok(Some(breakdown)) = self.providers.calculated_billing(&provider_kind, &input) {
record.billing = Some(UsageBilling::Calculated(Box::new(breakdown)));
}
}
}
}
@@ -226,6 +226,23 @@ impl ObservabilityStore for CachedObservabilityStore {
) -> AdminStoreResult<Vec<RequestMetricPoint>> {
self.inner.dashboard_trend(range, granularity).await
}
async fn client_key_statistics(
&self,
range: TimeRange,
id: &gateway_core::policy::ClientApiKeyId,
query: crate::model::observability::KeyUsageMetric,
) -> AdminStoreResult<crate::model::observability::KeyStatisticsOverview> {
self.inner.client_key_statistics(range, id, query).await
}
async fn client_key_models(
&self,
range: TimeRange,
id: &gateway_core::policy::ClientApiKeyId,
) -> AdminStoreResult<Vec<crate::model::observability::KeyModelRow>> {
self.inner.client_key_models(range, id).await
}
async fn usage_trend(
&self,
range: TimeRange,
@@ -74,6 +74,23 @@ pub(super) async fn quota_and_models(
let snapshot = client.snapshot();
let scope = client.policy().account_scope();
let mut observations = BTreeMap::<&str, ModelObservations>::new();
let mut provider_facts = BTreeMap::new();
for account in accounts {
let kind = &account.provider_kind;
if provider_facts.contains_key(kind) {
continue;
}
if let Ok(provider) = providers.require(kind) {
// 原生事实读取失败时保留未知,不能退回整号 Allowed 冒充各模型可用
provider_facts.insert(
kind.clone(),
provider
.peer_model_facts(accounts)
.await
.unwrap_or_else(|_| Some(BTreeMap::new())),
);
}
}
let mut model_bytes = 0usize;
let mut result = Vec::with_capacity(accounts.len());
for (index, account) in accounts.iter().enumerate() {
@@ -94,9 +111,32 @@ pub(super) async fn quota_and_models(
{
continue;
}
let eligible = provider
.as_ref()
.and_then(|provider| provider.peer_model_eligible(account, &upstream));
let (eligible, observation) = match provider_facts
.get(&account.provider_kind)
.and_then(Option::as_ref)
{
Some(facts) => match facts
.get(&account.id)
.filter(|f| f.credential_revision.get() == account.credential_revision.get())
{
Some(facts) => match facts.models.get(&upstream) {
Some(quota) => (
Some(true),
quota.and_then(|quota| {
model_quota_observation(account, runtime, quota, now)
}),
),
None => (Some(false), None),
},
None => (None, None),
},
None => (
provider
.as_ref()
.and_then(|provider| provider.peer_model_eligible(account, &upstream)),
observation,
),
};
if eligible == Some(false) {
continue;
}
@@ -205,6 +245,32 @@ struct ModelObservation {
expires_at: DateTime<Utc>,
}
fn model_quota_observation(
account: &AccountRecord,
runtime: &AccountRuntimeSnapshot,
quota: crate::ports::provider::ProviderPeerModelQuota,
now: DateTime<Utc>,
) -> Option<ModelObservation> {
if !matches!(
status(account, runtime, now),
AccountStatus::Normal | AccountStatus::QuotaExhausted
) {
return None;
}
let state = match quota.state.access() {
QuotaAccessState::Allowed => PeerModelState::Available,
QuotaAccessState::Exhausted => PeerModelState::Exhausted,
QuotaAccessState::Unknown => return None,
};
let observed_at = DateTime::<Utc>::from(quota.state.observed_at()?);
let expires_at = DateTime::<Utc>::from(quota.valid_until).min(now + TimeDelta::minutes(5));
(observed_at <= now && expires_at > now).then_some(ModelObservation {
state,
observed_at,
expires_at,
})
}
#[derive(Default)]
struct ModelObservations {
incomplete: bool,
@@ -53,6 +53,8 @@ impl PluginResourceAccess for DefaultPluginResourceAccess {
resource_key,
NewAccountGroup {
allow_image_generation: command.allow_image_generation,
allow_subagents: command.allow_subagents,
model_access: command.model_access,
id,
name: command.name,
description: command.description,
@@ -81,7 +81,7 @@ pub(crate) struct DefaultSettingsService {
}
impl DefaultSettingsService {
fn profile_provider(
fn registered_provider(
&self,
provider: &str,
) -> Result<std::sync::Arc<dyn crate::ports::provider::ProviderAdmin>, AdminError> {
@@ -89,7 +89,7 @@ impl DefaultSettingsService {
.map_err(|_| AdminError::invalid("服务商无效"))?;
self.providers
.require(&kind)
.map_err(|error| super::map_provider_error(error, "client profile"))
.map_err(|error| super::map_provider_error(error, "provider registry"))
}
#[must_use]
@@ -116,10 +116,10 @@ fn validate_settings(command: &ReplaceRuntimeSettings) -> Result<(), AdminError>
.map(|(requested, upstream)| (requested.as_str(), upstream.as_str())),
)
.map_err(|_| AdminError::invalid("运行时设置不满足约束"))?;
command
.values
.validate()
.map_err(|_| AdminError::invalid("运行时设置不满足约束"))
command.values.validate().map_err(|field| match field {
"openai_request_country" => AdminError::invalid("请求国家必须是两位大写 ASCII 字母"),
_ => AdminError::invalid("运行时设置不满足约束"),
})
}
#[async_trait]
@@ -128,7 +128,7 @@ impl SettingsService for DefaultSettingsService {
&self,
request: gateway_core::settings::privacy::PrivacyPreviewRequest,
) -> Result<gateway_core::settings::privacy::PrivacyPreviewResult, AdminError> {
self.profile_provider("openai")?
self.registered_provider("openai")?
.preview_privacy_policy(request)
.map_err(|error| {
AdminError::invalid(format!(
@@ -142,7 +142,9 @@ impl SettingsService for DefaultSettingsService {
async fn preview_pricing_sync(
&self,
) -> Result<crate::model::pricing::PricingSyncPreview, AdminError> {
self.pricing_source.fetch().await
let scope = self.providers.pricing_source_scope();
let prices = self.pricing_source.fetch(&scope).await?;
Ok(scope.project(prices))
}
async fn sync_pricing(
@@ -172,7 +174,7 @@ impl SettingsService for DefaultSettingsService {
{
return Err(AdminError::invalid("该服务商不支持价目管理"));
}
let mut current = self.pricing_source.fetch().await?;
let mut current = self.preview_pricing_sync().await?;
if current != command.preview {
return Err(AdminError::invalid(
"models.dev 价目已变化,请重新预览后确认",
@@ -217,6 +219,7 @@ impl SettingsService for DefaultSettingsService {
.await
.map_err(|error| map_store_error(error, "model pricing"))?;
Ok(crate::model::pricing::PricingCatalog {
supported_bands: self.providers.supported_pricing_bands(),
defaults: self.providers.pricing_catalog(),
overrides: stored.overrides,
synced: stored.synced,
@@ -231,8 +234,10 @@ impl SettingsService for DefaultSettingsService {
) -> Result<(), AdminError> {
use crate::model::pricing::PricingChange;
let catalog = self.pricing().await?;
if !catalog.defaults.contains_key(&command.provider)
|| command.models.is_empty()
let Some(supported) = catalog.supported_bands.get(&command.provider) else {
return Err(AdminError::invalid("服务商、模型 ID 或批量数量不合法"));
};
if command.models.is_empty()
|| command.models.len() > 500
|| command.models.iter().any(|model| {
model.is_empty()
@@ -259,15 +264,8 @@ impl SettingsService for DefaultSettingsService {
match &command.change {
PricingChange::Replace(pricing) => {
pricing.validate().map_err(AdminError::invalid)?;
if command.provider == "xai"
&& pricing.bands.keys().any(|band| {
matches!(
band.as_str(),
"image" | "flex" | "long_flex" | "ultrafast" | "long_ultrafast"
)
})
{
return Err(AdminError::invalid("xAI 不支持此价格档位"));
if pricing.bands.keys().any(|band| !supported.contains(band)) {
return Err(AdminError::invalid("当前平台不支持此价格档位"));
}
if !pricing.bands.contains_key("standard")
&& command
@@ -307,7 +305,7 @@ impl SettingsService for DefaultSettingsService {
&self,
provider: &str,
) -> Result<gateway_core::account::OpaqueProviderData, AdminError> {
let profile_provider = self.profile_provider(provider)?;
let profile_provider = self.registered_provider(provider)?;
let mut options = profile_provider
.client_profile_options()
.map_err(|error| super::map_provider_error(error, "client profile"))?
@@ -331,7 +329,7 @@ impl SettingsService for DefaultSettingsService {
provider: &str,
configuration: Option<&gateway_core::account::OpaqueProviderData>,
) -> Result<gateway_core::account::OpaqueProviderData, AdminError> {
let profile_provider = self.profile_provider(provider)?;
let profile_provider = self.registered_provider(provider)?;
let independent = configuration.filter(|key| {
gateway_core::settings::request_profiles::inherited_fields(key).is_none()
});
@@ -378,7 +376,7 @@ impl SettingsService for DefaultSettingsService {
) -> Result<RuntimeSettings, AdminError> {
validate_settings(&command)?;
if command.values.codex_privacy_policy != Default::default() {
self.profile_provider("openai")?
self.registered_provider("openai")?
.compile_privacy_policy(&command.values.codex_privacy_policy)
.map_err(|error| {
AdminError::invalid(format!(
@@ -388,37 +386,30 @@ impl SettingsService for DefaultSettingsService {
))
})?;
}
if command
.request_profile_updates
.values()
.any(Option::is_some)
{
if !command.request_profile_updates.is_empty() {
let current = self
.store
.load_runtime_settings()
.await
.map_err(|error| map_store_error(error, "runtime settings"))?;
command.request_profile_updates.retain(|provider, update| {
!update
.as_ref()
.is_some_and(|profile| current.request_profiles.get(provider) == Some(profile))
});
}
if command
.request_profile_updates
.values()
.any(Option::is_some)
{
let providers = &self.providers;
for (provider, profile) in &command.request_profile_updates {
let Some(profile) = profile else {
continue;
};
providers
.require(provider)
.and_then(|provider| provider.preview_client_profile(profile))
for (kind, update) in &command.request_profile_updates {
let provider = self
.providers
.require(kind)
.map_err(|error| super::map_provider_error(error, "client profile"))?;
if let Some(profile) = update
&& current.request_profiles.get(kind) != Some(profile)
{
provider
.preview_client_profile(profile)
.map_err(|error| super::map_provider_error(error, "client profile"))?;
}
}
command.request_profile_updates.retain(|kind, update| {
update
.as_ref()
.is_none_or(|profile| current.request_profiles.get(kind) != Some(profile))
});
}
let settings = self
.store
@@ -0,0 +1,8 @@
//! 系统管理用例与更新前置检查的模块门面
mod preflight;
mod service;
pub(crate) use preflight::PluginSystemUpdatePreflight;
pub(crate) use service::DefaultSystemService;
pub use service::SystemService;
@@ -19,7 +19,7 @@ use crate::{
},
};
use super::plugins::official::{update_compatibility, validate_update_release};
use super::super::plugins::official::{update_compatibility, validate_update_release};
/// 只读取启用实例及其固定包体,检查目标宿主合同;不准备或执行插件
pub(crate) struct PluginSystemUpdatePreflight {
@@ -2,7 +2,7 @@
use std::sync::Arc;
use super::system_preflight::{ConfirmedPluginRestart, PluginSystemUpdatePreflight};
use super::preflight::{ConfirmedPluginRestart, PluginSystemUpdatePreflight};
use crate::model::{MutationContext, system::SystemRestartPlan};
use async_trait::async_trait;
@@ -95,6 +95,7 @@ pub(crate) struct FakeBackupRepository {
audits: Mutex<Vec<AdminAuditEvent>>,
settings: Mutex<BackupSettings>,
settings_unavailable: AtomicBool,
rotate_before_verification: bool,
records: Mutex<Vec<BackupRecord>>,
}
@@ -104,10 +105,16 @@ impl FakeBackupRepository {
settings: Mutex::new(settings),
audits: Mutex::new(Vec::new()),
settings_unavailable: AtomicBool::new(false),
rotate_before_verification: false,
records: Mutex::new(Vec::new()),
}
}
pub(crate) fn rotating_before_verification(mut self) -> Self {
self.rotate_before_verification = true;
self
}
pub(crate) fn audit_events(&self) -> Vec<AdminAuditEvent> {
self.audits.lock().expect("audits").clone()
}
@@ -206,6 +213,10 @@ impl BackupRepository for FakeBackupRepository {
at: DateTime<Utc>,
) -> AdminStoreResult<bool> {
let mut settings = self.settings.lock().expect("settings");
if self.rotate_before_verification {
settings.storage_revision += 1;
settings.last_verified_at = None;
}
if settings.storage_revision != storage_revision {
return Ok(false);
}
@@ -213,6 +213,7 @@ async fn retention_cleans_expired_scheduled_backups() {
repository
.update_schedule_settings(
UpdateBackupScheduleCommand {
storage_revision: 1,
schedule_enabled: false,
cron_expression: "0 2 * * *".to_owned(),
@@ -0,0 +1,121 @@
//! 跨模块行为合同测试
use super::*;
#[test]
fn status_transition_accepts_every_legal_edge() {
let transitions = [
(BackupStatus::Queued, BackupStatus::Dumping),
(BackupStatus::Queued, BackupStatus::Failed),
(BackupStatus::Dumping, BackupStatus::Uploading),
(BackupStatus::Dumping, BackupStatus::Failed),
(BackupStatus::Uploading, BackupStatus::Completed),
(BackupStatus::Uploading, BackupStatus::Failed),
(BackupStatus::Completed, BackupStatus::Deleting),
(BackupStatus::Failed, BackupStatus::Deleting),
];
assert!(
transitions
.into_iter()
.all(|(from, to)| { BackupStatusTransition::try_new(from, to).is_some() })
);
}
#[test]
fn status_transition_rejects_invalid_edges() {
let transitions = [
(BackupStatus::Queued, BackupStatus::Completed),
(BackupStatus::Completed, BackupStatus::Dumping),
(BackupStatus::Deleting, BackupStatus::Failed),
(BackupStatus::Deleting, BackupStatus::Completed),
];
assert!(
transitions
.into_iter()
.all(|(from, to)| { BackupStatusTransition::try_new(from, to).is_none() })
);
}
#[test]
fn status_classification() {
assert!(BackupStatus::Queued.is_active());
assert!(BackupStatus::Uploading.is_active());
assert!(!BackupStatus::Completed.is_active());
assert!(BackupStatus::Completed.can_be_deleted());
assert!(BackupStatus::Failed.can_be_deleted());
assert!(!BackupStatus::Queued.can_be_deleted());
}
#[test]
fn object_key_shape() {
let at = Utc.with_ymd_and_hms(2026, 8, 1, 12, 30, 0).unwrap();
let key = build_object_key("production/backups", "backup_abc", at).unwrap();
assert_eq!(
key,
"production/backups/2026/08/01/codex-proxy-rs_20260801_123000_abc.sql.gz"
);
}
#[test]
fn object_key_rejects_dangerous_prefixes() {
let at = Utc::now();
assert!(build_object_key("/leading", "backup_x", at).is_err());
assert!(build_object_key("a/../b", "backup_x", at).is_err());
assert!(build_object_key("a\\b", "backup_x", at).is_err());
assert!(build_object_key("a\u{0001}b", "backup_x", at).is_err());
assert!(build_object_key("", "backup_x", at).is_err());
assert!(build_object_key("trailing//", "backup_x", at).is_ok());
}
#[test]
fn trigger_and_status_roundtrip() {
for status in [
BackupStatus::Queued,
BackupStatus::Dumping,
BackupStatus::Uploading,
BackupStatus::Completed,
BackupStatus::Failed,
BackupStatus::Deleting,
] {
assert_eq!(BackupStatus::parse(status.as_str()), Some(status));
}
assert_eq!(
BackupTriggerKind::parse("manual"),
Some(BackupTriggerKind::Manual)
);
assert_eq!(
BackupTriggerKind::parse("scheduled"),
Some(BackupTriggerKind::Scheduled)
);
assert_eq!(BackupTriggerKind::parse("unknown"), None);
assert_eq!(BackupStatus::parse("skipped"), None);
assert_eq!(BackupStatus::parse("deleted"), None);
assert_eq!(BackupStatus::parse("unknown"), None);
}
#[test]
fn config_from_settings_redacts_secret_in_debug() {
let mut settings = BackupSettings {
storage_revision: 3,
endpoint: Some("https://example.com".to_owned()),
region: Some("auto".to_owned()),
bucket: Some("b".to_owned()),
access_key_id: Some("ak".to_owned()),
secret_access_key: Some(SecretString::from("sk-secret")),
prefix: Some("p".to_owned()),
force_path_style: false,
schedule_enabled: false,
cron_expression: None,
schedule_timezone: None,
retention_days: 0,
retention_count: 0,
next_run_at: None,
last_verified_at: None,
updated_at: Utc::now(),
};
assert!(!format!("{:?}", settings).contains("sk-secret"));
let config = BackupStorageConfig::from_settings(&settings).unwrap();
assert!(!format!("{config:?}").contains("sk-secret"));
settings.endpoint = None;
assert!(BackupStorageConfig::from_settings(&settings).is_none());
}
@@ -1,5 +1,6 @@
//! 备份领域模型(model/backup)的纯逻辑测试
mod contract;
use chrono::{TimeZone as _, Utc};
use secrecy::SecretString;
@@ -7,121 +8,3 @@ use gateway_admin::model::backup::{
BackupSettings, BackupStatus, BackupStatusTransition, BackupStorageConfig, BackupTriggerKind,
build_object_key,
};
#[test]
fn status_transition_accepts_every_legal_edge() {
let transitions = [
(BackupStatus::Queued, BackupStatus::Dumping),
(BackupStatus::Queued, BackupStatus::Failed),
(BackupStatus::Dumping, BackupStatus::Uploading),
(BackupStatus::Dumping, BackupStatus::Failed),
(BackupStatus::Uploading, BackupStatus::Completed),
(BackupStatus::Uploading, BackupStatus::Failed),
(BackupStatus::Completed, BackupStatus::Deleting),
(BackupStatus::Failed, BackupStatus::Deleting),
];
assert!(
transitions
.into_iter()
.all(|(from, to)| { BackupStatusTransition::try_new(from, to).is_some() })
);
}
#[test]
fn status_transition_rejects_invalid_edges() {
let transitions = [
(BackupStatus::Queued, BackupStatus::Completed),
(BackupStatus::Completed, BackupStatus::Dumping),
(BackupStatus::Deleting, BackupStatus::Failed),
(BackupStatus::Deleting, BackupStatus::Completed),
];
assert!(
transitions
.into_iter()
.all(|(from, to)| { BackupStatusTransition::try_new(from, to).is_none() })
);
}
#[test]
fn status_classification() {
assert!(BackupStatus::Queued.is_active());
assert!(BackupStatus::Uploading.is_active());
assert!(!BackupStatus::Completed.is_active());
assert!(BackupStatus::Completed.can_be_deleted());
assert!(BackupStatus::Failed.can_be_deleted());
assert!(!BackupStatus::Queued.can_be_deleted());
}
#[test]
fn object_key_shape() {
let at = Utc.with_ymd_and_hms(2026, 8, 1, 12, 30, 0).unwrap();
let key = build_object_key("production/backups", "backup_abc", at).unwrap();
assert_eq!(
key,
"production/backups/2026/08/01/codex-proxy-rs_20260801_123000_abc.sql.gz"
);
}
#[test]
fn object_key_rejects_dangerous_prefixes() {
let at = Utc::now();
assert!(build_object_key("/leading", "backup_x", at).is_err());
assert!(build_object_key("a/../b", "backup_x", at).is_err());
assert!(build_object_key("a\\b", "backup_x", at).is_err());
assert!(build_object_key("a\u{0001}b", "backup_x", at).is_err());
assert!(build_object_key("", "backup_x", at).is_err());
assert!(build_object_key("trailing//", "backup_x", at).is_ok());
}
#[test]
fn trigger_and_status_roundtrip() {
for status in [
BackupStatus::Queued,
BackupStatus::Dumping,
BackupStatus::Uploading,
BackupStatus::Completed,
BackupStatus::Failed,
BackupStatus::Deleting,
] {
assert_eq!(BackupStatus::parse(status.as_str()), Some(status));
}
assert_eq!(
BackupTriggerKind::parse("manual"),
Some(BackupTriggerKind::Manual)
);
assert_eq!(
BackupTriggerKind::parse("scheduled"),
Some(BackupTriggerKind::Scheduled)
);
assert_eq!(BackupTriggerKind::parse("unknown"), None);
assert_eq!(BackupStatus::parse("skipped"), None);
assert_eq!(BackupStatus::parse("deleted"), None);
assert_eq!(BackupStatus::parse("unknown"), None);
}
#[test]
fn config_from_settings_redacts_secret_in_debug() {
let mut settings = BackupSettings {
storage_revision: 3,
endpoint: Some("https://example.com".to_owned()),
region: Some("auto".to_owned()),
bucket: Some("b".to_owned()),
access_key_id: Some("ak".to_owned()),
secret_access_key: Some(SecretString::from("sk-secret")),
prefix: Some("p".to_owned()),
force_path_style: false,
schedule_enabled: false,
cron_expression: None,
schedule_timezone: None,
retention_days: 0,
retention_count: 0,
next_run_at: None,
last_verified_at: None,
updated_at: Utc::now(),
};
assert!(!format!("{:?}", settings).contains("sk-secret"));
let config = BackupStorageConfig::from_settings(&settings).unwrap();
assert!(!format!("{config:?}").contains("sk-secret"));
settings.endpoint = None;
assert!(BackupStorageConfig::from_settings(&settings).is_none());
}
@@ -8,5 +8,4 @@ mod observability;
mod plugins;
mod provider_credentials;
mod quota_forecast;
mod quota_forecast_sampling;
mod retention;
@@ -0,0 +1,93 @@
//! 跨模块行为合同测试
use super::*;
#[test]
fn metadata_ignores_unknown_fields_at_each_object_boundary() {
let mut original = metadata();
original["icon"] = json!({"light": "light.svg", "dark": "dark.svg"});
original["stateNamespaces"] = json!([{
"namespace": "cache", "schemaVersion": 1, "schemaSha256": "b".repeat(64),
"schema": {}, "maximumRecords": 10, "maximumBytes": 1024,
"maximumValueBytes": 128, "migratesFrom": []
}]);
let expected: PluginArtifactMetadata = serde_json::from_value(original.clone()).unwrap();
for path in ["", "/contributes/middleware", "/icon", "/stateNamespaces/0"] {
let mut extended = original.clone();
extended.pointer_mut(path).unwrap()["futureField"] = json!({"enabled": true});
assert_eq!(
serde_json::from_value::<PluginArtifactMetadata>(extended).unwrap(),
expected,
"unknown field at {path}"
);
}
}
#[test]
fn metadata_defaults_only_optional_fields() {
let original = metadata();
let expected: PluginArtifactMetadata = serde_json::from_value(original.clone()).unwrap();
let mut older = original;
for field in ["configurationSchema", "secretFields", "stateNamespaces"] {
older.as_object_mut().unwrap().remove(field);
}
for field in ["stages", "inputFormats", "outputFormats"] {
older["contributes"]["middleware"]
.as_object_mut()
.unwrap()
.remove(field);
}
assert_eq!(
serde_json::from_value::<PluginArtifactMetadata>(older).unwrap(),
expected
);
}
#[test]
fn metadata_still_requires_identity_and_execution_facts() {
for field in [
"pluginId",
"version",
"name",
"publisher",
"sha256",
"platforms",
"contributes",
] {
let mut incomplete = metadata();
incomplete.as_object_mut().unwrap().remove(field);
assert!(
serde_json::from_value::<PluginArtifactMetadata>(incomplete).is_err(),
"missing {field}"
);
}
for field in ["id", "version"] {
let mut incomplete = metadata();
incomplete["contributes"]["middleware"]
.as_object_mut()
.unwrap()
.remove(field);
assert!(
serde_json::from_value::<PluginArtifactMetadata>(incomplete).is_err(),
"missing contribution {field}"
);
}
}
#[test]
fn metadata_still_rejects_wrong_types_in_known_fields() {
for (path, value) in [
("/version", json!(1)),
("/secretFields", json!(false)),
("/stateNamespaces", json!({})),
("/contributes/middleware/version", json!("3")),
("/contributes/middleware/stages", json!("http")),
] {
let mut invalid = metadata();
*invalid.pointer_mut(path).unwrap() = value;
assert!(
serde_json::from_value::<PluginArtifactMetadata>(invalid).is_err(),
"wrong type at {path}"
);
}
}
@@ -1,5 +1,6 @@
//! 验证插件元数据兼容新增字段,同时保留已知字段的类型约束
mod contract;
use gateway_admin::model::plugins::PluginArtifactMetadata;
use serde_json::{Value, json};
@@ -15,93 +16,3 @@ fn metadata() -> Value {
"configurationSchema": {}, "secretFields": [], "stateNamespaces": []
})
}
#[test]
fn metadata_ignores_unknown_fields_at_each_object_boundary() {
let mut original = metadata();
original["icon"] = json!({"light": "light.svg", "dark": "dark.svg"});
original["stateNamespaces"] = json!([{
"namespace": "cache", "schemaVersion": 1, "schemaSha256": "b".repeat(64),
"schema": {}, "maximumRecords": 10, "maximumBytes": 1024,
"maximumValueBytes": 128, "migratesFrom": []
}]);
let expected: PluginArtifactMetadata = serde_json::from_value(original.clone()).unwrap();
for path in ["", "/contributes/middleware", "/icon", "/stateNamespaces/0"] {
let mut extended = original.clone();
extended.pointer_mut(path).unwrap()["futureField"] = json!({"enabled": true});
assert_eq!(
serde_json::from_value::<PluginArtifactMetadata>(extended).unwrap(),
expected,
"unknown field at {path}"
);
}
}
#[test]
fn metadata_defaults_only_optional_fields() {
let original = metadata();
let expected: PluginArtifactMetadata = serde_json::from_value(original.clone()).unwrap();
let mut older = original;
for field in ["configurationSchema", "secretFields", "stateNamespaces"] {
older.as_object_mut().unwrap().remove(field);
}
for field in ["stages", "inputFormats", "outputFormats"] {
older["contributes"]["middleware"]
.as_object_mut()
.unwrap()
.remove(field);
}
assert_eq!(
serde_json::from_value::<PluginArtifactMetadata>(older).unwrap(),
expected
);
}
#[test]
fn metadata_still_requires_identity_and_execution_facts() {
for field in [
"pluginId",
"version",
"name",
"publisher",
"sha256",
"platforms",
"contributes",
] {
let mut incomplete = metadata();
incomplete.as_object_mut().unwrap().remove(field);
assert!(
serde_json::from_value::<PluginArtifactMetadata>(incomplete).is_err(),
"missing {field}"
);
}
for field in ["id", "version"] {
let mut incomplete = metadata();
incomplete["contributes"]["middleware"]
.as_object_mut()
.unwrap()
.remove(field);
assert!(
serde_json::from_value::<PluginArtifactMetadata>(incomplete).is_err(),
"missing contribution {field}"
);
}
}
#[test]
fn metadata_still_rejects_wrong_types_in_known_fields() {
for (path, value) in [
("/version", json!(1)),
("/secretFields", json!(false)),
("/stateNamespaces", json!({})),
("/contributes/middleware/version", json!("3")),
("/contributes/middleware/stages", json!("http")),
] {
let mut invalid = metadata();
*invalid.pointer_mut(path).unwrap() = value;
assert!(
serde_json::from_value::<PluginArtifactMetadata>(invalid).is_err(),
"wrong type at {path}"
);
}
}
@@ -335,3 +335,42 @@ fn pending_mutation_v1_should_keep_existing_storage_fields_and_reject_invalid_do
document["schema_version"] = json!(2);
assert!(PendingAuthorizationMutation::from_storage_v1(document).is_err());
}
#[test]
fn manual_key_alignment_only_accepts_the_current_account_wide_day_or_week() {
use chrono::{Duration, Utc};
use gateway_admin::model::{
client_keys::{ClientKeyBudgetReference, ClientKeyBudgetWindowPeriod},
upstream_info::UpstreamQuotaWindow,
};
let now = Utc::now();
for (seconds, period) in [
(86_400, ClientKeyBudgetWindowPeriod::Daily),
(604_800, ClientKeyBudgetWindowPeriod::Weekly),
] {
let mut window = usage_window("account", "quota", seconds);
let end = now + Duration::hours(2);
window.reset_at = Some(end);
let reference = ClientKeyBudgetReference::from_current_window(window.clone(), now).unwrap();
let selected = reference.period;
let bounds = reference.bounds;
assert_eq!(selected, period);
assert_eq!(bounds.starts_at, end - Duration::seconds(seconds as i64));
assert_eq!(bounds.ends_at, end);
assert!(bounds.resume_calendar);
assert!(ClientKeyBudgetReference::from_current_window(window.clone(), end).is_none());
window.upstream = Some(UpstreamQuotaWindow {
account_id: None,
observed_at: Some(now),
stale: true,
amount: None,
});
assert!(ClientKeyBudgetReference::from_current_window(window.clone(), now).is_none());
window.upstream = None;
window.local_usage_attribution = QuotaLocalUsageAttribution::Unavailable;
assert!(ClientKeyBudgetReference::from_current_window(window.clone(), now).is_none());
}
let mut short = usage_window("primary", "short", 18_000);
short.reset_at = Some(now + Duration::hours(1));
assert!(ClientKeyBudgetReference::from_current_window(short, now).is_none());
}
@@ -0,0 +1,4 @@
//! 额度预测投影与采样测试
mod projection;
mod sampling;
@@ -6,7 +6,7 @@ use gateway_admin::model::{
observability::CostCoverage,
provider_credentials::{ProviderQuota, ProviderQuotaWindow, QuotaLocalUsageAttribution},
quota_forecast::{AccountQuotaForecast, account_quota_forecasts},
quota_forecast_sampling::{QuotaForecastMethod, QuotaForecastSample, QuotaForecastUsage},
quota_forecast::{QuotaForecastMethod, QuotaForecastSample, QuotaForecastUsage},
};
fn now() -> DateTime<Utc> {
@@ -1,7 +1,7 @@
//! 验证额度预测采样的去重、回退处理与近期窗口选择
use chrono::{DateTime, Duration, Utc};
use gateway_admin::model::quota_forecast_sampling::{
use gateway_admin::model::quota_forecast::{
QuotaForecastMethod, QuotaForecastPoint, QuotaForecastSample, QuotaForecastUsage,
select_forecast_sample,
};
@@ -12,7 +12,9 @@ fn time(minutes: i64) -> DateTime<Utc> {
fn point(minute: i64, percent: f64, tokens: u64) -> QuotaForecastPoint {
QuotaForecastPoint {
started_at: time(minute) - Duration::seconds(1),
observed_at: time(minute),
reset_at: time(7 * 24 * 60),
used_percent: percent,
usage: QuotaForecastUsage {
request_count: minute as u64,
@@ -188,7 +190,41 @@ fn repeated_same_window_recoveries_preserve_recorded_cycle_usage() {
}
#[test]
fn changed_window_restarts_cycle_totals_at_first_matching_observation() {
fn an_expired_deadline_alone_cannot_cut_totals_or_anchor_remaining_usage() {
let mut older = point(1, 15.0, 100);
older.reset_at = time(3);
let mut previous = point(2, 20.0, 200);
previous.reset_at = time(3) + Duration::seconds(4);
let first = point(4, 25.0, 700);
let sample = select(vec![older, previous, first], point(6, 35.0, 900));
assert_eq!(sample.cycle_usage.tokens, 900);
assert_eq!(sample.baseline_percent, 25.0);
assert_eq!(sample.usage.tokens, 200);
}
#[test]
fn copied_concurrent_or_contradictory_readings_cannot_confirm_a_recovery() {
let mut older = point(1, 75.0, 100);
older.reset_at = time(3);
let mut previous = point(2, 85.0, 200);
previous.reset_at = time(3);
let first = point(4, 5.0, 300);
let current = point(6, 40.0, 900);
let mut overlapping = point(5, 20.0, 400);
overlapping.started_at = first.started_at;
for extra in [None, Some(overlapping), Some(current.clone())] {
let mut points = vec![older.clone(), previous.clone(), first.clone()];
points.extend(extra);
let sample = select(points, current.clone());
assert_eq!(sample.cycle_usage.tokens, 900);
assert!(sample.discontinuous);
}
let sample = select(vec![older, previous, first, point(5, 86.0, 400)], current);
assert_eq!(sample.cycle_usage.tokens, 900);
}
#[test]
fn changed_plan_restarts_cycle_totals_at_first_matching_observation() {
let sample = select_forecast_sample(
"week".to_owned(),
time(0),
@@ -344,6 +344,8 @@ fn group_record() -> AccountGroupRecord {
let now = Utc::now();
AccountGroupRecord {
allow_image_generation: true,
allow_subagents: true,
model_access: Default::default(),
fast_mode: FastMode::Default,
id: group_id(),
name: "Primary".to_owned(),
@@ -420,6 +422,8 @@ async fn invalid_group_fields_are_rejected_before_store_mutations() {
&context,
CreateAccountGroup {
allow_image_generation: true,
allow_subagents: true,
model_access: Default::default(),
fast_mode: FastMode::Default,
name: " invalid".to_owned(),
description: None,
@@ -434,6 +438,8 @@ async fn invalid_group_fields_are_rejected_before_store_mutations() {
&context,
UpdateAccountGroup {
allow_image_generation: None,
allow_subagents: None,
model_access: None,
fast_mode: None,
id: record.id,
name: "valid".to_owned(),
@@ -52,7 +52,7 @@ use gateway_admin::{
ProviderQuotaWindow, ProviderResetCreditResult, ProviderSubscription,
QuotaLocalUsageAttribution,
},
quota_forecast_sampling::{QuotaForecastHistory, QuotaForecastUsage},
quota_forecast::{QuotaForecastHistory, QuotaForecastUsage},
settings::{
AdminApiKey, AdminApiKeyMutation, ReplaceRuntimeSettings, RotationStrategy,
RuntimeSettings,
@@ -266,6 +266,7 @@ impl FakeProviderAdmin {
plan_type: account.plan_type.clone(),
preserve_profile: false,
preserve_credential_state: false,
preserve_access_token_expiry: false,
provider_material: document(),
has_refresh_token: account.has_refresh_token,
access_token_expires_at: account
@@ -560,10 +561,10 @@ impl ProviderAdmin for FakeProviderAdmin {
&self,
document: &ProviderDocument,
_: &ProviderQuotaWindow,
) -> Option<gateway_admin::model::quota_forecast_sampling::QuotaForecastObservation> {
) -> Option<gateway_admin::model::quota_forecast::QuotaForecastObservation> {
let fields = document.expose_to_provider().expose_to_provider();
Some(
gateway_admin::model::quota_forecast_sampling::QuotaForecastObservation {
gateway_admin::model::quota_forecast::QuotaForecastObservation {
used_percent: fields.get("percent")?.as_f64()?,
reset_at: fields.get("reset")?.as_str()?.parse().ok()?,
plan_type: fields.get("plan")?.as_str().map(str::to_owned),
@@ -616,6 +617,7 @@ pub(super) struct FakeAccountStore {
audit_requests: Mutex<Vec<String>>,
import_settings: Mutex<Vec<Option<gateway_admin::model::accounts::AccountImportSettings>>>,
quota_window_usage: Mutex<Vec<AccountUsageWindowResult>>,
rolling_usage: Mutex<Vec<AccountUsage>>,
quota_window_queries: Mutex<Vec<AccountUsageWindowQuery>>,
quota_forecast_history: Mutex<QuotaForecastHistory>,
update_commands: Mutex<Vec<UpdateAccount>>,
@@ -639,6 +641,7 @@ impl FakeAccountStore {
audit_requests: Mutex::new(Vec::new()),
import_settings: Mutex::new(Vec::new()),
quota_window_usage: Mutex::new(Vec::new()),
rolling_usage: Mutex::new(Vec::new()),
quota_window_queries: Mutex::new(Vec::new()),
quota_forecast_history: Mutex::new(QuotaForecastHistory::default()),
update_commands: Mutex::new(Vec::new()),
@@ -827,7 +830,7 @@ impl AccountStore for FakeAccountStore {
_: TimeRange,
_: &[String],
) -> AdminStoreResult<Vec<AccountUsage>> {
Ok(Vec::new())
Ok(self.rolling_usage.lock().unwrap().clone())
}
async fn load_account_usage_by_windows(
@@ -1173,6 +1176,8 @@ impl SettingsStore for StaticSettingsStore {
rotation_strategy: RotationStrategy::Smart,
updated_at: Utc::now(),
values: gateway_admin::model::settings::RuntimeSettingsValues {
openai_oauth_guardian_review_model: false,
openai_request_country: Default::default(),
codex_privacy_policy: Default::default(),
request_location_enabled: false,
request_location: Default::default(),
@@ -1445,9 +1450,31 @@ async fn connection_test_should_preserve_disabled_account_status() {
));
}
#[tokio::test]
async fn unsupported_account_export_stops_before_loading_credentials() {
let calls = events();
let provider = FakeProviderAdmin::new("fixture", calls.clone());
let store = FakeAccountStore::new("fixture", calls.clone());
let id = ProviderAccountId::new(store.accounts.lock().unwrap()[0].id.clone()).unwrap();
let services = accounts_service(provider, store).await;
let error = services
.accounts()
.export(&context("export-unsupported"), vec![id])
.await
.unwrap_err();
assert_eq!(error.kind(), gateway_admin::model::AdminErrorKind::Invalid);
assert!(
!calls
.lock()
.unwrap()
.contains(&"store.load_credentials_for_export")
);
}
#[tokio::test]
async fn accounts_export_should_pass_store_loaded_timestamps_and_material_to_provider() {
let provider = FakeProviderAdmin::new("openai", events());
provider.capabilities.lock().unwrap().credential_export = true;
let store = FakeAccountStore::new("openai", events());
let expected = store.accounts.lock().expect("accounts")[0].clone();
accounts_service(provider.clone(), store)
@@ -2514,7 +2541,7 @@ async fn quota_forecast_only_queries_the_two_selected_source_windows() {
#[tokio::test]
async fn quota_forecast_same_window_reversal_keeps_recorded_usage_in_the_report() {
use gateway_admin::model::quota_forecast_sampling::QuotaForecastHistoryPoint;
use gateway_admin::model::quota_forecast::QuotaForecastHistoryPoint;
for (percents, tokens, expected_tokens, expected_usd) in [
([32.0, 30.0, 35.0], [100, 120, 140], 400, 0.4),
@@ -2573,7 +2600,9 @@ async fn quota_forecast_same_window_reversal_keeps_recorded_usage_in_the_report(
usage: usage(index as u64 + 1, tokens),
provider_observation: ProviderDocument::new(OpaqueProviderData::new(
serde_json::json!({
"percent": percent, "reset": reset.to_rfc3339(), "plan": "pro",
"percent": percent,
"reset": (reset + TimeDelta::seconds(17 * index as i64)).to_rfc3339(),
"plan": "pro",
})
.as_object()
.unwrap()
@@ -2602,14 +2631,14 @@ async fn quota_forecast_same_window_reversal_keeps_recorded_usage_in_the_report(
}
#[tokio::test]
async fn quota_forecast_mid_cycle_sampling_accepts_small_reset_jitter_but_not_a_changed_bucket() {
use gateway_admin::model::quota_forecast_sampling::QuotaForecastHistoryPoint;
async fn quota_forecast_keeps_cycle_totals_through_reset_jitter_and_restarts_after_a_reset() {
use gateway_admin::model::quota_forecast::QuotaForecastHistoryPoint;
let now = Utc::now();
let observed = now - TimeDelta::minutes(1);
let reset = now + TimeDelta::days(1);
let added = now - TimeDelta::hours(5);
let provider = FakeProviderAdmin::new("openai", events());
provider.set_quota(ProviderQuota {
let mut quota = ProviderQuota {
upstream: None,
credits: None,
plan_type: Some("pro".to_owned()),
@@ -2624,67 +2653,102 @@ async fn quota_forecast_mid_cycle_sampling_accepts_small_reset_jitter_but_not_a_
role: None,
local_usage_attribution: QuotaLocalUsageAttribution::AccountWide,
window_seconds: Some(604_800),
used_percent: Some(40.0),
used_percent: Some(65.0),
reset_at: Some(reset),
limit_reached: false,
local_usage: None,
provider_data: None,
}],
..empty_quota()
});
};
let mut account = account_record("openai");
account.created_at = added;
let store = FakeAccountStore::with_account(account, events());
let make_point = |hours, percent, tokens, delta| {
QuotaForecastHistoryPoint {
started_at: now - TimeDelta::hours(hours) - TimeDelta::seconds(10),
completed_at: now - TimeDelta::hours(hours),
usage: QuotaForecastUsage { request_count: tokens / 100, tokens, ..Default::default() },
provider_observation: ProviderDocument::new(OpaqueProviderData::new(serde_json::json!({
"percent": percent, "reset": (reset + TimeDelta::seconds(delta)).to_rfc3339(), "plan": "pro",
}).as_object().unwrap().clone())),
}
let usage = |tokens| QuotaForecastUsage {
request_count: tokens / 100,
tokens,
known_cost_count: tokens / 100,
usd: tokens as f64 / 100.0,
..Default::default()
};
let point_with_plan = |hours, percent, tokens, delta, plan: Option<&str>| {
let observation = serde_json::json!({
"percent": percent,
"reset": (reset + TimeDelta::seconds(delta)).to_rfc3339(),
"plan": plan,
});
QuotaForecastHistoryPoint {
started_at: now - TimeDelta::hours(hours) - TimeDelta::seconds(10),
completed_at: now - TimeDelta::hours(hours),
usage: usage(tokens),
provider_observation: ProviderDocument::new(OpaqueProviderData::new(
observation.as_object().unwrap().clone(),
)),
}
};
let make_point =
|hours, percent, tokens, delta| point_with_plan(hours, percent, tokens, delta, Some("pro"));
*store.quota_forecast_history.lock().unwrap() = QuotaForecastHistory {
points: vec![
make_point(3, 20.0, 1_000, 1),
make_point(2, 30.0, 1_500, -1),
make_point(4, 20.0, 20_000, 0),
make_point(3, 58.0, 62_000, 17),
make_point(2, 58.0, 62_500, 0),
],
usage: QuotaForecastUsage {
request_count: 20,
tokens: 2_000,
..Default::default()
},
usage: usage(70_600),
pending_request_count: 1,
};
let services = accounts_service(provider, store.clone()).await;
let result = services
.accounts()
.quota_forecast(&ProviderAccountId::new("acct_test").unwrap())
.await
.unwrap();
assert!(result.forecasts[0].unavailable_reason.is_none());
assert_eq!(result.forecasts[0].estimated_tokens, Some(5_000));
let services = accounts_service(provider.clone(), store.clone()).await;
let account_id = ProviderAccountId::new("acct_test").unwrap();
let read_report = async || {
services
.accounts()
.quota_forecast(&account_id)
.await
.unwrap()
};
// 回放 #759 的金额和百分比,历史与快照各自报告的到期时间偏移时仍应保留整段累计
for offset in [0, 3, 6, 7, 17, -23] {
quota.windows[0].reset_at = Some(reset + TimeDelta::seconds(offset));
provider.set_quota(quota.clone());
let report = read_report().await;
let week = &report.forecasts[0];
let source = week.source.as_ref().unwrap();
assert_eq!(source.tokens, Some(70_600));
assert_eq!(source.usd, Some(706.0));
assert_eq!(week.estimated_tokens, Some(109_956));
assert!((week.estimated_usd.unwrap() - (706.0 + 506.0 * 35.0 / 45.0)).abs() < 1e-9);
assert!(week.unavailable_reason.is_none());
}
assert_eq!(store.quota_window_queries()[0].range.start, added);
store
.quota_forecast_history
.lock()
.unwrap()
.points
.push(make_point(1, 35.0, 1_700, 3_600));
let result = services
.accounts()
.quota_forecast(&ProviderAccountId::new("acct_test").unwrap())
.await
.unwrap();
assert!(result.forecasts[0].estimated_tokens.is_none());
assert!(
result.forecasts[0]
.unavailable_reason
.unwrap()
.contains("不连续")
.push(make_point(1, 62.0, 66_000, 3_600));
let result = read_report().await;
assert_eq!(
result.forecasts[0].source.as_ref().unwrap().tokens,
Some(70_600)
);
// 新额度段已有足够观测后恢复预测,但总量不能带回重置前的累计用量
assert!(result.forecasts[0].estimated_tokens.is_some());
// 两份旧读数的截止时刻均已过去,新请求开始于旧窗口结束后
quota.windows[0].used_percent = Some(40.0);
provider.set_quota(quota.clone());
*store.quota_forecast_history.lock().unwrap() = QuotaForecastHistory {
points: vec![
make_point(4, 75.0, 1_000, -90_000),
make_point(2, 85.0, 1_500, -90_021),
],
usage: usage(2_000),
..Default::default()
};
let waiting = read_report().await;
assert_eq!(
waiting.forecasts[0].source.as_ref().unwrap().tokens,
Some(2_000)
);
assert!(waiting.forecasts[0].estimated_tokens.is_none());
let mut first = make_point(1, 5.0, 1_750, 0);
first.completed_at = now - TimeDelta::minutes(45);
first.started_at = first.completed_at - TimeDelta::seconds(10);
@@ -2697,15 +2761,42 @@ async fn quota_forecast_mid_cycle_sampling_accepts_small_reset_jitter_but_not_a_
.unwrap()
.points
.extend([first, next]);
let result = services
.accounts()
.quota_forecast(&ProviderAccountId::new("acct_test").unwrap())
.await
.unwrap();
let result = read_report().await;
let cycle = &result.forecasts[0];
assert!(cycle.unavailable_reason.is_none());
assert_eq!(cycle.source.as_ref().unwrap().tokens, Some(250));
assert_eq!(cycle.estimated_tokens, Some(679));
for (plan, expected_tokens) in [(None, 2_000), (Some("plus"), 500)] {
store.quota_forecast_history.lock().unwrap().points = vec![
make_point(4, 20.0, 1_000, 0),
point_with_plan(3, 25.0, 1_200, 0, plan),
make_point(2, 30.0, 1_500, 0),
];
let report = read_report().await;
assert_eq!(
report.forecasts[0].source.as_ref().unwrap().tokens,
Some(expected_tokens)
);
}
// 上游提前给出新的七天窗口时,直接从新起点查询,首条配对样本前的用量也留在累计中
let new_start = now - TimeDelta::hours(1);
quota.windows[0].reset_at = Some(new_start + TimeDelta::days(7));
provider.set_quota(quota);
*store.quota_forecast_history.lock().unwrap() = QuotaForecastHistory {
usage: usage(400),
..Default::default()
};
let report = read_report().await;
assert_eq!(
store.quota_window_queries().last().unwrap().range.start,
new_start
);
assert_eq!(
report.forecasts[0].source.as_ref().unwrap().tokens,
Some(400)
);
}
#[tokio::test]
@@ -2909,6 +3000,63 @@ async fn api_key_list_and_detail_should_accumulate_local_usage_without_subscript
assert_eq!(store.quota_window_queries()[0].range.start, added_at);
}
#[tokio::test]
async fn accounts_list_and_detail_keep_rolling_usage_separate_from_group_quotas() {
use gateway_admin::model::provider_credentials::AccountUsagePeriod;
let provider = FakeProviderAdmin::new("antigravity", events());
let store = FakeAccountStore::new("antigravity", events());
let expected_usage = quota_local_usage("acct_test", 139);
*store.rolling_usage.lock().unwrap() = vec![expected_usage.clone()];
let services = accounts_service(provider.clone(), store.clone()).await;
let grouped_window = ProviderQuotaWindow {
upstream: None,
key: "gemini-weekly".to_owned(),
group: "shortTerm".to_owned(),
label: "周额度".to_owned(),
limit_id: Some("gemini".to_owned()),
limit_name: Some("Gemini Models".to_owned()),
role: None,
local_usage_attribution: QuotaLocalUsageAttribution::Unavailable,
window_seconds: Some(604_800),
used_percent: Some(25.0),
reset_at: Some(Utc::now() + TimeDelta::days(6)),
limit_reached: false,
local_usage: None,
provider_data: None,
};
for windows in [Vec::new(), vec![grouped_window]] {
provider.set_quota(ProviderQuota {
windows: windows.clone(),
..empty_quota()
});
let page = services
.accounts()
.list(AccountListQuery {
page: 1,
page_size: gateway_admin::model::PageSize::new(20).unwrap(),
provider_kind: None,
group_filter: None,
search: None,
status: None,
sort: None,
})
.await
.unwrap();
let detail = services
.accounts()
.quota(&ProviderAccountId::new("acct_test").unwrap(), false)
.await
.unwrap();
for item in [&page.items[0], &detail] {
assert_eq!(item.quota.windows, windows);
assert_eq!(item.usage.as_ref(), Some(&expected_usage));
assert_eq!(item.usage_period, Some(AccountUsagePeriod::Daily));
}
assert!(store.quota_window_queries().is_empty());
}
}
#[tokio::test]
async fn accounts_list_should_attach_local_usage_to_quota_windows() {
let provider = FakeProviderAdmin::new("openai", events());
@@ -3513,6 +3661,7 @@ fn plugin_rotation_facts(account: &AccountRecord) -> PreparedCredentialRotationF
plan_type: account.plan_type.clone(),
preserve_profile: true,
preserve_credential_state: false,
preserve_access_token_expiry: false,
provider_material: document(),
has_refresh_token: account.has_refresh_token,
access_token_expires_at: account.access_token_expires_at,
@@ -115,6 +115,7 @@ async fn failed_delete_probe_does_not_refresh_verification() {
for succeeds in [false, true] {
let mut settings = configured_settings();
settings.last_verified_at = None;
let revision = settings.storage_revision;
let repository = Arc::new(FakeBackupRepository::new(settings));
let auth = Arc::new(FakeAuthStore::new());
let store = FakeObjectStore::new();
@@ -132,9 +133,15 @@ async fn failed_delete_probe_does_not_refresh_verification() {
))
.build()
.await;
let stale = services
.backups()
.test_connection(&system_context(), revision + 1)
.await
.unwrap_err();
assert_eq!(stale.kind(), gateway_admin::model::AdminErrorKind::Conflict);
let result = services
.backups()
.test_connection(&system_context())
.test_connection(&system_context(), revision)
.await
.unwrap();
assert_eq!(result.ok, succeeds);
@@ -156,3 +163,27 @@ async fn failed_delete_probe_does_not_refresh_verification() {
);
}
}
#[tokio::test]
async fn successful_probe_of_replaced_storage_reports_a_conflict() {
use gateway_admin::ports::backup::BackupRepository as _;
let settings = configured_settings();
let revision = settings.storage_revision;
let repository = Arc::new(FakeBackupRepository::new(settings).rotating_before_verification());
let services = AdminHarness::new()
.backup(BackupStorePorts::new(
repository.clone(),
Arc::new(FakeDumpPort::new()),
Arc::new(FakeObjectStore::new()),
))
.build()
.await;
let error = services
.backups()
.test_connection(&system_context(), revision)
.await
.unwrap_err();
assert_eq!(error.kind(), gateway_admin::model::AdminErrorKind::Conflict);
assert!(!repository.load_settings().await.unwrap().storage_verified());
}
@@ -35,6 +35,26 @@ struct TestClientKeyStore {
#[async_trait]
impl ClientKeyStore for TestClientKeyStore {
async fn budget_reference_accounts(
&self,
_: &gateway_core::policy::ClientApiKeyId,
_: &str,
_: &str,
) -> gateway_admin::ports::store::AdminStoreResult<
gateway_admin::model::client_keys::BudgetReferenceAccountPage,
> {
Err(unused())
}
async fn batch_update_client_keys(
&self,
_: gateway_admin::model::client_keys::BatchUpdateClientKeys,
_: gateway_admin::ports::store::BatchClientKeyProfileMerger,
_: &MutationContext,
) -> AdminStoreResult<Revision> {
Err(unused())
}
async fn client_key_budget_window(
&self,
_: &gateway_core::policy::ClientApiKeyId,
@@ -80,6 +100,15 @@ impl ClientKeyStore for TestClientKeyStore {
Ok(())
}
async fn client_key_budget(
&self,
id: &gateway_core::policy::ClientApiKeyId,
) -> AdminStoreResult<Option<gateway_core::engine::budget::ClientBudgetStatus>> {
self.get_client_key(id)
.await
.map(|key| key.map(|row| row.budget))
}
async fn get_client_key(
&self,
_: &ClientApiKeyId,
@@ -172,6 +201,34 @@ impl ClientKeyStore for TestClientKeyStore {
}
}
#[tokio::test]
async fn batch_keys_require_a_change_and_unique_targets() {
use gateway_admin::model::client_keys::BatchUpdateClientKeys;
let services = super::AdminHarness::new()
.client_keys(Arc::new(TestClientKeyStore::default()))
.build()
.await;
let id = ClientApiKeyId::new("key_a").unwrap();
for patch in [
BatchUpdateClientKeys {
ids: vec![id.clone()],
..Default::default()
},
BatchUpdateClientKeys {
ids: vec![id.clone(), id],
enabled: Some(false),
..Default::default()
},
] {
let error = services
.client_keys()
.batch_update(&mutation_context(), patch)
.await
.unwrap_err();
assert_eq!(error.kind(), AdminErrorKind::Invalid);
}
}
#[tokio::test]
async fn reset_budget_forwards_scope_and_returns_only_key_identity() {
use gateway_admin::model::client_keys::{ClientKeyBudgetPeriod, ResetClientKeyBudget};
@@ -530,3 +587,32 @@ async fn duplicate_group_ids_are_rejected_before_key_creation_or_update() {
assert_eq!(updated.kind(), AdminErrorKind::Invalid);
assert!(store.plaintexts.lock().unwrap().is_empty());
}
#[tokio::test]
async fn clearing_an_unregistered_provider_profile_is_rejected_before_writing() {
let services = super::AdminHarness::new().build().await;
let command = UpdateClientKey {
id: ClientApiKeyId::new("key_existing").unwrap(),
name: "test".to_owned(),
label: None,
group_ids: Vec::new(),
limits: RateLimits::unlimited(),
daily_limit_usd: None,
weekly_limit_usd: None,
peer_sharing: None,
request_profile_override_updates: [(
gateway_core::routing::ProviderKind::new("unregistered").unwrap(),
None,
)]
.into(),
};
assert_eq!(
services
.client_keys()
.update(&mutation_context(), command)
.await
.unwrap_err()
.kind(),
AdminErrorKind::Invalid
);
}
@@ -107,8 +107,7 @@ async fn openai_import_should_expose_only_explicit_public_errors_without_committ
] {
let events = events();
let provider = FakeProviderAdmin::new("openai", events.clone());
provider
.fail_next_with_public_message(provider_kind, "Codex PAT 验证失败,请检查令牌后重试");
provider.fail_next_with_public_message(provider_kind, "PAT 验证失败,请检查令牌");
let store = FakeAccountStore::new("openai", events.clone());
let services = service(provider, store.clone()).await;
let error = services
@@ -124,7 +123,7 @@ async fn openai_import_should_expose_only_explicit_public_errors_without_committ
.await
.expect_err("validation must fail before committing accounts");
assert_eq!(error.kind(), admin_kind);
assert_eq!(error.to_string(), "Codex PAT 验证失败,请检查令牌后重试");
assert_eq!(error.to_string(), "PAT 验证失败,请检查令牌");
assert!(!format!("{error:?}").contains("secret token"));
assert_eq!(recorded(&events), ["provider.prepare_import"]);
assert!(store.audit_requests().is_empty());
@@ -33,6 +33,8 @@ 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 {
openai_oauth_guardian_review_model: false,
openai_request_country: Default::default(),
codex_privacy_policy: Default::default(),
request_location_enabled: false,
request_location: Default::default(),
@@ -15,7 +15,6 @@ mod plugins;
mod proxies;
mod settings;
mod system;
mod system_preflight;
mod usage_data;
use std::{
@@ -560,7 +559,7 @@ impl AccountStore for UnavailableStore {
async fn load_quota_forecast_history(
&self,
_: &AccountUsageWindowQuery,
) -> AdminStoreResult<gateway_admin::model::quota_forecast_sampling::QuotaForecastHistory> {
) -> AdminStoreResult<gateway_admin::model::quota_forecast::QuotaForecastHistory> {
Err(unavailable("quota forecast history"))
}
@@ -719,6 +718,26 @@ impl AccountRuntimeStore for UnavailableStore {
#[async_trait]
impl ClientKeyStore for UnavailableStore {
async fn budget_reference_accounts(
&self,
_: &gateway_core::policy::ClientApiKeyId,
_: &str,
_: &str,
) -> gateway_admin::ports::store::AdminStoreResult<
gateway_admin::model::client_keys::BudgetReferenceAccountPage,
> {
Err(unavailable("reference accounts"))
}
async fn batch_update_client_keys(
&self,
_: gateway_admin::model::client_keys::BatchUpdateClientKeys,
_: gateway_admin::ports::store::BatchClientKeyProfileMerger,
_: &MutationContext,
) -> AdminStoreResult<Revision> {
Err(unavailable("client key batch update"))
}
async fn client_key_budget_window(
&self,
_: &gateway_core::policy::ClientApiKeyId,
@@ -763,6 +782,15 @@ impl ClientKeyStore for UnavailableStore {
Err(unavailable("client key budget reset"))
}
async fn client_key_budget(
&self,
id: &gateway_core::policy::ClientApiKeyId,
) -> AdminStoreResult<Option<gateway_core::engine::budget::ClientBudgetStatus>> {
self.get_client_key(id)
.await
.map(|key| key.map(|row| row.budget))
}
async fn get_client_key(
&self,
_: &ClientApiKeyId,
@@ -844,6 +872,23 @@ impl ObservabilityStore for UnavailableStore {
Err(unavailable("dashboard trend"))
}
async fn client_key_statistics(
&self,
_: TimeRange,
_: &gateway_core::policy::ClientApiKeyId,
_: gateway_admin::model::observability::KeyUsageMetric,
) -> AdminStoreResult<gateway_admin::model::observability::KeyStatisticsOverview> {
Ok(Default::default())
}
async fn client_key_models(
&self,
_: TimeRange,
_: &gateway_core::policy::ClientApiKeyId,
) -> AdminStoreResult<Vec<gateway_admin::model::observability::KeyModelRow>> {
Ok(Default::default())
}
async fn usage_trend(
&self,
_: TimeRange,
@@ -966,6 +1011,8 @@ impl SettingsStore for UnavailableStore {
}
struct UnavailableProvider {
pricing_bands: &'static [&'static str],
pricing_references: std::collections::BTreeMap<String, (String, String)>,
peer_enabled: bool,
kind: ProviderKind,
dashboard_profile: Option<DashboardWireProfile>,
@@ -977,6 +1024,7 @@ struct UnavailablePricingSource;
impl gateway_admin::ports::pricing::PricingSource for UnavailablePricingSource {
async fn fetch(
&self,
_: &gateway_admin::ports::pricing::PricingSourceScope,
) -> Result<gateway_admin::model::pricing::PricingSyncPreview, gateway_admin::model::AdminError>
{
Err(gateway_admin::model::AdminError::internal(
@@ -990,6 +1038,8 @@ impl UnavailableProvider {
Self {
kind: ProviderKind::new(kind).expect("provider kind"),
peer_enabled: false,
pricing_references: Default::default(),
pricing_bands: &["standard"],
dashboard_profile: None,
calculated_billing: None,
}
@@ -1002,6 +1052,31 @@ pub(super) fn test_provider(kind: &str) -> Arc<dyn ProviderAdmin> {
#[async_trait]
impl ProviderAdmin for UnavailableProvider {
fn supported_pricing_bands(&self) -> &'static [&'static str] {
self.pricing_bands
}
fn pricing_source(&self) -> gateway_admin::ports::pricing::PricingCatalogSource {
use gateway_admin::ports::pricing::PricingCatalogSource;
if self.pricing_references.is_empty() {
return PricingCatalogSource::Direct;
}
PricingCatalogSource::References(
self.pricing_references
.iter()
.map(|(model, (provider, source))| {
(
model.clone(),
gateway_admin::ports::pricing::PricingSourceModel {
provider: provider.clone(),
model: source.clone(),
},
)
})
.collect(),
)
}
fn peer_authentication_kinds(&self) -> &[&str] {
if self.peer_enabled {
&["peer_test"]
@@ -1112,6 +1187,8 @@ impl ProviderAdmin for UnavailableProvider {
pub(super) fn dashboard_profile_provider() -> Arc<dyn ProviderAdmin> {
Arc::new(UnavailableProvider {
pricing_bands: &["standard"],
pricing_references: Default::default(),
peer_enabled: false,
kind: ProviderKind::new("openai").expect("provider kind"),
dashboard_profile: Some(DashboardWireProfile {
@@ -1156,6 +1233,8 @@ pub(super) fn calculated_billing_provider() -> Arc<dyn ProviderAdmin> {
.expect("test billing amount"),
};
Arc::new(UnavailableProvider {
pricing_bands: &["standard"],
pricing_references: Default::default(),
peer_enabled: false,
kind: ProviderKind::new("openai").expect("provider kind"),
dashboard_profile: None,
@@ -0,0 +1,571 @@
//! 仪表盘指标、时间桶与账号聚合测试
use super::*;
#[tokio::test]
async fn health_timeline_should_keep_exactly_china_day_quarter_hour_slots() {
let now = Utc::now();
let day_start = gateway_core::time::DeploymentTimeZone::default()
.day_start(now)
.unwrap();
let current_slot = quarter_hour_start(now);
let store = Arc::new(FixtureObservabilityStore::new(observation_range(now)));
store.replace_trend(vec![
health_metric_point(
day_start - Duration::minutes(15),
RequestMetrics {
success_count: 100,
..RequestMetrics::default()
},
),
health_metric_point(
current_slot,
RequestMetrics {
success_count: 2,
..RequestMetrics::default()
},
),
health_metric_point(
current_slot + Duration::minutes(15),
RequestMetrics {
success_count: 100,
..RequestMetrics::default()
},
),
]);
let services = observability_services(store).await;
let timeline = services
.observability()
.dashboard_summary(observation_range(now), TrendKind::Usage)
.await
.expect("dashboard summary")
.health_timeline;
assert_eq!(timeline.points.len(), 96);
assert_eq!(
timeline.points.first().map(|point| point.bucket_start),
Some(day_start)
);
assert_eq!(
timeline.points.last().map(|point| point.bucket_start),
Some(day_start + Duration::minutes(95 * 15))
);
assert_eq!(timeline.success_requests, 2);
assert_eq!(
timeline
.points
.iter()
.find(|point| point.bucket_start == current_slot)
.map(|point| point.status),
Some(HealthStatus::LowSample)
);
assert!(timeline.points.iter().all(|point| {
point.bucket_start <= quarter_hour_start(Utc::now())
|| (point.status == HealthStatus::Future && point.success_requests == 0)
}));
}
#[tokio::test]
async fn dashboard_summary_should_derive_first_token_average_from_trend() {
let now = Utc::now();
let current_slot = quarter_hour_start(now);
let store = Arc::new(FixtureObservabilityStore::new(observation_range(now)));
store.replace_trend(vec![
health_metric_point(
current_slot - Duration::minutes(15),
RequestMetrics {
first_token_latency_sum_ms: 120,
first_token_latency_count: 2,
..RequestMetrics::default()
},
),
health_metric_point(
current_slot,
RequestMetrics {
first_token_latency_sum_ms: 180,
first_token_latency_count: 1,
..RequestMetrics::default()
},
),
]);
let services = observability_services(store).await;
let summary = services
.observability()
.dashboard_summary(observation_range(now), TrendKind::Usage)
.await
.expect("dashboard summary");
assert_eq!(summary.average_first_token_latency_ms, Some(100));
}
#[test]
fn dashboard_comparison_should_follow_deployment_calendar_across_dst() {
let timezone = "America/New_York".parse().unwrap();
for (end, previous_start, previous_end, hours) in [
(
"2026-03-09T16:00:00Z",
"2026-03-08T05:00:00Z",
"2026-03-09T04:00:00Z",
23,
),
(
"2026-11-02T17:00:00Z",
"2026-11-01T04:00:00Z",
"2026-11-02T05:00:00Z",
25,
),
(
"2026-11-02T05:00:00Z",
"2026-11-01T04:00:00Z",
"2026-11-02T05:00:00Z",
25,
),
] {
let end = end.parse().unwrap();
let range = TimeRange::calendar_at(
gateway_admin::model::observability::CalendarPeriod::Today,
end,
timezone,
)
.unwrap();
let query = DashboardQuery::new(range, timezone).unwrap();
assert_eq!(query.range, range);
assert_eq!(
query.yesterday_range.start,
previous_start.parse::<DateTime<Utc>>().unwrap()
);
assert_eq!(
query.yesterday_range.end,
previous_end.parse::<DateTime<Utc>>().unwrap()
);
assert_eq!(
(query.yesterday_range.end - query.yesterday_range.start).num_hours(),
hours
);
}
}
#[tokio::test]
async fn dashboard_summary_should_compare_separate_yesterday_metrics_with_today_only_trend() {
let end: DateTime<Utc> = "2026-10-18T04:00:00Z".parse().unwrap();
let range = TimeRange::calendar_at(
gateway_admin::model::observability::CalendarPeriod::Today,
end,
Default::default(),
)
.unwrap();
let store = Arc::new(FixtureObservabilityStore::new(range));
store.replace_trend(vec![health_metric_point(
range.start,
RequestMetrics {
request_count: 2,
input_tokens: 100,
cached_input_tokens: 20,
total_tokens: 120,
..Default::default()
},
)]);
*store.yesterday.lock().unwrap() = RequestMetrics {
request_count: 4,
input_tokens: 400,
cached_input_tokens: 200,
total_tokens: 500,
..Default::default()
};
let result = observability_services(store.clone())
.await
.observability()
.dashboard_summary(range, TrendKind::Usage)
.await
.unwrap();
assert_eq!(result.today.request_count, 2);
assert_eq!(result.today.total_tokens, 120);
assert_eq!(result.today.observed_cached_token_rate, Some(0.2));
assert_eq!(result.yesterday.request_count, 4);
assert_eq!(result.yesterday.total_tokens, 500);
assert_eq!(result.yesterday.observed_cached_token_rate, Some(0.5));
assert_eq!(result.observation.range, range);
assert_eq!(result.observation.trend.len(), 1);
assert_eq!(result.observation.trend[0].bucket_start, range.start);
assert_eq!(
store
.summary_query
.lock()
.unwrap()
.as_ref()
.unwrap()
.yesterday_range
.end,
range.start
);
}
#[tokio::test]
async fn dashboard_summary_should_keep_missing_yesterday_cache_rate_unknown() {
let range = observation_range(Utc::now());
let store = Arc::new(FixtureObservabilityStore::new(range));
let result = observability_services(store)
.await
.observability()
.dashboard_summary(range, TrendKind::Usage)
.await
.unwrap();
assert_eq!(result.yesterday.request_count, 0);
assert_eq!(result.yesterday.total_tokens, 0);
assert_eq!(result.yesterday.observed_cached_token_rate, None);
}
#[tokio::test]
async fn health_timeline_should_apply_status_precedence_and_thresholds() {
let now = Utc::now();
let current_slot = quarter_hour_start(now);
let store = Arc::new(FixtureObservabilityStore::new(observation_range(now)));
let services = observability_services(store.clone()).await;
let fixtures = [
(
RequestMetrics {
failure_count: 1,
cancelled_count: 1,
caller_error_count: 1,
..RequestMetrics::default()
},
HealthStatus::NoData,
None,
),
(
RequestMetrics {
incomplete_count: 1,
..RequestMetrics::default()
},
HealthStatus::LowSample,
Some(0.0),
),
(
RequestMetrics {
incomplete_count: 3,
..RequestMetrics::default()
},
HealthStatus::Unavailable,
Some(0.0),
),
(
RequestMetrics {
failure_count: 3,
..RequestMetrics::default()
},
HealthStatus::Unavailable,
Some(0.0),
),
(
RequestMetrics {
success_count: 1,
failure_count: 1,
..RequestMetrics::default()
},
HealthStatus::LowSample,
Some(50.0),
),
(
RequestMetrics {
success_count: 94,
failure_count: 6,
..RequestMetrics::default()
},
HealthStatus::Unstable,
Some(94.0),
),
(
RequestMetrics {
success_count: 95,
incomplete_count: 5,
..RequestMetrics::default()
},
HealthStatus::Stable,
Some(95.0),
),
];
for (index, (metrics, expected_status, expected_reliability)) in
fixtures.into_iter().enumerate()
{
store.replace_trend(vec![health_metric_point(current_slot, metrics)]);
let range_end =
now + Duration::seconds(i64::try_from(index).expect("fixture index fits i64") * 2);
let timeline = services
.observability()
.dashboard_summary(observation_range(range_end), TrendKind::Usage)
.await
.expect("dashboard summary")
.health_timeline;
let point = timeline
.points
.iter()
.find(|point| point.bucket_start == current_slot)
.expect("current health slot");
assert_eq!(point.status, expected_status);
assert_eq!(point.reliability_percent, expected_reliability);
}
}
#[tokio::test]
async fn health_views_should_include_incomplete_and_keep_final_outcomes_separate() {
let now = Utc::now();
let current_slot = quarter_hour_start(now);
let store = Arc::new(FixtureObservabilityStore::new(observation_range(now)));
let services = observability_services(store.clone()).await;
let fixtures = [
(162, 0, 2, 0, 0, 0, Some(98.780_487_804_878_05)),
(297, 0, 2, 5, 0, 0, Some(99.331_103_678_929_76)),
(467, 1, 5, 0, 0, 0, Some(98.731_501_057_082_45)),
(95, 2, 3, 4, 1, 7, Some(95.0)),
(100, 0, 0, 0, 0, 0, Some(100.0)),
(0, 0, 0, 0, 0, 0, None),
(0, 0, 0, 4, 3, 2, None),
(0, 1, 2, 0, 0, 0, Some(0.0)),
];
for (
index,
(success, failed, incomplete, cancelled, caller_error, running, expected_percent),
) in fixtures.into_iter().enumerate()
{
let range = observation_range(
now + Duration::seconds(i64::try_from(index).expect("fixture index fits i64") * 2),
);
let metrics = RequestMetrics {
request_count: success + failed + incomplete + cancelled + caller_error + running,
success_count: success,
failure_count: failed + caller_error,
incomplete_count: incomplete,
cancelled_count: cancelled,
caller_error_count: caller_error,
..RequestMetrics::default()
};
store.replace_trend(vec![health_metric_point(current_slot, metrics.clone())]);
store.replace_overview(UsageOverview {
analytics: Default::default(),
range,
requests: metrics,
// 中间尝试失败不会增加最终失败请求数
attempts: AttemptMetrics {
failure_count: 2,
..AttemptMetrics::default()
},
providers: Vec::new(),
});
let mut item = diagnostic(
"model",
success + failed + incomplete + cancelled + caller_error + running,
);
item.success_count = success;
item.failure_count = failed + caller_error;
item.incomplete_count = incomplete;
item.cancelled_count = cancelled;
item.caller_error_count = caller_error;
store.replace_diagnostics(DiagnosticsObservation {
analytics: Default::default(),
total_request_count: item.request_count,
items: vec![item],
});
let diagnostics = services
.observability()
.diagnostics(range, UsageFilter::default(), DiagnosticDimension::Model)
.await
.unwrap();
assert_eq!(diagnostics.items[0].error_count, failed + incomplete);
let dashboard = services
.observability()
.dashboard_summary(range, TrendKind::Usage)
.await
.expect("dashboard summary");
let timeline = dashboard.health_timeline;
let point = timeline
.points
.iter()
.find(|point| point.bucket_start == current_slot)
.expect("current health slot");
assert_eq!(dashboard.trend.summary.error_count, failed + incomplete);
assert_eq!(dashboard.trend.points[0].error_count, failed + incomplete);
assert_eq!(point.failed_requests, failed);
assert_eq!(point.incomplete_requests, incomplete);
assert_eq!(point.cancelled_requests, cancelled);
assert_eq!(point.caller_error_requests, caller_error);
let insights = services
.observability()
.usage_insights(range, UsageFilter::default())
.await
.expect("usage insights");
assert_eq!(insights.health.failed_requests, failed);
assert_eq!(insights.health.incomplete_requests, incomplete);
for actual in [
timeline.reliability_percent,
point.reliability_percent,
dashboard
.trend
.summary
.success_rate
.map(|rate| rate * 100.0),
dashboard.trend.points[0]
.success_rate
.map(|rate| rate * 100.0),
insights.health.success_rate.map(|rate| rate * 100.0),
insights.health.points[0]
.error_rate
.map(|rate| (1.0 - rate) * 100.0),
diagnostics.items[0]
.error_rate
.map(|rate| (1.0 - rate) * 100.0),
] {
match (actual, expected_percent) {
(Some(actual), Some(expected)) => assert!((actual - expected).abs() < 1e-10),
(None, None) => {}
_ => panic!("unexpected rate: {actual:?}, expected {expected_percent:?}"),
}
}
}
}
#[tokio::test]
async fn dashboard_summary_should_project_rebuildable_runtime_slots() {
let now = Utc::now();
let store = Arc::new(FixtureObservabilityStore::new(observation_range(now)));
store.replace_runtime_slots(Some(DashboardRuntimeSlots {
inherited_versions: Vec::new(),
inherited_accounts: 2,
overridden_slots: 5,
used_slots: Some(2),
}));
let services = observability_services(store).await;
let capacity = services
.observability()
.dashboard_summary(observation_range(now), TrendKind::Usage)
.await
.expect("dashboard summary")
.capacity;
assert_eq!(capacity.total_slots, Some(7));
assert_eq!(capacity.used_slots, Some(2));
assert_eq!(capacity.available_slots, Some(5));
}
#[tokio::test]
async fn dashboard_capacity_distinguishes_unlimited_inheritance_finite_overrides_and_empty_pool() {
for (inherited_accounts, overridden_slots, expected_total, expected_available) in [
(2, 5, None, None),
(0, 5, Some(5), Some(3)),
(0, 0, Some(0), Some(0)),
] {
let now = Utc::now();
let store = Arc::new(FixtureObservabilityStore::new(observation_range(now)));
store.replace_runtime_slots(Some(DashboardRuntimeSlots {
inherited_versions: Vec::new(),
inherited_accounts,
overridden_slots,
used_slots: Some(2),
}));
let services = crate::use_case::AdminHarness::new()
.observability(store)
.settings(Arc::new(FixtureSettingsStore {
max_concurrent_per_account: 0,
}))
.provider(crate::use_case::dashboard_profile_provider())
.build()
.await;
let capacity = services
.observability()
.dashboard_summary(observation_range(now), TrendKind::Usage)
.await
.expect("dashboard")
.capacity;
assert_eq!(capacity.total_slots, expected_total);
assert_eq!(capacity.available_slots, expected_available);
assert_eq!(capacity.used_slots, Some(2));
}
}
#[tokio::test]
async fn dashboard_summary_should_observe_current_accounts_for_a_historical_range() {
let historical_end = Utc::now() - Duration::hours(1);
let store = Arc::new(FixtureObservabilityStore::new(observation_range(
historical_end,
)));
let services = observability_services(store.clone()).await;
services
.observability()
.dashboard_summary(observation_range(historical_end), TrendKind::Usage)
.await
.expect("dashboard summary");
let summary_observed_at = *store.summary_observed_at.lock().unwrap();
assert!(summary_observed_at.is_some_and(|value| value > historical_end));
}
#[tokio::test]
async fn dashboard_should_preserve_provider_plan_names() {
let now = Utc::now();
let range = observation_range(now);
let store = Arc::new(FixtureObservabilityStore::new(range));
let plans = [("prolite", "ProLite"), ("pro", "Pro"), ("promax", "ProMax")];
*store.account_usage.lock().unwrap() = plans
.iter()
.map(|(plan, _)| DashboardAccountUsage {
upstream: None,
account_id: format!("account-{plan}"),
provider_kind: "openai".to_owned(),
authentication_kind: "oauth".to_owned(),
name: (*plan).to_owned(),
email: None,
notes: None,
plan_type: Some((*plan).to_owned()),
plan_type_display: None,
request_count: 0,
success_count: 0,
input_tokens: None,
output_tokens: None,
cached_input_tokens: None,
cache_write_input_tokens: None,
reasoning_output_tokens: None,
image_input_tokens: None,
image_output_tokens: None,
image_request_count: 0,
image_request_failed_count: 0,
total_tokens: None,
cost_coverage: CostCoverage::default(),
costs: Vec::new(),
last_used_at: None,
request_buckets: Vec::new(),
quota_used_percent: None,
quota_window: None,
models: Vec::new(),
})
.collect();
let provider = crate::use_case::accounts::FakeProviderAdmin::new(
"openai",
Arc::new(Mutex::new(Vec::new())),
);
let services = crate::use_case::AdminHarness::new()
.observability(store)
.settings(Arc::new(FixtureSettingsStore {
max_concurrent_per_account: 1,
}))
.provider(provider)
.build()
.await;
let result = services
.observability()
.dashboard_summary(range, TrendKind::Usage)
.await
.unwrap();
assert_eq!(result.observation.account_usage.len(), plans.len());
for (account, (raw, display)) in result.observation.account_usage.iter().zip(plans) {
assert_eq!(account.plan_type.as_deref(), Some(raw));
assert_eq!(account.plan_type_display.as_deref(), Some(display));
}
}
@@ -0,0 +1,49 @@
//! 用量洞察的指标聚合测试
use super::*;
#[tokio::test]
async fn usage_insights_should_weight_concurrency_by_effective_bucket_duration() {
let bucket_start = DateTime::parse_from_rfc3339("2026-09-01T10:00:00Z")
.unwrap()
.with_timezone(&Utc);
let range = TimeRange::new(
bucket_start + Duration::minutes(5),
bucket_start + Duration::minutes(20),
)
.unwrap();
let store = Arc::new(FixtureObservabilityStore::new(range));
store.replace_trend(vec![
health_metric_point(bucket_start, RequestMetrics::default()),
health_metric_point(
bucket_start + Duration::minutes(15),
RequestMetrics::default(),
),
]);
*store.concurrency.lock().unwrap() = vec![
UsageConcurrencyPoint {
bucket_start,
average_concurrency: 1.0,
peak_concurrency: 1,
},
UsageConcurrencyPoint {
bucket_start: bucket_start + Duration::minutes(15),
average_concurrency: 3.0,
peak_concurrency: 4,
},
];
let insights = observability_services(store)
.await
.observability()
.usage_insights(range, UsageFilter::default())
.await
.unwrap();
assert!((insights.performance.load.average_concurrency - 5.0 / 3.0).abs() < 1e-10);
assert_eq!(insights.performance.load.peak_concurrency, 4);
assert_eq!(insights.performance.points[0].load.average_concurrency, 1.0);
assert_eq!(insights.performance.points[0].load.peak_concurrency, 1);
assert_eq!(insights.performance.points[1].load.average_concurrency, 3.0);
assert_eq!(insights.performance.points[1].load.peak_concurrency, 4);
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,407 @@
//! 观测查询协调、错误传播与费用补充测试
use super::*;
#[test]
fn external_observability_range_accepts_exactly_366_days() {
let end = Utc::now();
let range = TimeRange::new(end - Duration::days(366), end)
.expect("366-day external range should be accepted");
assert_eq!(range.end, end);
}
#[test]
fn external_observability_range_rejects_over_366_days_and_reversed_range() {
let end = Utc::now();
assert!(TimeRange::new(end - Duration::days(367), end).is_err());
assert!(TimeRange::new(end, end).is_err());
assert!(TimeRange::new(end + Duration::seconds(1), end).is_err());
}
#[tokio::test]
async fn observability_services_should_calculate_usage_insights_and_diagnostic_shares() {
let now = Utc::now();
let range = observation_range(now);
let store = Arc::new(FixtureObservabilityStore::new(range));
let metrics = RequestMetrics {
request_count: 10,
success_count: 6,
failure_count: 4,
caller_error_count: 2,
input_tokens: 800,
output_tokens: 200,
total_tokens: 1_000,
latency_count: 5,
admission_decision_count: 10,
admission_decision_percentiles: LatencyPercentiles {
p50_ms: Some(PercentileMilliseconds::new(2.0).expect("admission P50")),
p95_ms: Some(PercentileMilliseconds::new(5.0).expect("admission P95")),
p99_ms: Some(PercentileMilliseconds::new(8.0).expect("admission P99")),
},
account_selection_wait_count: 8,
account_selection_wait_percentiles: LatencyPercentiles {
p50_ms: Some(PercentileMilliseconds::new(10.0).expect("selection P50")),
p95_ms: Some(PercentileMilliseconds::new(40.0).expect("selection P95")),
p99_ms: Some(PercentileMilliseconds::new(70.0).expect("selection P99")),
},
output_throughput_p10: Some(40),
output_throughput_p50: Some(50),
output_throughput_p90: Some(60),
capacity_sample_count: 8,
capacity_utilization_avg_basis_points: Some(6_500),
capacity_utilization_p95_basis_points: Some(8_000),
..RequestMetrics::default()
};
store.replace_overview(UsageOverview {
analytics: Default::default(),
range,
requests: metrics.clone(),
attempts: AttemptMetrics {
attempt_count: 12,
cost_coverage: CostCoverage {
calculated_count: 10,
..CostCoverage::default()
},
costs: vec![CurrencyCost {
currency: "USD".to_owned(),
amount: gateway_admin::model::observability::DecimalAmount::from_str("1.25")
.expect("USD cost"),
}],
..AttemptMetrics::default()
},
providers: Vec::new(),
});
store.replace_trend(vec![RequestMetricPoint {
bucket_start: quarter_hour_start(now),
granularity: Granularity::FifteenMinutes,
metrics,
cost_coverage: CostCoverage::default(),
costs: vec![CurrencyCost {
currency: "USD".to_owned(),
amount: gateway_admin::model::observability::DecimalAmount::from_str("0.25")
.expect("bucket USD cost"),
}],
}]);
store.replace_projected_costs(vec![UsageProjectedCostPoint {
bucket_start: quarter_hour_start(now),
standard_amount: Some("1".parse().expect("standard cost")),
no_cache_amount: Some("1.25".parse().expect("no-cache cost")),
}]);
store.replace_diagnostics(DiagnosticsObservation {
analytics: Default::default(),
total_request_count: 4,
items: vec![diagnostic("openai", 3), diagnostic("xai", 1)],
});
let services = observability_services_with_calculated_billing(store).await;
let insights = services
.observability()
.usage_insights(range, UsageFilter::default())
.await
.expect("usage insights");
let diagnostics = services
.observability()
.diagnostics(range, UsageFilter::default(), DiagnosticDimension::Provider)
.await
.expect("usage diagnostics");
assert_eq!(insights.health.total_requests, 10);
assert_eq!(insights.health.failed_requests, 2);
assert_eq!(insights.health.success_rate, Some(0.75));
assert_eq!(insights.health.completion_rate, 1.0);
assert_eq!(insights.granularity, Granularity::FifteenMinutes);
assert_eq!(
insights
.performance
.load
.admission_decision_p95_ms
.map(|value| value.as_f64()),
Some(5.0)
);
assert_eq!(
insights
.performance
.load
.account_selection_wait_p95_ms
.map(|value| value.as_f64()),
Some(40.0)
);
assert_eq!(
insights.performance.points[0].load,
insights.performance.load
);
assert_eq!(insights.performance.output_throughput_p50, Some(50));
assert_eq!(insights.cost.tokens_per_request, 100.0);
assert_eq!(
insights
.cost
.estimated_cost
.as_ref()
.map(gateway_admin::model::observability::DecimalAmount::as_str),
Some("1.25")
);
assert_eq!(
insights
.cost
.cost_per_request
.as_ref()
.map(gateway_admin::model::observability::DecimalAmount::as_str),
Some("0.125")
);
assert_eq!(
insights.cost.points[0]
.estimated_cost
.as_ref()
.map(gateway_admin::model::observability::DecimalAmount::as_str),
Some("0.25")
);
assert_eq!(
insights
.cost
.standard_cost
.as_ref()
.map(gateway_admin::model::observability::DecimalAmount::as_str),
Some("1")
);
assert_eq!(
insights.cost.points[0]
.standard_cost
.as_ref()
.map(gateway_admin::model::observability::DecimalAmount::as_str),
Some("1")
);
assert_eq!(
insights
.cost
.no_cache_cost
.as_ref()
.map(gateway_admin::model::observability::DecimalAmount::as_str),
Some("1.25")
);
assert_eq!(
insights
.cost
.tier_premium
.as_ref()
.map(gateway_admin::model::observability::DecimalAmount::as_str),
Some("0.25")
);
assert_eq!(diagnostics.items[0].request_share, 0.75);
assert_eq!(diagnostics.items[1].request_share, 0.25);
}
#[tokio::test]
async fn diagnostics_should_preserve_request_order_when_a_small_sample_fails() {
let now = Utc::now();
let range = observation_range(now);
let store = Arc::new(FixtureObservabilityStore::new(range));
let success = diagnostic("popular", 100);
let mut failure = diagnostic("single_failure", 1);
failure.success_count = 0;
failure.failure_count = 1;
store.replace_diagnostics(DiagnosticsObservation {
analytics: Default::default(),
total_request_count: 101,
items: vec![success, failure],
});
let services = observability_services_with_calculated_billing(store).await;
let result = services
.observability()
.diagnostics(range, UsageFilter::default(), DiagnosticDimension::Model)
.await
.expect("diagnostics");
assert_eq!(result.items[0].key, "popular");
assert_eq!(result.items[1].key, "single_failure");
assert_eq!(result.items[0].error_count, 0);
assert_eq!(result.items[1].error_count, 1);
assert_eq!(result.items[1].error_rate, Some(1.0));
}
#[tokio::test]
async fn diagnostics_should_use_the_total_before_truncating_groups() {
let range = observation_range(Utc::now());
let store = Arc::new(FixtureObservabilityStore::new(range));
store.replace_diagnostics(DiagnosticsObservation {
analytics: Default::default(),
total_request_count: 200,
items: (0..100)
.map(|index| diagnostic(&format!("model-{index}"), 1))
.collect(),
});
let services = observability_services_with_calculated_billing(store).await;
let result = services
.observability()
.diagnostics(range, UsageFilter::default(), DiagnosticDimension::Model)
.await
.expect("limited diagnostics");
assert!(result.items.iter().all(|item| item.request_share == 0.005));
}
#[tokio::test]
async fn diagnostics_should_count_each_retried_request_once() {
let range = observation_range(Utc::now());
let store = Arc::new(FixtureObservabilityStore::new(range));
let mut item = diagnostic("model", 8);
item.attempt_count = 14;
item.retry_count = 6;
item.retried_request_count = 2;
store.replace_diagnostics(DiagnosticsObservation {
analytics: Default::default(),
total_request_count: 8,
items: vec![item],
});
let services = observability_services_with_calculated_billing(store).await;
let result = services
.observability()
.diagnostics(range, UsageFilter::default(), DiagnosticDimension::Model)
.await
.expect("retry diagnostics");
assert_eq!(
(result.items[0].retry_count, result.items[0].retry_rate),
(6, 0.25)
);
}
#[tokio::test]
async fn diagnostics_should_preserve_empty_results() {
let range = observation_range(Utc::now());
let store = Arc::new(FixtureObservabilityStore::new(range));
let services = observability_services_with_calculated_billing(store).await;
let result = services
.observability()
.diagnostics(range, UsageFilter::default(), DiagnosticDimension::Account)
.await
.expect("empty diagnostics");
assert!(result.items.is_empty());
}
#[tokio::test]
async fn usage_records_should_tolerate_records_that_fail_billing_enrichment() {
let now = Utc::now();
let store = Arc::new(FixtureObservabilityStore::new(observation_range(now)));
let invalid_kind = "x".repeat(65);
store.replace_usage_records(vec![
total_record(
"request_invalid_kind",
Some(&invalid_kind),
"calculated",
now,
),
total_record(
"request_unregistered_kind",
Some("anthropic"),
"calculated",
now,
),
total_record("request_enriched", Some("openai"), "calculated", now),
]);
let services = observability_services_with_calculated_billing(store).await;
let page = services
.observability()
.usage_records(usage_query(now))
.await
.expect("one bad record must not fail the whole usage list");
assert_eq!(page.items.len(), 3);
assert!(
matches!(page.items[0].billing, Some(UsageBilling::Total { .. })),
"invalid Provider kind keeps the stored total"
);
assert!(
matches!(page.items[1].billing, Some(UsageBilling::Total { .. })),
"unregistered Provider kind keeps the stored total"
);
assert!(
matches!(page.items[2].billing, Some(UsageBilling::Calculated(_))),
"healthy record is still enriched"
);
}
#[tokio::test]
async fn usage_records_should_enrich_provider_reported_totals_when_pricing_matches() {
let now = Utc::now();
let store = Arc::new(FixtureObservabilityStore::new(observation_range(now)));
store.replace_usage_records(vec![total_record(
"request_provider_reported",
Some("openai"),
"provider_reported",
now,
)]);
let services = observability_services_with_calculated_billing(store).await;
let page = services
.observability()
.usage_records(usage_query(now))
.await
.expect("usage records");
assert!(matches!(
page.items[0].billing,
Some(UsageBilling::Calculated(_))
));
}
#[tokio::test]
async fn usage_insights_should_reject_partial_costs_when_insights_fail() {
let now = Utc::now();
let range = observation_range(now);
let store = Arc::new(FixtureObservabilityStore::new(range));
store.replace_projected_costs(vec![UsageProjectedCostPoint {
bucket_start: quarter_hour_start(now),
standard_amount: Some("1".parse().expect("standard cost")),
no_cache_amount: Some("1.25".parse().expect("no-cache cost")),
}]);
store.insights_fail.store(true, Ordering::SeqCst);
let services = observability_services_with_calculated_billing(store).await;
assert!(
services
.observability()
.usage_insights(range, UsageFilter::default())
.await
.is_err()
);
}
#[tokio::test]
async fn admin_selects_dashboard_defaults_and_matching_usage_buckets_at_range_boundaries() {
let now = Utc::now();
for (duration, expected) in [
(Duration::days(2), Granularity::FifteenMinutes),
(Duration::days(2) + Duration::seconds(1), Granularity::Hour),
(Duration::days(31), Granularity::Hour),
(Duration::days(31) + Duration::seconds(1), Granularity::Day),
] {
let range = TimeRange::new(now - duration, now).unwrap();
let store = Arc::new(FixtureObservabilityStore::new(range));
let services = observability_services(store.clone()).await;
services
.observability()
.dashboard_summary(range, TrendKind::Usage)
.await
.unwrap();
let query = store.summary_query.lock().unwrap().clone().unwrap();
assert_eq!(query.range, range);
assert_eq!(query.granularity, expected);
assert_eq!(query.account_limit, 4);
assert_eq!(query.recent_request_limit, 10);
assert_eq!(
query.recent_request_filter.outcome,
Some(gateway_admin::model::observability::RequestOutcome::Succeeded)
);
services
.observability()
.usage_insights(range, UsageFilter::default())
.await
.unwrap();
assert_eq!(*store.usage_granularities.lock().unwrap(), vec![expected]);
}
}
@@ -0,0 +1,363 @@
//! 观测缓存的合并、隔离与失效测试
use super::*;
#[tokio::test]
async fn dashboard_summary_should_keep_distinct_exact_ranges_in_one_short_window() {
let end_bucket = Utc::now().timestamp().div_euclid(2) * 2;
let first_end = DateTime::from_timestamp(end_bucket, 100_000_000).expect("first end");
let second_end = DateTime::from_timestamp(end_bucket, 900_000_000).expect("second end");
let first_range = TimeRange::new(
gateway_core::time::DeploymentTimeZone::default()
.day_start(first_end)
.unwrap(),
first_end,
)
.expect("first range");
let second_range = TimeRange::new(
gateway_core::time::DeploymentTimeZone::default()
.day_start(second_end)
.unwrap(),
second_end,
)
.expect("second range");
let store = Arc::new(FixtureObservabilityStore::new(first_range));
store.set_dashboard_delay(StdDuration::from_millis(20));
let services = observability_services(store.clone()).await;
let observability = services.observability();
let (first, second) = tokio::join!(
observability.dashboard_summary(first_range, TrendKind::Usage),
observability.dashboard_summary(second_range, TrendKind::Errors),
);
first.expect("first dashboard summary");
second.expect("second dashboard summary");
assert_eq!(store.dashboard_summary_calls(), 2);
}
#[tokio::test]
async fn dashboard_summary_should_reload_after_the_short_window_changes() {
let end_bucket = Utc::now().timestamp().div_euclid(2) * 2;
let first_end = DateTime::from_timestamp(end_bucket, 100_000_000).expect("first end");
let second_end = first_end + Duration::seconds(2);
let first_range = TimeRange::new(
gateway_core::time::DeploymentTimeZone::default()
.day_start(first_end)
.unwrap(),
first_end,
)
.expect("first range");
let second_range = TimeRange::new(
gateway_core::time::DeploymentTimeZone::default()
.day_start(second_end)
.unwrap(),
second_end,
)
.expect("second range");
let store = Arc::new(FixtureObservabilityStore::new(first_range));
let services = observability_services(store.clone()).await;
let observability = services.observability();
observability
.dashboard_summary(first_range, TrendKind::Usage)
.await
.expect("first dashboard summary");
observability
.dashboard_summary(second_range, TrendKind::Usage)
.await
.expect("second dashboard summary");
assert_eq!(store.dashboard_summary_calls(), 2);
}
#[tokio::test]
async fn dashboard_and_usage_insights_keep_concurrency_cache_entries_separate() {
for dashboard_first in [true, false] {
let now = Utc::now();
let range = observation_range(now);
let store = Arc::new(FixtureObservabilityStore::new(range));
store
.concurrency
.lock()
.unwrap()
.push(UsageConcurrencyPoint {
bucket_start: range.start,
average_concurrency: 2.0,
peak_concurrency: 3,
});
let services = observability_services(store.clone()).await;
for dashboard in [
dashboard_first,
!dashboard_first,
dashboard_first,
!dashboard_first,
] {
if dashboard {
services
.observability()
.dashboard_trend(range, TrendKind::Usage)
.await
.unwrap();
} else {
let result = services
.observability()
.usage_insights(range, UsageFilter::default())
.await
.unwrap();
assert_eq!(result.performance.load.peak_concurrency, 3);
}
}
assert_eq!(
*store.concurrency_selections.lock().unwrap(),
vec![!dashboard_first, dashboard_first]
);
}
}
#[tokio::test]
async fn usage_summary_cache_should_coalesce_identical_queries_and_invalidate_deleted_generation() {
let range = observation_range(Utc::now());
let store = Arc::new(FixtureObservabilityStore::new(range));
store.set_dashboard_delay(StdDuration::from_millis(20));
let services = observability_services(store.clone()).await;
let service = services.observability();
let filter = UsageFilter {
client_api_key_ref: Some("deleted-key".to_owned()),
..Default::default()
};
let (first, second) = tokio::join!(
service.usage_summary(range, filter.clone()),
service.usage_summary(range, filter.clone()),
);
first.expect("first summary");
second.expect("coalesced summary");
assert_eq!(store.usage_summary_filters.lock().unwrap().len(), 1);
{
let mut overview = store.overview.lock().unwrap();
overview.analytics.generation = 1;
overview.requests.request_count = 7;
}
let refreshed = service
.usage_summary(range, filter)
.await
.expect("generation refresh");
assert_eq!(refreshed.observation.analytics.generation, 1);
assert_eq!(refreshed.observation.requests.request_count, 7);
assert_eq!(store.usage_summary_filters.lock().unwrap().len(), 2);
}
#[tokio::test(start_paused = true)]
async fn usage_summary_cache_should_coalesce_when_generation_advances_during_the_first_load() {
let range = observation_range(Utc::now());
let store = Arc::new(FixtureObservabilityStore::new(range));
store.set_dashboard_delay(StdDuration::from_millis(20));
let services = observability_services(store.clone()).await;
let service = services.observability();
let (first, second, ()) = tokio::join!(
service.usage_summary(range, UsageFilter::default()),
service.usage_summary(range, UsageFilter::default()),
async {
tokio::time::sleep(StdDuration::from_millis(5)).await;
store.overview.lock().unwrap().analytics.generation = 1;
},
);
assert_eq!(
first
.expect("first summary")
.observation
.analytics
.generation,
1
);
assert_eq!(
second
.expect("coalesced summary")
.observation
.analytics
.generation,
1
);
assert_eq!(store.usage_summary_filters.lock().unwrap().len(), 1);
}
#[tokio::test]
async fn usage_summary_cache_should_isolate_key_identity_and_filters() {
let range = observation_range(Utc::now());
let store = Arc::new(FixtureObservabilityStore::new(range));
let services = observability_services(store.clone()).await;
let service = services.observability();
for (key, model) in [
("key-a", None),
("key-a", None),
("key-b", None),
("key-a", Some("model-a")),
] {
service
.usage_summary(
range,
UsageFilter {
client_api_key_ref: Some(key.to_owned()),
model: model.map(str::to_owned),
..Default::default()
},
)
.await
.expect("isolated summary");
}
let calls = store.usage_summary_filters.lock().unwrap();
assert_eq!(calls.len(), 3);
assert_eq!(calls[0].client_api_key_ref.as_deref(), Some("key-a"));
assert_eq!(calls[1].client_api_key_ref.as_deref(), Some("key-b"));
assert_eq!(calls[2].model.as_deref(), Some("model-a"));
}
#[tokio::test(start_paused = true)]
async fn usage_summary_cache_should_bound_waiting_after_failed_refresh_and_allow_recovery() {
let range = observation_range(Utc::now());
let store = Arc::new(FixtureObservabilityStore::new(range));
store.set_dashboard_delay(store.query_timeout().mul_f64(0.7));
store.summary_fail.store(true, Ordering::SeqCst);
let services = observability_services(store.clone()).await;
let service = services.observability();
let started = tokio::time::Instant::now();
let (first, second, third, fourth) = tokio::join!(
service.usage_summary(range, UsageFilter::default()),
service.usage_summary(range, UsageFilter::default()),
service.usage_summary(range, UsageFilter::default()),
service.usage_summary(range, UsageFilter::default()),
);
assert!(first.is_err() && second.is_err() && third.is_err() && fourth.is_err());
assert!(
started.elapsed() <= store.query_timeout(),
"同键失败不能使后续请求逐个等待完整数据库超时: {:?}",
started.elapsed()
);
store.summary_fail.store(false, Ordering::SeqCst);
store.set_dashboard_delay(StdDuration::ZERO);
service
.usage_summary(range, UsageFilter::default())
.await
.expect("cancelled cache refresh releases its slot for recovery");
}
#[tokio::test(start_paused = true)]
async fn insights_cache_should_bound_stale_lifetime_without_renewing_failed_refreshes() {
let range = observation_range(Utc::now());
let store = Arc::new(FixtureObservabilityStore::new(range));
{
let mut overview = store.overview.lock().unwrap();
overview.analytics.state = AnalyticsState::Ready;
overview.analytics.generated_at = Utc::now();
overview.analytics.lag_seconds = 7;
overview.requests.request_count = 19;
}
let services = observability_services(store.clone()).await;
let service = services.observability();
service
.usage_insights(range, UsageFilter::default())
.await
.unwrap();
store.insights_fail.store(true, Ordering::SeqCst);
tokio::time::advance(StdDuration::from_secs(16)).await;
let stale = service
.usage_insights(range, UsageFilter::default())
.await
.unwrap();
assert_eq!(stale.analytics.state, AnalyticsState::Stale);
assert!(stale.analytics.lag_seconds >= 7);
assert_eq!(stale.health.total_requests, 19);
tokio::time::advance(StdDuration::from_secs(45)).await;
assert!(
service
.usage_insights(range, UsageFilter::default())
.await
.is_err()
);
}
#[tokio::test(start_paused = true)]
async fn insights_cache_should_reject_deleted_building_and_old_generation_times() {
for reason in ["deleted", "building", "generated-too-long-ago"] {
let range = observation_range(Utc::now());
let store = Arc::new(FixtureObservabilityStore::new(range));
{
let mut overview = store.overview.lock().unwrap();
overview.analytics.state = if reason == "building" {
AnalyticsState::Building
} else {
AnalyticsState::Ready
};
overview.analytics.generated_at = Utc::now()
- Duration::seconds(if reason == "generated-too-long-ago" {
61
} else {
0
});
}
let services = observability_services(store.clone()).await;
let service = services.observability();
service
.usage_insights(range, UsageFilter::default())
.await
.unwrap();
store.insights_fail.store(true, Ordering::SeqCst);
if reason == "deleted" {
store.overview.lock().unwrap().analytics.generation += 1;
}
tokio::time::advance(StdDuration::from_secs(16)).await;
assert!(
service
.usage_insights(range, UsageFilter::default())
.await
.is_err(),
"{reason}"
);
}
}
#[tokio::test]
async fn usage_metric_cache_isolates_selections_and_filters() {
use gateway_admin::model::observability::UsageInsightMetric as Metric;
let range = observation_range(Utc::now());
let store = Arc::new(FixtureObservabilityStore::new(range));
let services = observability_services(store.clone()).await;
let metrics = [
Metric::Health,
Metric::Latency,
Metric::FirstToken,
Metric::Throughput,
Metric::Load,
Metric::Cost,
Metric::Savings,
Metric::Cache,
];
for _ in 0..2 {
for metric in metrics {
services
.observability()
.usage_metric(range, UsageFilter::default(), metric)
.await
.unwrap();
}
}
assert_eq!(*store.metric_selections.lock().unwrap(), metrics);
assert_eq!(
*store.concurrency_selections.lock().unwrap(),
vec![false, false, false, false, true, false, false, false]
);
services
.observability()
.usage_metric(
range,
UsageFilter {
provider_kind: Some("openai".into()),
..Default::default()
},
Metric::Latency,
)
.await
.unwrap();
assert_eq!(store.metric_selections.lock().unwrap().len(), 9);
}
@@ -254,7 +254,7 @@ fn sdk_settings_contract_matches_host_declarations() {
),
(
"../gateway-core/src/account/location.rs",
&["RequestLocation"][..],
&["RequestLocation", "OpenAiRequestCountry"][..],
),
(
"../gateway-core/src/account/scheduling.rs",
@@ -23,6 +23,7 @@ struct UnusedSettingsStore;
#[derive(Default)]
struct PricingSettingsStore {
synced: Mutex<Option<gateway_admin::model::pricing::PricingSyncChanges>>,
updated: Mutex<Option<UpdatePricing>>,
}
@@ -60,7 +61,7 @@ async fn explicit_service_calls_freeze_empty_plan_and_cancel_before_entering_ter
)
.await
.unwrap();
// 内部 pricing 不再单独进入插件链;显式调用只解析一次发布集合
// 每次显式调价只解析一次插件发布集合
assert_eq!(resolutions.load(Ordering::SeqCst), expected);
}
store.updated.lock().unwrap().take();
@@ -101,19 +102,39 @@ async fn client_profile_preview_rejects_unknown_provider_before_loading_settings
}
#[tokio::test]
async fn pricing_accepts_ultrafast_for_openai_but_rejects_it_for_xai() {
for provider in ["openai", "xai"] {
async fn pricing_validates_the_bands_declared_by_the_registered_provider() {
for (provider, supported) in [
("text-provider", &["standard", "fast"][..]),
("image-provider", &["standard", "image"][..]),
] {
let store = Arc::new(PricingSettingsStore::default());
let services = super::AdminHarness::new()
.settings(store.clone())
.provider(super::test_provider(provider))
.provider(Arc::new(super::UnavailableProvider {
pricing_bands: supported,
..super::UnavailableProvider::new(provider)
}))
.build()
.await;
assert_eq!(
services.settings().pricing().await.unwrap().supported_bands[provider],
supported
);
let context = MutationContext {
actor: gateway_admin::model::MutationActor::System,
request_id: "request-ultrafast-pricing".to_owned(),
request_id: "request-band-pricing".to_owned(),
};
for band in ["ultrafast", "long_ultrafast"] {
for band in [
"standard",
"fast",
"ultrafast",
"flex",
"long_standard",
"long_fast",
"long_ultrafast",
"long_flex",
"image",
] {
let pricing = serde_json::from_value(serde_json::json!({
"multiplierBps": 10000,
"bands": {
@@ -121,7 +142,7 @@ async fn pricing_accepts_ultrafast_for_openai_but_rejects_it_for_xai() {
(band): {"input":"12", "output":"60", "cacheRead":"0.6", "cacheWrite":"15"}
}
}))
.expect("Ultrafast override");
.expect("valid token price override");
let update = UpdatePricing {
provider: provider.to_owned(),
models: vec!["example-model".to_owned()],
@@ -131,12 +152,14 @@ async fn pricing_accepts_ultrafast_for_openai_but_rejects_it_for_xai() {
.settings()
.update_pricing(&context, update.clone())
.await;
if provider == "openai" {
result.expect("OpenAI accepts Ultrafast overrides");
assert_eq!(store.updated.lock().unwrap().as_ref(), Some(&update));
if supported.contains(&band) {
result.expect("provider accepts its supported band");
assert_eq!(store.updated.lock().unwrap().take(), Some(update));
} else {
assert_eq!(
result.expect_err("xAI rejects Ultrafast").kind(),
result
.expect_err("provider rejects unsupported band")
.kind(),
AdminErrorKind::Invalid
);
assert!(store.updated.lock().unwrap().is_none());
@@ -259,10 +282,11 @@ impl SettingsStore for PricingSettingsStore {
async fn sync_pricing(
&self,
_: gateway_admin::model::pricing::PricingSyncChanges,
command: gateway_admin::model::pricing::PricingSyncChanges,
_: &MutationContext,
) -> AdminStoreResult<Revision> {
panic!("unexpected pricing sync")
*self.synced.lock().unwrap() = Some(command);
Ok(Revision::new(2).unwrap())
}
async fn update_pricing(
@@ -325,6 +349,8 @@ 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 {
openai_oauth_guardian_review_model: true,
openai_request_country: Default::default(),
codex_privacy_policy: Default::default(),
request_location_enabled: false,
request_location: Default::default(),
@@ -374,3 +400,89 @@ fn unused() -> AdminStoreError {
"unused in this test",
)
}
struct ReferencePrices(Mutex<PricingSyncPreview>);
#[async_trait]
impl gateway_admin::ports::pricing::PricingSource for ReferencePrices {
async fn fetch(
&self,
_: &gateway_admin::ports::pricing::PricingSourceScope,
) -> Result<PricingSyncPreview, gateway_admin::model::AdminError> {
Ok(self.0.lock().unwrap().clone())
}
}
#[tokio::test]
async fn external_reference_prices_project_to_exact_provider_ids_in_preview_and_sync() {
let price: gateway_core::metering::ModelPriceOverride = serde_json::from_value(serde_json::json!({"multiplierBps":10000,"bands":{"standard":{"input":"1","output":"2","cacheRead":"0.1","cacheWrite":"1"}}})).unwrap();
let source = Arc::new(ReferencePrices(Mutex::new(PricingSyncPreview {
prices: BTreeMap::from([(
"google".into(),
BTreeMap::from([
("base-model".into(), price.clone()),
("unmapped".into(), price),
]),
)]),
skipped: vec!["google/missing".into(), "google/unrelated-image".into()],
})));
let mut provider = super::UnavailableProvider::new("antigravity");
provider.pricing_references = BTreeMap::from([
("ag-high".into(), ("google".into(), "base-model".into())),
("ag-low".into(), ("google".into(), "base-model".into())),
("ag-image".into(), ("google".into(), "missing".into())),
]);
let store = Arc::new(PricingSettingsStore::default());
let service = gateway_admin::initialize_settings(
store.clone(),
Arc::new(super::NoopSnapshot),
gateway_admin::ports::provider::ProviderAdminRegistry::new(vec![
Arc::new(provider) as Arc<dyn gateway_admin::ports::provider::ProviderAdmin>
])
.unwrap(),
source.clone(),
);
let preview = service.preview_pricing_sync().await.unwrap();
assert_eq!(
preview.prices.keys().cloned().collect::<Vec<_>>(),
["antigravity"]
);
assert_eq!(
preview.prices["antigravity"]
.keys()
.cloned()
.collect::<Vec<_>>(),
["ag-high", "ag-low"]
);
assert_eq!(preview.skipped, ["antigravity/ag-image"]);
// 未登记外部型号的变化不会污染同步确认,但实际保存仍重新读取并校验投影价目
source
.0
.lock()
.unwrap()
.prices
.get_mut("google")
.unwrap()
.remove("unmapped");
service
.sync_pricing(
&MutationContext {
actor: gateway_admin::model::MutationActor::System,
request_id: "reference-sync".into(),
},
SyncPricing {
preview,
models: BTreeMap::from([(
"antigravity".into(),
BTreeSet::from(["ag-high".into()]),
)]),
},
)
.await
.unwrap();
let saved = store.synced.lock().unwrap();
let saved = saved.as_ref().unwrap();
assert_eq!(
saved["antigravity"].keys().cloned().collect::<Vec<_>>(),
["ag-high"]
);
}
@@ -0,0 +1,4 @@
//! 系统管理用例测试
mod preflight;
mod service;
@@ -327,7 +327,7 @@ impl SystemOperations for PreflightingSystem {
#[tokio::test]
async fn system_update_accepts_compatible_enabled_plugins_at_the_same_revision() {
let fixture = Fixture::new(requirements("^1.0", "executor"), &[7]);
let services = super::AdminHarness::new()
let services = crate::use_case::AdminHarness::new()
.plugins(fixture.clone(), fixture)
.system(Arc::new(PreflightingSystem {
candidate: candidate("executor"),
@@ -345,7 +345,7 @@ async fn system_update_accepts_compatible_enabled_plugins_at_the_same_revision()
#[tokio::test]
async fn rollback_preserves_plugins_when_target_capability_is_missing() {
let incompatible = Fixture::new(requirements("^1.0", "executor"), &[7]);
let services = super::AdminHarness::new()
let services = crate::use_case::AdminHarness::new()
.plugins(incompatible.clone(), incompatible.clone())
.system(Arc::new(PreflightingSystem {
candidate: candidate("models"),
@@ -363,7 +363,7 @@ async fn rollback_preserves_plugins_when_target_capability_is_missing() {
#[tokio::test]
async fn system_update_rejects_revision_changes() {
let stale = Fixture::new(requirements("^1.0", "executor"), &[7, 8]);
let services = super::AdminHarness::new()
let services = crate::use_case::AdminHarness::new()
.plugins(stale.clone(), stale)
.system(Arc::new(PreflightingSystem {
candidate: candidate("executor"),
@@ -392,7 +392,7 @@ async fn system_update_accepts_new_plugin_contracts_for_empty_disabled_and_enabl
manifest["plugin_host"] =
serde_json::json!({"schema_version": 99, "future_contract": true});
candidate.release_manifest = serde_json::to_vec(&manifest).unwrap().into();
let services = super::AdminHarness::new()
let services = crate::use_case::AdminHarness::new()
.plugins(fixture.clone(), fixture)
.system(Arc::new(PreflightingSystem { candidate }))
.build()
@@ -420,7 +420,7 @@ async fn system_update_keeps_release_identity_validation_without_plugins() {
serde_json::from_slice(&candidate.release_manifest).unwrap();
manifest[field] = value;
candidate.release_manifest = serde_json::to_vec(&manifest).unwrap().into();
let services = super::AdminHarness::new()
let services = crate::use_case::AdminHarness::new()
.plugins(fixture.clone(), fixture)
.system(Arc::new(PreflightingSystem { candidate }))
.build()
@@ -440,7 +440,7 @@ async fn system_update_keeps_release_identity_validation_without_plugins() {
async fn system_update_still_rechecks_revision_without_plugins() {
let mut fixture = Fixture::new(requirements("^1.0", "executor"), &[7, 8]);
Arc::get_mut(&mut fixture).unwrap().instances.clear();
let services = super::AdminHarness::new()
let services = crate::use_case::AdminHarness::new()
.plugins(fixture.clone(), fixture)
.system(Arc::new(PreflightingSystem {
candidate: candidate("executor"),
@@ -510,7 +510,7 @@ fn context() -> MutationContext {
#[tokio::test]
async fn incompatible_restart_requires_exact_confirmation_and_preserves_enabled_plugins() {
let fixture = Fixture::new(requirements("^1.0", "executor"), &[7]);
let services = super::AdminHarness::new()
let services = crate::use_case::AdminHarness::new()
.plugins(fixture.clone(), fixture.clone())
.system(Arc::new(PreflightingSystem {
candidate: candidate("models"),
@@ -563,7 +563,7 @@ async fn incompatible_restart_requires_exact_confirmation_and_preserves_enabled_
#[tokio::test]
async fn compatible_restart_does_not_change_plugin_configuration() {
let fixture = Fixture::new(requirements("^1.0", "executor"), &[7]);
let services = super::AdminHarness::new()
let services = crate::use_case::AdminHarness::new()
.plugins(fixture.clone(), fixture.clone())
.system(Arc::new(PreflightingSystem {
candidate: candidate("executor"),
@@ -587,7 +587,7 @@ async fn compatible_restart_does_not_change_plugin_configuration() {
#[tokio::test]
async fn changed_configuration_after_restart_check_requires_a_new_confirmation() {
let fixture = Fixture::new(requirements("^1.0", "executor"), &[7, 8]);
let services = super::AdminHarness::new()
let services = crate::use_case::AdminHarness::new()
.plugins(fixture.clone(), fixture.clone())
.system(Arc::new(PreflightingSystem {
candidate: candidate("models"),
@@ -137,7 +137,10 @@ async fn system_failure_should_preserve_safe_message_source_and_redaction_marker
),
..RecordingSystemOperations::default()
});
let services = super::AdminHarness::new().system(operations).build().await;
let services = super::super::AdminHarness::new()
.system(operations)
.build()
.await;
let error = services.system().version().await.expect_err("host failure");
assert_eq!(
error.kind(),
@@ -154,7 +157,7 @@ async fn system_failure_should_preserve_safe_message_source_and_redaction_marker
#[tokio::test]
async fn system_update_should_normalize_blank_target_to_latest() {
let operations = std::sync::Arc::new(RecordingSystemOperations::default());
let services = super::AdminHarness::new()
let services = super::super::AdminHarness::new()
.system(operations.clone())
.build()
.await;
@@ -170,7 +173,7 @@ async fn system_update_should_normalize_blank_target_to_latest() {
#[tokio::test]
async fn system_update_should_forward_the_confirmed_channel() {
let operations = std::sync::Arc::new(RecordingSystemOperations::default());
let services = super::AdminHarness::new()
let services = super::super::AdminHarness::new()
.system(operations.clone())
.build()
.await;
@@ -0,0 +1,108 @@
//! 跨模块行为合同测试
use super::*;
#[test]
fn counters_preserve_integer_precision_and_reject_json_numbers() {
assert_eq!(
serde_json::from_value::<UsageCount>(json!(u64::MAX.to_string()))
.unwrap()
.get(),
u64::MAX
);
assert_eq!(
serde_json::from_value::<UsageDelta>(json!(i64::MIN.to_string()))
.unwrap()
.get(),
i64::MIN
);
for value in [json!(1), json!("1.5"), json!("+1")] {
assert!(serde_json::from_value::<UsageCount>(value.clone()).is_err());
assert!(serde_json::from_value::<UsageDelta>(value).is_err());
}
}
#[tokio::test]
async fn usage_mutations_require_a_trusted_actor() {
let admin = super::super::AdminHarness::new().build().await;
let registry = admin.public_services();
let denied = registry
.call("usage.records.write", json!({"changes":[]}))
.await
.unwrap_err();
assert!(denied.message.contains("trusted caller"));
assert!(
registry
.call(
"usage.records.write",
json!({"changes":[],"actor":{"kind":"system"}})
)
.await
.is_err()
);
}
#[test]
fn sdk_wire_types_match_host_contracts() {
use quote::ToTokens as _;
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
let items = |path: std::path::PathBuf| {
syn::parse_file(&std::fs::read_to_string(path).unwrap())
.unwrap()
.items
.into_iter()
.filter(|item| {
matches!(
item,
syn::Item::Struct(_)
| syn::Item::Enum(_)
| syn::Item::Impl(_)
| syn::Item::Type(_)
)
})
.map(|item| item.into_token_stream().to_string())
.collect::<Vec<_>>()
};
for name in [
"value.rs",
"record.rs",
"query.rs",
"read.rs",
"aggregate.rs",
"pricing.rs",
"error.rs",
] {
assert_eq!(
items(root.join("src/model/usage_data").join(name)),
items(
root.join("../gateway-plugin/sdk/src/call/services/usage")
.join(name)
),
"{name}"
);
}
}
#[tokio::test]
async fn batch_and_wire_limits_fail_before_reaching_storage() {
let admin = super::super::AdminHarness::new().build().await;
let registry = admin.public_services();
let changes = (0..501)
.map(|i| json!({"kind":"delete","id":format!("item_{i}")}))
.collect::<Vec<_>>();
let too_many = gateway_admin::public_service::scope_actor(
UsageActor::System,
registry.call("usage.records.write", json!({"changes":changes})),
)
.await
.unwrap_err();
assert_eq!(too_many.kind, "capacity_exceeded");
let oversized = registry
.call(
"usage.records.get",
json!({"id":"x".repeat(USAGE_DATA_MAX_REQUEST_BYTES)}),
)
.await
.unwrap_err();
assert_eq!(oversized.kind, "capacity_exceeded");
}
@@ -1,105 +1,5 @@
//! 用量服务的 wire 精度、可信主体和独立 SDK 合同校验
use gateway_admin::model::usage_data::*;
use serde_json::json;
#[test]
fn counters_preserve_integer_precision_and_reject_json_numbers() {
assert_eq!(
serde_json::from_value::<UsageCount>(json!(u64::MAX.to_string()))
.unwrap()
.get(),
u64::MAX
);
assert_eq!(
serde_json::from_value::<UsageDelta>(json!(i64::MIN.to_string()))
.unwrap()
.get(),
i64::MIN
);
for value in [json!(1), json!("1.5"), json!("+1")] {
assert!(serde_json::from_value::<UsageCount>(value.clone()).is_err());
assert!(serde_json::from_value::<UsageDelta>(value).is_err());
}
}
#[tokio::test]
async fn usage_mutations_require_a_trusted_actor() {
let admin = super::AdminHarness::new().build().await;
let registry = admin.public_services();
let denied = registry
.call("usage.records.write", json!({"changes":[]}))
.await
.unwrap_err();
assert!(denied.message.contains("trusted caller"));
assert!(
registry
.call(
"usage.records.write",
json!({"changes":[],"actor":{"kind":"system"}})
)
.await
.is_err()
);
}
#[test]
fn sdk_wire_types_match_host_contracts() {
use quote::ToTokens as _;
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
let items = |path: std::path::PathBuf| {
syn::parse_file(&std::fs::read_to_string(path).unwrap())
.unwrap()
.items
.into_iter()
.filter(|item| {
matches!(
item,
syn::Item::Struct(_)
| syn::Item::Enum(_)
| syn::Item::Impl(_)
| syn::Item::Type(_)
)
})
.map(|item| item.into_token_stream().to_string())
.collect::<Vec<_>>()
};
for name in [
"value.rs",
"record.rs",
"query.rs",
"read.rs",
"aggregate.rs",
"pricing.rs",
"error.rs",
] {
assert_eq!(
items(root.join("src/model/usage_data").join(name)),
items(
root.join("../gateway-plugin/sdk/src/call/services/usage")
.join(name)
),
"{name}"
);
}
}
#[tokio::test]
async fn batch_and_wire_limits_fail_before_reaching_storage() {
let admin = super::AdminHarness::new().build().await;
let registry = admin.public_services();
let changes = (0..501)
.map(|i| json!({"kind":"delete","id":format!("item_{i}")}))
.collect::<Vec<_>>();
let too_many = gateway_admin::public_service::scope_actor(
UsageActor::System,
registry.call("usage.records.write", json!({"changes":changes})),
)
.await
.unwrap_err();
assert_eq!(too_many.kind, "capacity_exceeded");
let oversized = registry
.call(
"usage.records.get",
json!({"id":"x".repeat(USAGE_DATA_MAX_REQUEST_BYTES)}),
)
.await
.unwrap_err();
assert_eq!(oversized.kind, "capacity_exceeded");
}
mod contract;
@@ -1,6 +1,6 @@
//! 账号分组管理的 HTTP 数据合同与固定路由
use crate::auth::SessionState;
use crate::SessionState;
use std::collections::BTreeMap;
@@ -21,12 +21,15 @@ use gateway_admin::model::{
UpdateAccountGroup,
},
};
use gateway_core::{account::FastMode, routing::AccountGroupId};
use gateway_core::{
account::{AccountModelAccess, FastMode},
routing::AccountGroupId,
};
use serde::{Deserialize, Serialize};
use super::{
AdminAuth, AdminEnvelope, AdminError, AdminJson, AdminQuery, AdminResponse, PageMeta,
WireValidationError, wire::map_admin_service_error,
WireValidationError, accounts::AccountModelView, wire::map_admin_service_error,
};
/// 账号、代理与 Client Key 共用的分组引用
@@ -51,7 +54,6 @@ impl From<gateway_admin::model::account_groups::AccountGroupRef> for AccountGrou
}
const DEFAULT_PAGE_SIZE: u32 = 50;
const MAX_PAGE_SIZE: u32 = 200;
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
@@ -66,7 +68,7 @@ impl ListAccountGroupsQuery {
fn into_command(self) -> Result<AccountGroupListQuery, WireValidationError> {
let page = self.page.unwrap_or(1);
let page_size = self.page_size.unwrap_or(DEFAULT_PAGE_SIZE);
if page == 0 || page_size == 0 || page_size > MAX_PAGE_SIZE {
if page == 0 {
return Err(WireValidationError::new("page"));
}
let search = self
@@ -91,15 +93,19 @@ impl ListAccountGroupsQuery {
}
}
const fn default_allow_image_generation() -> bool {
const fn default_allowed() -> bool {
true
}
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct CreateAccountGroupRequest {
#[serde(default = "default_allow_image_generation")]
#[serde(default = "default_allowed")]
allow_image_generation: bool,
#[serde(default = "default_allowed")]
allow_subagents: bool,
#[serde(default)]
model_access: AccountModelAccess,
#[serde(default)]
fast_mode: FastMode,
name: String,
@@ -111,6 +117,8 @@ struct CreateAccountGroupRequest {
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct UpdateAccountGroupRequest {
allow_image_generation: Option<bool>,
allow_subagents: Option<bool>,
model_access: Option<AccountModelAccess>,
fast_mode: Option<FastMode>,
id: String,
name: String,
@@ -128,6 +136,8 @@ struct AccountGroupIdRequest {
#[serde(rename_all = "camelCase")]
struct AccountGroupView {
allow_image_generation: bool,
allow_subagents: bool,
model_access: AccountModelAccess,
fast_mode: FastMode,
id: String,
name: String,
@@ -176,6 +186,8 @@ impl From<(AccountGroupRecord, crate::time::TimePresenter)> for AccountGroupView
description: record.description,
fast_mode: record.fast_mode,
allow_image_generation: record.allow_image_generation,
allow_subagents: record.allow_subagents,
model_access: record.model_access,
color: record.color.as_str().to_owned(),
enabled: record.enabled,
member_count: record.member_count,
@@ -305,6 +317,7 @@ where
{
Router::new()
.route("/api/admin/account-groups", get(list::<S>))
.route("/api/admin/account-groups/models", get(models::<S>))
.route("/api/admin/account-groups/options", get(list_options::<S>))
.route("/api/admin/account-groups/create", post(create::<S>))
.route("/api/admin/account-groups/update", post(update::<S>))
@@ -333,6 +346,32 @@ where
))
}
#[derive(Serialize)]
struct AccountGroupModelsData {
models: Vec<AccountModelView>,
}
async fn models<S>(
_auth: AdminAuth,
State(state): State<S>,
AdminQuery(query): AdminQuery<AccountGroupIdRequest>,
) -> Result<impl IntoResponse, AdminError>
where
S: SessionState + Send + Sync,
{
let models = state
.admin_services()
.account_groups()
.models(&group_id(query.id)?)
.map_err(map_service_error)?;
Ok(AdminResponse::new(
StatusCode::OK,
AdminEnvelope::ok(AccountGroupModelsData {
models: models.into_iter().map(AccountModelView::from).collect(),
}),
))
}
async fn list<S>(
_auth: AdminAuth,
State(state): State<S>,
@@ -372,6 +411,8 @@ where
&auth.context().mutation_context(),
CreateAccountGroup {
allow_image_generation: request.allow_image_generation,
allow_subagents: request.allow_subagents,
model_access: request.model_access,
name: request.name,
description: request.description,
fast_mode: request.fast_mode,
@@ -401,6 +442,8 @@ where
&auth.context().mutation_context(),
UpdateAccountGroup {
allow_image_generation: request.allow_image_generation,
allow_subagents: request.allow_subagents,
model_access: request.model_access,
id: group_id(request.id)?,
name: request.name,
description: request.description,
@@ -507,11 +550,16 @@ fn group_color(value: &str) -> Result<AccountGroupColor, AdminError> {
fn validate_group_fields(name: &str, description: Option<&str>) -> Result<(), AdminError> {
gateway_admin::model::account_groups::validate_group_fields(name, description)
.map_err(|_| AdminError::bad_request("账号组请求不合法"))
.map_err(map_admin_service_error)
}
fn map_wire_error(_: WireValidationError) -> AdminError {
AdminError::bad_request("账号组查询参数不合法")
fn map_wire_error(error: WireValidationError) -> AdminError {
match error.field() {
"page" => AdminError::bad_request("页码须大于 0"),
"pageSize" => AdminError::bad_request(format!("每页数量须为 1 至 {}", PageSize::MAX)),
"search" => AdminError::bad_request("搜索内容最多 256 字节,不能包含控制字符"),
field => AdminError::bad_request(format!("{field} 字段不合法")),
}
}
fn map_service_error(error: gateway_admin::model::AdminError) -> AdminError {
@@ -1,7 +1,7 @@
//! 账号普通池并发明细的有界实时查询
use super::*;
use crate::auth::SessionState;
use crate::SessionState;
#[derive(Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
@@ -118,7 +118,6 @@ pub struct StartAccountAuthorizationRequest {
pub provider: String,
pub name: String,
pub account_id: Option<String>,
pub outbound_proxy_url: Option<super::wire::AccountProxyUpdate>,
}
impl StartAccountAuthorizationRequest {
@@ -148,10 +147,7 @@ impl StartAccountAuthorizationRequest {
context,
name: self.name.trim().to_owned(),
reauthorization,
outbound_proxy: super::wire::proxy_selection(
self.outbound_proxy_id,
self.outbound_proxy_url,
)?,
outbound_proxy: super::wire::proxy_selection(self.outbound_proxy_id)?,
},
))
}
@@ -219,7 +215,6 @@ fn validate_authorization_flow(
pub struct UpdateAccountRequest {
pub connection: Option<AccountConnectionUpdateRequest>,
pub outbound_proxy_id: Option<String>,
pub outbound_proxy_url: Option<super::wire::AccountProxyUpdate>,
pub account_id: String,
pub name: Option<String>,
pub notes: Option<String>,
@@ -255,10 +250,7 @@ impl UpdateAccountRequest {
.connection
.map(AccountConnectionUpdateRequest::into_document);
let settings = UpdateAccount {
outbound_proxy: super::wire::proxy_selection(
self.outbound_proxy_id,
self.outbound_proxy_url,
)?,
outbound_proxy: super::wire::proxy_selection(self.outbound_proxy_id)?,
account_id: self.account_id,
name: self.name.map(|name| name.trim().to_owned()),
notes: self.notes,
@@ -2,7 +2,7 @@
use gateway_core::engine::probe::AccountProbeTarget;
use crate::auth::SessionState;
use crate::SessionState;
use super::*;
@@ -7,7 +7,7 @@ use gateway_admin::model::import_tasks::{
use sha2::{Digest as _, Sha256};
use super::*;
use crate::auth::SessionState;
use crate::SessionState;
pub(super) fn router<S>() -> Router<S>
where
@@ -53,13 +53,7 @@ pub(super) fn account_models_data(
models: result
.models
.into_iter()
.map(|model| {
let id = model.id.to_string();
AccountModelView {
label: id.clone(),
id,
}
})
.map(|model| AccountModelView::from(model.id))
.collect(),
observed_at: observed_at.map(|value| time.rfc3339(&value)),
observed_at_display: observed_at
@@ -79,6 +73,7 @@ pub(super) fn account_view(
plan_type_display,
projection,
usage,
usage_period,
quota,
protection_rules,
} = item;
@@ -90,7 +85,6 @@ pub(super) fn account_view(
.map(|value| time.rfc3339(value));
let added_at = time.rfc3339(&account.created_at);
let updated_at = time.rfc3339(&account.updated_at);
let usage_period = quota.usage_window().map(|(_, period)| period);
let mut usage = account_usage_view(usage, usage_period, now, time);
if account.authentication_kind == "api_key" {
usage.window_kind = if quota
@@ -2,46 +2,22 @@
use super::*;
#[derive(Debug, Clone)]
pub struct AccountProxyUpdate(pub Option<gateway_core::account::OutboundProxy>);
impl<'de> Deserialize<'de> for AccountProxyUpdate {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let value = String::deserialize(deserializer)?;
if value.is_empty() {
return Ok(Self(None));
}
gateway_core::account::OutboundProxy::parse(&value)
.map(|proxy| Self(Some(proxy)))
.map_err(serde::de::Error::custom)
}
}
pub(super) fn proxy_selection(
id: Option<String>,
url: Option<AccountProxyUpdate>,
) -> Result<Option<gateway_admin::model::proxies::AccountProxySelection>, WireValidationError> {
use gateway_admin::model::proxies::AccountProxySelection;
match (id, url) {
(Some(_), Some(_)) => Err(WireValidationError::new("outboundProxyId")),
(Some(id), None) if id.is_empty() => Ok(Some(AccountProxySelection::Direct)),
(Some(id), None) => {
if id.len() > 128
|| !id
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-'))
{
return Err(WireValidationError::new("outboundProxyId"));
}
Ok(Some(AccountProxySelection::Saved(id)))
}
(None, Some(value)) => Ok(Some(
value
.0
.map_or(AccountProxySelection::Direct, AccountProxySelection::Url),
)),
(None, None) => Ok(None),
let Some(id) = id else { return Ok(None) };
if id.is_empty() {
return Ok(Some(AccountProxySelection::Direct));
}
if id.len() > 128
|| !id
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-'))
{
return Err(WireValidationError::new("outboundProxyId"));
}
Ok(Some(AccountProxySelection::Saved(id)))
}
/// 账号列表查询参数
@@ -64,7 +40,6 @@ pub struct BatchUpdateAccountsRequest {
pub quota_settings: Option<gateway_core::account::AccountQuotaSettings>,
pub auto_use_quota_credits: Option<bool>,
pub outbound_proxy_id: Option<String>,
pub outbound_proxy_url: Option<AccountProxyUpdate>,
pub account_ids: Vec<String>,
pub enabled: Option<bool>,
#[serde(default, deserialize_with = "deserialize_optional_nullable_limit")]
@@ -127,7 +102,6 @@ impl BatchUpdateAccountsRequest {
&& self.group_ids.is_none()
&& self.model_access.is_none()
&& self.outbound_proxy_id.is_none()
&& self.outbound_proxy_url.is_none()
{
return Err(WireValidationError::new("accountSettings"));
}
@@ -139,7 +113,7 @@ impl BatchUpdateAccountsRequest {
Ok(BatchUpdateAccounts {
quota_settings: self.quota_settings,
auto_use_quota_credits: self.auto_use_quota_credits,
outbound_proxy: proxy_selection(self.outbound_proxy_id, self.outbound_proxy_url)?,
outbound_proxy: proxy_selection(self.outbound_proxy_id)?,
account_ids: self.account_ids,
enabled: self.enabled,
concurrency_limit: self
@@ -327,6 +301,10 @@ pub struct AccountCapacityView {
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AccountCapabilitiesView {
pub credential_refresh: bool,
pub reauthorize: bool,
pub credential_export: bool,
pub model_catalog_download: bool,
pub quota_settings_supported: bool,
pub quota_credits: bool,
pub quota: bool,
@@ -341,6 +319,10 @@ pub struct AccountCapabilitiesView {
impl From<gateway_admin::model::accounts::ProviderAccountCapabilities> for AccountCapabilitiesView {
fn from(value: gateway_admin::model::accounts::ProviderAccountCapabilities) -> Self {
Self {
credential_refresh: value.credential_refresh,
reauthorize: value.reauthorize,
credential_export: value.credential_export,
model_catalog_download: value.model_catalog_download,
quota: value.quota,
quota_refresh: value.quota_refresh,
profile: value.profile,
@@ -743,6 +725,16 @@ pub struct AccountModelView {
pub label: String,
}
impl From<UpstreamModelId> for AccountModelView {
fn from(model: UpstreamModelId) -> Self {
let id = model.to_string();
Self {
label: id.clone(),
id,
}
}
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AccountModelsData {
+2 -2
View File
@@ -7,7 +7,7 @@ use axum::{
use gateway_admin::model::auth::{AdminPrincipal, AdminRequestContext};
use tower_http::request_id::RequestId;
use crate::{auth::SessionState, session_cookie};
use crate::{SessionState, session};
use super::{AdminError, wire::map_admin_service_error};
@@ -71,7 +71,7 @@ where
match state
.admin_services()
.auth()
.resolve_admin_user_id(session_cookie::value(headers).as_deref())
.resolve_admin_user_id(session::value(headers).as_deref())
.await
{
Ok(Some(admin_user_id)) => Ok(admin_user_id),
+23 -12
View File
@@ -3,7 +3,7 @@
//!
//! 路径统一位于 `/api/admin/settings/backups/*`,内部由独立 `BackupService` 承担业务
use crate::auth::SessionState;
use crate::SessionState;
use axum::{
Router,
@@ -17,7 +17,7 @@ use gateway_admin::model::backup::{
BackupRecord, BackupSettings, BackupStatus, BackupTriggerKind, ConnectionTestResult,
UpdateBackupScheduleCommand, UpdateBackupStorageCommand,
};
use secrecy::{ExposeSecret as _, SecretString};
use secrecy::SecretString;
use serde::{Deserialize, Serialize};
use super::{
@@ -25,7 +25,7 @@ use super::{
PageMeta, wire::map_admin_service_error,
};
/// 备份设置视图;`secretAccessKey` 返回已保存的明文凭据,由前端掩码显示
/// 读写响应只公开 Secret 的配置状态
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BackupSettingsView {
@@ -34,7 +34,7 @@ pub struct BackupSettingsView {
pub region: Option<String>,
pub bucket: Option<String>,
pub access_key_id: Option<String>,
pub secret_access_key: Option<String>,
pub secret_configured: bool,
pub prefix: Option<String>,
pub force_path_style: bool,
pub verified: bool,
@@ -59,9 +59,7 @@ impl From<(BackupSettings, crate::time::TimePresenter)> for BackupSettingsView {
region: settings.region,
bucket: settings.bucket,
access_key_id: settings.access_key_id,
secret_access_key: settings
.secret_access_key
.map(|secret| secret.expose_secret().to_owned()),
secret_configured: settings.secret_access_key.is_some(),
prefix: settings.prefix,
force_path_style: settings.force_path_style,
verified,
@@ -86,9 +84,10 @@ impl From<(BackupSettings, crate::time::TimePresenter)> for BackupSettingsView {
}
/// 更新 S3 存储配置请求;`secretAccessKey` 缺省表示保留旧值
#[derive(Debug, Clone, Deserialize)]
#[derive(Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct UpdateBackupStorageRequest {
pub storage_revision: u64,
pub endpoint: String,
pub region: String,
pub bucket: String,
@@ -103,6 +102,7 @@ pub struct UpdateBackupStorageRequest {
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct UpdateBackupScheduleRequest {
pub storage_revision: u64,
pub schedule_enabled: bool,
pub cron_expression: String,
pub retention_days: u32,
@@ -206,19 +206,27 @@ impl From<gateway_admin::model::backup::DownloadUrlResult> for DownloadUrlView {
}
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct TestBackupStorageRequest {
storage_revision: u64,
}
/// 连接测试响应
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ConnectionTestView {
pub storage_revision: u64,
pub ok: bool,
pub stage: String,
pub code: Option<String>,
pub message: String,
}
impl From<ConnectionTestResult> for ConnectionTestView {
fn from(result: ConnectionTestResult) -> Self {
impl From<(u64, ConnectionTestResult)> for ConnectionTestView {
fn from((storage_revision, result): (u64, ConnectionTestResult)) -> Self {
Self {
storage_revision,
ok: result.ok,
stage: result.stage.to_owned(),
code: result.code.map(str::to_owned),
@@ -294,6 +302,7 @@ where
{
let time = crate::time::TimePresenter::new(state.admin_services().timezone());
let command = UpdateBackupStorageCommand {
storage_revision: request.storage_revision,
endpoint: request.endpoint,
region: request.region,
bucket: request.bucket,
@@ -317,6 +326,7 @@ where
async fn test_backup_storage<S>(
auth: AdminAuth,
State(state): State<S>,
AdminJson(request): AdminJson<TestBackupStorageRequest>,
) -> Result<impl IntoResponse, AdminError>
where
S: SessionState + Send + Sync,
@@ -324,12 +334,12 @@ where
let result = state
.admin_services()
.backups()
.test_connection(&auth.context().mutation_context())
.test_connection(&auth.context().mutation_context(), request.storage_revision)
.await
.map_err(map_service_error)?;
Ok(AdminResponse::new(
StatusCode::OK,
AdminEnvelope::ok(ConnectionTestView::from(result)),
AdminEnvelope::ok(ConnectionTestView::from((request.storage_revision, result))),
))
}
@@ -343,6 +353,7 @@ where
{
let time = crate::time::TimePresenter::new(state.admin_services().timezone());
let command = UpdateBackupScheduleCommand {
storage_revision: request.storage_revision,
schedule_enabled: request.schedule_enabled,
cron_expression: request.cron_expression,
retention_days: request.retention_days,
@@ -0,0 +1,291 @@
//! 管理员查看单个密钥的模型统计与手动对齐本期额度的接口
use axum::{Router, extract::State, http::StatusCode, response::IntoResponse, routing::get};
use chrono::{DateTime, Utc};
use gateway_admin::model::observability::{KeyStatisticsOverview, KeyUsageMetric, TimeRange};
use gateway_admin::{
AdminServices,
model::client_keys::{
ClientKeyBudgetMutationOrigin, ClientKeyBudgetReference, ClientKeyBudgetWindowPeriod,
SetClientKeyBudgetWindow,
},
};
use gateway_core::{account::ProviderAccountId, policy::ClientApiKeyId};
use serde::{Deserialize, Serialize};
use super::{
AdminAuth, AdminEnvelope, AdminError, AdminJson, AdminQuery, AdminResponse,
client_keys::ClientBudgetView, wire::map_admin_service_error,
};
use crate::{SessionState, time::TimePresenter};
pub(super) fn router<S: SessionState + Clone + Send + Sync + 'static>() -> Router<S> {
Router::new()
.route(
"/api/admin/client-keys/budget-reference-accounts",
get(accounts::<S>),
)
.route("/api/admin/client-keys/statistics", get(statistics::<S>))
.route("/api/admin/client-keys/statistics/models", get(models::<S>))
.route(
"/api/admin/client-keys/budget-alignment",
get(preview::<S>).post(align::<S>),
)
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct StatisticsQuery {
id: String,
period: Option<String>,
#[serde(default)]
metric: KeyUsageMetric,
as_of: Option<i64>,
}
fn key_id(value: String) -> Result<ClientApiKeyId, AdminError> {
ClientApiKeyId::new(value).map_err(|_| AdminError::bad_request("API Key ID 无效"))
}
#[derive(Serialize)]
struct Statistics {
budget: ClientBudgetView,
dates: Vec<chrono::NaiveDate>,
#[serde(rename = "asOf")]
as_of: i64,
#[serde(flatten)]
overview: KeyStatisticsOverview,
}
async fn statistics<S: SessionState>(
_auth: AdminAuth,
State(state): State<S>,
AdminQuery(query): AdminQuery<StatisticsQuery>,
) -> Result<impl IntoResponse, AdminError> {
let services = state.admin_services();
let id = key_id(query.id.clone())?;
let tz = services.timezone();
let range = statistics_range(&query, tz)?;
let budget = services
.client_keys()
.budget(&id)
.await
.map_err(map_admin_service_error)?;
let overview = services
.observability()
.client_key_statistics(range, &id, query.metric)
.await
.map_err(map_admin_service_error)?;
let end = tz.local(range.end).date_naive();
let dates = tz
.local(range.start)
.date_naive()
.iter_days()
.take_while(|date| *date <= end)
.collect();
Ok(AdminResponse::new(
StatusCode::OK,
AdminEnvelope::ok(Statistics {
budget: ClientBudgetView::from((budget, TimePresenter::new(tz))),
dates,
as_of: range.end.timestamp_millis(),
overview,
}),
))
}
fn statistics_range(
query: &StatisticsQuery,
tz: gateway_core::time::DeploymentTimeZone,
) -> Result<TimeRange, AdminError> {
let period = query.period.as_deref().unwrap_or("7d");
if !matches!(period, "7d" | "30d") {
return Err(AdminError::bad_request("统计周期须为 7 天或 30 天"));
}
crate::time::query_range(
None,
None,
Some(period),
Some(query.as_of.unwrap_or_else(|| Utc::now().timestamp_millis())),
tz,
"7d",
)
.map_err(|_| AdminError::bad_request("统计时间范围无效"))
}
async fn models<S: SessionState>(
_auth: AdminAuth,
State(state): State<S>,
AdminQuery(query): AdminQuery<StatisticsQuery>,
) -> Result<impl IntoResponse, AdminError> {
let services = state.admin_services();
let range = statistics_range(&query, services.timezone())?;
let id = key_id(query.id)?;
services
.client_keys()
.budget(&id)
.await
.map_err(map_admin_service_error)?;
let items = services
.observability()
.client_key_models(range, &id)
.await
.map_err(map_admin_service_error)?;
Ok(AdminResponse::new(StatusCode::OK, AdminEnvelope::ok(items)))
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct AccountSearch {
id: String,
#[serde(default)]
search: String,
#[serde(default)]
cursor: String,
}
async fn accounts<S: SessionState>(
_auth: AdminAuth,
State(state): State<S>,
AdminQuery(query): AdminQuery<AccountSearch>,
) -> Result<impl IntoResponse, AdminError> {
let page = state
.admin_services()
.client_keys()
.budget_reference_accounts(&key_id(query.id)?, &query.search, &query.cursor)
.await
.map_err(map_admin_service_error)?;
Ok(AdminResponse::new(StatusCode::OK, AdminEnvelope::ok(page)))
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct ReferenceQuery {
id: String,
account_id: String,
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct ReferenceWindow {
key: String,
label: String,
period: &'static str,
starts_at: DateTime<Utc>,
ends_at: DateTime<Utc>,
starts_at_display: String,
ends_at_display: String,
}
#[derive(Serialize)]
struct Preview {
revision: u64,
windows: Vec<ReferenceWindow>,
}
async fn reference_windows(
services: &AdminServices,
id: &ClientApiKeyId,
account: String,
) -> Result<Vec<ClientKeyBudgetReference>, AdminError> {
let account_id =
ProviderAccountId::new(account).map_err(|_| AdminError::bad_request("参考账号 ID 无效"))?;
let key = services
.client_keys()
.get(id)
.await
.map_err(map_admin_service_error)?;
services
.accounts()
.key_budget_references(&account_id, &key.groups)
.await
.map_err(map_admin_service_error)
}
async fn preview<S: SessionState>(
_auth: AdminAuth,
State(state): State<S>,
AdminQuery(query): AdminQuery<ReferenceQuery>,
) -> Result<impl IntoResponse, AdminError> {
let services = state.admin_services();
let id = key_id(query.id)?;
let time = TimePresenter::new(services.timezone());
let windows = reference_windows(services, &id, query.account_id)
.await?
.into_iter()
.map(
|ClientKeyBudgetReference {
key,
label,
period,
bounds,
}| ReferenceWindow {
key,
label,
period: period.as_str(),
starts_at: bounds.starts_at,
ends_at: bounds.ends_at,
starts_at_display: time.datetime(&bounds.starts_at),
ends_at_display: time.datetime(&bounds.ends_at),
},
)
.collect();
// 日周窗口共享配置版本,普通请求的消费累计不会让预览失效
let revision = services
.client_keys()
.budget_window(&id, ClientKeyBudgetWindowPeriod::Weekly)
.await
.map_err(map_admin_service_error)?
.revision;
Ok(AdminResponse::new(
StatusCode::OK,
AdminEnvelope::ok(Preview { revision, windows }),
))
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct AlignRequest {
id: String,
account_id: String,
window_key: String,
starts_at: DateTime<Utc>,
ends_at: DateTime<Utc>,
revision: u64,
}
async fn align<S: SessionState>(
auth: AdminAuth,
State(state): State<S>,
AdminJson(input): AdminJson<AlignRequest>,
) -> Result<impl IntoResponse, AdminError> {
let services = state.admin_services();
let id = key_id(input.id)?;
let reference = reference_windows(services, &id, input.account_id)
.await?
.into_iter()
.find(|reference| {
reference.key == input.window_key
&& reference.bounds.starts_at == input.starts_at
&& reference.bounds.ends_at == input.ends_at
})
.ok_or_else(|| AdminError::conflict("参考窗口已变化,请重新预览"))?;
let revision = services
.client_keys()
.set_budget_window(
&auth.context().mutation_context(),
SetClientKeyBudgetWindow {
id,
period: reference.period,
expected_revision: input.revision,
window: Some(reference.bounds),
},
ClientKeyBudgetMutationOrigin::Admin,
)
.await
.map_err(map_admin_service_error)?;
Ok(AdminResponse::new(
StatusCode::OK,
AdminEnvelope::ok(revision),
))
}
@@ -1,17 +1,18 @@
//! Client API Key 管理 wire contract
use crate::auth::SessionState;
use crate::SessionState;
use std::{collections::BTreeMap, fmt};
use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
use chrono::{DateTime, Utc};
use gateway_admin::model::client_keys::{
ClientKeyBudgetPeriod, ClientKeyCursor, ClientKeyCursorValue as DomainCursorValue,
ClientKeyListQuery, ClientKeyMutation, ClientKeyPage, ClientKeyPageSize, ClientKeyRecord,
ClientKeySecret, ClientKeySort as DomainSort, ClientKeySortField as DomainSortField,
CreateClientKey, CreatedClientKey, DeleteClientKey, ResetClientKeyBudget, SetClientKeyEnabled,
SortDirection, UpdateClientKey,
BatchUpdateClientKeys, ClientKeyBudgetPeriod, ClientKeyCursor,
ClientKeyCursorValue as DomainCursorValue, ClientKeyListQuery, ClientKeyMutation,
ClientKeyPage, ClientKeyPageSize, ClientKeyRecord, ClientKeySecret,
ClientKeySort as DomainSort, ClientKeySortField as DomainSortField, CreateClientKey,
CreatedClientKey, DeleteClientKey, ResetClientKeyBudget, SetClientKeyEnabled, SortDirection,
UpdateClientKey,
};
use gateway_core::{
engine::budget::ClientBudgetLimits,
@@ -156,8 +157,6 @@ pub struct CreateClientKeyRequest {
peer_sharing: gateway_core::policy::ClientPeerSharing,
#[serde(default)]
provider_request_profile_overrides: ProviderRequestProfileOverrides,
openai_client_profile_override: Option<serde_json::Map<String, serde_json::Value>>,
xai_client_profile_override: Option<serde_json::Map<String, serde_json::Value>>,
custom_key: Option<String>,
name: String,
label: Option<String>,
@@ -186,11 +185,8 @@ impl CreateClientKeyRequest {
let group_ids = validate_group_ids(self.group_ids)?;
validate_limit(self.max_concurrency, "maxConcurrency")?;
validate_limit(self.requests_per_minute, "requestsPerMinute")?;
let request_profile_overrides = normalize_request_profile_overrides(
self.provider_request_profile_overrides,
self.openai_client_profile_override,
self.xai_client_profile_override,
)?;
let request_profile_overrides =
normalize_request_profile_overrides(self.provider_request_profile_overrides)?;
Ok(CreateClientKey {
peer_sharing: self.peer_sharing,
request_profile_overrides,
@@ -223,10 +219,6 @@ pub struct UpdateClientKeyRequest {
peer_sharing: Option<gateway_core::policy::ClientPeerSharing>,
#[serde(default)]
provider_request_profile_overrides: ProviderRequestProfileOverrideUpdates,
#[serde(default, deserialize_with = "deserialize_profile_override")]
openai_client_profile_override: Option<Option<serde_json::Map<String, serde_json::Value>>>,
#[serde(default, deserialize_with = "deserialize_profile_override")]
xai_client_profile_override: Option<Option<serde_json::Map<String, serde_json::Value>>>,
id: String,
name: String,
label: Option<String>,
@@ -246,11 +238,8 @@ impl UpdateClientKeyRequest {
let group_ids = validate_group_ids(self.group_ids)?;
validate_limit(self.max_concurrency, "maxConcurrency")?;
validate_limit(self.requests_per_minute, "requestsPerMinute")?;
let request_profile_override_updates = normalize_request_profile_override_updates(
self.provider_request_profile_overrides,
self.openai_client_profile_override,
self.xai_client_profile_override,
)?;
let request_profile_override_updates =
normalize_request_profile_override_updates(self.provider_request_profile_overrides)?;
Ok(UpdateClientKey {
peer_sharing: self.peer_sharing,
request_profile_override_updates,
@@ -335,16 +324,54 @@ impl ClientKeyMutationRequest {
}
}
#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub(super) struct ClientBudgetView {
daily_limit_usd: String,
weekly_limit_usd: String,
daily_used_usd: String,
weekly_used_usd: String,
daily_resets_at: Option<DateTime<Utc>>,
daily_resets_at_display: Option<String>,
weekly_resets_at: Option<DateTime<Utc>>,
weekly_resets_at_display: Option<String>,
}
impl
From<(
gateway_core::engine::budget::ClientBudgetStatus,
crate::time::TimePresenter,
)> for ClientBudgetView
{
fn from(
(budget, time): (
gateway_core::engine::budget::ClientBudgetStatus,
crate::time::TimePresenter,
),
) -> Self {
Self {
daily_limit_usd: budget.limits.daily_usd.canonical(),
weekly_limit_usd: budget.limits.weekly_usd.canonical(),
daily_used_usd: budget.daily_used_usd.canonical(),
weekly_used_usd: budget.weekly_used_usd.canonical(),
daily_resets_at_display: budget
.daily_resets_at()
.map(|value| time.datetime(&value.into())),
daily_resets_at: budget.daily_resets_at().map(DateTime::from),
weekly_resets_at_display: budget
.weekly_resets_at()
.map(|value| time.datetime(&value.into())),
weekly_resets_at: budget.weekly_resets_at().map(DateTime::from),
}
}
}
/// 不含完整 Key 的管理端安全视图
#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ClientKeyView {
peer_sharing: gateway_core::policy::ClientPeerSharing,
provider_request_profile_overrides: ProviderRequestProfileOverrides,
/// 固定兼容字段;值始终从 provider_request_profile_overrides 派生
openai_client_profile_override: Option<serde_json::Map<String, serde_json::Value>>,
/// 固定兼容字段;值始终从 provider_request_profile_overrides 派生
xai_client_profile_override: Option<serde_json::Map<String, serde_json::Value>>,
id: String,
name: String,
label: Option<String>,
@@ -355,14 +382,8 @@ pub struct ClientKeyView {
enabled: bool,
max_concurrency: u64,
requests_per_minute: u64,
daily_limit_usd: String,
weekly_limit_usd: String,
daily_used_usd: String,
weekly_used_usd: String,
daily_resets_at: Option<DateTime<Utc>>,
daily_resets_at_display: Option<String>,
weekly_resets_at: Option<DateTime<Utc>>,
weekly_resets_at_display: Option<String>,
#[serde(flatten)]
budget: ClientBudgetView,
created_at: DateTime<Utc>,
created_at_display: String,
updated_at: DateTime<Utc>,
@@ -385,10 +406,6 @@ impl From<(ClientKeyRecord, crate::time::TimePresenter)> for ClientKeyView {
.map(|(provider, profile)| (provider.as_str().to_owned(), profile.into_inner()))
.collect::<ProviderRequestProfileOverrides>();
Self {
openai_client_profile_override: provider_request_profile_overrides
.get("openai")
.cloned(),
xai_client_profile_override: provider_request_profile_overrides.get("xai").cloned(),
provider_request_profile_overrides,
peer_sharing: record.peer_sharing,
id: record.id.to_string(),
@@ -409,20 +426,7 @@ impl From<(ClientKeyRecord, crate::time::TimePresenter)> for ClientKeyView {
enabled: record.enabled,
max_concurrency: record.limits.max_concurrency,
requests_per_minute: record.limits.requests_per_minute,
daily_limit_usd: record.budget.limits.daily_usd.canonical(),
weekly_limit_usd: record.budget.limits.weekly_usd.canonical(),
daily_used_usd: record.budget.daily_used_usd.canonical(),
weekly_used_usd: record.budget.weekly_used_usd.canonical(),
daily_resets_at_display: record
.budget
.daily_resets_at()
.map(|value| time.datetime(&value.into())),
daily_resets_at: record.budget.daily_resets_at().map(DateTime::from),
weekly_resets_at_display: record
.budget
.weekly_resets_at()
.map(|value| time.datetime(&value.into())),
weekly_resets_at: record.budget.weekly_resets_at().map(DateTime::from),
budget: ClientBudgetView::from((record.budget, time)),
created_at_display: time.datetime(&record.created_at),
created_at: record.created_at,
updated_at_display: time.datetime(&record.updated_at),
@@ -739,16 +743,11 @@ fn validate_limit(value: u64, field: &'static str) -> Result<(), WireValidationE
fn normalize_request_profile_overrides(
profiles: ProviderRequestProfileOverrides,
openai: Option<serde_json::Map<String, serde_json::Value>>,
xai: Option<serde_json::Map<String, serde_json::Value>>,
) -> Result<gateway_admin::model::client_keys::ProviderRequestProfileOverrides, WireValidationError>
{
let mut normalized = profiles
profiles
.into_iter()
.map(|(provider, profile)| {
if !matches!(provider.as_str(), "openai" | "xai") {
return Err(WireValidationError::new("providerRequestProfileOverrides"));
}
validate_request_profile_size(&profile)?;
Ok((
ProviderKind::new(provider)
@@ -756,72 +755,28 @@ fn normalize_request_profile_overrides(
gateway_core::account::OpaqueProviderData::new(profile),
))
})
.collect::<Result<gateway_admin::model::client_keys::ProviderRequestProfileOverrides, _>>(
)?;
for (provider, profile) in [("openai", openai), ("xai", xai)] {
let Some(profile) = profile else {
continue;
};
validate_request_profile_size(&profile)?;
let provider = ProviderKind::new(provider).expect("static Provider kind is valid");
let profile = gateway_core::account::OpaqueProviderData::new(profile);
if normalized
.get(&provider)
.is_some_and(|current| current != &profile)
{
return Err(WireValidationError::new("providerRequestProfileOverrides"));
}
normalized.insert(provider, profile);
}
Ok(normalized)
.collect()
}
fn normalize_request_profile_override_updates(
profiles: ProviderRequestProfileOverrideUpdates,
openai: Option<Option<serde_json::Map<String, serde_json::Value>>>,
xai: Option<Option<serde_json::Map<String, serde_json::Value>>>,
) -> Result<
gateway_admin::model::client_keys::ProviderRequestProfileOverrideUpdates,
WireValidationError,
> {
let mut normalized = profiles
profiles
.into_iter()
.map(|(provider, profile)| {
if !matches!(provider.as_str(), "openai" | "xai") {
return Err(WireValidationError::new("providerRequestProfileOverrides"));
}
if let Some(profile) = profile.as_ref() {
validate_request_profile_size(profile)?;
}
Ok((
ProviderKind::new(provider).map_err(|_| {
WireValidationError::new("providerRequestProfileOverrides")
})?,
ProviderKind::new(provider)
.map_err(|_| WireValidationError::new("providerRequestProfileOverrides"))?,
profile.map(gateway_core::account::OpaqueProviderData::new),
))
})
.collect::<Result<
gateway_admin::model::client_keys::ProviderRequestProfileOverrideUpdates,
_,
>>()?;
for (provider, profile) in [("openai", openai), ("xai", xai)] {
let Some(profile) = profile else {
continue;
};
if let Some(profile) = profile.as_ref() {
validate_request_profile_size(profile)?;
}
let provider = ProviderKind::new(provider).expect("static Provider kind is valid");
let profile = profile.map(gateway_core::account::OpaqueProviderData::new);
if normalized
.get(&provider)
.is_some_and(|current| current != &profile)
{
return Err(WireValidationError::new("providerRequestProfileOverrides"));
}
normalized.insert(provider, profile);
}
Ok(normalized)
.collect()
}
fn validate_request_profile_size(
@@ -866,7 +821,12 @@ where
S: SessionState + Clone + Send + Sync + 'static,
{
Router::new()
.merge(super::client_key_usage::router::<S>())
.route("/api/admin/client-keys", get(list_client_keys::<S>))
.route(
"/api/admin/client-keys/batch-update",
post(batch_update_client_keys::<S>),
)
.route(
"/api/admin/client-keys/create",
post(create_client_key::<S>),
@@ -913,6 +873,94 @@ where
Ok(AdminResponse::new(StatusCode::OK, AdminEnvelope::ok(data)))
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct BatchUpdateClientKeysRequest {
ids: Vec<String>,
group_ids: Option<Vec<String>>,
enabled: Option<bool>,
max_concurrency: Option<u64>,
requests_per_minute: Option<u64>,
daily_limit_usd: Option<String>,
weekly_limit_usd: Option<String>,
peer_sharing: Option<gateway_admin::model::client_keys::ClientPeerSharingPatch>,
#[serde(default)]
provider_request_profile_overrides: ProviderRequestProfileOverrideUpdates,
installation_seed: Option<String>,
}
impl BatchUpdateClientKeysRequest {
/// 复用单把密钥的字段校验,缺省和显式零值分别保留
pub fn into_command(self) -> Result<BatchUpdateClientKeys, WireValidationError> {
if let Some(limit) = self.max_concurrency {
validate_limit(limit, "maxConcurrency")?;
}
if let Some(limit) = self.requests_per_minute {
validate_limit(limit, "requestsPerMinute")?;
}
let installation_seed = self
.installation_seed
.map(|value| {
if value.len() != uuid::fmt::Hyphenated::LENGTH {
return Err(WireValidationError::new("installationSeed"));
}
uuid::Uuid::try_parse(&value)
.map_err(|_| WireValidationError::new("installationSeed"))
})
.transpose()?;
Ok(BatchUpdateClientKeys {
ids: self
.ids
.into_iter()
.map(|id| client_key_id(id, "id"))
.collect::<Result<_, _>>()?,
group_ids: self.group_ids.map(validate_group_ids).transpose()?,
enabled: self.enabled,
max_concurrency: self.max_concurrency,
requests_per_minute: self.requests_per_minute,
daily_limit_usd: parse_budget(self.daily_limit_usd, "dailyLimitUsd")?,
weekly_limit_usd: parse_budget(self.weekly_limit_usd, "weeklyLimitUsd")?,
peer_sharing: self.peer_sharing.unwrap_or_default(),
request_profile_override_updates: normalize_request_profile_override_updates(
self.provider_request_profile_overrides,
)?,
installation_seed,
})
}
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct BatchUpdatedClientKeysData {
config_revision: gateway_admin::model::Revision,
updated: usize,
}
async fn batch_update_client_keys<S>(
auth: AdminAuth,
State(state): State<S>,
AdminJson(request): AdminJson<BatchUpdateClientKeysRequest>,
) -> Result<impl IntoResponse, AdminError>
where
S: SessionState + Send + Sync,
{
let command = request.into_command().map_err(map_wire_error)?;
let updated = command.ids.len();
let config_revision = state
.admin_services()
.client_keys()
.batch_update(&auth.context().mutation_context(), command)
.await
.map_err(map_service_error)?;
Ok(AdminResponse::new(
StatusCode::OK,
AdminEnvelope::ok(BatchUpdatedClientKeysData {
config_revision,
updated,
}),
))
}
async fn create_client_key<S>(
auth: AdminAuth,
State(state): State<S>,
@@ -1087,12 +1135,13 @@ fn map_wire_error(error: WireValidationError) -> AdminError {
"requestsPerMinute" => "每分钟请求上限超出支持范围",
"dailyLimitUsd" => "每日美元限额须非负,整数和小数各最多 10 位",
"weeklyLimitUsd" => "每周美元限额须非负,整数和小数各最多 10 位",
"providerRequestProfileOverrides" => "API Key 客户端身份配置无效或字段冲突",
"providerRequestProfileOverrides" => "API Key 客户端身份配置无效",
"installationSeed" => "安装身份种子必须是带连字符的 UUID",
"limit" => "每页数量须为 1 至 65535",
"search" => "搜索内容过长或包含控制字符",
"sortBy" => "排序字段不受支持",
"sortDirection" => "排序方向必须为 asc(升序)或 desc(降序)",
_ => "API Key 请求参数不合法",
field => return AdminError::bad_request(format!("{field} 字段不合法")),
};
AdminError::bad_request(message)
}
@@ -1100,10 +1149,3 @@ fn map_wire_error(error: WireValidationError) -> AdminError {
fn map_service_error(error: gateway_admin::model::AdminError) -> AdminError {
map_admin_service_error(error)
}
// 省略表示不修改,null 表示恢复跟随通用设置
fn deserialize_profile_override<'de, D: serde::Deserializer<'de>>(
deserializer: D,
) -> Result<Option<Option<serde_json::Map<String, serde_json::Value>>>, D::Error> {
Option::<serde_json::Map<String, serde_json::Value>>::deserialize(deserializer).map(Some)
}
+2 -1
View File
@@ -1,6 +1,6 @@
//! 管理端 HTTP adapter、wire contract 与固定路由
use crate::auth::SessionState;
use crate::SessionState;
use axum::{
Router,
@@ -15,6 +15,7 @@ pub mod account_groups;
pub mod accounts;
pub mod auth;
pub mod backups;
mod client_key_usage;
pub mod client_keys;
mod compression;
pub(crate) mod diagnostics;
@@ -11,7 +11,7 @@ use serde_json::{Value, json};
use super::{
AdminAuth, AdminError, AdminQuery, map_service_error, ops_error_view, usage_detail_view,
};
use crate::{auth::SessionState, time::TimePresenter};
use crate::{SessionState, time::TimePresenter};
mod archive;
mod privacy;
@@ -925,25 +925,9 @@ pub(crate) fn dashboard_view(
.filter(|window| window.used_percent.is_none())
.and_then(|window| window.local_usage.as_ref())
.map(|usage| usage.request_count);
let (metric, metric_value_raw, metric_label, metric_value) = match local_requests {
Some(count) => (
DashboardAccountMetric::Requests,
Some(count),
"次数".to_owned(),
if count > 0 {
format_compact_number(count)
} else {
"—".to_owned()
},
),
None => (
DashboardAccountMetric::Tokens,
credential.total_tokens,
"今日 Token".to_owned(),
credential
.total_tokens
.map_or_else(|| "—".to_owned(), format_compact_number),
),
let (metric, metric_value_raw) = match local_requests {
Some(count) => (DashboardAccountMetric::Requests, Some(count)),
None => (DashboardAccountMetric::Tokens, credential.total_tokens),
};
account_usage_views.push(DashboardAccountUsageView {
upstream: credential.upstream.map(|info| {
@@ -978,13 +962,10 @@ pub(crate) fn dashboard_view(
.map(|window| crate::admin::accounts::quota_window_view(window, time)),
metric,
metric_value_raw,
metric_label,
metric_value,
last_used_at: credential.last_used_at,
last_used_relative: credential
.last_used_at
.map(|value| time.relative_view(value, range.end)),
last_used: time.relative_optional(credential.last_used_at, range.end),
});
}
let unavailable_accounts = provider_accounts
@@ -1410,7 +1391,14 @@ pub(crate) fn map_wire_error(error: WireValidationError) -> AdminError {
"dimension" => "诊断维度不合法",
"id" => "用量记录 ID 不能为空",
"cursor" => "观测数据游标不合法",
_ => "观测查询参数不合法",
"currentPage" => "页码须大于 0",
"pageSize" => {
return AdminError::bad_request(format!("每页数量须为 1 至 {}", DomainPageSize::MAX));
}
"status" => "请求状态须为 success、error 或 all",
"errorOrigin" => "错误来源须为 proxy、upstream、connection 或 unknown",
"errorOriginStatus" => "仅错误请求支持按错误来源筛选",
field => return AdminError::bad_request(format!("{field} 字段不合法")),
};
AdminError::bad_request(message)
}
@@ -34,6 +34,7 @@ pub struct UsageQuery {
pub client_api_key_name: Option<String>,
pub account_search: Option<String>,
pub status: Option<String>,
pub error_origin: Option<String>,
pub current_page: Option<u32>,
pub page_size: Option<u16>,
pub provider: Option<String>,
@@ -354,11 +355,21 @@ pub(crate) fn usage_command(
let page_size_value =
DomainPageSize::new(page_size).map_err(|_| WireValidationError::new("pageSize"))?;
Ok(domain::UsageQuery {
status: match query.status.as_deref() {
None | Some("success") => domain::UsageRecordStatus::Success,
Some("error") => domain::UsageRecordStatus::Error,
Some("all") => domain::UsageRecordStatus::All,
Some(_) => return Err(WireValidationError::new("status")),
status: match (query.status.as_deref(), query.error_origin.as_deref()) {
(None | Some("success"), None) => domain::UsageRecordStatus::Success,
(Some("all"), None) => domain::UsageRecordStatus::All,
(Some("error"), origin) => domain::UsageRecordStatus::Error(match origin {
None => None,
Some("proxy") => Some(domain::UsageErrorOrigin::Proxy),
Some("upstream") => Some(domain::UsageErrorOrigin::Upstream),
Some("connection") => Some(domain::UsageErrorOrigin::Connection),
Some("unknown") => Some(domain::UsageErrorOrigin::Unknown),
Some(_) => return Err(WireValidationError::new("errorOrigin")),
}),
(None | Some("success" | "all"), Some(_)) => {
return Err(WireValidationError::new("errorOriginStatus"));
}
(Some(_), _) => return Err(WireValidationError::new("status")),
},
range: usage_range(
query.start_time.as_deref(),

Some files were not shown because too many files have changed in this diff Show More