mirror of
https://github.com/zyycn/codex-proxy-rs.git
synced 2026-11-24 16:00:49 +00:00
Compare commits
174
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8176f5027d | ||
|
|
830f362bba | ||
|
|
c99bf1ac35 | ||
|
|
e41fdfc1c5 | ||
|
|
5fced665bf | ||
|
|
7ff77413c8 | ||
|
|
1ee67cd6b2 | ||
|
|
baf9992f99 | ||
|
|
5f7e50a031 | ||
|
|
939ae78c8c | ||
|
|
3039709f36 | ||
|
|
6900da36ee | ||
|
|
e9a5ee7e3b | ||
|
|
58cbb60750 | ||
|
|
b85f944c52 | ||
|
|
d1be306f03 | ||
|
|
aa34d5291d | ||
|
|
56d3078ee8 | ||
|
|
8b69fa4882 | ||
|
|
d05d38718e | ||
|
|
a1954c4746 | ||
|
|
636a3d2a26 | ||
|
|
e9627168a7 | ||
|
|
5a4f49036b | ||
|
|
8041ddab65 | ||
|
|
e645d6d4c9 | ||
|
|
5079700190 | ||
|
|
4db65d8e12 | ||
|
|
da866de2c7 | ||
|
|
a770419818 | ||
|
|
5b37b574e6 | ||
|
|
0df6c40091 | ||
|
|
4b5443d2f2 | ||
|
|
b02f13c9cc | ||
|
|
878d2858e8 | ||
|
|
369f17d654 | ||
|
|
3709ed2484 | ||
|
|
48a5c9d690 | ||
|
|
6fc6283f3a | ||
|
|
605b60e58f | ||
|
|
1bf948a24f | ||
|
|
d90b9d129e | ||
|
|
4b1cae89b2 | ||
|
|
6cfe7ce2fc | ||
|
|
1427dfc64a | ||
|
|
9996fae5b6 | ||
|
|
6420d86aa6 | ||
|
|
f8fa386a7e | ||
|
|
7c2c532b44 | ||
|
|
188a6817d1 | ||
|
|
d44bc64d1a | ||
|
|
6006cc8394 | ||
|
|
e7f8b5a354 | ||
|
|
d62868b692 | ||
|
|
0922f3486c | ||
|
|
f4058c1d2e | ||
|
|
8253fbc497 | ||
|
|
193e83f9f3 | ||
|
|
a9e8fa8a44 | ||
|
|
437322ee4b | ||
|
|
843e1367bd | ||
|
|
ab1bf4372c | ||
|
|
dca9806961 | ||
|
|
15ed54d452 | ||
|
|
050214860e | ||
|
|
d917f948cf | ||
|
|
3d834c9e93 | ||
|
|
8d282dcdf9 | ||
|
|
38446e8a0c | ||
|
|
1173f6263d | ||
|
|
f4bed2077f | ||
|
|
4a8b839780 | ||
|
|
f02bc80f15 | ||
|
|
32a95a9702 | ||
|
|
cc80401d5e | ||
|
|
8cc6b50d85 | ||
|
|
83521e82f5 | ||
|
|
ba8745a714 | ||
|
|
84bcd0e1c0 | ||
|
|
7459c16a3a | ||
|
|
3b4fb390c7 | ||
|
|
bb440a3cbb | ||
|
|
89b6d2256f | ||
|
|
ba2afe67d0 | ||
|
|
976359ad26 | ||
|
|
832858dade | ||
|
|
4d4c1e48ce | ||
|
|
9f873f5ac2 | ||
|
|
4bc59f32a1 | ||
|
|
4c5d2bc97e | ||
|
|
5033d9f19a | ||
|
|
68b297fc88 | ||
|
|
1b96c775b2 | ||
|
|
b9ccc0b702 | ||
|
|
f9e364860a | ||
|
|
ceeb68ba82 | ||
|
|
2abbfb1fac | ||
|
|
5b7f307bb2 | ||
|
|
e64fb2d955 | ||
|
|
7ee9ea8b63 | ||
|
|
ce12ba3f43 | ||
|
|
ac4ea71cd2 | ||
|
|
77de86e0b6 | ||
|
|
644296bf66 | ||
|
|
367a62bd7d | ||
|
|
62f321c82b | ||
|
|
c40e2f524e | ||
|
|
0f5bf03e13 | ||
|
|
28c8c536c5 | ||
|
|
4ee9abf9d2 | ||
|
|
779ccf4e6c | ||
|
|
d13a4a2138 | ||
|
|
a0e7f38f7f | ||
|
|
41f97ac836 | ||
|
|
975b73b33b | ||
|
|
d787195f4e | ||
|
|
8681d6851e | ||
|
|
d99ecf9aaf | ||
|
|
8f40bfda7c | ||
|
|
72215fe62a | ||
|
|
f61995e61d | ||
|
|
f85d80d756 | ||
|
|
e1f84c210b | ||
|
|
0e02a056b5 | ||
|
|
1eac929e9d | ||
|
|
9b4a042be5 | ||
|
|
3bd042181e | ||
|
|
2cae28d7f4 | ||
|
|
bab781cbe0 | ||
|
|
28ad8fb1c4 | ||
|
|
4888681a04 | ||
|
|
9739bb08be | ||
|
|
fac37ec563 | ||
|
|
9f0d712671 | ||
|
|
75be1287ef | ||
|
|
dad91fe9f7 | ||
|
|
b22b0cfa41 | ||
|
|
bd69329a37 | ||
|
|
151a3c6bfd | ||
|
|
e2f194875f | ||
|
|
07b61bdc83 | ||
|
|
c0fdc1bbff | ||
|
|
343c579017 | ||
|
|
914c00785c | ||
|
|
b3de0d637d | ||
|
|
1271fa0186 | ||
|
|
055da40476 | ||
|
|
36ba79ca5e | ||
|
|
1b24029a97 | ||
|
|
431992a7a4 | ||
|
|
d3143406dc | ||
|
|
478f2d1f21 | ||
|
|
3a0552df73 | ||
|
|
c72136c689 | ||
|
|
a2972d6455 | ||
|
|
b5365b5c38 | ||
|
|
a4e60c3d57 | ||
|
|
e3befd862a | ||
|
|
2fc347508a | ||
|
|
e079ba6e4b | ||
|
|
13edec0b07 | ||
|
|
725de6ead6 | ||
|
|
758bd24b32 | ||
|
|
114baf669b | ||
|
|
628533216a | ||
|
|
dd65665128 | ||
|
|
63db306ba2 | ||
|
|
de58b436b1 | ||
|
|
bec4c2d2a6 | ||
|
|
092789f5ff | ||
|
|
c6350fd234 | ||
|
|
620db1b877 | ||
|
|
4bf1208024 | ||
|
|
cf7a9bd501 |
@@ -1,6 +1,6 @@
|
||||
---
|
||||
name: cpr-dev-guide
|
||||
description: Codex Proxy RS 开发、修复、排障、代码审查和文档修改入口;页面、样式、文案、接口、调度、数据库及宿主 SDK、Runtime、插件接入均适用;PR、Issue、独立网关插件与发版叠加对应技能
|
||||
description: Codex Proxy RS 的需求评估、排障、开发、代码审查与文档维护入口
|
||||
---
|
||||
|
||||
# 开发指南
|
||||
@@ -12,39 +12,38 @@ description: Codex Proxy RS 开发、修复、排障、代码审查和文档修
|
||||
- 先写读者需要知道的事实或动作。删掉一句不影响理解、判断或操作,就删;标题、正文和通知不重复同一信息
|
||||
- 保留会改变决定的条件、权限、后果和恢复步骤。错误通知只说已知问题,有明确办法才补一句;后端返回的提示在后端改,前端不重复解释。上游原文、用户内容和诊断事实保持原样
|
||||
|
||||
## 核实问题根因与宿主职责
|
||||
|
||||
评估功能建议、排障、开发和审查时,先按[问题与方案依据](../../../CONTRIBUTING.md#问题与方案依据)核实使用者要完成什么、当前行为造成了什么影响。反馈直接给出改法时,先弄清提出这个改法的原因
|
||||
|
||||
排查故障时,从症状沿实际调用链回溯,定位行为最早偏离预期的环节,用源码、诊断或对照复现说明触发条件如何导致结果。原因尚未确定时,区分已知事实与假设,指出哪项证据能区分可能原因。确认根因后,在负责该行为的模块修复,用原触发场景验证
|
||||
|
||||
涉及 Codex 时,以对应版本的官方源码核实客户端行为,默认透明转发,只做必要适配。建议宿主接管已有决定时,指出需要它介入的网关职责或实际约束。若只是个别部署希望采用不同策略,说明不建议内置的原因。实现可行性不能证明宿主应当承担这项需求
|
||||
|
||||
## 先确定领域与必读规范
|
||||
|
||||
按用户意图、受影响行为与对象初判,定位后按实际文件复核,不要求用户说出“前端”“后端”或技能名。**所有命中行共同构成本次必读规范,先读完再确定方案、修改或给出审查结论**;跨领域叠加,不能只选最像当前步骤的一行
|
||||
|
||||
职责边界决定问题由谁修复;即使代码位于账号、调度或 API 模块,只要影响插件接入或为插件增加处理,也命中插件边界。确定方案时说明相关业务事实的归属及已有实现的复用依据,不能以功能恢复或测试通过替代职责判断
|
||||
按受影响行为和实际文件执行下表所有命中项。流程引用首次完整读取,长文档按标题定位指定章节
|
||||
|
||||
| 领域或操作,行为影响与文件路径满足其一即可 | 确定方案前读取与执行 |
|
||||
| --- | --- |
|
||||
| 调整页面、弹窗、表单、按钮、文案、样式或交互;目标在 `frontend/`、`modules/ui/`、插件前端,或是 `.vue` 文件 | [前端流程](references/frontend.md),局部修改同样按影响范围检查组件复用、文案、Token、样式、视觉状态和运行证据 |
|
||||
| 开发、排查或审查插件接入、宿主 SDK、Runtime、扩展接口或独立网关插件;目标在 `backend/crates/gateway-plugin/`、`modules/plugins/` | 完整读取[插件职责边界](references/plugin-boundaries.md)及所用 [SDK](../../../backend/crates/gateway-plugin/sdk/README.md) 类型与能力合同;宿主维护自身合同、资源与稳定性,插件业务错误在插件侧修复,不在宿主、SDK 或 Runtime 中补偿;独立插件开发、排查、审查另用 [cpr-plugin-dev](../cpr-plugin-dev/SKILL.md) |
|
||||
| 插件接入、SDK、Runtime、扩展接口或独立网关插件,含账号、调度或 API 中为插件新增的处理;目标在 `backend/crates/gateway-plugin/`、`modules/plugins/` | [插件职责边界](references/plugin-boundaries.md)及所用 [SDK](../../../backend/crates/gateway-plugin/sdk/README.md) 类型与能力合同;独立插件开发、排查或审查同时执行 [cpr-plugin-dev](../cpr-plugin-dev/SKILL.md) |
|
||||
| 开发、排查或审查服务端接口、路由、调度、账号与用量规则、持久化、后台任务或协议行为;目标是 `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)及相关章节,尚无文档差异时也检查是否漏更;纯文档任务不默认读取代码开发、页面验收或发布流程 |
|
||||
| 修改或审查文档;实现或审查用法、公开合同、职责、约束或运维操作的变化 | [文档检查](references/documentation.md),按最终行为核对是否漏更;纯文档任务只补读核实所述事实需要的领域条款 |
|
||||
| 代码审查,包括 PR 审查 | [审查标准](../../../CONTRIBUTING.md#审查标准),叠加被审查行为所属领域的规范;审查默认只读 |
|
||||
| PR / Issue / 发版 | 按当前意图选 [PR](../cpr-github-pr/SKILL.md)、[Issue](../cpr-github-issue/SKILL.md)或[发版](../cpr-release/SKILL.md),普通提交不创建 PR |
|
||||
|
||||
纯文档任务按文档分支执行;核实文中的合同与职责时读对应领域条款,不因提及代码路径或语言加载实现、构建与页面验收流程
|
||||
|
||||
首次命中的流程引用完整读取,并落实其中指定的必读章节;长文档先用 `rg -n '^#{1,4} ' 文件` 定位,分段读取指定章节,避免输出截断。`#章节` 不会自动截取,“按需”仅用于未命中的领域和后续操作资料,不能省略必读规范;读取记录与验证证据的复用按 [任务延续与收尾](../../../AGENTS.md#任务延续与收尾) 执行
|
||||
|
||||
## 参考仓库的优先级
|
||||
|
||||
开发、排障和代码审查先按[问题与方案依据](../../../CONTRIBUTING.md#问题与方案依据)核实问题与方案。涉及 Codex 行为时执行其中的官方行为优先约束:对应版本的官方源码优先,以透明转发和最小必要适配为默认方案,先判断偏离是否必要再评价实现
|
||||
|
||||
## 执行与收尾
|
||||
|
||||
1. 遵守已提供的 [AGENTS.md](../../../AGENTS.md),按其 CodeGraph 约定定位代码;确认工作区、任务范围与已有改动,找到事实归属、同类实现和调用链,补齐上表命中规范及[项目约定](../../../CONTRIBUTING.md#项目约定)对应条目后再修改
|
||||
2. 以最终差异重新匹配上表,补齐新增领域的规范并检查实际实现,再处理本次引入的职责越界、重复规则、冗余状态与无依据分支;删除或替换功能时一并清理失效的配置、类型、调用、测试与文档,已部署数据和公开合同仍遵守所属迁移及兼容规则;仅审查时报告,不自行修复
|
||||
3. 按最终行为执行[文档检查](references/documentation.md),核对所属正文及相关概述、示例和引用,在本任务内完成必要同步;不以尚无文档差异跳过检查。内部重构等未改变文档所述事实时无需改文档;常规文档只写当前状态,普通开发不自动修改 `release/notes.md`
|
||||
3. 模块移动或重命名时,同步核对源码、测试、公开导出及配置、脚本中的名称和路径引用;在本任务内更新受影响的文档、示例和引用
|
||||
4. 按变更范围执行[验证](../../../CONTRIBUTING.md#验证)及其停止条件,后端命令见[验证命令](../../../docs/architecture.md#验证命令);复用仍适用的验证证据与用户已确定的验收分工,区分通过、失败、跳过与未执行
|
||||
5. 交付前按[首要写作要求](#首要写作要求言简意赅)通读本次新增或修改的文字。交代实际结果与验证缺口;前端按[前端流程](references/frontend.md)核对运行证据,后端按上表检查生命周期,不把构建通过当作行为验收
|
||||
6. 按授权完成提交与交付;提交前按[提交约定](../../../CONTRIBUTING.md#项目约定)准备提交信息与实际共同作者署名,提交后核对实际提交消息,PR 的 AI 披露不能替代提交署名
|
||||
@@ -52,9 +51,11 @@ description: Codex Proxy RS 开发、修复、排障、代码审查和文档修
|
||||
## 测试维护
|
||||
|
||||
- 测试随当前功能维护,名称、夹具和断言描述当前输入、行为与结果;功能变更时优先更新所属模块的现有用例,不为每次改动叠加一组记录变更经过的测试
|
||||
- 移动或重命名测试时,核对受影响的场景覆盖是否保留;涉及子进程调用或名称过滤时,同步更新调用入口并实际运行,确认目标用例确实执行且行为断言通过
|
||||
- 清理只证明旧字段、旧路由或旧实现已经消失的用例与附带断言;未知字段校验使用合法请求基线加无业务含义的未知字段,避免因缺少必填项等其他错误而误通过
|
||||
- 同一层对同一行为的重复覆盖合并为清晰的场景矩阵,复用相邻测试夹具;跨层测试确有不同职责或失败路径时保留,不为统一而扩大测试辅助抽象
|
||||
- 断言可观察的行为与业务不变量,避免复述结构体赋值、罗列表列或字段清单、匹配 SQL 文本与源码布局;项目明确要求的架构边界检查继续维护
|
||||
- 断言可观察的行为与业务不变量,避免复述结构体赋值、罗列表列或字段清单、匹配 SQL 文本与源码布局
|
||||
- 维护项目明确要求的架构边界检查;发现漏检时,对照规则核实扫描范围、排除项与被检查的依赖关系,优先补齐现有检查中能稳定判定的缺口
|
||||
- 当前协议兼容、数据读取兼容、安全边界、并发和资源生命周期仍需覆盖,不按 `old`、`legacy` 等名称机械删除,也不能用改名代替无效用例清理
|
||||
- 不在仓库中新增或保留迁移 SQL 专项测试,包括迁移文本、schema 演变与指定版本升级用例;需要验证迁移执行、数据保留或回滚时,在临时目录编写一次性验证并使用隔离数据库,测试通过即可,临时脚本不纳入维护测试集
|
||||
- 持久化功能测试使用当前完整 schema,验证现行读写、事务与数据约束;插件运行时状态迁移等业务能力按当前功能测试,不归为迁移 SQL 专项测试
|
||||
|
||||
@@ -7,32 +7,11 @@
|
||||
- 以当前目标分支及任务内工作区的实现、配置和有效运行证据核实行为;提交记录用于发现待核实的主题,不能直接当作现行事实或按提交顺序组织正文。按 [CodeGraph 约定](../../../../AGENTS.md#codegraph)同步索引后定位,证据不足时报告缺口,不把计划或推测写成已支持能力
|
||||
- 开发任务按最终行为检查哪些用法、合同、职责、约束或运维操作需要同步,即使尚无 Markdown 差异也要检查;独立文档更新按用户范围核对现行说明,不等到发版时再补普通开发所需的文档
|
||||
- 沿同一事实查找所属正文及相关概述、示例和引用,重点核对“支持/不支持”等能力声明、默认值、配置模板和命令。概述保留必要摘要并链接详细合同;不能只更新详细章节,留下 README 或示例中的矛盾说明,也不扩展为无关全仓改写
|
||||
|
||||
## 写之前
|
||||
|
||||
先确定读者、必须说明的当前事实与所属章节,再决定是否需要修改及详略;文档职责与更新条件按上节核对。涉及合同或职责说明时,补读所属架构、API 或 SDK 的对应条款,核实事实;不因文档提及实现而执行无关的开发与构建流程
|
||||
|
||||
在所属章节就地替换失效说明,先组织读者现在需要的操作、结果和限制,不从变更摘要改写正文。仅介绍被替代实现、修复动机或修改经过的段落直接删除;删掉“新增”“此前”“不再”等词后仍在回答变更经过的内容,也不保留
|
||||
|
||||
## 逐段验收
|
||||
|
||||
检查工作区和暂存区中本任务的最终文档差异,并连同受影响章节及相关概述、示例通读,按内容用途处理,不只搜索关键词:
|
||||
|
||||
| 段落回答的问题 | 处理 |
|
||||
| --- | --- |
|
||||
| 现在如何使用、配置或理解结果 | 保留当前事实与必要边界,放回所属章节 |
|
||||
| 谁负责状态、事务、资源和失败处理 | 放入所属架构章节,避免在 API 或部署文档复述实现 |
|
||||
| 这次做了什么、以前怎样、为什么这样修、跑过哪些测试 | 移入 PR、Issue 或任务报告,不以换成现在时的方式留在常规文档 |
|
||||
| 特定配置或数据状态下如何升级、恢复 | 写明适用条件、操作及限制,删除演变过程 |
|
||||
| 别处已完整说明的事实 | 合并或改为必要摘要与链接 |
|
||||
|
||||
脱离提交日期、Issue 和本次任务背景后,读者仍应能独立理解正文
|
||||
|
||||
业务中的请求历史、审计记录、旧数据兼容与回滚操作是当前功能,不能因含“历史”“旧”等词而删除
|
||||
- 涉及合同或职责时核对所属架构、API 或 SDK 条款,在所属章节就地修订。审计记录、旧数据兼容和回滚仍是现行能力时,保留读者需要的说明
|
||||
|
||||
## 交付检查
|
||||
|
||||
- 完成上述逐段验收及[行文检查](../../../../CONTRIBUTING.md#层次与行文),发现问题先处理,未完成内容审查不能称文档已检查
|
||||
- 通读工作区与暂存区中本任务的最终差异、受影响章节及相关概述和示例,按[层次与行文](../../../../CONTRIBUTING.md#层次与行文)逐段验收
|
||||
- 检查相对链接、章节锚点、表格与命令示例,`git diff --check` 或构建通过不能代替内容审查
|
||||
- 交付时简述已同步的文档范围;涉及更新条件却未改文档时,说明现有内容为何仍准确或还有什么缺口。仅报告实际核对范围,不把链接检查通过称为事实核实,也不把检查记录写进常规文档
|
||||
|
||||
|
||||
@@ -32,8 +32,11 @@
|
||||
对照最终差异和实际页面核对适用项,不以读取过规范代替检查:
|
||||
|
||||
- **复用与范围**:是否沿用参考页面和基础组件,已有组件能承载时不手写替代控件;共用缺陷按职责修复,修复后清理本次已失效的页面补丁,不顺带重排无关区域或新增重复入口
|
||||
- **文案与层级**:标点是否合规,标题、状态和帮助是否重复,详细说明与当前决策必需提示的位置是否合适
|
||||
- **核对位置与对齐**时,结合周围内容查看实际页面或 PR 截图,确认操作归属一眼可辨,对照相邻行列检查边缘、文字基线和组间留白。发现错位时指出具体控件、对齐参照和受影响的状态
|
||||
- **精简文案**,删去重复说明,压短必要提示,检查自写文案中的句号和分号
|
||||
- **样式与状态**:是否使用对应 Token 与 utility,局部样式是否符合适用边界,受影响的主题、窄屏及交互状态是否正确
|
||||
- **模块归属**从调用方核对公开入口。页面或多文件组件通过 `index.vue` 提供界面,其他页面复用整页时引用所属模块的布局入口,独立复用的业务组件按领域放置
|
||||
- **Provider 边界**涉及账号操作、身份配置或定价时,沿接口响应、控件和提交载荷追踪同一条规则。服务端决定的能力使用接口字段,Provider 专属表单解释自己的字段,多个页面共用的编辑流程只维护一份。按[前端职责](../../../../docs/architecture.md#34-前端模块职责)核对归属
|
||||
- **查询与动作**:区分首次加载、刷新、分页、单行与批量操作,核对 loading、禁用状态的影响范围;沿用请求层错误处理,不在页面叠加同一错误的提示
|
||||
- **运行证据**:按界面验证核对截图与实际交互,证据对应当前实现;页面 PR 的可访问图片和 Draft 条件按该节执行
|
||||
|
||||
|
||||
@@ -11,20 +11,18 @@ description: 草拟、创建、补充或回复 GitHub Issue,包括缺陷、功
|
||||
|
||||
草拟只准备正文,明确创建或提交才发布;已有授权直接执行,自动命中技能本身不授权远程写入
|
||||
|
||||
补充已有 Issue 先读原帖和讨论,按授权更新或追加,不重复新建;无法推断的目标或关键事实才向用户补齐
|
||||
补充已有 Issue 按授权更新原帖或追加评论
|
||||
|
||||
## 按动作读取与核实
|
||||
|
||||
目标、授权、事实与脱敏要求适用于草拟、提交和回复;按下列动作读取必需规则与证据,再组织正文。症状反馈可保留未知根因,进入技术排查或方案判断时补齐对应规范
|
||||
|
||||
- 新建 Issue 时,读取本仓库的[提交 Issue](../../../CONTRIBUTING.md#提交-issue)及本次匹配的一张表单:[接口问题](../../../.github/ISSUE_TEMPLATE/api-bug-report.yml)、[常规问题](../../../.github/ISSUE_TEMPLATE/general-bug-report.yml)或[功能建议](../../../.github/ISSUE_TEMPLATE/feature-request.yml);协作规则提案可用普通 Issue
|
||||
- 回复时读取原帖、相关讨论与支撑答复的证据,按下方回复口吻组织内容,不套用新建 Issue 的表单
|
||||
- 补充或回复时先读原帖和讨论,按 [GitHub 回复口吻](../../../CONTRIBUTING.md#github-回复口吻)决定答复内容和是否追问
|
||||
- 其他仓库读取它自己的相关规则与实际模板,长文档先定位标题再截取,不预读全部模板或 CONTRIBUTING
|
||||
- 搜索同场景 open/closed Issues、相关 PR 和发布记录,区分主分支修复与已发布修复,不凭标题判断重复;没有新证据时返回已有链接,用户仍要求新建则按其要求处理
|
||||
- 新建或判断重复时查找同场景的 open/closed Issues 和相关 PR,按实际场景核对。已有相同反馈且无新证据时返回原链接,用户仍要求新建则按其要求处理。答复修复状态时核对发布记录,区分已合入和已发布
|
||||
- 需要技术排查、判断实现方案或修改时执行 [cpr-dev-guide](../cpr-dev-guide/SKILL.md)的领域必读,不能仅凭症状建议跨职责补偿;提交症状反馈不以找到根因为前提
|
||||
- 引用上游行为或提出方案时执行[问题与方案依据](../../../CONTRIBUTING.md#问题与方案依据),注明适用版本、来源与缺口
|
||||
|
||||
## 正文与证据
|
||||
## 新建 Issue 的正文
|
||||
|
||||
标题说明症状或期望行为,区分发生问题的部署版本、实测结果、预期结果与根因假设
|
||||
|
||||
@@ -34,22 +32,14 @@ YAML 表单按 `attributes.label` 和字段顺序组织正文,手工核对必
|
||||
|
||||
未知信息如实标明,影响理解或复现的关键事实先补齐,不提交原始 YAML、占位答案或未确认的勾选项
|
||||
|
||||
日志和附件仅含定位所需的脱敏片段,不公开凭据、完整配置或请求转储,不擅自修改代理、TUN、证书环境取证
|
||||
|
||||
附件须获授权且可访问,本机路径不算附件;labels 和 assignees 仅按模板或用户要求设置,并确认实际存在
|
||||
labels 和 assignees 仅按模板或用户要求设置,并确认实际存在
|
||||
|
||||
Issue 可记录复现、排查和变更经过;涉及常规文档修改时执行[文档检查](../cpr-dev-guide/references/documentation.md)
|
||||
|
||||
## 回复口吻
|
||||
|
||||
草拟、发布或修改 Issue 回复时,按 [GitHub 回复口吻](../../../CONTRIBUTING.md#github-回复口吻)将核实结果写成面向提问者的交流答复,具体口吻规则集中维护在该节
|
||||
|
||||
按平常回帖的口吻写,语气自然、委婉,说清判断和原因,少用铺垫、转折和自我说明;暂不采纳或提出不同意见时说明具体原因
|
||||
|
||||
发送或更新前从提问者视角通读:判断和原因是否清楚,建议是否便于尝试,补充材料的用途是否明确。删去不影响理解的客套、重复解释和过程说明;发现生硬时调整整句,不能仅加缓和词,保留已核实的结论
|
||||
|
||||
## 发布与收尾
|
||||
|
||||
日志和附件只含定位所需的脱敏片段,不公开凭据、完整配置或请求转储,不擅自修改代理、TUN、证书环境取证。附件须获授权且可访问,本机路径不算附件
|
||||
|
||||
使用可用连接器或 `gh`,不为提交反馈安装工具、修改仓库配置或启用服务
|
||||
|
||||
多行正文通过结构化字段或 UTF-8 文件传递,以下变量须先从已确认的目标与正文赋值:
|
||||
@@ -58,6 +48,6 @@ Issue 可记录复现、排查和变更经过;涉及常规文档修改时执
|
||||
gh issue create --repo "$issue_repo" --title "$issue_title" --body-file "$issue_body_file"
|
||||
```
|
||||
|
||||
发布前核对目标、必填内容、脱敏与重复记录,更新时保留无关原文;不擅自评论、重开或关闭重复 Issue
|
||||
发布前核对目标和脱敏内容,新建时确认必填项,更新时保留无关原文;不擅自评论、重开或关闭重复 Issue
|
||||
|
||||
超时或结果不明确时先查询远端再重试,发布后回读确认并返回链接;仅草拟或发布失败时提供正文并注明未提交
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
interface:
|
||||
display_name: "cpr-github-issue"
|
||||
short_description: "整理、提交或补充 Issue,核对复现、重复反馈与发布范围"
|
||||
default_prompt: "使用 $cpr-github-issue 按当前请求整理、提交或补充 Issue,核对目标、复现证据、重复记录和脱敏,不将草拟自动变成发布。"
|
||||
short_description: "草拟、提交或回复 GitHub Issue,处理缺陷反馈和功能建议"
|
||||
default_prompt: "使用 $cpr-github-issue 按当前请求整理反馈或回复已有 Issue"
|
||||
policy:
|
||||
allow_implicit_invocation: true
|
||||
|
||||
@@ -17,8 +17,6 @@ description: 准备、创建、更新或审查 GitHub PR,含回复讨论与处
|
||||
|
||||
为本仓库拟写或更新 PR 标题时,完整标题使用英文,沿用提交信息的 Conventional Commits 格式,例如 `fix(store): preserve client key ledgers after deletion`
|
||||
|
||||
涉及上游行为的判断按[问题与方案依据](../../../CONTRIBUTING.md#问题与方案依据)执行
|
||||
|
||||
## 按模式读取
|
||||
|
||||
先完成上述范围判断,再按当前动作与差异涉及的领域叠加下表。命中的流程引用完整读取,长文档读取指定章节;只复用已实际读取且仍适用的内容,单纯整理正文或回复不扩展为完整实现审查
|
||||
@@ -28,22 +26,17 @@ description: 准备、创建、更新或审查 GitHub PR,含回复讨论与处
|
||||
| 只整理标题或描述 | 当前 PR、最终 diff、实际模板、[AI 披露](../../../CONTRIBUTING.md#ai-使用披露),在授权范围内改文案,不自行修改实现;不读取推送或审查流程 |
|
||||
| 创建或更新 PR | [创建流程](references/create.md)、[PR 流程](../../../CONTRIBUTING.md#pr-流程)与[规则文件保护](../../../CONTRIBUTING.md#规则文件保护) |
|
||||
| 审查 PR | [审查流程](references/review.md)、[审查标准](../../../CONTRIBUTING.md#审查标准) |
|
||||
| 回复讨论或审查意见 | 目标评论、相关上下文与实际处理结果,按下方回复口吻答复;仅回复不加载创建或完整审查流程 |
|
||||
| 回复讨论或审查意见 | 读取目标评论和相关上下文,按[GitHub 回复口吻](../../../CONTRIBUTING.md#github-回复口吻)答复实际处理结果 |
|
||||
| 实现自审、审查或修改代码与文档 | 执行 [cpr-dev-guide](../cpr-dev-guide/SKILL.md)的领域必读与对应检查,包括后端、插件、测试和 API 等命中项;只读审查同样执行,不能仅核对 PR 正文与 CI |
|
||||
| 含前端改动 | [前端流程](../cpr-dev-guide/references/frontend.md),核对适用规范与当前实现的运行证据 |
|
||||
| 含文档改动 | [文档检查](../cpr-dev-guide/references/documentation.md) |
|
||||
|
||||
## 回复口吻
|
||||
|
||||
草拟和发布 PR 讨论、审查意见的回复时,执行 [GitHub 回复口吻](../../../CONTRIBUTING.md#github-回复口吻)
|
||||
|
||||
## 创建与审查的公共核对
|
||||
|
||||
- 按[问题与方案依据](../../../CONTRIBUTING.md#问题与方案依据)核实触发条件、发生版本与目标分支现状,分别判断问题是否成立、是否属于目标项目职责及方案是否必要
|
||||
- 核对最新目标分支及同场景 open/closed PR、Issue,按实际行为和测试判断重复,不凭标题下结论,也不擅自关闭他人 PR
|
||||
- 自审或审查覆盖完整差异与调用链,前端与文档按模式表检查
|
||||
- 核对[AI 使用披露](../../../CONTRIBUTING.md#ai-使用披露),填写实际工具与模型,不猜型号;必需截图或型号待补时保留 Draft
|
||||
- 验证结果对应实际 head,区分通过、失败、跳过与未执行;无文档改动时只核对现有说明是否失真
|
||||
- 自审或审查覆盖完整差异和调用链,按[验证](../../../CONTRIBUTING.md#验证)执行适用检查,确认结果对应当前 head
|
||||
- 核对[界面验证](../../../CONTRIBUTING.md#界面验证)要求的截图和 [AI 使用披露](../../../CONTRIBUTING.md#ai-使用披露),必需材料待补时保留 Draft
|
||||
|
||||
远程操作优先使用可用连接器,`gh` 显式指定 `--repo`,多行正文使用结构化字段或 `--body-file`
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
interface:
|
||||
display_name: "cpr-github-pr"
|
||||
short_description: "提交、更新与审查 PR,核对问题、自审、页面截图和 AI 模型披露"
|
||||
default_prompt: "使用 $cpr-github-pr 按当前请求准备、提交、更新或审查 PR,实现自审与审查叠加开发指南的领域规范,核实问题、方案、验证、页面截图和 AI 模型披露。"
|
||||
short_description: "准备、更新或审查 GitHub PR,回复讨论和审查意见"
|
||||
default_prompt: "使用 $cpr-github-pr 按当前请求准备、更新、审查 PR 或回复讨论"
|
||||
policy:
|
||||
allow_implicit_invocation: true
|
||||
|
||||
@@ -6,16 +6,12 @@
|
||||
不用提交日志拼接正文,也不假定仓库一定有模板。
|
||||
2. 更新并确认 base/head,查看相对 merge-base 的完整差异和待提交内容;核对仓库的受保护文件与准入规则。
|
||||
只纳入任务范围的文件和提交;需要整理时用独立功能分支,保留用户其他改动,不擅自改写已发布历史。
|
||||
3. 已完成的改动也须按入口公共核对复核问题与方案。原问题不成立时不包装成已修复的缺陷,证据不足时保留结论。
|
||||
实现与自审按 [cpr-dev-guide](../../cpr-dev-guide/SKILL.md)执行,包括适用的后端生命周期和前端检查;需要修正时只修改已授权范围。
|
||||
4. 查找同一来源仓库、head 和 base 的现有 PR;已存在则复用其链接,不重复创建。
|
||||
3. 查找同一来源仓库、head 和 base 的现有 PR;已存在则复用其链接,不重复创建。
|
||||
更新现有标题或正文须在本次整理/更新请求范围内。
|
||||
5. 按[验证](../../../../CONTRIBUTING.md#验证)执行适用检查,记录对应提交或工作区状态;文档、页面证据与模型披露按入口核对。
|
||||
6. 将任务范围内的提交推送到正确远端,核对远端 head。标题遵循项目约定,正文先说明问题成立的依据和最终行为,
|
||||
再给必要的设计取舍、自审结论、验证与遗留事项,按模板附页面截图和 AI 使用情况。涉及上游行为时,按[问题与方案依据](../../../../CONTRIBUTING.md#问题与方案依据)写明官方源码位置、版本、处理方式及本次方案关系。按规模压缩,不强填无关章节。
|
||||
7. 明确要求草稿或仍有阻塞项时创建或保持 Draft PR,并解释原因;必需截图或 AI 模型披露待补时也不标为可审阅。具备审查条件且未要求草稿时创建普通 PR。
|
||||
4. 将任务范围内的提交推送到正确远端,核对远端 head。按实际模板写明问题依据、最终行为、自审与验证结果,附上适用的审阅材料
|
||||
5. 明确要求草稿或仍有阻塞项时创建或保持 Draft PR,并说明原因;具备审查条件且未要求草稿时创建普通 PR。
|
||||
GitHub Draft 状态与“只写本地草稿正文”不同,后者不创建远程对象。
|
||||
8. 创建或更新后回读正文与附件,核对链接、base、head、草稿状态、模型披露和最新检查结果。网络超时或结果不确定时先查询远端,再决定是否重试。
|
||||
6. 创建或更新后回读正文与附件,核对链接、base、head、草稿状态、模型披露和最新检查结果。网络超时或结果不确定时先查询远端,再决定是否重试。
|
||||
|
||||
CLI 示例中的变量必须先根据上述检查赋值;`pr_body_file` 是精确写入 UTF-8 正文的临时文件:
|
||||
|
||||
|
||||
@@ -4,20 +4,10 @@
|
||||
|
||||
1. 获取 PR 的 base/head SHA、描述、文件差异、已有讨论及 CI 状态。记录实际审查的 head,使用 merge-base 差异。
|
||||
需要源码上下文时先遵守目标仓库的定位规则;需检出时使用隔离工作区,保留用户当前分支和运行环境。
|
||||
按实际行为与文件执行 [cpr-dev-guide](../../cpr-dev-guide/SKILL.md)的领域必读,再判断方案与实现;只读审查也核对职责边界与生命周期。
|
||||
2. 按入口公共核对在目标分支基线核实问题,区分原有问题、环境或配置差异与 PR 新引入的问题,说明主分支已覆盖的部分。
|
||||
3. 按[问题与方案依据](../../../../CONTRIBUTING.md#问题与方案依据)评估解决方向,涉及上游时说明官方处理方式及本次方案关系;缺少必要性依据的偏离明确指出,不因测试通过就认定方案合理。
|
||||
4. 按[审查标准](../../../../CONTRIBUTING.md#审查标准)追踪完整调用链,找到共享业务事实、同类实现及已有验证。
|
||||
对既有特殊分支查清服务的场景,再判断本次改动是否引入或加重问题。
|
||||
主动检查本次变更新引入或加重的冗余与代码异味,说明具体位置、维护成本或行为影响及最小修复方向;
|
||||
不能仅因功能可用、CI 通过而略过,也不把个人写法偏好判为缺陷。
|
||||
5. 前端改动执行[前端流程](../../cpr-dev-guide/references/frontend.md),浏览器可用时检查相关交互;缺少必需截图时要求补齐并列为未具备审阅条件。
|
||||
6. 核对 CI 与本地证据是否覆盖当前 head;根据风险补充必要验证,不触发无关部署或真实账号业务请求。
|
||||
文档差异按[文档检查](../../cpr-dev-guide/references/documentation.md)核对最终 diff。
|
||||
核对 AI 使用与模型披露,缺项明确指出。工具不可用、集成测试跳过或环境不足时具体说明影响范围。
|
||||
7. 按审查标准用中文输出问题是否成立、方案是否合理及对应依据,再列实现问题与验证缺口;复用建议指出具体已有实现。
|
||||
没有问题的类别可省略,未发现问题时直接说明并交代覆盖范围。
|
||||
8. 结束前核对 head 是否变化。发生变化时检查新增差异并更新结论,或明确结论只适用于原 SHA。
|
||||
2. 对照目标分支区分原有问题、环境差异和本次引入或加重的问题。修改既有特殊分支时,查清它原先服务的场景
|
||||
3. 根据风险补充必要验证。浏览器可用时实测受影响的交互,避免触发无关部署或真实账号业务请求
|
||||
4. 用中文说明问题是否成立、方案是否合理,再报告可定位的实现问题与验证缺口。建议复用时指出已有实现;未发现问题时交代实际覆盖范围
|
||||
5. 结束前复核 head。发生变化时检查新增差异并更新结论,或明确结论只适用于原 SHA
|
||||
|
||||
审查本身不修改源码、不发表评论、不提交 GitHub 的批准或请求修改状态。
|
||||
用户明确要求发布时,先复核当前 head 和重复评论,再通过结构化字段或 `--body-file` 发布对应内容;
|
||||
|
||||
@@ -1,17 +1,13 @@
|
||||
---
|
||||
name: cpr-plugin-dev
|
||||
description: 开发、修复、排查、审查或打包 Codex Proxy RS 独立网关插件,含处理器、清单与插件页面;仅改宿主能力时使用 cpr-dev-guide 的插件边界,不适用于 Codex 插件或 Vue 插件
|
||||
description: Codex Proxy RS 独立网关插件的开发、排障、审查与打包
|
||||
---
|
||||
|
||||
# 网关插件开发
|
||||
|
||||
## 先读职责边界
|
||||
|
||||
插件在独立项目中通过公开 SDK 实现业务,插件业务错误在插件侧修复;宿主维护自身合同、资源与稳定性,不猜测插件意图、不补造业务数据,不在宿主、SDK 或 Runtime 中增加插件专属补偿
|
||||
|
||||
开发、排查和审查先完整读取[插件职责边界](../cpr-dev-guide/references/plugin-boundaries.md),再选择实现步骤;已有处理器修复和页面改动也执行,不以是否新增能力为条件。需要新增宿主能力时,先界定可独立使用的基础接口及其职责;必要的协议保护与资源回收仍由宿主负责
|
||||
|
||||
同时执行 [cpr-dev-guide](../cpr-dev-guide/SKILL.md)的领域必读与收尾要求;已实际读取且仍适用的内容复用,不递归重读入口。仅构建、打包或分发已有插件时按对应操作读取,若需诊断或修改行为,再补齐开发分支
|
||||
开发、排查或审查独立插件时,执行 [cpr-dev-guide](../cpr-dev-guide/SKILL.md) 并先读[插件职责边界](../cpr-dev-guide/references/plugin-boundaries.md),包括修改已有处理器或页面。仅构建、打包或分发已有插件时,按下表读取对应步骤
|
||||
|
||||
## 范围与合同
|
||||
|
||||
|
||||
@@ -61,6 +61,6 @@ release/publish "$release_version"
|
||||
工作流附加的安装说明和自动提交列表按其当前配置处理,不用它们替代手写的中文变更说明。
|
||||
- 回读 `main:release/version.yaml` 的 `published`。正式版参与同一大版本四个普通通道的比较;RC 参与 RC、Beta、Alpha,Beta 参与 Beta、Alpha,Alpha 只参与自身。实验版只推进 `exp["X.Y.Z"]`。有通道推进时应有 `chore(release): update release channels to <version>` 提交;重复执行或较旧版本未推进任何通道时无提交
|
||||
- 通道表写入失败时,确认该版本已公开、工作流能写入 `main`,再按已有授权执行 `gh workflow run release.yml --ref main -f tag="v$release_version" -f index_only=true`。恢复任务重新校验公开附件、读取并合并当前清单,不重新打包或改 tag
|
||||
- v3.42.0 在线升级:首个包含新更新器的 3.x 正式版公开并通过校验后,从该次通道提交取出 `release/version.yaml`,将顶层 `version` 设为该正式版,作为同名附件上传到该 Release。回读附件,确认 3.x 稳定通道指向该版本且安装包可用,再手动将已有 `update-index` 正文改为 `{"current":"<该正式版>"}`。此后保留该页与附件,无需再编辑
|
||||
- 保留 v3.42.0 在线升级使用的 `update-index` 页面和 v3.42.1 的 `version.yaml` 附件
|
||||
- 返回版本、tag 对应提交、Release/工作流链接及实际结果。失败、仍在构建或缺失产物时明确说明,不能称为发布成功;
|
||||
Release 和镜像已生成也不表示用户的运行实例已经升级。
|
||||
|
||||
@@ -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@3a3daafd3b7f23b8f65d9f5ba2db203fb59b79e2 # v2.90.2
|
||||
uses: taiki-e/install-action@75a7c0f87bd666af3cdb75c5b9e9d03ab6044e6f # v2.90.6
|
||||
with:
|
||||
tool: cargo-nextest@0.9.143
|
||||
fallback: none
|
||||
|
||||
@@ -115,7 +115,7 @@ jobs:
|
||||
cache-bin: false
|
||||
save-if: ${{ github.event_name != 'pull_request' }}
|
||||
- name: Setup nextest
|
||||
uses: taiki-e/install-action@3a3daafd3b7f23b8f65d9f5ba2db203fb59b79e2 # v2.90.2
|
||||
uses: taiki-e/install-action@75a7c0f87bd666af3cdb75c5b9e9d03ab6044e6f # v2.90.6
|
||||
with:
|
||||
tool: cargo-nextest@0.9.143
|
||||
fallback: none
|
||||
|
||||
@@ -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@3a3daafd3b7f23b8f65d9f5ba2db203fb59b79e2 # v2.90.2
|
||||
uses: taiki-e/install-action@75a7c0f87bd666af3cdb75c5b9e9d03ab6044e6f # v2.90.6
|
||||
with:
|
||||
tool: cargo-audit@0.22.2
|
||||
fallback: none
|
||||
|
||||
@@ -17,11 +17,15 @@
|
||||
/.runtime/
|
||||
*.log
|
||||
|
||||
# Local planning documents
|
||||
/docs/plans/
|
||||
|
||||
# Local configuration and secrets
|
||||
/deploy/config.yaml
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
!/frontend/.env
|
||||
|
||||
# Editors and operating systems
|
||||
/.idea/
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
| 任务意图与常见说法 | 必用技能 |
|
||||
| --- | --- |
|
||||
| 开发、修复、排障、代码审查、改文档;包括“改弹窗/样式/文案”“修接口/调度/数据库”等省略请求 | [cpr-dev-guide](.agents/skills/cpr-dev-guide/SKILL.md),按实际操作和文件匹配规范,跨前后端同时执行 |
|
||||
| 需求评估、排障、开发、修复、代码审查、改文档,包括“看下这个 Issue”“改弹窗/样式/文案”“修接口/调度/数据库” | [cpr-dev-guide](.agents/skills/cpr-dev-guide/SKILL.md),按实际操作和文件匹配规范,跨前后端同时执行 |
|
||||
| 提交/提个 PR、准备或更新 PR、看下 PR、回复 PR 讨论、处理 PR 审查意见 | [cpr-github-pr](.agents/skills/cpr-github-pr/SKILL.md);实现自审、审查或修改同时执行 cpr-dev-guide |
|
||||
| 提 Issue、反馈到仓库、把问题或建议整理成 Issue、补充或回复 Issue | [cpr-github-issue](.agents/skills/cpr-github-issue/SKILL.md) |
|
||||
| 写、修或审查独立网关插件,排查插件接入、打包插件 | [cpr-plugin-dev](.agents/skills/cpr-plugin-dev/SKILL.md),同时执行 cpr-dev-guide;仅改宿主能力时由 cpr-dev-guide 加载插件边界 |
|
||||
|
||||
+4
-10
@@ -21,17 +21,11 @@
|
||||
|
||||
### GitHub 回复口吻
|
||||
|
||||
AI 草拟、发布或修改 Issue、PR 讨论及审查意见的回复时,以一起排查问题、讨论方案的口吻交流:
|
||||
Issue 和 PR 回帖直接回应对方遇到的问题,有不同意见时结合具体场景说明理由。语气自然、委婉,用短句,少用句号。说明个人判断或行动时用“我”,确需提问时称呼一次“佬”
|
||||
|
||||
- 围绕问题、事实和结论展开,能自然省略主语时省略;需要说明个人判断或行动归属时用“我”,避免反复以“我”起句或强调自己,不用“我们”“本助手”代称自己
|
||||
- 普通回复直接回应问题,不加问候语或称呼;向对方提问时称呼“佬”,同一条回复不重复称呼
|
||||
- 先接住对方想完成的事和遇到的困难,再给出核实结果与建议;回复让对方感到问题被理解、有下一步可做,避免一上来归类、纠正或划定责任
|
||||
- 给出操作建议时说明它能帮助判断什么,措辞自然、委婉,不靠堆叠缓和词修饰命令
|
||||
- 回应已有能力、暂不支持或未采纳的建议时,结合场景说明可用入口或具体原因,有可行替代办法时一并说明,再交代必要边界;避免只回复“已有功能”“重复问题”“不在范围内”等结论
|
||||
- 需要补充材料或配合操作时,先利用已有信息,只询问仍缺少的部分,说明用途和最小范围;例如“佬,方便再观察几次吗?如果还出现,可以附一下对应请求的诊断包,便于对照终态用量”
|
||||
- 澄清误解或提出不同意见时,从观察和依据说起,照顾对方的使用环境与理解路径,避免责备、反问或居高临下的判断;已确认的事实保持明确,尚未确认的原因保留余地
|
||||
- 使用自然短句,简单回复用短段,并列信息较多时再分点;少用句号,避免客服套话、机械模板和空泛保证
|
||||
- 排查、复现、修改和验证的完成状态与实际一致;未采纳的意见说明依据,未确认、待处理或未验证的内容如实交代,说清结论、限制和下一步
|
||||
- 用法问题给出操作入口,功能取舍或关闭 Issue 说明与该场景相关的原因,有可行替代办法时再提。问题已答清即可结束
|
||||
- 排障先看原帖、已有材料和自己能核实的实现或发布记录。回复只附有助于理解结论或采取行动的排查信息,如相关版本、复现结果或脱敏片段。区分推测和实测
|
||||
- 只有缺失信息会改变判断或处理方式,且只能由对方提供时才追问。说清需要哪一项、用来区分什么情况
|
||||
|
||||
## 问题与方案依据
|
||||
|
||||
|
||||
@@ -12,114 +12,37 @@
|
||||
[](https://github.com/zyycn/codex-proxy-rs/pkgs/container/codex-proxy-rs)
|
||||
[](LICENSE)
|
||||
|
||||
[快速预览](#快速预览) · [快速开始](#快速开始) · [客户端接入](#客户端接入) · [文档](#文档) · [社区](#社区) · [许可证](#许可证)
|
||||
[快速预览](#快速预览) · [快速开始](#快速开始) · [文档](#文档) · [社区](#社区) · [贡献者](#贡献者) · [Star History](#star-history) · [支持项目](#支持项目) · [许可证](#许可证)
|
||||
|
||||
</div>
|
||||
|
||||
> [!NOTE]
|
||||
> 本项目提供 Responses API 和 Chat Completions API;Chat Completions 请求通过 Responses 链路执行,支持范围见 [API 参考](docs/api.md#chat-completions-请求)
|
||||
> 生成请求支持 [OpenAI Responses](docs/api.md#responses-请求与传输)、[Chat Completions](docs/api.md#chat-completions-请求) 和 [Anthropic Messages](docs/api.md#messages-请求) 三种协议
|
||||
|
||||
## 快速预览
|
||||
|
||||
无需部署即可体验管理端的系统概览、账号分组、代理管理与用量统计:
|
||||
|
||||
| 登录信息 | 默认值 |
|
||||
| --- | --- |
|
||||
| 地址 | <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#客户端配置)
|
||||
|
||||
**其他 Responses / Chat Completions API 客户端**:填写以下信息:
|
||||
|
||||
| 配置 | 值 |
|
||||
| --- | --- |
|
||||
| Base URL | `http://127.0.0.1:8080/v1`;远程接入使用服务器的 HTTPS 地址 |
|
||||
| API Key | 管理端创建的客户端密钥 |
|
||||
|
||||
查询该密钥可见的模型目录:
|
||||
|
||||
```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&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&Date">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://simrepo.dera.page/svg?repos=zyycn/codex-proxy-rs&type=Date&theme=dark">
|
||||
<img src="https://simrepo.dera.page/svg?repos=zyycn/codex-proxy-rs&type=Date" alt="Codex Proxy RS 的 GitHub Star 增长趋势" width="560">
|
||||
</picture>
|
||||
</a>
|
||||
|
||||
## 支持项目
|
||||
|
||||
如果 Codex Proxy RS 帮助到你了,欢迎请我喝杯咖啡 ☕
|
||||
|
||||
[](https://ko-fi.com/zyycn)
|
||||
|
||||
[<img src="docs/donations/wechat-tips.png" alt="WeChat appreciation code" width="138">](docs/donations/wechat-tips.png)
|
||||
[<img src="docs/donations/alipay.png" alt="Alipay QR code" width="138">](docs/donations/alipay.png)
|
||||
|
||||
## 许可证
|
||||
|
||||
本项目基于 [Apache License 2.0](LICENSE) 开源
|
||||
|
||||
Generated
+223
-120
@@ -102,6 +102,12 @@ dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "anyhow"
|
||||
version = "1.0.104"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
|
||||
|
||||
[[package]]
|
||||
name = "arc-swap"
|
||||
version = "1.9.2"
|
||||
@@ -198,7 +204,7 @@ checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.9",
|
||||
"syn 3.0.10",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -260,9 +266,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "aws-runtime"
|
||||
version = "1.10.2"
|
||||
version = "1.10.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9a0cc2144962cc5e358467b16e3d82981b1d424a7c3d34602be0036103814a1a"
|
||||
checksum = "de8930c11353c72ae54aa24dc94d692df74d59814839cbaf8069d63dbcb4c519"
|
||||
dependencies = [
|
||||
"aws-credential-types",
|
||||
"aws-sigv4",
|
||||
@@ -286,9 +292,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "aws-sdk-s3"
|
||||
version = "1.157.0"
|
||||
version = "1.161.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6ea9794c741520d8baec9462bcd0ad12164d4f5f78d008a8da9d6a0b7222caa8"
|
||||
checksum = "d9c63e3ca6e56670513469e992759f4a51041603fde329471b29c5c1f5eaeefe"
|
||||
dependencies = [
|
||||
"arc-swap",
|
||||
"aws-credential-types",
|
||||
@@ -312,7 +318,7 @@ dependencies = [
|
||||
"hmac",
|
||||
"http",
|
||||
"http-body",
|
||||
"lru",
|
||||
"lru 0.18.5",
|
||||
"percent-encoding",
|
||||
"regex-lite",
|
||||
"sha2",
|
||||
@@ -322,9 +328,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "aws-sigv4"
|
||||
version = "1.6.4"
|
||||
version = "1.6.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f385da9b7757ed4c8214797ad663ff534fb622006143530aa80e21f8e06ff85c"
|
||||
checksum = "6c5aa04c533733a77879294f1854c27b3715cc50ea71756d1f6a958702b1a9fb"
|
||||
dependencies = [
|
||||
"aws-credential-types",
|
||||
"aws-smithy-eventstream",
|
||||
@@ -355,9 +361,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "aws-smithy-checksums"
|
||||
version = "0.65.0"
|
||||
version = "0.65.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b67ecd999972b58e67cab052f5129906c08c25883bd0788ceefc55ef97d61307"
|
||||
checksum = "ab2f2d12a431aab3703d55277278bad45f02208569b11506220b95fdc1ef0507"
|
||||
dependencies = [
|
||||
"aws-smithy-http",
|
||||
"aws-smithy-types",
|
||||
@@ -408,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",
|
||||
@@ -443,18 +449,20 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "aws-smithy-observability"
|
||||
version = "0.3.0"
|
||||
version = "0.3.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8e86338c869539a581bf161247762a6e87f92c5c075060057b5ed6d06632ed0c"
|
||||
checksum = "a416257d7b1b0f32a517a470a8c1dd354d8c4aa697ccab81a11a1e6cfb7418e3"
|
||||
dependencies = [
|
||||
"aws-smithy-runtime-api",
|
||||
"aws-smithy-types",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "aws-smithy-runtime"
|
||||
version = "1.16.2"
|
||||
version = "1.16.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4cb80fb19c084da5fca9d797845735e184445e5b958599440d67529bf6ef1b64"
|
||||
checksum = "7ed38b842f93dd8220cc8816750c72ce914b22c6eb3df02beb9632333ccb366d"
|
||||
dependencies = [
|
||||
"aws-smithy-async",
|
||||
"aws-smithy-http",
|
||||
@@ -475,9 +483,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "aws-smithy-runtime-api"
|
||||
version = "1.19.2"
|
||||
version = "1.22.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8c4e85cffe9944b10d576b075432bd8f98dbc081e8681cb37d5b2d87dc27bc84"
|
||||
checksum = "c0b79dbb5331ccd297686df811d50ab3f39db171f5c765372a69272a0990b014"
|
||||
dependencies = [
|
||||
"aws-smithy-async",
|
||||
"aws-smithy-runtime-api-macros",
|
||||
@@ -503,9 +511,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "aws-smithy-schema"
|
||||
version = "1.1.2"
|
||||
version = "1.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9543fc722ed4865ab29fb66bd7ed0bef7b029d265ba8c587144511e30006d431"
|
||||
checksum = "f7ef30d39e131651359b60a1c560de9a9502a4c3754172ab2d6e8734fe21bcba"
|
||||
dependencies = [
|
||||
"aws-smithy-runtime-api",
|
||||
"aws-smithy-types",
|
||||
@@ -514,9 +522,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "aws-smithy-types"
|
||||
version = "1.9.1"
|
||||
version = "1.9.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cf183d70774ea2cfcc101ca74a8884e4c76be8b9df65cd303f6a1175c88e8f80"
|
||||
checksum = "aff4bf014c512840b2bba80a20417b723cbd6a0a65c02e2d81f50b4268aedfc7"
|
||||
dependencies = [
|
||||
"base64-simd",
|
||||
"bytes",
|
||||
@@ -526,7 +534,6 @@ dependencies = [
|
||||
"http-body",
|
||||
"http-body-util",
|
||||
"itoa",
|
||||
"num-integer",
|
||||
"pin-project-lite",
|
||||
"ryu",
|
||||
"serde",
|
||||
@@ -716,6 +723,17 @@ version = "0.2.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "dc0b364ead1874514c8c2855ab558056ebfeb775653e7ae45ff72f28f8f3166c"
|
||||
|
||||
[[package]]
|
||||
name = "bstr"
|
||||
version = "1.13.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6bb31b46c14244e20ee9984b11bf5c992b91fb6939fea616e3512c8baecdbe5f"
|
||||
dependencies = [
|
||||
"memchr",
|
||||
"regex-automata",
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bumpalo"
|
||||
version = "3.20.3"
|
||||
@@ -748,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"
|
||||
@@ -824,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",
|
||||
@@ -846,14 +864,14 @@ 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",
|
||||
"quote",
|
||||
"syn 3.0.9",
|
||||
"syn 3.0.10",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -903,11 +921,12 @@ dependencies = [
|
||||
"gateway-host",
|
||||
"gateway-plugin-runtime",
|
||||
"gateway-store",
|
||||
"provider-antigravity",
|
||||
"provider-openai",
|
||||
"provider-xai",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"syn 3.0.9",
|
||||
"syn 3.0.10",
|
||||
"tempfile",
|
||||
"thiserror",
|
||||
"tokio",
|
||||
@@ -975,6 +994,15 @@ version = "0.10.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c"
|
||||
|
||||
[[package]]
|
||||
name = "constant_time_eq"
|
||||
version = "0.6.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9eb6feb175df65d0a3ccd3e73484e940d0ac664e8034f0519fd49a93db3071d9"
|
||||
dependencies = [
|
||||
"rustversion",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cookie"
|
||||
version = "0.18.2"
|
||||
@@ -1081,9 +1109,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "crc32fast"
|
||||
version = "1.5.4"
|
||||
version = "1.5.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5f97d3416d5337d15c4b0d78c8c91df922ca143f57ec20e2d1c188333047ef04"
|
||||
checksum = "2b929dd2a135771f40afabd1073f85eed59c800b7c61901e5c254270497dad64"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
]
|
||||
@@ -1126,9 +1154,9 @@ checksum = "61803da095bee82a81bb1a452ecc25d3b2f1416d1897eb86430c6159ef717c17"
|
||||
|
||||
[[package]]
|
||||
name = "crypto-bigint"
|
||||
version = "0.7.6"
|
||||
version = "0.7.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6bb08299a6046833a879ace115697f12fd2bd6c8d3e93c909ffc9e0738e7cae0"
|
||||
checksum = "914c195c4d7fbc5ed7f88d14cbf85914d5c664967658d43404b263913a477e82"
|
||||
dependencies = [
|
||||
"cpubits",
|
||||
"ctutils",
|
||||
@@ -1186,9 +1214,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ctutils"
|
||||
version = "0.4.5"
|
||||
version = "0.4.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "38d28fb6aa7dd680b3ffd1a3e64e115c177bdba63c0ae7f9cd48129ff05c4fa0"
|
||||
checksum = "261af4dc7a06ea8a527a8717d8cbba3417530d6ea14e1edb3de6b67806be474f"
|
||||
dependencies = [
|
||||
"cmov",
|
||||
"subtle",
|
||||
@@ -1335,7 +1363,7 @@ dependencies = [
|
||||
"digest 0.11.3",
|
||||
"elliptic-curve",
|
||||
"rfc6979",
|
||||
"signature 3.0.0",
|
||||
"signature",
|
||||
"spki",
|
||||
"zeroize",
|
||||
]
|
||||
@@ -1451,6 +1479,17 @@ dependencies = [
|
||||
"regex-syntax",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fancy-regex"
|
||||
version = "0.20.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0a2e16b9a584b602f1e0e5e22c30ca0906786088c27500653e432d086def8b53"
|
||||
dependencies = [
|
||||
"bit-set",
|
||||
"regex-automata",
|
||||
"regex-syntax",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fastrand"
|
||||
version = "2.4.1"
|
||||
@@ -1478,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",
|
||||
@@ -1494,9 +1533,9 @@ checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582"
|
||||
|
||||
[[package]]
|
||||
name = "flate2"
|
||||
version = "1.1.10"
|
||||
version = "1.1.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb"
|
||||
checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4"
|
||||
dependencies = [
|
||||
"crc32fast",
|
||||
"miniz_oxide 0.9.1",
|
||||
@@ -1554,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",
|
||||
]
|
||||
@@ -1654,7 +1693,7 @@ checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.9",
|
||||
"syn 3.0.10",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1718,7 +1757,7 @@ dependencies = [
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"subtle",
|
||||
"syn 3.0.9",
|
||||
"syn 3.0.10",
|
||||
"tempfile",
|
||||
"thiserror",
|
||||
"tokio",
|
||||
@@ -1773,9 +1812,11 @@ dependencies = [
|
||||
"bytes",
|
||||
"chrono",
|
||||
"chrono-tz",
|
||||
"cron",
|
||||
"event-listener",
|
||||
"futures",
|
||||
"futures-timer",
|
||||
"gateway-protocol",
|
||||
"http",
|
||||
"http-body-util",
|
||||
"semver",
|
||||
@@ -1788,6 +1829,17 @@ dependencies = [
|
||||
"uuid",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gateway-egress"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"gateway-core",
|
||||
"http",
|
||||
"hyper-util",
|
||||
"reqwest",
|
||||
"url",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gateway-host"
|
||||
version = "0.0.0"
|
||||
@@ -1798,11 +1850,11 @@ dependencies = [
|
||||
"bytes",
|
||||
"chrono",
|
||||
"config",
|
||||
"filetime",
|
||||
"flate2",
|
||||
"futures",
|
||||
"gateway-admin",
|
||||
"gateway-core",
|
||||
"gateway-egress",
|
||||
"gateway-protocol",
|
||||
"hex",
|
||||
"http",
|
||||
@@ -2495,15 +2547,15 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "jsonschema"
|
||||
version = "0.60.2"
|
||||
version = "0.61.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a42a11b47492e6a2cc76e9c7bcc8077776cb31dac444e0795d7f61bcc6441c08"
|
||||
checksum = "0e37f27df77c7887edbc5f5a59ecd8e5ec4a669319266ec1b61068667a603183"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"bytecount",
|
||||
"data-encoding",
|
||||
"email_address",
|
||||
"fancy-regex",
|
||||
"fancy-regex 0.20.2",
|
||||
"fraction",
|
||||
"getrandom 0.3.4",
|
||||
"itoa",
|
||||
@@ -2523,18 +2575,18 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "jsonschema-regex"
|
||||
version = "0.60.2"
|
||||
version = "0.61.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "107aeb6ff14b8deb5610096a8ce5c554ec89806b521147eaeb3cae05b07edb7a"
|
||||
checksum = "7e41151614b6c927e21982be8bef5a26741ae5a0ae6a781eedee2aa930a980e6"
|
||||
dependencies = [
|
||||
"regex-syntax",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "jsonschema-value"
|
||||
version = "0.60.2"
|
||||
version = "0.61.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e281d6b177bb4834f2ffd6f92aa0443cffe29c996b251c8d94eb6f456186feba"
|
||||
checksum = "1515b9a91134ef67d7bac95c2d76fbc7e383c4c55ee544204ceec8088f881fef"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"bytecount",
|
||||
@@ -2549,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",
|
||||
]
|
||||
|
||||
@@ -2586,9 +2638,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "libsqlite3-sys"
|
||||
version = "0.37.0"
|
||||
version = "0.39.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b1f111c8c41e7c61a49cd34e44c7619462967221a6443b0ec299e0ac30cfb9b1"
|
||||
checksum = "14a5f01b87b92705d07b433c06f96cbc764637d81a0bffb5734ce17cf0f9a2b3"
|
||||
dependencies = [
|
||||
"pkg-config",
|
||||
"vcpkg",
|
||||
@@ -2629,9 +2681,18 @@ checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad"
|
||||
|
||||
[[package]]
|
||||
name = "lru"
|
||||
version = "0.18.3"
|
||||
version = "0.18.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0d317b4b9eb398e6acce275758ec6125535505e7a146fb1a9b8bda2451b0ff4c"
|
||||
checksum = "ef9ac18847474e638e3702b76c65d4eb93428471a74778ef0f1be711717f89b5"
|
||||
dependencies = [
|
||||
"hashbrown 0.17.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "lru"
|
||||
version = "0.19.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4a9f71e3591c7ec44d3e563e87bf14ddc2bada8519dca046e5b0e560cd004e2d"
|
||||
dependencies = [
|
||||
"hashbrown 0.17.1",
|
||||
]
|
||||
@@ -2945,15 +3006,14 @@ checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"
|
||||
|
||||
[[package]]
|
||||
name = "openssl"
|
||||
version = "0.10.75"
|
||||
version = "0.10.82"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "08838db121398ad17ab8531ce9de97b244589089e290a384c900cb9ff7434328"
|
||||
checksum = "4de8111e94a56adca7ebfe6c365b6d42f99deb69b74b6becacd4204e2f193aa2"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"cfg-if",
|
||||
"foreign-types",
|
||||
"libc",
|
||||
"once_cell",
|
||||
"openssl-macros",
|
||||
"openssl-sys",
|
||||
]
|
||||
@@ -2992,9 +3052,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "openssl-sys"
|
||||
version = "0.9.111"
|
||||
version = "0.9.118"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "82cab2d520aa75e3c58898289429321eb788c3106963d0dc886ec7a5f4adc321"
|
||||
checksum = "19c413d6ec9ebaf5e1c829d355cb3e9f783778d700f135be0921d52fce3c60ae"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"libc",
|
||||
@@ -3278,7 +3338,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2bfe0f4c752e450fc2faf62654f1c134747922825d5b04ca717b8874f41a40c0"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"syn 3.0.9",
|
||||
"syn 3.0.10",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3310,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"
|
||||
@@ -3335,6 +3426,7 @@ dependencies = [
|
||||
"futures",
|
||||
"gateway-admin",
|
||||
"gateway-core",
|
||||
"gateway-egress",
|
||||
"gateway-host",
|
||||
"gateway-protocol",
|
||||
"getrandom 0.4.3",
|
||||
@@ -3343,6 +3435,7 @@ dependencies = [
|
||||
"hyper",
|
||||
"hyper-rustls",
|
||||
"hyper-util",
|
||||
"lru 0.19.0",
|
||||
"native-tls",
|
||||
"openssl",
|
||||
"openssl-sys",
|
||||
@@ -3361,6 +3454,7 @@ dependencies = [
|
||||
"tar",
|
||||
"tempfile",
|
||||
"thiserror",
|
||||
"tiktoken-rs",
|
||||
"tokio",
|
||||
"tokio-rustls",
|
||||
"tokio-tungstenite 0.28.0",
|
||||
@@ -3390,6 +3484,7 @@ dependencies = [
|
||||
"futures",
|
||||
"gateway-admin",
|
||||
"gateway-core",
|
||||
"gateway-egress",
|
||||
"gateway-protocol",
|
||||
"getrandom 0.4.3",
|
||||
"jsonwebtoken",
|
||||
@@ -3458,9 +3553,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "quinn-proto"
|
||||
version = "0.11.18"
|
||||
version = "0.11.19"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a9746dbde176634f4f2f1faf2404e30a31b2bc1e9cafb5329c95d8177a18c9fc"
|
||||
checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"getrandom 0.4.3",
|
||||
@@ -3480,9 +3575,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "quinn-udp"
|
||||
version = "0.5.15"
|
||||
version = "0.5.16"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "35a133f956daabe89a61a685c2649f13d82d5aa4bd5d12d1277e1072a21c0694"
|
||||
checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016"
|
||||
dependencies = [
|
||||
"cfg_aliases",
|
||||
"libc",
|
||||
@@ -3588,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",
|
||||
@@ -3639,14 +3734,14 @@ checksum = "92ecd8964f8453721699a1ed72037b0db49ce2f5a5138486ee89bed6f67cdf3a"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.9",
|
||||
"syn 3.0.10",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "referencing"
|
||||
version = "0.60.2"
|
||||
version = "0.61.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f42818036d3b37cda6bd4c494543158a36e431cb717015ef7c93acc6ba214d3b"
|
||||
checksum = "a028057ef852c58a42d75e09da87b5e733f4030f4c7411728955e4f87203a577"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"fluent-uri",
|
||||
@@ -3661,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",
|
||||
@@ -3673,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",
|
||||
@@ -3690,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"
|
||||
@@ -3793,9 +3888,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustix"
|
||||
version = "1.1.4"
|
||||
version = "1.1.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190"
|
||||
checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"errno",
|
||||
@@ -4009,7 +4104,7 @@ checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.9",
|
||||
"syn 3.0.10",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4143,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"
|
||||
@@ -4227,7 +4313,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "sqlx"
|
||||
version = "0.9.0"
|
||||
source = "git+https://github.com/transact-rs/sqlx?rev=f1e94ec34dd5f11ad6488a3a8ac7988439a3f757#f1e94ec34dd5f11ad6488a3a8ac7988439a3f757"
|
||||
source = "git+https://github.com/transact-rs/sqlx?rev=10462fa4414c6c7f1ed1d39bb31678e3b726878c#10462fa4414c6c7f1ed1d39bb31678e3b726878c"
|
||||
dependencies = [
|
||||
"sqlx-core",
|
||||
"sqlx-macros",
|
||||
@@ -4239,7 +4325,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "sqlx-core"
|
||||
version = "0.9.0"
|
||||
source = "git+https://github.com/transact-rs/sqlx?rev=f1e94ec34dd5f11ad6488a3a8ac7988439a3f757#f1e94ec34dd5f11ad6488a3a8ac7988439a3f757"
|
||||
source = "git+https://github.com/transact-rs/sqlx?rev=10462fa4414c6c7f1ed1d39bb31678e3b726878c#10462fa4414c6c7f1ed1d39bb31678e3b726878c"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"bytes",
|
||||
@@ -4276,7 +4362,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "sqlx-macros"
|
||||
version = "0.9.0"
|
||||
source = "git+https://github.com/transact-rs/sqlx?rev=f1e94ec34dd5f11ad6488a3a8ac7988439a3f757#f1e94ec34dd5f11ad6488a3a8ac7988439a3f757"
|
||||
source = "git+https://github.com/transact-rs/sqlx?rev=10462fa4414c6c7f1ed1d39bb31678e3b726878c#10462fa4414c6c7f1ed1d39bb31678e3b726878c"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
@@ -4288,7 +4374,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "sqlx-macros-core"
|
||||
version = "0.9.0"
|
||||
source = "git+https://github.com/transact-rs/sqlx?rev=f1e94ec34dd5f11ad6488a3a8ac7988439a3f757#f1e94ec34dd5f11ad6488a3a8ac7988439a3f757"
|
||||
source = "git+https://github.com/transact-rs/sqlx?rev=10462fa4414c6c7f1ed1d39bb31678e3b726878c#10462fa4414c6c7f1ed1d39bb31678e3b726878c"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"dotenvy",
|
||||
@@ -4313,7 +4399,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "sqlx-mysql"
|
||||
version = "0.9.0"
|
||||
source = "git+https://github.com/transact-rs/sqlx?rev=f1e94ec34dd5f11ad6488a3a8ac7988439a3f757#f1e94ec34dd5f11ad6488a3a8ac7988439a3f757"
|
||||
source = "git+https://github.com/transact-rs/sqlx?rev=10462fa4414c6c7f1ed1d39bb31678e3b726878c#10462fa4414c6c7f1ed1d39bb31678e3b726878c"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"byteorder",
|
||||
@@ -4340,7 +4426,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "sqlx-postgres"
|
||||
version = "0.9.0"
|
||||
source = "git+https://github.com/transact-rs/sqlx?rev=f1e94ec34dd5f11ad6488a3a8ac7988439a3f757#f1e94ec34dd5f11ad6488a3a8ac7988439a3f757"
|
||||
source = "git+https://github.com/transact-rs/sqlx?rev=10462fa4414c6c7f1ed1d39bb31678e3b726878c#10462fa4414c6c7f1ed1d39bb31678e3b726878c"
|
||||
dependencies = [
|
||||
"atoi",
|
||||
"base64 0.22.1",
|
||||
@@ -4376,7 +4462,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "sqlx-sqlite"
|
||||
version = "0.9.0"
|
||||
source = "git+https://github.com/transact-rs/sqlx?rev=f1e94ec34dd5f11ad6488a3a8ac7988439a3f757#f1e94ec34dd5f11ad6488a3a8ac7988439a3f757"
|
||||
source = "git+https://github.com/transact-rs/sqlx?rev=10462fa4414c6c7f1ed1d39bb31678e3b726878c#10462fa4414c6c7f1ed1d39bb31678e3b726878c"
|
||||
dependencies = [
|
||||
"atoi",
|
||||
"chrono",
|
||||
@@ -4491,9 +4577,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "3.0.9"
|
||||
version = "3.0.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b"
|
||||
checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
@@ -4591,7 +4677,7 @@ checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.9",
|
||||
"syn 3.0.10",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4603,6 +4689,20 @@ dependencies = [
|
||||
"cfg-if",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tiktoken-rs"
|
||||
version = "0.12.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2aeff724640cfe13037336ddf35befdffd2909cbdb65cf041cc8a4cf8c584cfa"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"base64 0.22.1",
|
||||
"bstr",
|
||||
"fancy-regex 0.19.2",
|
||||
"regex",
|
||||
"rustc-hash",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "time"
|
||||
version = "0.3.53"
|
||||
@@ -4719,7 +4819,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "tokio-tungstenite"
|
||||
version = "0.28.0"
|
||||
source = "git+https://github.com/openai-oss-forks/tokio-tungstenite?rev=0e5b2d73aa18dd9f0a50ee9ff199d5aef7594186#0e5b2d73aa18dd9f0a50ee9ff199d5aef7594186"
|
||||
source = "git+https://github.com/openai-oss-forks/tokio-tungstenite?rev=7447c427513cfe685f236e1ac0513c4ea3dd9c0b#7447c427513cfe685f236e1ac0513c4ea3dd9c0b"
|
||||
dependencies = [
|
||||
"futures-util",
|
||||
"log",
|
||||
@@ -4928,7 +5028,7 @@ checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
|
||||
[[package]]
|
||||
name = "tungstenite"
|
||||
version = "0.27.0"
|
||||
source = "git+https://github.com/openai-oss-forks/tungstenite-rs?rev=4fffad30fe373adbdcffab9545e9e9bf4f2fc19f#4fffad30fe373adbdcffab9545e9e9bf4f2fc19f"
|
||||
source = "git+https://github.com/openai-oss-forks/tungstenite-rs?rev=bc589d684755a8c02da0fc7e58d0861cbfc306f1#bc589d684755a8c02da0fc7e58d0861cbfc306f1"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"data-encoding",
|
||||
@@ -5032,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]]
|
||||
@@ -5062,9 +5163,9 @@ checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
|
||||
|
||||
[[package]]
|
||||
name = "uuid"
|
||||
version = "1.29.0"
|
||||
version = "1.29.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4a0e2d11620c50695fe12bbbfde96b3477fe606e7284c22d505c12ce51214514"
|
||||
checksum = "3c14b15dffa2f4bd712103e857140aa04a4f2ff6e955c77d7eb8e53ee02a3b64"
|
||||
dependencies = [
|
||||
"getrandom 0.4.3",
|
||||
"js-sys",
|
||||
@@ -5614,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",
|
||||
]
|
||||
@@ -5667,10 +5768,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "zip"
|
||||
version = "9.4.0"
|
||||
version = "9.8.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3cec733c9820347a592f6375c3c0089b479ba0a0b1cbf3dd1958b02959b7c033"
|
||||
checksum = "721c8158b9503b2660291ad3056a20f722deaeed21bb908a9a363d7e17b34f0e"
|
||||
dependencies = [
|
||||
"constant_time_eq",
|
||||
"crc32fast",
|
||||
"flate2",
|
||||
"getrandom 0.4.3",
|
||||
@@ -5680,13 +5782,14 @@ dependencies = [
|
||||
"nix",
|
||||
"typed-path",
|
||||
"windows-sys 0.61.2",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zlib-rs"
|
||||
version = "0.6.6"
|
||||
version = "0.6.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b142a20ec14a91d5bc708c1dc21b080c550113d8aa77afa29635673a65dd02c5"
|
||||
checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112"
|
||||
|
||||
[[package]]
|
||||
name = "zmij"
|
||||
|
||||
+4
-2
@@ -5,11 +5,13 @@ members = [
|
||||
"crates/gateway-admin",
|
||||
"crates/gateway-api",
|
||||
"crates/gateway-core",
|
||||
"crates/gateway-egress",
|
||||
"crates/gateway-host",
|
||||
"crates/gateway-plugin/runtime",
|
||||
"crates/gateway-plugin/sdk",
|
||||
"crates/gateway-protocol",
|
||||
"crates/gateway-store",
|
||||
"crates/providers/antigravity",
|
||||
"crates/providers/openai",
|
||||
"crates/providers/xai",
|
||||
]
|
||||
@@ -61,5 +63,5 @@ codegen-units = 1
|
||||
panic = "abort"
|
||||
|
||||
[patch.crates-io]
|
||||
# 固定上游 BEGIN 取消回滚修复,避免未结束事务复用;见 transact-rs/sqlx#4394
|
||||
sqlx = { git = "https://github.com/transact-rs/sqlx", rev = "f1e94ec34dd5f11ad6488a3a8ac7988439a3f757" }
|
||||
# 固定包含 BEGIN 取消回滚及 SQLite 安全版本支持的上游提交;见 transact-rs/sqlx#4394、#4502
|
||||
sqlx = { git = "https://github.com/transact-rs/sqlx", rev = "10462fa4414c6c7f1ed1d39bb31678e3b726878c" }
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -128,9 +128,11 @@ pub async fn run() -> Result<(), BootstrapError> {
|
||||
let mut probes = store.health_probes();
|
||||
probes.extend(core.health_probes());
|
||||
probes.push(host.logging_health_probe());
|
||||
let peer_node = or_shutdown!(plugin_runtime, store.peer_routing_id().await);
|
||||
let api = or_shutdown!(
|
||||
plugin_runtime,
|
||||
gateway_api::initialize(
|
||||
peer_node,
|
||||
config.api,
|
||||
core.execution_service(),
|
||||
admin.services(),
|
||||
@@ -172,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!(
|
||||
|
||||
@@ -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,
|
||||
})
|
||||
|
||||
@@ -16,11 +16,13 @@ pub(super) const WORKSPACE_MEMBERS: &[&str] = &[
|
||||
"crates/gateway-admin",
|
||||
"crates/gateway-api",
|
||||
"crates/gateway-core",
|
||||
"crates/gateway-egress",
|
||||
"crates/gateway-host",
|
||||
"crates/gateway-plugin/runtime",
|
||||
"crates/gateway-plugin/sdk",
|
||||
"crates/gateway-protocol",
|
||||
"crates/gateway-store",
|
||||
"crates/providers/antigravity",
|
||||
"crates/providers/openai",
|
||||
"crates/providers/xai",
|
||||
];
|
||||
@@ -61,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",
|
||||
],
|
||||
@@ -80,6 +83,7 @@ fn core_value_owners_do_not_depend_on_execution_or_routing() {
|
||||
"account/selection.rs" => Some(&["account", "concurrency", "identity", "validation"]),
|
||||
"concurrency.rs" => Some(&["error"]),
|
||||
"account/store.rs" => Some(&["account", "error", "identity", "validation"]),
|
||||
"account/proxy.rs" => Some(&["upstream"]),
|
||||
path if path.starts_with("policy/") => {
|
||||
Some(&["account", "identity", "policy", "validation"])
|
||||
}
|
||||
@@ -113,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);
|
||||
@@ -133,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"]),
|
||||
];
|
||||
@@ -187,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(
|
||||
@@ -250,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"))
|
||||
}
|
||||
|
||||
@@ -428,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]
|
||||
@@ -447,11 +549,13 @@ const PACKAGE_TO_MEMBER: &[(&str, &str)] = &[
|
||||
("gateway-admin", "crates/gateway-admin"),
|
||||
("gateway-api", "crates/gateway-api"),
|
||||
("gateway-core", "crates/gateway-core"),
|
||||
("gateway-egress", "crates/gateway-egress"),
|
||||
("gateway-host", "crates/gateway-host"),
|
||||
("gateway-plugin-runtime", "crates/gateway-plugin/runtime"),
|
||||
("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"),
|
||||
];
|
||||
@@ -460,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",
|
||||
&[
|
||||
@@ -482,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 整体契约的根级测试场景
|
||||
@@ -502,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"),
|
||||
@@ -509,8 +615,11 @@ const ALLOWED_INTERNAL_EDGES: &[(&str, &str)] = &[
|
||||
("gateway-api", "gateway-admin"),
|
||||
("gateway-api", "gateway-core"),
|
||||
("gateway-api", "gateway-protocol"),
|
||||
("gateway-core", "gateway-protocol"),
|
||||
("gateway-egress", "gateway-core"),
|
||||
("gateway-host", "gateway-admin"),
|
||||
("gateway-host", "gateway-core"),
|
||||
("gateway-host", "gateway-egress"),
|
||||
("gateway-host", "gateway-protocol"),
|
||||
("gateway-plugin-runtime", "gateway-host"),
|
||||
("gateway-plugin-runtime", "gateway-core"),
|
||||
@@ -519,11 +628,17 @@ 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"),
|
||||
("provider-openai", "gateway-protocol"),
|
||||
("provider-xai", "gateway-admin"),
|
||||
("provider-xai", "gateway-core"),
|
||||
("provider-xai", "gateway-egress"),
|
||||
("provider-xai", "gateway-protocol"),
|
||||
];
|
||||
|
||||
@@ -638,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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -78,7 +78,12 @@ async fn proxy_probe_should_use_provider_custom_ca_for_https_proxies() {
|
||||
});
|
||||
let probe = HttpProxyProbe::new("http://unresolvable.invalid/ip")
|
||||
.with_client_builder(provider_openai::build_reqwest_client_with_custom_ca);
|
||||
let result = probe.test(Some(&proxy), false).await;
|
||||
let result = probe
|
||||
.test(
|
||||
gateway_admin::ports::proxy::ProbeRoute::Proxy(&proxy),
|
||||
false,
|
||||
)
|
||||
.await;
|
||||
assert!(result.success, "{}", result.message);
|
||||
assert_eq!(result.exit_ip.unwrap().to_string(), "203.0.113.8");
|
||||
tokio::time::timeout(Duration::from_secs(5), server)
|
||||
|
||||
@@ -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,11 @@ 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,
|
||||
pub quota_refresh: bool,
|
||||
@@ -111,6 +116,8 @@ pub enum AccountGroupFilter {
|
||||
/// 账号公共存储投影;Provider 专属字段不进入此结构
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct AccountRecord {
|
||||
pub quota_paused: bool,
|
||||
pub quota_settings: gateway_core::account::AccountQuotaSettings,
|
||||
pub auto_use_quota_credits: bool,
|
||||
pub id: String,
|
||||
pub provider_kind: ProviderKind,
|
||||
@@ -143,7 +150,7 @@ pub struct AccountRecord {
|
||||
}
|
||||
|
||||
impl AccountRecord {
|
||||
/// 配置保留绑定,执行请求时禁用代理按直连处理
|
||||
/// 配置保留绑定,执行请求时禁用代理使用部署默认出口
|
||||
#[must_use]
|
||||
pub fn effective_outbound_proxy(&self) -> Option<&gateway_core::account::OutboundProxy> {
|
||||
self.outbound_proxy
|
||||
@@ -251,6 +258,7 @@ pub struct AccountUpdateResult {
|
||||
/// 仅修改显式字段的批量账号设置命令
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct BatchUpdateAccounts {
|
||||
pub quota_settings: Option<gateway_core::account::AccountQuotaSettings>,
|
||||
pub auto_use_quota_credits: Option<bool>,
|
||||
pub account_ids: Vec<String>,
|
||||
pub enabled: Option<bool>,
|
||||
@@ -261,6 +269,18 @@ pub struct BatchUpdateAccounts {
|
||||
pub outbound_proxy: Option<super::proxies::AccountProxySelection>,
|
||||
}
|
||||
|
||||
/// 已按拟提交策略重算的账号暂停结果,以快照版本防止旧判断覆盖新观测
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct PreparedQuotaPause {
|
||||
pub settings: gateway_core::account::AccountQuotaSettings,
|
||||
pub previous_settings: gateway_core::account::AccountQuotaSettings,
|
||||
pub observed_at: Option<DateTime<Utc>>,
|
||||
pub revision: Revision,
|
||||
pub paused: bool,
|
||||
}
|
||||
|
||||
pub type PreparedQuotaPauses = std::collections::BTreeMap<String, PreparedQuotaPause>;
|
||||
|
||||
/// 批量账号更新结果
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct AccountsUpdateResult {
|
||||
|
||||
@@ -16,6 +16,7 @@ pub enum MutationAuditOperation {
|
||||
AccountGroupEnabled { enabled: bool },
|
||||
AccountGroupDelete,
|
||||
ClientApiKeyResetBudget,
|
||||
ClientApiKeySetBudgetWindow,
|
||||
ProviderAccountUpdate,
|
||||
BackupStorageUpdate,
|
||||
BackupScheduleUpdate,
|
||||
@@ -35,6 +36,7 @@ pub enum MutationAuditOperation {
|
||||
PluginSourceCredentialCreate,
|
||||
PluginSourceCredentialDelete,
|
||||
ClientApiKeyUpdateBudgetLimits,
|
||||
ClientApiKeyBatchUpdate,
|
||||
ClientApiKeyCreate,
|
||||
ClientApiKeyUpdate,
|
||||
ClientApiKeyEnabled { enabled: bool },
|
||||
@@ -76,6 +78,7 @@ impl MutationAuditOperation {
|
||||
}
|
||||
Self::AccountGroupDelete => ("delete", "account_group"),
|
||||
Self::ClientApiKeyResetBudget => ("reset_budget", "client_api_key"),
|
||||
Self::ClientApiKeySetBudgetWindow => ("set_budget_window", "client_api_key"),
|
||||
Self::ProviderAccountUpdate => ("update", "provider_account"),
|
||||
Self::BackupStorageUpdate => ("backup.s3_config_updated", "backup_settings"),
|
||||
Self::BackupScheduleUpdate => ("backup.schedule_updated", "backup_settings"),
|
||||
@@ -95,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 {
|
||||
@@ -233,13 +293,116 @@ pub enum ClientKeyBudgetPeriod {
|
||||
All,
|
||||
}
|
||||
|
||||
/// 清零所选窗口已用金额,保留限额、到期时间与历史费用
|
||||
/// 清零所选窗口并恢复日历规则,保留限额与历史费用
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ResetClientKeyBudget {
|
||||
pub id: ClientApiKeyId,
|
||||
pub period: ClientKeyBudgetPeriod,
|
||||
}
|
||||
|
||||
/// 显式窗口复用已有日/周金额上限,外部周期的选择归调用方
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ClientKeyBudgetWindowPeriod {
|
||||
Daily,
|
||||
Weekly,
|
||||
}
|
||||
|
||||
impl ClientKeyBudgetWindowPeriod {
|
||||
#[must_use]
|
||||
pub const fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::Daily => "daily",
|
||||
Self::Weekly => "weekly",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 手动对齐只需要账号身份,列表不读取凭据、额度或用量
|
||||
#[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>,
|
||||
}
|
||||
|
||||
/// 窗口配置版本独立于费用累计与全局配置版本
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ClientKeyBudgetWindow {
|
||||
pub revision: u64,
|
||||
pub explicit: bool,
|
||||
pub starts_at: Option<DateTime<Utc>>,
|
||||
pub ends_at: Option<DateTime<Utc>>,
|
||||
pub used_usd: gateway_core::metering::Decimal,
|
||||
}
|
||||
|
||||
/// 当前窗口版本标识一次操作,同版本同参数可重试;None 释放显式控制
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct SetClientKeyBudgetWindow {
|
||||
pub id: ClientApiKeyId,
|
||||
pub period: ClientKeyBudgetWindowPeriod,
|
||||
pub expected_revision: u64,
|
||||
pub window: Option<ExplicitClientKeyBudgetWindow>,
|
||||
}
|
||||
|
||||
/// 仅更新指定金额上限;省略的周期保持不变,不修改已用金额或窗口
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct UpdateClientKeyBudgetLimits {
|
||||
|
||||
@@ -22,7 +22,7 @@ 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;
|
||||
pub mod settings;
|
||||
@@ -235,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")]
|
||||
|
||||
@@ -158,7 +158,7 @@ impl OtherRequestOutcome {
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
|
||||
pub struct UsageFilter {
|
||||
pub client_api_key_name: Option<String>,
|
||||
pub provider_account_name: Option<String>,
|
||||
pub provider_account_search: Option<String>,
|
||||
pub client_api_key_ref: Option<String>,
|
||||
pub request_id: Option<String>,
|
||||
pub provider_account_ref: Option<String>,
|
||||
@@ -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 {
|
||||
@@ -690,11 +740,12 @@ pub struct RequestMetricPoint {
|
||||
pub costs: Vec<CurrencyCost>,
|
||||
}
|
||||
|
||||
/// 账号池的统一五态统计
|
||||
/// 账号池的状态统计
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub struct AccountPoolMetrics {
|
||||
pub total: u64,
|
||||
pub normal: u64,
|
||||
pub quota_paused: u64,
|
||||
pub quota_exhausted: u64,
|
||||
pub rate_limited: u64,
|
||||
pub disabled: u64,
|
||||
@@ -804,10 +855,44 @@ pub struct DashboardObservation {
|
||||
pub recent_requests: Vec<UsageListRecord>,
|
||||
}
|
||||
|
||||
/// 根据已记录事实推导的错误位置,不表示责任归属
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum UsageErrorOrigin {
|
||||
Proxy,
|
||||
Upstream,
|
||||
Connection,
|
||||
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 {
|
||||
match self {
|
||||
Self::Proxy => "proxy",
|
||||
Self::Upstream => "upstream",
|
||||
Self::Connection => "connection",
|
||||
Self::Unknown => "unknown",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 使用记录表格的窄读模型
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct UsageListRecord {
|
||||
pub outcome: RequestOutcome,
|
||||
/// 已保存的上游错误对象含非空字符串 code、type 或 message
|
||||
pub has_upstream_error: bool,
|
||||
pub error_code: Option<String>,
|
||||
pub error_message: Option<String>,
|
||||
pub error_kind: Option<String>,
|
||||
@@ -816,6 +901,7 @@ pub struct UsageListRecord {
|
||||
pub upstream_connection_exit_reason: Option<String>,
|
||||
pub recovered: bool,
|
||||
pub client_status_code: Option<u16>,
|
||||
pub upstream_status_code: Option<u16>,
|
||||
pub client_api_key_name: Option<String>,
|
||||
pub id: String,
|
||||
pub endpoint: String,
|
||||
@@ -1002,7 +1088,8 @@ pub struct UsageAttempt {
|
||||
pub upstream_transport: Option<String>,
|
||||
pub upstream_send_state: Option<String>,
|
||||
pub outcome: RequestOutcome,
|
||||
pub downstream_committed: bool,
|
||||
/// 未记录尝试交付边界时保持未知,不以 false 代替
|
||||
pub downstream_committed: Option<bool>,
|
||||
pub status_code: Option<u16>,
|
||||
pub provider_error_code: Option<String>,
|
||||
pub failure_kind: Option<String>,
|
||||
|
||||
@@ -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,
|
||||
@@ -845,6 +854,7 @@ pub struct ProviderQuotaReadRequest<'a> {
|
||||
/// Provider 已解析的 quota 结果及其不透明差异字段
|
||||
#[derive(Debug, Default, Clone, PartialEq)]
|
||||
pub struct ProviderQuota {
|
||||
pub paused_windows: Vec<String>,
|
||||
pub upstream: Option<super::upstream_info::ProviderUpstreamInfo>,
|
||||
/// 上游额度响应明确提供的套餐,可用于补全账号展示
|
||||
pub plan_type: Option<String>,
|
||||
@@ -852,7 +862,7 @@ pub struct ProviderQuota {
|
||||
pub refresh_token_expires_at: Option<DateTime<Utc>>,
|
||||
pub windows: Vec<ProviderQuotaWindow>,
|
||||
pub credits: Option<ProviderQuotaCredits>,
|
||||
/// 展示用快照级触顶事实(顶层或任一窗口触顶);不参与账号五态派生
|
||||
/// 展示用快照级触顶事实(顶层或任一窗口触顶);不参与账号状态派生
|
||||
pub limit_reached: bool,
|
||||
pub provider_data: Option<ProviderDocument>,
|
||||
}
|
||||
@@ -1296,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,
|
||||
};
|
||||
+3
-3
@@ -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,
|
||||
+68
-18
@@ -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, ¤t);
|
||||
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(¤t);
|
||||
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(¤t)) {
|
||||
// 截至快照已过期的读数不能用于预测剩余量,窗口累计仍由上面的周期证据决定
|
||||
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;
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
//! 单个额度桶的历史观测;原始文档只在宿主内交给 Provider 解释
|
||||
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::{observability::TimeRange, provider_credentials::ProviderDocument};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct QuotaHistoryQuery {
|
||||
pub window_key: String,
|
||||
pub range: TimeRange,
|
||||
pub cursor: Option<QuotaHistoryCursor>,
|
||||
}
|
||||
|
||||
impl QuotaHistoryQuery {
|
||||
/// 起点基线最多回看一个查询区间
|
||||
pub fn scan_start(&self) -> DateTime<Utc> {
|
||||
self.range
|
||||
.start
|
||||
.checked_sub_signed(self.range.end - self.range.start)
|
||||
.unwrap_or(DateTime::<Utc>::MIN_UTC)
|
||||
}
|
||||
}
|
||||
|
||||
/// 完成时间可能相同,继续读取时保留数据库精度和请求 ID
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct QuotaHistoryCursor {
|
||||
pub completed_at: DateTime<Utc>,
|
||||
pub id: String,
|
||||
}
|
||||
|
||||
pub struct QuotaDocumentPage {
|
||||
pub documents: Vec<(DateTime<Utc>, ProviderDocument)>,
|
||||
pub next_cursor: Option<QuotaHistoryCursor>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct QuotaReading {
|
||||
pub plan_type: Option<String>,
|
||||
pub used_percent: f64,
|
||||
pub reset_at: Option<DateTime<Utc>>,
|
||||
}
|
||||
|
||||
pub type QuotaHistoryParser = fn(&ProviderDocument, &str) -> Option<QuotaReading>;
|
||||
|
||||
pub struct QuotaHistoryPoint {
|
||||
pub observed_at: DateTime<Utc>,
|
||||
pub reading: QuotaReading,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct QuotaHistoryPage {
|
||||
pub samples: Vec<QuotaHistoryPoint>,
|
||||
pub baseline: Option<QuotaHistoryPoint>,
|
||||
pub next_cursor: Option<QuotaHistoryCursor>,
|
||||
}
|
||||
|
||||
impl QuotaHistoryPage {
|
||||
pub fn from_documents(
|
||||
page: QuotaDocumentPage,
|
||||
query: &QuotaHistoryQuery,
|
||||
parse: QuotaHistoryParser,
|
||||
) -> Self {
|
||||
let mut result = Self {
|
||||
next_cursor: page.next_cursor,
|
||||
..Self::default()
|
||||
};
|
||||
for (observed_at, document) in page.documents {
|
||||
let Some(reading) = parse(&document, &query.window_key) else {
|
||||
continue;
|
||||
};
|
||||
let point = QuotaHistoryPoint {
|
||||
observed_at,
|
||||
reading,
|
||||
};
|
||||
if observed_at < query.range.start {
|
||||
// 倒序扫描遇到的第一个同桶读数就是最近基线,无需再向前翻页
|
||||
result.baseline = Some(point);
|
||||
result.next_cursor = None;
|
||||
break;
|
||||
}
|
||||
result.samples.push(point);
|
||||
}
|
||||
result
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,9 @@ pub struct PendingResetCredit {
|
||||
pub struct ResetCreditAutomationState {
|
||||
pub next_discovery_at: DateTime<Utc>,
|
||||
pub credits: Vec<PlannedResetCredit>,
|
||||
pub next_weekly_check_at: Option<DateTime<Utc>>,
|
||||
/// 同一次低额度只消费一次,等待消费后的恢复观测再允许提前用卡
|
||||
pub awaiting_weekly_recovery_since: Option<DateTime<Utc>>,
|
||||
pub pending: Option<PendingResetCredit>,
|
||||
pub retry_at: Option<DateTime<Utc>>,
|
||||
pub failures: u32,
|
||||
@@ -39,6 +42,7 @@ pub struct ResetCreditAutomation {
|
||||
pub struct ResetCreditAutomationStatus {
|
||||
pub enabled: bool,
|
||||
pub lead_minutes: u32,
|
||||
pub weekly_trigger_remaining_percent: Option<u32>,
|
||||
pub next_discovery_at: Option<DateTime<Utc>>,
|
||||
pub next_consume_at: Option<DateTime<Utc>>,
|
||||
pub last_result: Option<String>,
|
||||
|
||||
@@ -24,7 +24,7 @@ impl RetentionPolicy {
|
||||
audit_days: u32,
|
||||
) -> Result<(), &'static str> {
|
||||
for (valid, field) in [
|
||||
((1..=31).contains(&usage_days), "usage_retention_days"),
|
||||
(usage_days > 0, "usage_retention_days"),
|
||||
(ops_days > 0, "ops_event_retention_days"),
|
||||
(audit_days > 0, "audit_retention_days"),
|
||||
] {
|
||||
@@ -38,7 +38,7 @@ impl RetentionPolicy {
|
||||
pub fn try_new(usage_days: u32, ops_days: u32, audit_days: u32) -> Result<Self, AdminError> {
|
||||
if Self::validate_values(usage_days, ops_days, audit_days).is_err() {
|
||||
return Err(AdminError::invalid(
|
||||
"请求保留期必须为 1~31 天,事件与审计保留期必须为正数",
|
||||
"请求、事件与审计保留期必须为正整数天数",
|
||||
));
|
||||
}
|
||||
Ok(Self {
|
||||
|
||||
@@ -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,
|
||||
@@ -63,6 +65,7 @@ pub struct RuntimeSettingsValues {
|
||||
pub openai_session_affinity_ttl_hours: u32,
|
||||
pub responses_max_decompressed_body_bytes: u64,
|
||||
pub smart_scheduling: gateway_core::account::SmartSchedulingConfig,
|
||||
pub quota_reset_window_weights: gateway_core::account::ResetWindowWeights,
|
||||
pub min_codex_desktop_version: Option<String>,
|
||||
pub min_codex_cli_version: Option<String>,
|
||||
pub usage_retention_days: u32,
|
||||
@@ -70,8 +73,9 @@ pub struct RuntimeSettingsValues {
|
||||
pub audit_retention_days: u32,
|
||||
pub account_error_protection: gateway_core::account::AccountErrorProtection,
|
||||
pub account_warmup_enabled: bool,
|
||||
pub account_warmup_schedule_time: String,
|
||||
pub account_warmup_cron: String,
|
||||
pub account_warmup_model: Option<String>,
|
||||
pub reset_credit_on_low_weekly_quota: bool,
|
||||
pub reset_credit_lead_minutes: u32,
|
||||
pub reset_credit_max_weekly_remaining_percent: Option<u32>,
|
||||
}
|
||||
@@ -197,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")?;
|
||||
@@ -233,7 +240,7 @@ impl RuntimeSettingsValues {
|
||||
self.account_error_protection.validate()?;
|
||||
gateway_core::provider_ports::ProviderWarmupPolicy::validate_values(
|
||||
self.account_warmup_enabled,
|
||||
&self.account_warmup_schedule_time,
|
||||
&self.account_warmup_cron,
|
||||
self.account_warmup_model.as_deref(),
|
||||
)?;
|
||||
Ok(())
|
||||
|
||||
@@ -34,6 +34,12 @@ pub trait PluginAccountAccess: Send + Sync {
|
||||
Err(AdminError::unavailable("插件额度事实查询暂不可用"))
|
||||
}
|
||||
|
||||
async fn quota_history(
|
||||
&self,
|
||||
account: &ProviderAccountId,
|
||||
query: crate::model::quota_history::QuotaHistoryQuery,
|
||||
) -> Result<crate::model::quota_history::QuotaHistoryPage, AdminError>;
|
||||
|
||||
/// 通过 Provider 原生管理路径刷新额度;不向插件暴露凭据或执行额度重置
|
||||
async fn refresh_quota(
|
||||
&self,
|
||||
|
||||
@@ -5,13 +5,28 @@ use gateway_core::{engine::budget::ClientBudgetStatus, policy::ClientApiKeyId};
|
||||
|
||||
use crate::model::{
|
||||
AdminError, MutationContext,
|
||||
client_keys::{ResetClientKeyBudget, UpdateClientKeyBudgetLimits},
|
||||
client_keys::{
|
||||
ClientKeyBudgetWindow, ClientKeyBudgetWindowPeriod, ResetClientKeyBudget,
|
||||
SetClientKeyBudgetWindow, UpdateClientKeyBudgetLimits,
|
||||
},
|
||||
plugin_client_keys::{PluginClientKeyFacts, PluginClientKeyListQuery, PluginClientKeyPage},
|
||||
plugin_resources::PluginResourceOwner,
|
||||
};
|
||||
|
||||
#[async_trait]
|
||||
pub trait PluginClientKeyAccess: Send + Sync {
|
||||
async fn budget_window(
|
||||
&self,
|
||||
id: &ClientApiKeyId,
|
||||
period: ClientKeyBudgetWindowPeriod,
|
||||
) -> Result<ClientKeyBudgetWindow, AdminError>;
|
||||
async fn set_budget_window(
|
||||
&self,
|
||||
owner: &PluginResourceOwner,
|
||||
command: SetClientKeyBudgetWindow,
|
||||
context: &MutationContext,
|
||||
) -> Result<u64, AdminError>;
|
||||
|
||||
async fn facts(&self, id: &ClientApiKeyId) -> Result<PluginClientKeyFacts, AdminError>;
|
||||
|
||||
async fn budget(&self, id: &ClientApiKeyId) -> Result<ClientBudgetStatus, AdminError>;
|
||||
|
||||
@@ -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)
|
||||
@@ -349,6 +393,11 @@ pub trait ProviderAdmin: Send + Sync {
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// 历史文档由 Provider 按稳定窗口键解释,不支持的 Provider 不扫描请求记录
|
||||
fn quota_history_parser(&self) -> Option<crate::model::quota_history::QuotaHistoryParser> {
|
||||
None
|
||||
}
|
||||
|
||||
/// 历史观测的协议字段仅由具体 Provider 解释;不支持时保留累计估算
|
||||
fn quota_forecast_observation(
|
||||
&self,
|
||||
@@ -418,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 {
|
||||
@@ -425,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()
|
||||
|
||||
@@ -69,8 +69,14 @@ pub struct ProxyImportReservation {
|
||||
pub guard: Box<dyn ProxyImportGuard>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub enum ProbeRoute<'a> {
|
||||
Direct,
|
||||
Deployment,
|
||||
Proxy(&'a OutboundProxy),
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait ProxyProbe: Send + Sync {
|
||||
/// 未指定代理时探测服务器直连出口,不继承进程代理环境变量
|
||||
async fn test(&self, proxy: Option<&OutboundProxy>, detect_location: bool) -> ProxyTestResult;
|
||||
async fn test(&self, proxy: ProbeRoute<'_>, detect_location: bool) -> ProxyTestResult;
|
||||
}
|
||||
|
||||
@@ -22,9 +22,11 @@ use crate::model::{
|
||||
},
|
||||
auth::{AdminAuditEvent, AuthSession},
|
||||
client_keys::{
|
||||
ClientKeyBudgetMutationOrigin, ClientKeyListQuery, ClientKeyPage, ClientKeyRecord,
|
||||
ClientKeySecret, DeleteClientKey, NewClientKey, ResetClientKeyBudget, SetClientKeyEnabled,
|
||||
UpdateClientKey, UpdateClientKeyBudgetLimits,
|
||||
BatchUpdateClientKeys, BudgetReferenceAccountPage, ClientKeyBudgetMutationOrigin,
|
||||
ClientKeyBudgetWindow, ClientKeyBudgetWindowPeriod, ClientKeyListQuery, ClientKeyPage,
|
||||
ClientKeyRecord, ClientKeySecret, DeleteClientKey, NewClientKey, ResetClientKeyBudget,
|
||||
SetClientKeyBudgetWindow, SetClientKeyEnabled, UpdateClientKey,
|
||||
UpdateClientKeyBudgetLimits,
|
||||
},
|
||||
observability::{
|
||||
DashboardObservation, DashboardQuery, DiagnosticDimension, DiagnosticsObservation,
|
||||
@@ -38,7 +40,7 @@ use crate::model::{
|
||||
CredentialMutationResult, CredentialRotationCommit, PluginAccountListQuery,
|
||||
PluginAccountPage, ProviderExportCredentialInput,
|
||||
},
|
||||
quota_forecast_sampling::QuotaForecastHistory,
|
||||
quota_forecast::QuotaForecastHistory,
|
||||
settings::{AdminApiKey, AdminApiKeyMutation, ReplaceRuntimeSettings, RuntimeSettings},
|
||||
};
|
||||
|
||||
@@ -108,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:
|
||||
@@ -179,6 +188,16 @@ pub trait AccountStore:
|
||||
windows: &[AccountUsageWindowQuery],
|
||||
) -> AdminStoreResult<Vec<AccountUsageWindowResult>>;
|
||||
|
||||
/// 按完成时间倒序读取一页保留的请求观测,不按本地计费结果筛选
|
||||
async fn quota_documents(
|
||||
&self,
|
||||
account: &gateway_core::account::ProviderAccountId,
|
||||
provider: &gateway_core::routing::ProviderKind,
|
||||
created_at: DateTime<Utc>,
|
||||
range: TimeRange,
|
||||
before: Option<&crate::model::quota_history::QuotaHistoryCursor>,
|
||||
) -> AdminStoreResult<crate::model::quota_history::QuotaDocumentPage>;
|
||||
|
||||
/// 从同一数据库语句取得截止快照的累计用量和有界历史观测
|
||||
async fn load_quota_forecast_history(
|
||||
&self,
|
||||
@@ -254,6 +273,7 @@ pub trait AccountStore:
|
||||
async fn batch_update_accounts(
|
||||
&self,
|
||||
command: BatchUpdateAccounts,
|
||||
pauses: crate::model::accounts::PreparedQuotaPauses,
|
||||
context: &MutationContext,
|
||||
) -> AdminStoreResult<AccountsUpdateResult>;
|
||||
|
||||
@@ -365,6 +385,31 @@ 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,
|
||||
period: ClientKeyBudgetWindowPeriod,
|
||||
) -> AdminStoreResult<ClientKeyBudgetWindow>;
|
||||
|
||||
async fn set_client_key_budget_window(
|
||||
&self,
|
||||
command: SetClientKeyBudgetWindow,
|
||||
origin: ClientKeyBudgetMutationOrigin,
|
||||
context: &MutationContext,
|
||||
) -> AdminStoreResult<u64>;
|
||||
|
||||
/// 按已验证的 ID 读取资料,不读取完整明文 Key
|
||||
async fn get_client_key(
|
||||
&self,
|
||||
@@ -390,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,
|
||||
@@ -455,6 +507,7 @@ pub trait AccountGroupStore: Send + Sync {
|
||||
context: &MutationContext,
|
||||
) -> AdminStoreResult<AccountGroupMutation>;
|
||||
|
||||
/// 仍有 API Key 引用分组时返回 Conflict
|
||||
async fn delete_account_group(
|
||||
&self,
|
||||
command: DeleteAccountGroup,
|
||||
@@ -492,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("a))
|
||||
.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,
|
||||
"a,
|
||||
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,
|
||||
"a,
|
||||
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("a),
|
||||
),
|
||||
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)
|
||||
@@ -759,6 +764,7 @@ impl AccountsService for DefaultAccountsService {
|
||||
self.accounts
|
||||
.batch_update_accounts(
|
||||
BatchUpdateAccounts {
|
||||
quota_settings: None,
|
||||
auto_use_quota_credits: None,
|
||||
account_ids: vec![account_id.to_string()],
|
||||
enabled: Some(true),
|
||||
@@ -768,6 +774,7 @@ impl AccountsService for DefaultAccountsService {
|
||||
group_ids: None,
|
||||
outbound_proxy: None,
|
||||
},
|
||||
Default::default(),
|
||||
context,
|
||||
)
|
||||
.await
|
||||
@@ -841,8 +848,58 @@ impl AccountsService for DefaultAccountsService {
|
||||
Vec<ProviderAccountId>,
|
||||
),
|
||||
>::new();
|
||||
let mut pauses = BTreeMap::new();
|
||||
for account_id in &account_ids {
|
||||
let (item, provider) = self.provider_for_account(account_id).await?;
|
||||
let (mut item, provider) = self.provider_for_account(account_id).await?;
|
||||
if let Some(settings) = &command.quota_settings {
|
||||
if !provider
|
||||
.account_capabilities(account_id, &item.account.authentication_kind)
|
||||
.quota_settings_supported
|
||||
{
|
||||
return Err(AdminError::invalid("该账号不支持额度桶设置"));
|
||||
}
|
||||
let previous_settings = item.account.quota_settings.clone();
|
||||
let settings = settings.clone();
|
||||
let mut observed_at = None;
|
||||
let mut paused = false;
|
||||
if !settings.is_empty() {
|
||||
item.account.quota_settings = settings.clone();
|
||||
let quota = provider
|
||||
.read_quotas(&[ProviderQuotaReadRequest {
|
||||
account: &item.account,
|
||||
rolling_usage: None,
|
||||
}])
|
||||
.await
|
||||
.into_iter()
|
||||
.next()
|
||||
.ok_or_else(|| AdminError::invalid("缺少账号额度观测结果"))?
|
||||
.map_err(|error| map_provider_error(error, "provider quota"))?;
|
||||
for key in settings.keys() {
|
||||
let window = quota.windows.iter().find(|window| window.key == key);
|
||||
if window.is_none() && !previous_settings.contains(key) {
|
||||
return Err(AdminError::invalid("只能设置已观测的额度桶"));
|
||||
}
|
||||
if window.is_some_and(|window| {
|
||||
window.local_usage_attribution
|
||||
!= QuotaLocalUsageAttribution::AccountWide
|
||||
}) {
|
||||
return Err(AdminError::invalid("只能设置通用额度桶"));
|
||||
}
|
||||
}
|
||||
observed_at = quota.observed_at;
|
||||
paused = !quota.paused_windows.is_empty();
|
||||
}
|
||||
pauses.insert(
|
||||
item.account.id.clone(),
|
||||
crate::model::accounts::PreparedQuotaPause {
|
||||
settings,
|
||||
previous_settings,
|
||||
revision: item.account.credential_revision,
|
||||
observed_at,
|
||||
paused,
|
||||
},
|
||||
);
|
||||
}
|
||||
if command.auto_use_quota_credits.is_some()
|
||||
&& !provider
|
||||
.account_capabilities(account_id, &item.account.authentication_kind)
|
||||
@@ -864,7 +921,7 @@ impl AccountsService for DefaultAccountsService {
|
||||
let enabled = command.enabled;
|
||||
let result = self
|
||||
.accounts
|
||||
.batch_update_accounts(command, context)
|
||||
.batch_update_accounts(command, pauses, context)
|
||||
.await
|
||||
.map_err(|error| map_store_error(error, "provider accounts"))?;
|
||||
for (provider, provider_ids, _) in providers.values() {
|
||||
@@ -920,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,
|
||||
@@ -955,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
|
||||
@@ -964,7 +1065,6 @@ impl AccountsService for DefaultAccountsService {
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let reset_at = query.range.end;
|
||||
query.range.end = observed;
|
||||
let history = self
|
||||
.accounts
|
||||
@@ -972,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,
|
||||
});
|
||||
@@ -1001,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);
|
||||
}
|
||||
@@ -1231,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 {
|
||||
@@ -1252,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 {
|
||||
|
||||
@@ -2,12 +2,66 @@
|
||||
|
||||
use super::*;
|
||||
|
||||
use crate::model::{MutationActor, reset_credit_automation::*};
|
||||
use crate::model::{MutationActor, reset_credit_automation::*, settings::RuntimeSettingsValues};
|
||||
use chrono::{DateTime, Utc};
|
||||
use gateway_core::time::DeploymentTimeZone;
|
||||
use rand_core::{OsRng, RngCore as _};
|
||||
use sha2::{Digest as _, Sha256};
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum Trigger {
|
||||
Expiry {
|
||||
lead: u32,
|
||||
max_remaining: Option<u32>,
|
||||
},
|
||||
Weekly {
|
||||
max_remaining: u32,
|
||||
},
|
||||
}
|
||||
|
||||
impl Trigger {
|
||||
fn from_settings(settings: &RuntimeSettingsValues) -> Self {
|
||||
if settings.reset_credit_on_low_weekly_quota {
|
||||
Self::Weekly {
|
||||
max_remaining: settings
|
||||
.reset_credit_max_weekly_remaining_percent
|
||||
.unwrap_or(0),
|
||||
}
|
||||
} else {
|
||||
Self::Expiry {
|
||||
lead: settings.reset_credit_lead_minutes,
|
||||
max_remaining: settings.reset_credit_max_weekly_remaining_percent,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn weekly_trigger(self) -> Option<u32> {
|
||||
match self {
|
||||
Self::Expiry { .. } => None,
|
||||
Self::Weekly { max_remaining } => Some(max_remaining),
|
||||
}
|
||||
}
|
||||
|
||||
fn quota_limit(self) -> Option<u32> {
|
||||
match self {
|
||||
Self::Expiry { max_remaining, .. } => max_remaining,
|
||||
Self::Weekly { max_remaining } => Some(max_remaining),
|
||||
}
|
||||
}
|
||||
|
||||
fn eligible(self, remaining: f64, limit: u32) -> bool {
|
||||
// 周额度模式即使配置 100% 也不消耗卡片重置满额窗口
|
||||
match self {
|
||||
Self::Expiry { .. } => remaining <= f64::from(limit),
|
||||
Self::Weekly { .. } => weekly_low(remaining, limit),
|
||||
}
|
||||
}
|
||||
|
||||
fn expiry_due(self, account_id: &str, credit: &PlannedResetCredit, now: DateTime<Utc>) -> bool {
|
||||
matches!(self, Self::Expiry { lead, .. } if consume_at(account_id, credit, lead) <= now)
|
||||
}
|
||||
}
|
||||
|
||||
impl DefaultAccountsService {
|
||||
pub(super) async fn reset_credits_upstream(
|
||||
&self,
|
||||
@@ -74,7 +128,9 @@ impl DefaultAccountsService {
|
||||
account_id: &ProviderAccountId,
|
||||
) -> Result<ResetCreditAutomationStatus, AdminError> {
|
||||
self.require_reset_credit_automation(account_id).await?;
|
||||
let lead_minutes = self.automation_settings().await?.reset_credit_lead_minutes;
|
||||
let settings = self.automation_settings().await?;
|
||||
let lead_minutes = settings.reset_credit_lead_minutes;
|
||||
let weekly_trigger_remaining_percent = Trigger::from_settings(&settings).weekly_trigger();
|
||||
let record = self
|
||||
.accounts
|
||||
.reset_credit_automation(account_id.as_str())
|
||||
@@ -83,20 +139,23 @@ impl DefaultAccountsService {
|
||||
Ok(ResetCreditAutomationStatus {
|
||||
enabled: record.as_ref().is_some_and(|r| r.enabled),
|
||||
lead_minutes,
|
||||
weekly_trigger_remaining_percent,
|
||||
next_discovery_at: record
|
||||
.as_ref()
|
||||
.filter(|r| r.enabled)
|
||||
.map(|r| r.state.next_discovery_at),
|
||||
next_consume_at: record.as_ref().filter(|r| r.enabled).and_then(|r| {
|
||||
next_consumption(r, lead_minutes)
|
||||
.or_else(|| {
|
||||
r.state
|
||||
.pending
|
||||
.as_ref()
|
||||
.map(|pending| consume_at(&r.account_id, &pending.credit, lead_minutes))
|
||||
})
|
||||
.map(|due| r.state.retry_at.map_or(due, |retry| due.max(retry)))
|
||||
}),
|
||||
next_consume_at: record
|
||||
.as_ref()
|
||||
.filter(|r| r.enabled && weekly_trigger_remaining_percent.is_none())
|
||||
.and_then(|r| {
|
||||
next_consumption(r, lead_minutes)
|
||||
.or_else(|| {
|
||||
r.state.pending.as_ref().map(|pending| {
|
||||
consume_at(&r.account_id, &pending.credit, lead_minutes)
|
||||
})
|
||||
})
|
||||
.map(|due| r.state.retry_at.map_or(due, |retry| due.max(retry)))
|
||||
}),
|
||||
last_result: record.and_then(|r| {
|
||||
if r.state
|
||||
.pending
|
||||
@@ -104,6 +163,15 @@ impl DefaultAccountsService {
|
||||
.is_some_and(|pending| pending.credit.expires_at <= Utc::now())
|
||||
{
|
||||
Some("expired_unknown".to_owned())
|
||||
} else if r.enabled
|
||||
&& weekly_trigger_remaining_percent.is_some()
|
||||
&& r.state.awaiting_weekly_recovery_since.is_some()
|
||||
&& matches!(
|
||||
r.state.last_result.as_deref(),
|
||||
Some("reset" | "already_redeemed")
|
||||
)
|
||||
{
|
||||
Some("awaiting_weekly_recovery".to_owned())
|
||||
} else {
|
||||
r.state.last_result
|
||||
}
|
||||
@@ -145,6 +213,8 @@ impl DefaultAccountsService {
|
||||
revision: 0,
|
||||
next_run_at: now,
|
||||
state: ResetCreditAutomationState {
|
||||
next_weekly_check_at: None,
|
||||
awaiting_weekly_recovery_since: None,
|
||||
next_discovery_at: now,
|
||||
credits: vec![],
|
||||
pending: None,
|
||||
@@ -160,8 +230,8 @@ impl DefaultAccountsService {
|
||||
record.state.next_discovery_at =
|
||||
now + chrono::Duration::seconds(i64::from(OsRng.next_u32() % 60));
|
||||
}
|
||||
let lead = self.automation_settings().await?.reset_credit_lead_minutes;
|
||||
reschedule(&mut record, lead, now);
|
||||
let trigger = Trigger::from_settings(&self.automation_settings().await?);
|
||||
reschedule(&mut record, trigger, now);
|
||||
self.save_automation(&mut record, Some(context)).await?;
|
||||
let settings = self
|
||||
.settings
|
||||
@@ -246,7 +316,7 @@ impl DefaultAccountsService {
|
||||
self.observe_reset_credits(&mut record, credits, now)?;
|
||||
reschedule(
|
||||
&mut record,
|
||||
self.automation_settings().await?.reset_credit_lead_minutes,
|
||||
Trigger::from_settings(&self.automation_settings().await?),
|
||||
now,
|
||||
);
|
||||
self.save_automation(&mut record, None).await
|
||||
@@ -255,18 +325,16 @@ impl DefaultAccountsService {
|
||||
async fn automation_failed(
|
||||
&self,
|
||||
record: &mut ResetCreditAutomation,
|
||||
lead: u32,
|
||||
trigger: Trigger,
|
||||
now: DateTime<Utc>,
|
||||
) -> Result<(), AdminError> {
|
||||
if record.state.pending.is_none()
|
||||
&& !next_consumption(record, lead).is_some_and(|due| due <= now)
|
||||
{
|
||||
if record.state.pending.is_none() && record.state.retry_at.is_none() {
|
||||
record.state.next_discovery_at =
|
||||
next_discovery(now, self.timezone, OsRng.next_u64())
|
||||
.ok_or_else(|| AdminError::internal("无法计算重置卡发现时间"))?;
|
||||
record.state.retry_at = None;
|
||||
record.state.last_result = Some("discovery_failed".to_owned());
|
||||
reschedule(record, lead, now);
|
||||
reschedule(record, trigger, now);
|
||||
return self.save_automation(record, None).await;
|
||||
}
|
||||
record.state.failures = record.state.failures.saturating_add(1);
|
||||
@@ -281,7 +349,7 @@ impl DefaultAccountsService {
|
||||
}
|
||||
.to_owned(),
|
||||
);
|
||||
reschedule(record, lead, now);
|
||||
reschedule(record, trigger, now);
|
||||
self.save_automation(record, None).await
|
||||
}
|
||||
|
||||
@@ -289,7 +357,7 @@ impl DefaultAccountsService {
|
||||
async fn defer_automation(
|
||||
&self,
|
||||
record: &mut ResetCreditAutomation,
|
||||
lead: u32,
|
||||
trigger: Trigger,
|
||||
reason: &str,
|
||||
) -> Result<(), AdminError> {
|
||||
let now = Utc::now();
|
||||
@@ -305,38 +373,24 @@ impl DefaultAccountsService {
|
||||
);
|
||||
record.state.last_result = Some(reason.to_owned());
|
||||
record.state.failures = 0;
|
||||
reschedule(record, lead, now);
|
||||
reschedule(record, trigger, now);
|
||||
self.save_automation(record, None).await
|
||||
}
|
||||
|
||||
async fn weekly_reset_credit_gate(
|
||||
async fn reset_credit_quota(
|
||||
&self,
|
||||
account_id: &ProviderAccountId,
|
||||
max_remaining: u32,
|
||||
) -> Result<Option<&'static str>, AdminError> {
|
||||
refresh: bool,
|
||||
) -> Result<ProviderQuota, AdminError> {
|
||||
let (_, provider) = self.provider_for_account(account_id).await?;
|
||||
let quota = provider
|
||||
provider
|
||||
.quota(ProviderQuotaRequest {
|
||||
account_id: account_id.clone(),
|
||||
refresh: true,
|
||||
refresh,
|
||||
rolling_usage: None,
|
||||
})
|
||||
.await
|
||||
.map_err(|error| map_provider_error(error, "reset-credit weekly quota"))?;
|
||||
// 复用账号周窗口归属,不把短期、月度或模型专属桶当作剩余周额度
|
||||
let remaining = quota
|
||||
.usage_windows()
|
||||
.find(|(_, period)| *period == AccountUsagePeriod::Weekly)
|
||||
.and_then(|(window, _)| window.used_percent)
|
||||
.filter(|used| used.is_finite())
|
||||
.map(|used| 100.0 - used.clamp(0.0, 100.0));
|
||||
Ok(match remaining {
|
||||
Some(remaining) if remaining > f64::from(max_remaining) => {
|
||||
Some("weekly_quota_above_threshold")
|
||||
}
|
||||
Some(_) => None,
|
||||
None => Some("weekly_quota_unavailable"),
|
||||
})
|
||||
.map_err(|error| map_provider_error(error, "reset-credit weekly quota"))
|
||||
}
|
||||
|
||||
pub(super) async fn reconcile_automation(
|
||||
@@ -368,7 +422,7 @@ impl DefaultAccountsService {
|
||||
}
|
||||
let now = Utc::now();
|
||||
let settings = self.automation_settings().await?;
|
||||
let lead = settings.reset_credit_lead_minutes;
|
||||
let trigger = Trigger::from_settings(&settings);
|
||||
record
|
||||
.state
|
||||
.credits
|
||||
@@ -382,18 +436,51 @@ impl DefaultAccountsService {
|
||||
record.state.pending = None;
|
||||
record.state.retry_at = None;
|
||||
record.state.last_result = Some("expired_unknown".to_owned());
|
||||
record.state.awaiting_weekly_recovery_since = Some(now);
|
||||
}
|
||||
if record.state.retry_at.is_some_and(|retry| retry > now) {
|
||||
reschedule(&mut record, lead, now);
|
||||
reschedule(&mut record, trigger, now);
|
||||
return self.save_automation(&mut record, None).await;
|
||||
}
|
||||
let context = MutationContext {
|
||||
actor: MutationActor::System,
|
||||
request_id: "reset-credit-automation".to_owned(),
|
||||
};
|
||||
let due_credit = next_consumption(&record, lead).is_some_and(|due| due <= now);
|
||||
let due_credit = record
|
||||
.state
|
||||
.credits
|
||||
.iter()
|
||||
.any(|credit| trigger.expiry_due(account_id.as_str(), credit, now));
|
||||
let early_limit = trigger.weekly_trigger();
|
||||
// 错峰读取本地快照,等待恢复期间不因卡片用完而漏过下一轮额度
|
||||
record.state.next_weekly_check_at = early_limit
|
||||
.map(|_| now + chrono::Duration::seconds(60 + i64::from(OsRng.next_u32() % 30)));
|
||||
let mut early_due = false;
|
||||
if let Some(limit) = early_limit
|
||||
&& record.state.pending.is_none()
|
||||
&& needs_weekly_observation(&record.state)
|
||||
{
|
||||
match self.reset_credit_quota(account_id, false).await {
|
||||
Ok(quota) => {
|
||||
observe_weekly_recovery(&mut record.state, "a, limit);
|
||||
early_due = !record.state.credits.is_empty()
|
||||
&& record.state.awaiting_weekly_recovery_since.is_none()
|
||||
&& weekly_remaining("a)
|
||||
.is_some_and(|remaining| trigger.eligible(remaining, limit));
|
||||
}
|
||||
Err(error) => {
|
||||
// 额度读取失败不能阻塞独立的卡片发现计划
|
||||
tracing::warn!(
|
||||
account_id = account_id.as_str(),
|
||||
error_kind = error.kind().as_str(),
|
||||
"重置卡周额度快照读取失败"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
if record.state.pending.is_none()
|
||||
&& (due_credit
|
||||
|| early_due
|
||||
|| record.state.next_discovery_at <= now
|
||||
|| record.state.retry_at.is_some())
|
||||
{
|
||||
@@ -403,10 +490,10 @@ impl DefaultAccountsService {
|
||||
next_discovery(now, self.timezone, OsRng.next_u64())
|
||||
.ok_or_else(|| AdminError::internal("无法计算重置卡发现时间"))?;
|
||||
}
|
||||
if due_credit || record.state.retry_at.is_some() {
|
||||
if due_credit || early_due || record.state.retry_at.is_some() {
|
||||
record.state.retry_at = Some(now + chrono::Duration::seconds(30));
|
||||
}
|
||||
reschedule(&mut record, lead, now);
|
||||
reschedule(&mut record, trigger, now);
|
||||
self.save_automation(&mut record, None).await?;
|
||||
// 真正消费前重新核对卡片;每日发现结果也可直接承担本次核对
|
||||
match self
|
||||
@@ -415,7 +502,7 @@ impl DefaultAccountsService {
|
||||
{
|
||||
Ok(credits) => self.observe_reset_credits(&mut record, &credits, Utc::now())?,
|
||||
Err(error) => {
|
||||
self.automation_failed(&mut record, lead, Utc::now())
|
||||
self.automation_failed(&mut record, trigger, Utc::now())
|
||||
.await?;
|
||||
return Err(error);
|
||||
}
|
||||
@@ -424,24 +511,28 @@ impl DefaultAccountsService {
|
||||
.state
|
||||
.credits
|
||||
.iter()
|
||||
.find(|credit| consume_at(account_id.as_str(), credit, lead) <= Utc::now())
|
||||
.find(|credit| {
|
||||
early_due || trigger.expiry_due(account_id.as_str(), credit, Utc::now())
|
||||
})
|
||||
.cloned()
|
||||
{
|
||||
if let Some(max_remaining) = settings.reset_credit_max_weekly_remaining_percent {
|
||||
// 已发出的未决请求跳过此检查,继续沿原幂等键确认结果
|
||||
match self
|
||||
.weekly_reset_credit_gate(account_id, max_remaining)
|
||||
.await
|
||||
{
|
||||
Ok(Some(reason)) => {
|
||||
return self.defer_automation(&mut record, lead, reason).await;
|
||||
}
|
||||
Ok(None) => {}
|
||||
if let Some(limit) = trigger.quota_limit() {
|
||||
// 缓存只能唤醒检查,实际选中的卡片与额度都要重新核实
|
||||
let quota = match self.reset_credit_quota(account_id, true).await {
|
||||
Ok(quota) => quota,
|
||||
Err(error) => {
|
||||
self.defer_automation(&mut record, lead, "weekly_quota_unavailable")
|
||||
self.defer_automation(&mut record, trigger, "weekly_quota_unavailable")
|
||||
.await?;
|
||||
return Err(error);
|
||||
}
|
||||
};
|
||||
let reason = match weekly_remaining("a) {
|
||||
Some(remaining) if trigger.eligible(remaining, limit) => None,
|
||||
Some(_) => Some("weekly_quota_above_threshold"),
|
||||
None => Some("weekly_quota_unavailable"),
|
||||
};
|
||||
if let Some(reason) = reason {
|
||||
return self.defer_automation(&mut record, trigger, reason).await;
|
||||
}
|
||||
}
|
||||
// 刷新额度期间卡片可能到期,不能把已过期卡片持久化为待消费
|
||||
@@ -450,7 +541,7 @@ impl DefaultAccountsService {
|
||||
.state
|
||||
.credits
|
||||
.retain(|credit| credit.expires_at > Utc::now());
|
||||
reschedule(&mut record, lead, Utc::now());
|
||||
reschedule(&mut record, trigger, Utc::now());
|
||||
return self.save_automation(&mut record, None).await;
|
||||
}
|
||||
record.state.pending = Some(PendingResetCredit {
|
||||
@@ -459,13 +550,13 @@ impl DefaultAccountsService {
|
||||
});
|
||||
record.state.last_result = Some("pending".to_owned());
|
||||
record.state.retry_at = Some(Utc::now() + chrono::Duration::seconds(30));
|
||||
reschedule(&mut record, lead, Utc::now());
|
||||
reschedule(&mut record, trigger, Utc::now());
|
||||
// 必须在发送消费请求前落盘,进程退出或响应丢失继续使用相同幂等键
|
||||
self.save_automation(&mut record, None).await?;
|
||||
}
|
||||
}
|
||||
let Some(pending) = record.state.pending.clone() else {
|
||||
reschedule(&mut record, lead, Utc::now());
|
||||
reschedule(&mut record, trigger, Utc::now());
|
||||
return self.save_automation(&mut record, None).await;
|
||||
};
|
||||
let command = ConsumeProviderResetCredit {
|
||||
@@ -478,9 +569,12 @@ impl DefaultAccountsService {
|
||||
Ok(result) => {
|
||||
let confirmed = matches!(result.code.as_str(), "reset" | "already_redeemed");
|
||||
record.state.pending = None;
|
||||
if confirmed {
|
||||
record.state.awaiting_weekly_recovery_since = Some(Utc::now());
|
||||
}
|
||||
if result.code == "nothing_to_reset" {
|
||||
return self
|
||||
.defer_automation(&mut record, lead, "nothing_to_reset")
|
||||
.defer_automation(&mut record, trigger, "nothing_to_reset")
|
||||
.await;
|
||||
}
|
||||
record
|
||||
@@ -494,15 +588,20 @@ impl DefaultAccountsService {
|
||||
} else {
|
||||
"not_redeemed".to_owned()
|
||||
});
|
||||
reschedule(&mut record, lead, Utc::now());
|
||||
reschedule(&mut record, trigger, Utc::now());
|
||||
// 已确认的结果先落盘,再刷新额度;观测失败不能重放已完成的消费
|
||||
self.save_automation(&mut record, None).await?;
|
||||
if confirmed {
|
||||
let _ = self.quota(account_id, true).await;
|
||||
if confirmed
|
||||
&& let Ok(account) = self.quota(account_id, true).await
|
||||
&& let Some(limit) = early_limit
|
||||
&& observe_weekly_recovery(&mut record.state, &account.quota, limit)
|
||||
{
|
||||
reschedule(&mut record, trigger, Utc::now());
|
||||
self.save_automation(&mut record, None).await?;
|
||||
}
|
||||
}
|
||||
Err(error) => {
|
||||
self.automation_failed(&mut record, lead, Utc::now())
|
||||
self.automation_failed(&mut record, trigger, Utc::now())
|
||||
.await?;
|
||||
return Err(error);
|
||||
}
|
||||
@@ -511,6 +610,42 @@ impl DefaultAccountsService {
|
||||
}
|
||||
}
|
||||
|
||||
/// 复用账号周窗口归属,忽略短期、模型专属和过期窗口
|
||||
fn weekly_remaining(quota: &ProviderQuota) -> Option<f64> {
|
||||
quota
|
||||
.usage_windows()
|
||||
.find(|(window, period)| {
|
||||
*period == AccountUsagePeriod::Weekly
|
||||
&& window.reset_at.is_some_and(|end| end > Utc::now())
|
||||
})
|
||||
.and_then(|(window, _)| window.used_percent)
|
||||
.filter(|used| used.is_finite())
|
||||
.map(|used| 100.0 - used.clamp(0.0, 100.0))
|
||||
}
|
||||
|
||||
fn weekly_low(remaining: f64, limit: u32) -> bool {
|
||||
remaining < 100.0 && remaining <= f64::from(limit)
|
||||
}
|
||||
|
||||
fn needs_weekly_observation(state: &ResetCreditAutomationState) -> bool {
|
||||
!state.credits.is_empty() || state.awaiting_weekly_recovery_since.is_some()
|
||||
}
|
||||
|
||||
fn observe_weekly_recovery(
|
||||
state: &mut ResetCreditAutomationState,
|
||||
quota: &ProviderQuota,
|
||||
limit: u32,
|
||||
) -> bool {
|
||||
if let Some(since) = state.awaiting_weekly_recovery_since
|
||||
&& quota.observed_at.is_some_and(|at| at > since)
|
||||
&& weekly_remaining(quota).is_some_and(|remaining| !weekly_low(remaining, limit))
|
||||
{
|
||||
state.awaiting_weekly_recovery_since = None;
|
||||
return true;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// 当地次日随机发现时间;随机数由调用者提供,结果持久化后不会因重启重抽
|
||||
fn next_discovery(
|
||||
now: DateTime<Utc>,
|
||||
@@ -550,14 +685,21 @@ fn next_consumption(record: &ResetCreditAutomation, lead_minutes: u32) -> Option
|
||||
.min()
|
||||
}
|
||||
|
||||
fn reschedule(record: &mut ResetCreditAutomation, lead_minutes: u32, now: DateTime<Utc>) {
|
||||
fn reschedule(record: &mut ResetCreditAutomation, trigger: Trigger, now: DateTime<Utc>) {
|
||||
record.next_run_at = if let Some(retry) = record.state.retry_at {
|
||||
retry
|
||||
} else if record.state.pending.is_some() {
|
||||
now
|
||||
} else {
|
||||
next_consumption(record, lead_minutes).map_or(record.state.next_discovery_at, |due| {
|
||||
due.min(record.state.next_discovery_at)
|
||||
let scheduled = match trigger {
|
||||
Trigger::Expiry { lead, .. } => next_consumption(record, lead),
|
||||
Trigger::Weekly { .. } if needs_weekly_observation(&record.state) => {
|
||||
Some(record.state.next_weekly_check_at.unwrap_or(now))
|
||||
}
|
||||
Trigger::Weekly { .. } => None,
|
||||
};
|
||||
scheduled.map_or(record.state.next_discovery_at, |at| {
|
||||
at.min(record.state.next_discovery_at)
|
||||
})
|
||||
};
|
||||
}
|
||||
|
||||
@@ -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,13 +15,17 @@ use crate::{
|
||||
model::{
|
||||
AdminError, MutationContext,
|
||||
client_keys::{
|
||||
ClientKeyBudgetMutationOrigin, ClientKeyCursorValue, ClientKeyListQuery,
|
||||
ClientKeyMutation, ClientKeyPage, ClientKeyRecord, ClientKeySecret, ClientKeySortField,
|
||||
CreateClientKey, CreatedClientKey, DeleteClientKey, NewClientKey, ResetClientKeyBudget,
|
||||
SetClientKeyEnabled, UpdateClientKey, UpdateClientKeyBudgetLimits,
|
||||
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};
|
||||
@@ -28,6 +33,25 @@ 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,
|
||||
period: ClientKeyBudgetWindowPeriod,
|
||||
) -> Result<ClientKeyBudgetWindow, AdminError>;
|
||||
async fn set_budget_window(
|
||||
&self,
|
||||
context: &MutationContext,
|
||||
command: SetClientKeyBudgetWindow,
|
||||
origin: ClientKeyBudgetMutationOrigin,
|
||||
) -> Result<u64, AdminError>;
|
||||
|
||||
async fn get(&self, id: &ClientApiKeyId) -> Result<ClientKeyRecord, AdminError>;
|
||||
async fn list(&self, query: ClientKeyListQuery) -> Result<ClientKeyPage, AdminError>;
|
||||
async fn reveal(&self, id: &ClientApiKeyId) -> Result<ClientKeySecret, AdminError>;
|
||||
@@ -41,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,
|
||||
@@ -85,10 +114,157 @@ 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,
|
||||
period: ClientKeyBudgetWindowPeriod,
|
||||
) -> Result<ClientKeyBudgetWindow, AdminError> {
|
||||
self.store
|
||||
.client_key_budget_window(id, period)
|
||||
.await
|
||||
.map_err(|error| map_store_error(error, "client API key"))
|
||||
}
|
||||
|
||||
async fn set_budget_window(
|
||||
&self,
|
||||
context: &MutationContext,
|
||||
command: SetClientKeyBudgetWindow,
|
||||
origin: ClientKeyBudgetMutationOrigin,
|
||||
) -> Result<u64, AdminError> {
|
||||
if command
|
||||
.window
|
||||
.is_some_and(|window| window.starts_at >= window.ends_at)
|
||||
{
|
||||
return Err(AdminError::invalid("预算窗口结束时间必须晚于开始时间"));
|
||||
}
|
||||
self.store
|
||||
.set_client_key_budget_window(command, origin, context)
|
||||
.await
|
||||
.map_err(|error| map_store_error(error, "client API key"))
|
||||
}
|
||||
|
||||
async fn get(&self, id: &ClientApiKeyId) -> Result<ClientKeyRecord, AdminError> {
|
||||
self.store
|
||||
.get_client_key(id)
|
||||
@@ -98,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(
|
||||
@@ -160,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()))
|
||||
@@ -206,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)?;
|
||||
@@ -271,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()
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
//! 从已保存的错误事实投影管理端来源,不参与执行错误分类或重试
|
||||
|
||||
use crate::model::observability::{
|
||||
UsageErrorEvidence, UsageErrorOrigin, UsageListRecord, UsageRecord,
|
||||
};
|
||||
|
||||
impl UsageListRecord {
|
||||
#[must_use]
|
||||
pub fn error_origin(&self) -> UsageErrorOrigin {
|
||||
error_origin(
|
||||
self.has_upstream_error,
|
||||
self.error_code.as_deref(),
|
||||
self.websocket_close_code,
|
||||
self.upstream_status_code,
|
||||
self.error_kind.as_deref(),
|
||||
self.continuation_unavailable_reason.as_deref(),
|
||||
self.upstream_connection_exit_reason.as_deref(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl UsageRecord {
|
||||
#[must_use]
|
||||
pub fn error_origin(&self) -> UsageErrorOrigin {
|
||||
let has_upstream_error = self.upstream_error.as_ref().is_some_and(|error| {
|
||||
[&error.message, &error.code, &error.error_type]
|
||||
.into_iter()
|
||||
.any(|value| value.as_ref().is_some_and(|value| !value.is_empty()))
|
||||
});
|
||||
error_origin(
|
||||
has_upstream_error,
|
||||
self.provider_error_code.as_deref(),
|
||||
self.websocket_close_code,
|
||||
self.upstream_status_code,
|
||||
self.error_kind.as_deref(),
|
||||
self.continuation_unavailable_reason.as_deref(),
|
||||
self.upstream_connection_exit_reason.as_deref(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// 上游原始事实优先;客户端 HTTP 状态和任意错误文案不能证明错误来源
|
||||
fn error_origin(
|
||||
has_upstream_error: bool,
|
||||
upstream_code: Option<&str>,
|
||||
websocket_close_code: Option<u16>,
|
||||
upstream_status_code: Option<u16>,
|
||||
error_kind: Option<&str>,
|
||||
continuation_reason: Option<&str>,
|
||||
connection_exit_reason: Option<&str>,
|
||||
) -> UsageErrorOrigin {
|
||||
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,
|
||||
|
||||
@@ -8,7 +8,9 @@ use std::{collections::BTreeMap, sync::Arc};
|
||||
|
||||
use async_trait::async_trait;
|
||||
use chrono::{TimeDelta, Utc};
|
||||
use gateway_core::{engine::execution::AuthenticatedClient, policy::ClientPeerSharing};
|
||||
use gateway_core::{
|
||||
account::ProviderAccountId, engine::execution::AuthenticatedClient, policy::ClientPeerSharing,
|
||||
};
|
||||
use tokio::sync::Semaphore;
|
||||
|
||||
use crate::{
|
||||
@@ -113,10 +115,7 @@ impl PeerLinkService for DefaultPeerLinkService {
|
||||
let mut result = PeerLinkExport {
|
||||
observed_at: now,
|
||||
expires_at: now + TimeDelta::minutes(5),
|
||||
budget_access: key
|
||||
.budget
|
||||
.limits
|
||||
.access(key.budget.daily_used_usd, key.budget.weekly_used_usd),
|
||||
budget_access: key.budget.access_at(budget_observed_at.into()),
|
||||
key_limits: key.limits,
|
||||
budget: key.budget,
|
||||
budget_observed_at,
|
||||
@@ -154,16 +153,37 @@ impl PeerLinkService for DefaultPeerLinkService {
|
||||
.filter(|group| group.enabled)
|
||||
.map(|group| group.id.clone())
|
||||
.collect::<Vec<_>>();
|
||||
let scope = client.policy().account_scope();
|
||||
let direct_ids = ids
|
||||
.iter()
|
||||
.filter(|id| {
|
||||
scope
|
||||
.directory()
|
||||
.account(id)
|
||||
.is_some_and(|account| account.is_direct_account())
|
||||
})
|
||||
.cloned()
|
||||
.collect::<Vec<_>>();
|
||||
let accounts = self
|
||||
.accounts
|
||||
.load_accounts_in_enabled_groups(&ids, &groups)
|
||||
.load_accounts_in_enabled_groups(&direct_ids, &groups)
|
||||
.await
|
||||
.map_err(|error| map_store_error(error, "peer accounts"))?
|
||||
.into_iter()
|
||||
.filter(|account| {
|
||||
self.providers
|
||||
.require(&account.provider_kind)
|
||||
.is_ok_and(|provider| provider.is_direct_account(&account.authentication_kind))
|
||||
ProviderAccountId::new(account.id.clone())
|
||||
.ok()
|
||||
.and_then(|id| scope.directory().account(&id))
|
||||
.is_some_and(|frozen| {
|
||||
frozen.direct_authentication_kind()
|
||||
== Some(account.authentication_kind.as_str())
|
||||
})
|
||||
&& self
|
||||
.providers
|
||||
.require(&account.provider_kind)
|
||||
.is_ok_and(|provider| {
|
||||
provider.is_direct_account(&account.authentication_kind)
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let account_ids = accounts
|
||||
@@ -232,26 +252,18 @@ impl PeerLinkService for DefaultPeerLinkService {
|
||||
));
|
||||
}
|
||||
if sharing.share_quota {
|
||||
let (quota, mut models) = projection::quota_and_models(
|
||||
let (quota, models) = projection::quota_and_models(
|
||||
client,
|
||||
&accounts,
|
||||
"as,
|
||||
&self.providers,
|
||||
&runtime,
|
||||
&public_models,
|
||||
&ids,
|
||||
now,
|
||||
limits.max_response_bytes,
|
||||
)
|
||||
.await?;
|
||||
// 发布窗口内缺失或已变更的账号不能被静默剔除后推导整个模型池耗尽
|
||||
if accounts.len() != ids.len() {
|
||||
for model in &mut models {
|
||||
model.complete = false;
|
||||
if model.state == crate::model::peer_link::PeerModelState::Exhausted {
|
||||
model.state = crate::model::peer_link::PeerModelState::Unknown;
|
||||
}
|
||||
}
|
||||
}
|
||||
result.quota = Some(quota);
|
||||
result.models = models;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! 从已授权的本地账号事实派生公开汇总,保留原始观测时间
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use chrono::{DateTime, TimeDelta, Utc};
|
||||
use gateway_core::{
|
||||
@@ -38,7 +38,7 @@ pub(super) fn pool_summary(
|
||||
for account in accounts {
|
||||
match status(account, runtime, now) {
|
||||
AccountStatus::Normal => summary.ready += 1,
|
||||
AccountStatus::RateLimited => summary.cooldown += 1,
|
||||
AccountStatus::QuotaPaused | AccountStatus::RateLimited => summary.cooldown += 1,
|
||||
AccountStatus::QuotaExhausted => summary.exhausted += 1,
|
||||
AccountStatus::Disabled => summary.disabled += 1,
|
||||
AccountStatus::Error => summary.error += 1,
|
||||
@@ -67,12 +67,30 @@ pub(super) async fn quota_and_models(
|
||||
providers: &ProviderAdminRegistry,
|
||||
runtime: &AccountRuntimeSnapshot,
|
||||
models: &[gateway_core::routing::PublicModelId],
|
||||
authorized: &[ProviderAccountId],
|
||||
now: DateTime<Utc>,
|
||||
max_response_bytes: usize,
|
||||
) -> Result<(Vec<PeerAccountQuota>, Vec<PeerModelSummary>), super::PeerLinkError> {
|
||||
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() {
|
||||
@@ -93,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;
|
||||
}
|
||||
@@ -151,6 +192,28 @@ pub(super) async fn quota_and_models(
|
||||
.collect(),
|
||||
});
|
||||
}
|
||||
// 转供账号及发布窗口内消失的账号没有本地观测,只影响它们获准执行的模型
|
||||
if accounts.len() != authorized.len() {
|
||||
let exported = accounts
|
||||
.iter()
|
||||
.map(|account| account.id.as_str())
|
||||
.collect::<BTreeSet<_>>();
|
||||
let missing = authorized
|
||||
.iter()
|
||||
.filter(|id| !exported.contains(id.as_str()))
|
||||
.collect::<Vec<_>>();
|
||||
for (index, model) in models.iter().enumerate() {
|
||||
if index % 16 == 0 {
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
if missing
|
||||
.iter()
|
||||
.any(|id| snapshot.allows_public_model_for_account(model, scope, id))
|
||||
{
|
||||
observations.entry(model.as_str()).or_default().incomplete = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
let summaries = models
|
||||
.iter()
|
||||
.map(|model| {
|
||||
@@ -182,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,
|
||||
@@ -248,6 +337,7 @@ fn status(
|
||||
) -> AccountStatus {
|
||||
resolve_account_status(
|
||||
&AccountStatusFacts {
|
||||
quota_paused: account.quota_paused,
|
||||
enabled: account.enabled,
|
||||
credential_state: account.credential_state,
|
||||
access_token_expires_at: account.access_token_expires_at.map(Into::into),
|
||||
|
||||
@@ -52,7 +52,7 @@ impl PeerInfoService {
|
||||
});
|
||||
let limits = peer.and_then(|peer| peer.key_limits);
|
||||
let info = ProviderUpstreamInfo {
|
||||
discovered: peer.is_some() || stored_failure == Some(UpstreamInfoFailure::Unauthorized),
|
||||
discovered: snapshot::is_discovered(peer, stored_failure),
|
||||
observed_at,
|
||||
stale,
|
||||
connection_revision: connection.revision.clone(),
|
||||
@@ -214,6 +214,7 @@ impl PeerInfoService {
|
||||
}
|
||||
}
|
||||
ProviderQuota {
|
||||
paused_windows: Vec::new(),
|
||||
upstream: Some(info),
|
||||
plan_type: None,
|
||||
observed_at,
|
||||
|
||||
@@ -170,6 +170,7 @@ impl PeerInfoService {
|
||||
.and_then(|peer| quota::observe(&peer, started_at, now))
|
||||
.unwrap_or(QuotaState::unknown());
|
||||
let observation = QuotaObservation {
|
||||
quota_pause: None,
|
||||
expected_connection: Some(connection.clone()),
|
||||
account_id: id.clone(),
|
||||
expected_revision: connection.credential_revision,
|
||||
|
||||
@@ -282,6 +282,21 @@ impl PeerInfoService {
|
||||
}
|
||||
|
||||
impl UpstreamInfoSource for PeerInfoService {
|
||||
fn is_peer(&self, account: &ProviderAccount) -> bool {
|
||||
if !self.supported(account) {
|
||||
return false;
|
||||
}
|
||||
let connection = UpstreamConnection::for_account(account);
|
||||
self.observations
|
||||
.read()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.get(account.id())
|
||||
.is_some_and(|cached| {
|
||||
cached.connection == connection
|
||||
&& snapshot::is_discovered(cached.summary.as_deref(), cached.stored_failure)
|
||||
})
|
||||
}
|
||||
|
||||
fn signal(
|
||||
&self,
|
||||
account: &ProviderAccount,
|
||||
|
||||
@@ -16,6 +16,10 @@ use serde::Deserialize as _;
|
||||
pub(super) const MAX_AGE: Duration = Duration::from_secs(30 * 60);
|
||||
pub(super) const FRESH_FOR: Duration = Duration::from_secs(5 * 60);
|
||||
|
||||
pub(super) fn is_discovered(peer: Option<&PeerLink>, failure: Option<UpstreamInfoFailure>) -> bool {
|
||||
peer.is_some() || failure == Some(UpstreamInfoFailure::Unauthorized)
|
||||
}
|
||||
|
||||
// 不支持协议是连接的识别结果,复用观测存储与版本保护,不伪造上游额度快照
|
||||
pub(super) fn unsupported(connection: &UpstreamConnection) -> OpaqueProviderData {
|
||||
OpaqueProviderData::new(serde_json::Map::from_iter([
|
||||
|
||||
@@ -126,6 +126,46 @@ impl PluginAccountAccess for DefaultPluginAccountAccess {
|
||||
self.quota(account_id, false).await
|
||||
}
|
||||
|
||||
async fn quota_history(
|
||||
&self,
|
||||
account_id: &ProviderAccountId,
|
||||
query: crate::model::quota_history::QuotaHistoryQuery,
|
||||
) -> Result<crate::model::quota_history::QuotaHistoryPage, AdminError> {
|
||||
use crate::model::{observability::TimeRange, quota_history::QuotaHistoryPage};
|
||||
|
||||
let account = self
|
||||
.accounts
|
||||
.load_account_record(account_id)
|
||||
.await
|
||||
.map_err(|error| map_store_error(error, "plugin quota history"))?
|
||||
.ok_or_else(|| AdminError::not_found("账号不存在"))?;
|
||||
let Some(parse) = self
|
||||
.provider(&account.provider_kind)?
|
||||
.quota_history_parser()
|
||||
else {
|
||||
return Ok(QuotaHistoryPage::default());
|
||||
};
|
||||
let start = query.scan_start().max(account.created_at);
|
||||
if start >= query.range.end {
|
||||
return Ok(QuotaHistoryPage::default());
|
||||
}
|
||||
let page = self
|
||||
.accounts
|
||||
.quota_documents(
|
||||
account_id,
|
||||
&account.provider_kind,
|
||||
account.created_at,
|
||||
TimeRange {
|
||||
start,
|
||||
end: query.range.end,
|
||||
},
|
||||
query.cursor.as_ref(),
|
||||
)
|
||||
.await
|
||||
.map_err(|error| map_store_error(error, "plugin quota history"))?;
|
||||
Ok(QuotaHistoryPage::from_documents(page, &query, parse))
|
||||
}
|
||||
|
||||
async fn refresh_quota(
|
||||
&self,
|
||||
account_id: &ProviderAccountId,
|
||||
|
||||
@@ -9,9 +9,10 @@ use crate::{
|
||||
model::{
|
||||
AdminError, MutationContext,
|
||||
client_keys::{
|
||||
ClientKeyBudgetMutationOrigin, ClientKeyCursor, ClientKeyCursorValue,
|
||||
ClientKeyListQuery, ClientKeyPageSize, ClientKeySort, ClientKeySortField,
|
||||
ResetClientKeyBudget, SortDirection, UpdateClientKeyBudgetLimits,
|
||||
ClientKeyBudgetMutationOrigin, ClientKeyBudgetWindow, ClientKeyBudgetWindowPeriod,
|
||||
ClientKeyCursor, ClientKeyCursorValue, ClientKeyListQuery, ClientKeyPageSize,
|
||||
ClientKeySort, ClientKeySortField, ResetClientKeyBudget, SetClientKeyBudgetWindow,
|
||||
SortDirection, UpdateClientKeyBudgetLimits,
|
||||
},
|
||||
plugin_client_keys::{
|
||||
PluginClientKey, PluginClientKeyCursor, PluginClientKeyFacts, PluginClientKeyListQuery,
|
||||
@@ -35,6 +36,29 @@ impl DefaultPluginClientKeyAccess {
|
||||
|
||||
#[async_trait]
|
||||
impl PluginClientKeyAccess for DefaultPluginClientKeyAccess {
|
||||
async fn budget_window(
|
||||
&self,
|
||||
id: &ClientApiKeyId,
|
||||
period: ClientKeyBudgetWindowPeriod,
|
||||
) -> Result<ClientKeyBudgetWindow, AdminError> {
|
||||
self.service.budget_window(id, period).await
|
||||
}
|
||||
|
||||
async fn set_budget_window(
|
||||
&self,
|
||||
owner: &PluginResourceOwner,
|
||||
command: SetClientKeyBudgetWindow,
|
||||
context: &MutationContext,
|
||||
) -> Result<u64, AdminError> {
|
||||
self.service
|
||||
.set_budget_window(
|
||||
context,
|
||||
command,
|
||||
ClientKeyBudgetMutationOrigin::Plugin(owner.clone()),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn facts(&self, id: &ClientApiKeyId) -> Result<PluginClientKeyFacts, AdminError> {
|
||||
let key = self.service.get(id).await?;
|
||||
Ok(PluginClientKeyFacts {
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -306,7 +306,9 @@ impl PluginsService {
|
||||
.await
|
||||
.map_err(|error| map_store_error(error, "proxy"))?;
|
||||
if !record.enabled {
|
||||
return Err(AdminError::invalid("下载代理已禁用,请启用或改为直连"));
|
||||
return Err(AdminError::invalid(
|
||||
"下载代理已禁用,请启用或改用部署默认出口",
|
||||
));
|
||||
}
|
||||
Ok(Some(PluginDistributionEgress::new(
|
||||
record.id,
|
||||
|
||||
@@ -23,7 +23,7 @@ use crate::{
|
||||
},
|
||||
ports::{
|
||||
provider::ProviderAdminRegistry,
|
||||
proxy::{PluginProxyAccess, ProxyProbe, ProxyStore},
|
||||
proxy::{PluginProxyAccess, ProbeRoute, ProxyProbe, ProxyStore},
|
||||
store::AdminStoreErrorKind,
|
||||
},
|
||||
};
|
||||
@@ -47,7 +47,7 @@ impl PluginProxyAccess for DefaultPluginProxyAccess {
|
||||
.get(id)
|
||||
.await
|
||||
.map_err(|error| map_store_error(error, "proxy"))?;
|
||||
// 显式选择代理时必须有可用配置,不能沿用账号停用代理后直连的语义
|
||||
// 显式选择代理时必须有可用配置,不能沿用账号停用代理后使用部署默认出口的语义
|
||||
if !record.enabled {
|
||||
return Err(AdminError::invalid("代理已禁用,请启用后再选择"));
|
||||
}
|
||||
@@ -114,10 +114,10 @@ pub trait ProxiesService: Send + Sync {
|
||||
detect_location: bool,
|
||||
context: &MutationContext,
|
||||
) -> Result<ProxyRecord, AdminError>;
|
||||
/// 探测未保存的连接地址或服务器直连出口,不写入配置或修改账号绑定
|
||||
/// 探测未保存的连接地址、部署默认出口或服务器直连出口,不写入配置或修改账号绑定
|
||||
async fn probe(
|
||||
&self,
|
||||
proxy: Option<&OutboundProxy>,
|
||||
proxy: ProbeRoute<'_>,
|
||||
detect_location: bool,
|
||||
) -> Result<ProxyTestResult, AdminError>;
|
||||
}
|
||||
@@ -323,7 +323,7 @@ impl ProxiesService for DefaultProxiesService {
|
||||
.transpose()
|
||||
.map_err(|_| AdminError::invalid("代理位置不合法"))?;
|
||||
command.test = if command.auto_location {
|
||||
Some(self.probe(Some(&command.proxy), true).await?)
|
||||
Some(self.probe(ProbeRoute::Proxy(&command.proxy), true).await?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
@@ -362,7 +362,7 @@ impl ProxiesService for DefaultProxiesService {
|
||||
if command.auto_location.unwrap_or(current.auto_location)
|
||||
&& (!current.auto_location || proxy != ¤t.proxy)
|
||||
{
|
||||
command.test = Some(self.probe(Some(proxy), true).await?);
|
||||
command.test = Some(self.probe(ProbeRoute::Proxy(proxy), true).await?);
|
||||
}
|
||||
}
|
||||
let result = self
|
||||
@@ -391,7 +391,7 @@ impl ProxiesService for DefaultProxiesService {
|
||||
|
||||
async fn probe(
|
||||
&self,
|
||||
proxy: Option<&OutboundProxy>,
|
||||
proxy: ProbeRoute<'_>,
|
||||
detect_location: bool,
|
||||
) -> Result<ProxyTestResult, AdminError> {
|
||||
let _permit = self
|
||||
@@ -423,7 +423,10 @@ impl ProxiesService for DefaultProxiesService {
|
||||
// 手动解析只为本次测试请求位置,不改变自动跟随的持久配置
|
||||
let result = self
|
||||
.probe
|
||||
.test(Some(&record.proxy), record.auto_location || detect_location)
|
||||
.test(
|
||||
ProbeRoute::Proxy(&record.proxy),
|
||||
record.auto_location || detect_location,
|
||||
)
|
||||
.await;
|
||||
let mutation = self
|
||||
.store
|
||||
|
||||
@@ -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;
|
||||
+1
-1
@@ -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 {
|
||||
+1
-1
@@ -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(),
|
||||
|
||||
|
||||
@@ -106,6 +106,7 @@ fn provider_document_debug_should_not_expose_opaque_material() {
|
||||
#[test]
|
||||
fn representative_quota_should_prefer_short_window_and_highest_usage() {
|
||||
let quota = ProviderQuota {
|
||||
paused_windows: Vec::new(),
|
||||
upstream: None,
|
||||
credits: None,
|
||||
plan_type: None,
|
||||
@@ -129,6 +130,7 @@ fn representative_quota_should_prefer_account_wide_window_over_model_specific_wi
|
||||
let mut model_specific = quota_window("shortTerm", Some(18_000), Some(64.0));
|
||||
model_specific.local_usage_attribution = QuotaLocalUsageAttribution::Unavailable;
|
||||
let quota = ProviderQuota {
|
||||
paused_windows: Vec::new(),
|
||||
upstream: None,
|
||||
credits: None,
|
||||
plan_type: None,
|
||||
@@ -148,6 +150,7 @@ fn representative_quota_should_prefer_account_wide_window_over_model_specific_wi
|
||||
#[test]
|
||||
fn exhausted_quota_should_project_full_usage_to_only_the_representative_window() {
|
||||
let mut quota = ProviderQuota {
|
||||
paused_windows: Vec::new(),
|
||||
upstream: None,
|
||||
credits: None,
|
||||
plan_type: None,
|
||||
@@ -178,6 +181,7 @@ fn exhausted_quota_should_preserve_the_provider_identified_reached_window() {
|
||||
let mut reached = quota_window("monthly", Some(2_592_000), Some(98.0));
|
||||
reached.limit_reached = true;
|
||||
let mut quota = ProviderQuota {
|
||||
paused_windows: Vec::new(),
|
||||
upstream: None,
|
||||
credits: None,
|
||||
plan_type: None,
|
||||
|
||||
@@ -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}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -116,6 +116,7 @@ fn selected_usage_window(quota: &ProviderQuota) -> Option<(&str, AccountUsagePer
|
||||
|
||||
fn usage_quota(windows: Vec<ProviderQuotaWindow>) -> ProviderQuota {
|
||||
ProviderQuota {
|
||||
paused_windows: Vec::new(),
|
||||
upstream: None,
|
||||
credits: None,
|
||||
plan_type: None,
|
||||
@@ -168,6 +169,7 @@ fn usage_window(key: &str, group: &str, seconds: u64) -> ProviderQuotaWindow {
|
||||
#[test]
|
||||
fn dashboard_quota_should_preserve_unknown_and_actual_window_facts() {
|
||||
let mut quota = ProviderQuota {
|
||||
paused_windows: Vec::new(),
|
||||
upstream: None,
|
||||
credits: None,
|
||||
plan_type: None,
|
||||
@@ -333,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;
|
||||
+2
-1
@@ -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> {
|
||||
@@ -59,6 +59,7 @@ fn window(key: &str, days: u64) -> ProviderQuotaWindow {
|
||||
|
||||
fn quota(windows: Vec<ProviderQuotaWindow>) -> ProviderQuota {
|
||||
ProviderQuota {
|
||||
paused_windows: Vec::new(),
|
||||
upstream: None,
|
||||
credits: None,
|
||||
plan_type: None,
|
||||
+38
-2
@@ -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),
|
||||
@@ -3,25 +3,15 @@
|
||||
use gateway_admin::model::retention::{RetentionPolicy, RetentionTarget};
|
||||
|
||||
#[test]
|
||||
fn retention_policy_rejects_invalid_windows_and_preserves_independent_windows() {
|
||||
for (usage, ops, audit) in [
|
||||
(0, 1, 1),
|
||||
(32, 1, 1),
|
||||
(u32::MAX, 1, 1),
|
||||
(1, 0, 1),
|
||||
(1, 1, 0),
|
||||
] {
|
||||
fn retention_policy_rejects_zero_for_each_target() {
|
||||
for (usage, ops, audit) in [(0, 1, 1), (1, 0, 1), (1, 1, 0)] {
|
||||
assert!(RetentionPolicy::try_new(usage, ops, audit).is_err());
|
||||
}
|
||||
let policy = RetentionPolicy::try_new(31, 7, 90).unwrap();
|
||||
assert_eq!(policy.days(RetentionTarget::ModelRequests), 31);
|
||||
assert_eq!(policy.days(RetentionTarget::OpsEvents), 7);
|
||||
assert_eq!(policy.days(RetentionTarget::AdminAuditEvents), 90);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn request_retention_accepts_short_windows_without_changing_other_targets() {
|
||||
for days in [1, 3, 7, 15, 30, 31] {
|
||||
fn request_retention_accepts_positive_windows_without_changing_other_targets() {
|
||||
for days in [1, 31, 32, 365, 3650, u32::MAX] {
|
||||
let policy = RetentionPolicy::try_new(days, 30, 90).unwrap();
|
||||
assert_eq!(policy.days(RetentionTarget::ModelRequests), days);
|
||||
assert_eq!(policy.days(RetentionTarget::OpsEvents), 30);
|
||||
|
||||
@@ -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(),
|
||||
@@ -377,6 +379,7 @@ fn member(account_id: &str, total_slots: u64) -> AccountGroupMemberFact {
|
||||
group_id: group_id(),
|
||||
account_id: account_id.to_owned(),
|
||||
status: AccountStatusFacts {
|
||||
quota_paused: false,
|
||||
enabled: true,
|
||||
credential_state: CredentialState::Ready,
|
||||
access_token_expires_at: None,
|
||||
@@ -419,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,
|
||||
@@ -433,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()),
|
||||
@@ -714,6 +717,7 @@ impl FakeAccountStore {
|
||||
|
||||
fn page_item(account: AccountRecord) -> AccountPageItem {
|
||||
let facts = AccountStatusFacts {
|
||||
quota_paused: false,
|
||||
enabled: account.enabled,
|
||||
credential_state: account.credential_state,
|
||||
access_token_expires_at: account.access_token_expires_at.map(Into::into),
|
||||
@@ -788,6 +792,7 @@ impl AccountStore for FakeAccountStore {
|
||||
summary: AccountSummary {
|
||||
total,
|
||||
normal: 1,
|
||||
quota_paused: 0,
|
||||
quota_exhausted: 0,
|
||||
rate_limited: 0,
|
||||
disabled: 0,
|
||||
@@ -825,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(
|
||||
@@ -843,6 +848,17 @@ impl AccountStore for FakeAccountStore {
|
||||
.clone())
|
||||
}
|
||||
|
||||
async fn quota_documents(
|
||||
&self,
|
||||
_: &gateway_core::account::ProviderAccountId,
|
||||
_: &gateway_core::routing::ProviderKind,
|
||||
_: chrono::DateTime<chrono::Utc>,
|
||||
_: gateway_admin::model::observability::TimeRange,
|
||||
_: Option<&gateway_admin::model::quota_history::QuotaHistoryCursor>,
|
||||
) -> AdminStoreResult<gateway_admin::model::quota_history::QuotaDocumentPage> {
|
||||
unreachable!("测试不读取历史额度文档")
|
||||
}
|
||||
|
||||
async fn load_quota_forecast_history(
|
||||
&self,
|
||||
window: &AccountUsageWindowQuery,
|
||||
@@ -1082,6 +1098,7 @@ impl AccountStore for FakeAccountStore {
|
||||
async fn batch_update_accounts(
|
||||
&self,
|
||||
command: BatchUpdateAccounts,
|
||||
_: gateway_admin::model::accounts::PreparedQuotaPauses,
|
||||
context: &MutationContext,
|
||||
) -> AdminStoreResult<AccountsUpdateResult> {
|
||||
self.record("store.batch_update_accounts");
|
||||
@@ -1128,6 +1145,7 @@ impl AccountStore for FakeAccountStore {
|
||||
|
||||
#[derive(Default)]
|
||||
struct StaticSettingsStore {
|
||||
reset_credit_on_low_weekly_quota: bool,
|
||||
reset_credit_max_weekly_remaining_percent: Option<u32>,
|
||||
}
|
||||
|
||||
@@ -1158,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(),
|
||||
@@ -1176,6 +1196,7 @@ impl SettingsStore for StaticSettingsStore {
|
||||
openai_session_affinity_ttl_hours: 24,
|
||||
responses_max_decompressed_body_bytes: 64 * 1024 * 1024,
|
||||
smart_scheduling: gateway_core::account::SmartSchedulingConfig::default(),
|
||||
quota_reset_window_weights: gateway_core::account::ResetWindowWeights::default(),
|
||||
min_codex_desktop_version: None,
|
||||
min_codex_cli_version: None,
|
||||
usage_retention_days: 30,
|
||||
@@ -1183,9 +1204,10 @@ impl SettingsStore for StaticSettingsStore {
|
||||
audit_retention_days: 30,
|
||||
account_error_protection: gateway_core::account::AccountErrorProtection::default(),
|
||||
account_warmup_enabled: false,
|
||||
account_warmup_schedule_time: "08:00".to_owned(),
|
||||
account_warmup_cron: "0 8 * * *".to_owned(),
|
||||
account_warmup_model: None,
|
||||
reset_credit_lead_minutes: 10,
|
||||
reset_credit_on_low_weekly_quota: self.reset_credit_on_low_weekly_quota,
|
||||
reset_credit_max_weekly_remaining_percent: self
|
||||
.reset_credit_max_weekly_remaining_percent,
|
||||
},
|
||||
@@ -1428,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)
|
||||
@@ -1908,6 +1952,7 @@ async fn accounts_batch_update_should_commit_once_and_notify_each_provider() {
|
||||
.batch_update(
|
||||
&context("batch-update-request"),
|
||||
BatchUpdateAccounts {
|
||||
quota_settings: None,
|
||||
auto_use_quota_credits: None,
|
||||
model_access: Default::default(),
|
||||
outbound_proxy: None,
|
||||
@@ -2076,6 +2121,7 @@ async fn accounts_list_should_degrade_quota_failure_to_empty_window_without_drop
|
||||
let events = events();
|
||||
let openai = FakeProviderAdmin::new("openai", events.clone());
|
||||
openai.set_quota(ProviderQuota {
|
||||
paused_windows: Vec::new(),
|
||||
upstream: None,
|
||||
credits: None,
|
||||
plan_type: None,
|
||||
@@ -2236,6 +2282,7 @@ async fn accounts_list_should_map_unknown_credential_to_error_not_normal() {
|
||||
async fn accounts_list_should_not_derive_rate_limited_from_provider_quota_view() {
|
||||
let provider = FakeProviderAdmin::new("openai", events());
|
||||
provider.set_quota(ProviderQuota {
|
||||
paused_windows: Vec::new(),
|
||||
upstream: None,
|
||||
credits: None,
|
||||
plan_type: None,
|
||||
@@ -2287,6 +2334,7 @@ async fn accounts_list_should_not_derive_rate_limited_from_provider_quota_view()
|
||||
async fn accounts_list_should_not_derive_exhaustion_from_provider_quota_view() {
|
||||
let provider = FakeProviderAdmin::new("openai", events());
|
||||
provider.set_quota(ProviderQuota {
|
||||
paused_windows: Vec::new(),
|
||||
upstream: None,
|
||||
credits: None,
|
||||
plan_type: None,
|
||||
@@ -2493,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),
|
||||
@@ -2552,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()
|
||||
@@ -2581,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()),
|
||||
@@ -2603,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);
|
||||
@@ -2676,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]
|
||||
@@ -2888,11 +3000,69 @@ 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());
|
||||
let reset_at = Utc::now() + TimeDelta::hours(1);
|
||||
provider.set_quota(ProviderQuota {
|
||||
paused_windows: Vec::new(),
|
||||
upstream: None,
|
||||
credits: None,
|
||||
plan_type: None,
|
||||
@@ -3057,6 +3227,7 @@ async fn accounts_list_should_not_attach_account_usage_to_model_specific_quota_w
|
||||
let provider = FakeProviderAdmin::new("openai", events());
|
||||
let reset_at = Utc::now() + TimeDelta::days(7);
|
||||
provider.set_quota(ProviderQuota {
|
||||
paused_windows: Vec::new(),
|
||||
upstream: None,
|
||||
credits: None,
|
||||
plan_type: None,
|
||||
@@ -3362,6 +3533,7 @@ pub(super) fn document() -> ProviderDocument {
|
||||
|
||||
fn empty_quota() -> ProviderQuota {
|
||||
ProviderQuota {
|
||||
paused_windows: Vec::new(),
|
||||
upstream: None,
|
||||
credits: None,
|
||||
plan_type: None,
|
||||
@@ -3399,6 +3571,8 @@ fn quota_local_usage(account_id: &str, total_tokens: u64) -> AccountUsage {
|
||||
pub(super) fn account_record(kind: &str) -> AccountRecord {
|
||||
let now = Utc::now();
|
||||
AccountRecord {
|
||||
quota_paused: false,
|
||||
quota_settings: Default::default(),
|
||||
auto_use_quota_credits: false,
|
||||
outbound_proxy_id: None,
|
||||
outbound_proxy_enabled: true,
|
||||
@@ -3487,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,
|
||||
|
||||
@@ -231,6 +231,8 @@ fn plan(expires_at: chrono::DateTime<Utc>) -> ResetCreditAutomation {
|
||||
revision: 1,
|
||||
next_run_at: Utc::now(),
|
||||
state: ResetCreditAutomationState {
|
||||
next_weekly_check_at: None,
|
||||
awaiting_weekly_recovery_since: None,
|
||||
next_discovery_at: Utc::now() + TimeDelta::days(1),
|
||||
credits: vec![PlannedResetCredit {
|
||||
id: "card_1".into(),
|
||||
@@ -309,7 +311,7 @@ async fn automation_restores_pending_idempotency_after_service_restart() {
|
||||
.state
|
||||
.retry_at = Some(Utc::now() - TimeDelta::seconds(1));
|
||||
drop(services);
|
||||
let restarted = threshold_services(provider.clone(), store.clone(), Some(0)).await;
|
||||
let restarted = threshold_services(provider.clone(), store.clone(), Some(0), true).await;
|
||||
restarted
|
||||
.accounts()
|
||||
.reconcile_reset_credit_automation(account_id)
|
||||
@@ -712,10 +714,12 @@ async fn threshold_services(
|
||||
provider: Arc<FakeProviderAdmin>,
|
||||
store: Arc<FakeAccountStore>,
|
||||
max_remaining: Option<u32>,
|
||||
early: bool,
|
||||
) -> AdminServices {
|
||||
super::super::AdminHarness::new()
|
||||
.accounts(store)
|
||||
.settings(Arc::new(StaticSettingsStore {
|
||||
reset_credit_on_low_weekly_quota: early,
|
||||
reset_credit_max_weekly_remaining_percent: max_remaining,
|
||||
}))
|
||||
.provider(provider)
|
||||
@@ -783,7 +787,7 @@ async fn automation_weekly_threshold_is_optional_inclusive_and_uses_remaining_qu
|
||||
let store = FakeAccountStore::new("openai", events());
|
||||
schedule_due_credit(&provider, &store);
|
||||
provider.set_quota(weekly_quota(used));
|
||||
let services = threshold_services(provider.clone(), store.clone(), threshold).await;
|
||||
let services = threshold_services(provider.clone(), store.clone(), threshold, false).await;
|
||||
services
|
||||
.accounts()
|
||||
.reconcile_reset_credit_automation(ProviderAccountId::new("acct_test").unwrap())
|
||||
@@ -825,7 +829,7 @@ async fn automation_retains_skipped_credit_and_refreshes_quota_on_next_attempt()
|
||||
let store = FakeAccountStore::new("openai", events());
|
||||
schedule_due_credit(&provider, &store);
|
||||
provider.set_quota(weekly_quota(10.0));
|
||||
let services = threshold_services(provider.clone(), store.clone(), Some(70)).await;
|
||||
let services = threshold_services(provider.clone(), store.clone(), Some(70), false).await;
|
||||
let id = ProviderAccountId::new("acct_test").unwrap();
|
||||
services
|
||||
.accounts()
|
||||
@@ -897,7 +901,7 @@ async fn automation_defers_missing_invalid_or_failed_weekly_quota() {
|
||||
schedule_due_credit(&provider, &store);
|
||||
provider.set_quota(quota);
|
||||
*provider.quota_failure.lock().unwrap() = failure;
|
||||
let services = threshold_services(provider.clone(), store.clone(), Some(70)).await;
|
||||
let services = threshold_services(provider.clone(), store.clone(), Some(70), false).await;
|
||||
let result = services
|
||||
.accounts()
|
||||
.reconcile_reset_credit_automation(ProviderAccountId::new("acct_test").unwrap())
|
||||
@@ -971,3 +975,256 @@ async fn automation_nothing_to_reset_retains_credit_and_retries_with_a_new_key()
|
||||
.is_empty()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn early_use_checks_only_known_cards_and_confirms_low_quota_before_spending() {
|
||||
for (enabled, threshold, used, expiring, expected) in [
|
||||
(false, Some(10), 100.0, false, false),
|
||||
(true, None, 99.9, true, false),
|
||||
(true, None, 100.0, false, true),
|
||||
(true, Some(10), 90.0, false, true),
|
||||
(true, Some(100), 0.0, false, false),
|
||||
] {
|
||||
let provider = FakeProviderAdmin::new("openai", events());
|
||||
let store = FakeAccountStore::new("openai", events());
|
||||
enable_capability(&provider);
|
||||
let expiry = Utc::now()
|
||||
+ if expiring {
|
||||
TimeDelta::minutes(5)
|
||||
} else {
|
||||
TimeDelta::days(3)
|
||||
};
|
||||
provider.reset_credits.lock().unwrap().push(card(expiry));
|
||||
let mut record = plan(expiry);
|
||||
let credits = std::mem::take(&mut record.state.credits);
|
||||
store
|
||||
.automations
|
||||
.lock()
|
||||
.unwrap()
|
||||
.insert("acct_test".into(), record);
|
||||
let services =
|
||||
threshold_services(provider.clone(), store.clone(), threshold, enabled).await;
|
||||
let id = ProviderAccountId::new("acct_test").unwrap();
|
||||
provider.set_quota(weekly_quota(used));
|
||||
services
|
||||
.accounts()
|
||||
.reconcile_reset_credit_automation(id.clone())
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(provider.quota_requests().is_empty());
|
||||
let no_card = store
|
||||
.reset_credit_automation("acct_test")
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(no_card.next_run_at, no_card.state.next_discovery_at);
|
||||
store
|
||||
.automations
|
||||
.lock()
|
||||
.unwrap()
|
||||
.get_mut("acct_test")
|
||||
.unwrap()
|
||||
.state
|
||||
.credits = credits;
|
||||
services
|
||||
.accounts()
|
||||
.reconcile_reset_credit_automation(id)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
provider.reset_credit_commands().len(),
|
||||
usize::from(expected)
|
||||
);
|
||||
let status = services
|
||||
.accounts()
|
||||
.reset_credit_automation_status(ProviderAccountId::new("acct_test").unwrap())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
status.weekly_trigger_remaining_percent,
|
||||
enabled.then_some(threshold.unwrap_or(0))
|
||||
);
|
||||
if enabled {
|
||||
assert!(status.next_consume_at.is_none());
|
||||
}
|
||||
let requests = provider.quota_requests();
|
||||
assert_eq!(
|
||||
requests.iter().filter(|r| !r.refresh).count(),
|
||||
usize::from(enabled)
|
||||
);
|
||||
assert_eq!(requests.iter().any(|r| r.refresh), expected);
|
||||
if enabled && !expected {
|
||||
assert!(
|
||||
store
|
||||
.reset_credit_automation("acct_test")
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.next_run_at
|
||||
<= Utc::now() + TimeDelta::seconds(90)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn early_use_rechecks_live_quota_and_waits_for_a_new_recovery_after_restart() {
|
||||
let provider = FakeProviderAdmin::new("openai", events());
|
||||
let store = FakeAccountStore::new("openai", events());
|
||||
enable_capability(&provider);
|
||||
let expiry = Utc::now() + TimeDelta::days(3);
|
||||
let mut later = card(expiry + TimeDelta::days(1));
|
||||
later.id = "later".into();
|
||||
*provider.reset_credits.lock().unwrap() = vec![later, card(expiry)];
|
||||
store
|
||||
.automations
|
||||
.lock()
|
||||
.unwrap()
|
||||
.insert("acct_test".into(), plan(expiry));
|
||||
let id = ProviderAccountId::new("acct_test").unwrap();
|
||||
let services = threshold_services(provider.clone(), store.clone(), Some(10), true).await;
|
||||
let high = ProviderQuota {
|
||||
observed_at: Some(Utc::now()),
|
||||
..weekly_quota(15.0)
|
||||
};
|
||||
provider.set_quota(weekly_quota(90.0));
|
||||
let (release, gate) = tokio::sync::oneshot::channel();
|
||||
*provider.reset_credit_query_gate.lock().unwrap() = Some(gate);
|
||||
let (result, ()) = tokio::join!(
|
||||
services
|
||||
.accounts()
|
||||
.reconcile_reset_credit_automation(id.clone()),
|
||||
async {
|
||||
tokio::time::timeout(
|
||||
std::time::Duration::from_secs(2),
|
||||
provider.reset_credit_query_started.notified(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
provider.set_quota(high.clone());
|
||||
release.send(()).unwrap();
|
||||
}
|
||||
);
|
||||
result.unwrap();
|
||||
assert!(provider.reset_credit_commands().is_empty());
|
||||
|
||||
advance_retry(&store);
|
||||
provider.set_quota(weekly_quota(95.0));
|
||||
services
|
||||
.accounts()
|
||||
.reconcile_reset_credit_automation(id.clone())
|
||||
.await
|
||||
.unwrap();
|
||||
let commands = provider.reset_credit_commands();
|
||||
assert_eq!(commands.len(), 1);
|
||||
assert_eq!(commands[0].credit_id.as_deref(), Some("card_1"));
|
||||
provider
|
||||
.reset_credits
|
||||
.lock()
|
||||
.unwrap()
|
||||
.retain(|credit| credit.id != "card_1");
|
||||
|
||||
let services = threshold_services(provider.clone(), store.clone(), Some(10), true).await;
|
||||
for quota in [weekly_quota(95.0), high, weekly_quota(95.0)] {
|
||||
provider.set_quota(quota);
|
||||
services
|
||||
.accounts()
|
||||
.reconcile_reset_credit_automation(id.clone())
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
assert_eq!(provider.reset_credit_commands().len(), 1);
|
||||
provider.set_quota(ProviderQuota {
|
||||
observed_at: Some(Utc::now()),
|
||||
..weekly_quota(20.0)
|
||||
});
|
||||
services
|
||||
.accounts()
|
||||
.reconcile_reset_credit_automation(id.clone())
|
||||
.await
|
||||
.unwrap();
|
||||
provider.set_quota(weekly_quota(100.0));
|
||||
services
|
||||
.accounts()
|
||||
.reconcile_reset_credit_automation(id)
|
||||
.await
|
||||
.unwrap();
|
||||
let commands = provider.reset_credit_commands();
|
||||
assert_eq!(commands.len(), 2);
|
||||
assert_eq!(commands[1].credit_id.as_deref(), Some("later"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn weekly_recovery_is_observed_without_cards_after_a_failed_quota_readback() {
|
||||
let events = events();
|
||||
let provider = FakeProviderAdmin::new("openai", events.clone());
|
||||
enable_capability(&provider);
|
||||
let store = FakeAccountStore::new("openai", events.clone());
|
||||
let expiry = Utc::now() + TimeDelta::days(3);
|
||||
let mut record = plan(expiry);
|
||||
record.state.pending = Some(PendingResetCredit {
|
||||
credit: record.state.credits[0].clone(),
|
||||
redeem_request_id: uuid::Uuid::new_v4().to_string(),
|
||||
});
|
||||
store
|
||||
.automations
|
||||
.lock()
|
||||
.unwrap()
|
||||
.insert("acct_test".into(), record);
|
||||
let id = ProviderAccountId::new("acct_test").unwrap();
|
||||
let services = threshold_services(provider.clone(), store.clone(), Some(10), true).await;
|
||||
let accounts = services.accounts();
|
||||
*provider.quota_failure.lock().unwrap() = Some(ProviderAdminErrorKind::Unavailable);
|
||||
accounts
|
||||
.reconcile_reset_credit_automation(id.clone())
|
||||
.await
|
||||
.unwrap();
|
||||
let waiting = store
|
||||
.reset_credit_automation("acct_test")
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(waiting.state.credits.is_empty());
|
||||
assert_eq!(waiting.state.last_result.as_deref(), Some("reset"));
|
||||
assert!(waiting.next_run_at <= Utc::now() + TimeDelta::seconds(90));
|
||||
|
||||
provider.set_quota(ProviderQuota {
|
||||
observed_at: Some(Utc::now()),
|
||||
..weekly_quota(20.0)
|
||||
});
|
||||
accounts
|
||||
.reconcile_reset_credit_automation(id.clone())
|
||||
.await
|
||||
.unwrap();
|
||||
let recovered = store
|
||||
.reset_credit_automation("acct_test")
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(recovered.next_run_at, recovered.state.next_discovery_at);
|
||||
assert!(!recorded(&events).contains(&"provider.reset_credits"));
|
||||
assert_eq!(
|
||||
provider
|
||||
.quota_requests()
|
||||
.iter()
|
||||
.map(|r| r.refresh)
|
||||
.collect::<Vec<_>>(),
|
||||
[true, false]
|
||||
);
|
||||
|
||||
provider.set_quota(weekly_quota(95.0));
|
||||
let mut new_card = card(expiry);
|
||||
new_card.id = "next".into();
|
||||
provider.reset_credits.lock().unwrap().push(new_card);
|
||||
accounts
|
||||
.reset_credits(&context("new-card"), id.clone())
|
||||
.await
|
||||
.unwrap();
|
||||
accounts
|
||||
.reconcile_reset_credit_automation(id)
|
||||
.await
|
||||
.unwrap();
|
||||
let commands = provider.reset_credit_commands();
|
||||
assert_eq!(commands.len(), 2);
|
||||
assert_eq!(commands[1].credit_id.as_deref(), Some("next"));
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user