mirror of
https://github.com/zyycn/codex-proxy-rs.git
synced 2026-12-06 00:00:51 +00:00
Compare commits
172
Commits
v3.56.0
...
v3.62.1-rc.2
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
177679a13c | ||
|
|
195c51c06c | ||
|
|
745bd15d3d | ||
|
|
3170b92d47 | ||
|
|
8b40e707fd | ||
|
|
15aabfc861 | ||
|
|
0ebf6739e2 | ||
|
|
b987cca4aa | ||
|
|
72e82c565e | ||
|
|
47ccdeb737 | ||
|
|
b20b0e2013 | ||
|
|
16fc302d46 | ||
|
|
95c35d0a67 | ||
|
|
259a2e1ba0 | ||
|
|
2f51412625 | ||
|
|
32f3b11ddf | ||
|
|
c2891e14ce | ||
|
|
b28eee6e18 | ||
|
|
6bf182677a | ||
|
|
8d4b0496e2 | ||
|
|
9b08c3a50d | ||
|
|
f43e1f95c3 | ||
|
|
21cf139c96 | ||
|
|
7d6e4cc4e7 | ||
|
|
2ddcd7c936 | ||
|
|
c71e6176c5 | ||
|
|
28d3e3c2cb | ||
|
|
dd793a84ab | ||
|
|
5ed8b626d7 | ||
|
|
96d8b25d0b | ||
|
|
a193de4eba | ||
|
|
e296bef65e | ||
|
|
89092272a1 | ||
|
|
09f3b39bbc | ||
|
|
7591845f74 | ||
|
|
67ac8fd067 | ||
|
|
b232e367fc | ||
|
|
0bdaa29907 | ||
|
|
cc798e33a1 | ||
|
|
6eabda047c | ||
|
|
3c560b9276 | ||
|
|
77c42cea98 | ||
|
|
dd234c3619 | ||
|
|
b5e691c63d | ||
|
|
2d0a52096a | ||
|
|
47620e217a | ||
|
|
48aeccd0e0 | ||
|
|
bdc618701b | ||
|
|
acd76a09dc | ||
|
|
808387442b | ||
|
|
5bc4e3e5c8 | ||
|
|
7e98130cac | ||
|
|
2821a5e3bd | ||
|
|
6a6a167d41 | ||
|
|
cffb6b35d2 | ||
|
|
17e50df06f | ||
|
|
f2d95cc3fa | ||
|
|
e4f6e1d4e3 | ||
|
|
66f650f097 | ||
|
|
ca4d02068a | ||
|
|
d185a639a9 | ||
|
|
3078dd9993 | ||
|
|
cad1a9245e | ||
|
|
d4d1114e73 | ||
|
|
9e8a5a9b61 | ||
|
|
9a5bf55bdf | ||
|
|
f57a375407 | ||
|
|
82cb91e1af | ||
|
|
441c012613 | ||
|
|
983eca5fe7 | ||
|
|
e0b0ab14da | ||
|
|
b4bb97d1dc | ||
|
|
9f979110d2 | ||
|
|
a5cddfe4a5 | ||
|
|
914c4c24d3 | ||
|
|
7251546c75 | ||
|
|
3c38925716 | ||
|
|
43ca35b027 | ||
|
|
95d545a7d8 | ||
|
|
db3324f90a | ||
|
|
30bcff3419 | ||
|
|
329503d967 | ||
|
|
eae19e211e | ||
|
|
294e9c8bd8 | ||
|
|
1b92c552b9 | ||
|
|
c9fb2ac465 | ||
|
|
6bf109e784 | ||
|
|
fa187c5031 | ||
|
|
5f7e1723f3 | ||
|
|
7d34be5d02 | ||
|
|
ebb3c4b1fa | ||
|
|
2bf0ca146d | ||
|
|
5c1e27fc47 | ||
|
|
03f21c26eb | ||
|
|
280ded5707 | ||
|
|
8fb07f993c | ||
|
|
ee691246c7 | ||
|
|
e406a6bcd8 | ||
|
|
4ffaeb3051 | ||
|
|
a126c194f5 | ||
|
|
964e22eb91 | ||
|
|
5a5d07d1c7 | ||
|
|
a41a0498d1 | ||
|
|
9aea228fa8 | ||
|
|
25965cbfb3 | ||
|
|
fa0bedd28b | ||
|
|
1bd27ef6c8 | ||
|
|
0981996ef3 | ||
|
|
783e4578ba | ||
|
|
0db3c6a215 | ||
|
|
fe1c38aeb7 | ||
|
|
2cbdd62b4e | ||
|
|
39cc23d2f0 | ||
|
|
102131056b | ||
|
|
c94a443620 | ||
|
|
ef870690e3 | ||
|
|
f4254104c9 | ||
|
|
36136728c6 | ||
|
|
0d731c5059 | ||
|
|
3fe4248fd6 | ||
|
|
3cc9c71ab5 | ||
|
|
2dc3ba8d56 | ||
|
|
7c16190936 | ||
|
|
c89152ce08 | ||
|
|
4b8825a28f | ||
|
|
95a89e9010 | ||
|
|
4fc8f836be | ||
|
|
ddd33da737 | ||
|
|
1d875def09 | ||
|
|
e6def7b634 | ||
|
|
f5d3c55d75 | ||
|
|
30487dfbf1 | ||
|
|
71cfdcb33e | ||
|
|
98954aefb6 | ||
|
|
c74c570228 | ||
|
|
fbf1aa1d9b | ||
|
|
91d3b8cad8 | ||
|
|
591dead0ec | ||
|
|
44cc0757a3 | ||
|
|
0cfaca2a2b | ||
|
|
3ec00a152c | ||
|
|
7633a62368 | ||
|
|
9684b9d00f | ||
|
|
4c49ddb479 | ||
|
|
be58d38aef | ||
|
|
40cab881d0 | ||
|
|
2ec300ecf4 | ||
|
|
2b6536236f | ||
|
|
01cebb810d | ||
|
|
909b514074 | ||
|
|
533a415a99 | ||
|
|
7b04e08d81 | ||
|
|
8acf376091 | ||
|
|
62e9cd03c5 | ||
|
|
81dacf603f | ||
|
|
5173314136 | ||
|
|
a51395bbc5 | ||
|
|
eece08a4a2 | ||
|
|
4bdb15ccd9 | ||
|
|
aad6304a33 | ||
|
|
db22550e61 | ||
|
|
6950c02ee4 | ||
|
|
5265cc8424 | ||
|
|
984b3e8e08 | ||
|
|
a5c23374e7 | ||
|
|
83bf9fafb3 | ||
|
|
409e36bf95 | ||
|
|
77ff65f400 | ||
|
|
75d0d0e0f8 | ||
|
|
1d92d638ba | ||
|
|
4e96567b6d | ||
|
|
42fdaecd7a |
No files matched your search
@@ -1,6 +1,6 @@
|
||||
---
|
||||
name: cpr-dev-guide
|
||||
description: Codex Proxy RS 的需求评估、排障、开发、代码审查与文档维护入口
|
||||
description: Codex Proxy RS 的需求评估、排障、开发、代码审查与文档维护,包括对代码和文档改动的验收
|
||||
---
|
||||
|
||||
# 开发指南
|
||||
@@ -16,15 +16,17 @@ description: Codex Proxy RS 的需求评估、排障、开发、代码审查与
|
||||
|
||||
评估功能建议、排障、开发和审查时,先按[问题与方案依据](../../../CONTRIBUTING.md#问题与方案依据)核实使用者要完成什么、当前行为造成了什么影响。反馈直接给出改法时,先弄清提出这个改法的原因
|
||||
|
||||
先确定正常使用时应得到的结果。设计校验、回退或故障恢复时,同时看它防住的具体风险和它可能挡住的正常用法。按协议、隔离要求和实际部署条件选择对正常路径影响最小的做法。只在假设的部署场景下才需要的处理,留到有相应需求时再做
|
||||
|
||||
排查故障时,从症状沿实际调用链回溯,定位行为最早偏离预期的环节,用源码、诊断或对照复现说明触发条件如何导致结果。原因尚未确定时,区分已知事实与假设,指出哪项证据能区分可能原因。确认根因后,在负责该行为的模块修复,用原触发场景验证
|
||||
|
||||
涉及 Codex 时,以对应版本的官方源码核实客户端行为,默认透明转发,只做必要适配。建议宿主接管已有决定时,指出需要它介入的网关职责或实际约束。若只是个别部署希望采用不同策略,说明不建议内置的原因。实现可行性不能证明宿主应当承担这项需求
|
||||
|
||||
## 先确定领域与必读规范
|
||||
|
||||
按受影响行为和实际文件执行下表所有命中项。流程引用首次完整读取,长文档按标题定位指定章节
|
||||
确定方案前按受影响行为和实际文件执行下表所有命中项。流程引用首次完整读取,长文档按标题定位指定章节。单独验收和开发收尾采用同一组领域规范
|
||||
|
||||
| 领域或操作,行为影响与文件路径满足其一即可 | 确定方案前读取与执行 |
|
||||
| 领域或操作,行为影响与文件路径满足其一即可 | 必读规范与检查 |
|
||||
| --- | --- |
|
||||
| 调整页面、弹窗、表单、按钮、文案、样式或交互;目标在 `frontend/`、`modules/ui/`、插件前端,或是 `.vue` 文件 | [前端流程](references/frontend.md),局部修改同样按影响范围检查组件复用、文案、Token、样式、视觉状态和运行证据 |
|
||||
| 插件接入、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) |
|
||||
@@ -41,11 +43,13 @@ description: Codex Proxy RS 的需求评估、排障、开发、代码审查与
|
||||
|
||||
## 执行与收尾
|
||||
|
||||
长任务按 [任务延续与收尾](../../../AGENTS.md#任务延续与收尾)恢复已匹配的领域、具体约束与验证进度。单独收到验收请求时,先确认待验收版本和范围,发现偏差按当前授权处理
|
||||
|
||||
1. 遵守已提供的 [AGENTS.md](../../../AGENTS.md),按其 CodeGraph 约定定位代码;确认工作区、任务范围与已有改动,找到事实归属、同类实现和调用链,补齐上表命中规范及[项目约定](../../../CONTRIBUTING.md#项目约定)对应条目后再修改
|
||||
2. 以最终差异重新匹配上表,补齐新增领域的规范并检查实际实现,再处理本次引入的职责越界、重复规则、冗余状态与无依据分支;删除或替换功能时一并清理失效的配置、类型、调用、测试与文档,已部署数据和公开合同仍遵守所属迁移及兼容规则;仅审查时报告,不自行修复
|
||||
2. 按最终差异与受影响行为重新匹配上表,逐项对照适用条款检查实际实现。处理本次引入的职责越界、重复规则、冗余状态与无依据分支;删除或替换功能时一并清理失效的配置、类型、调用、测试与文档,已部署数据和公开合同仍遵守所属迁移及兼容规则;仅审查时报告,不自行修复
|
||||
3. 模块移动或重命名时,同步核对源码、测试、公开导出及配置、脚本中的名称和路径引用;在本任务内更新受影响的文档、示例和引用
|
||||
4. 按变更范围执行[验证](../../../CONTRIBUTING.md#验证)及其停止条件,后端命令见[验证命令](../../../docs/architecture.md#验证命令);复用仍适用的验证证据与用户已确定的验收分工,区分通过、失败、跳过与未执行
|
||||
5. 交付前按[首要写作要求](#首要写作要求言简意赅)通读本次新增或修改的文字。交代实际结果与验证缺口;前端按[前端流程](references/frontend.md)核对运行证据,后端按上表检查生命周期,不把构建通过当作行为验收
|
||||
5. 交付前按[首要写作要求](#首要写作要求言简意赅)通读本次新增或修改的文字。验收结论同时依据规范核对结果与行为验证证据;有规范偏差或缺少必要证据时,指出具体位置或未验证场景。前端按[前端流程](references/frontend.md)核对运行证据,后端按上表检查生命周期
|
||||
6. 按授权完成提交与交付;提交前按[提交约定](../../../CONTRIBUTING.md#项目约定)准备提交信息与实际共同作者署名,提交后核对实际提交消息,PR 的 AI 披露不能替代提交署名
|
||||
|
||||
## 测试维护
|
||||
@@ -54,7 +58,7 @@ description: Codex Proxy RS 的需求评估、排障、开发、代码审查与
|
||||
- 移动或重命名测试时,核对受影响的场景覆盖是否保留;涉及子进程调用或名称过滤时,同步更新调用入口并实际运行,确认目标用例确实执行且行为断言通过
|
||||
- 清理只证明旧字段、旧路由或旧实现已经消失的用例与附带断言;未知字段校验使用合法请求基线加无业务含义的未知字段,避免因缺少必填项等其他错误而误通过
|
||||
- 同一层对同一行为的重复覆盖合并为清晰的场景矩阵,复用相邻测试夹具;跨层测试确有不同职责或失败路径时保留,不为统一而扩大测试辅助抽象
|
||||
- 断言可观察的行为与业务不变量,避免复述结构体赋值、罗列表列或字段清单、匹配 SQL 文本与源码布局
|
||||
- 断言可观察的行为与业务不变量,避免复述实现细节。验收上游兼容行为时,先从对应版本的上游实现确定预期,再核对网关对同一输入的处理。例如历史应增量续接时,要看出站请求是否只含预期的增量,因为回退全量也可能返回成功
|
||||
- 维护项目明确要求的架构边界检查;发现漏检时,对照规则核实扫描范围、排除项与被检查的依赖关系,优先补齐现有检查中能稳定判定的缺口
|
||||
- 当前协议兼容、数据读取兼容、安全边界、并发和资源生命周期仍需覆盖,不按 `old`、`legacy` 等名称机械删除,也不能用改名代替无效用例清理
|
||||
- 不在仓库中新增或保留迁移 SQL 专项测试,包括迁移文本、schema 演变与指定版本升级用例;需要验证迁移执行、数据保留或回滚时,在临时目录编写一次性验证并使用隔离数据库,测试通过即可,临时脚本不纳入维护测试集
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
interface:
|
||||
display_name: "cpr-dev-guide"
|
||||
short_description: "开发、排障与审查入口,按行为影响匹配领域边界并验证实现"
|
||||
default_prompt: "使用 $cpr-dev-guide 按请求、行为影响和实际文件匹配领域必读规范,读完职责边界再确定方案,完成已授权的开发或审查、自审与验证。"
|
||||
short_description: "开发、排障、审查与验收入口,按受影响行为匹配并执行领域规范"
|
||||
default_prompt: "使用 $cpr-dev-guide 按受影响行为和实际文件匹配领域规范,开发时据此确定方案,验收时对照最终实现和验证证据。"
|
||||
policy:
|
||||
allow_implicit_invocation: true
|
||||
@@ -4,7 +4,9 @@
|
||||
|
||||
## 领域必读
|
||||
|
||||
确定页面方案或审查结论前,读取[前端职责](../../../../docs/architecture.md#34-前端模块职责)、[文案与信息层级](../../../../docs/theme.md#界面文案与信息层级)和[界面验证](../../../../CONTRIBUTING.md#界面验证)的完整章节,局部修改同样读取。明确本次用户操作、原页面、最接近的同类实现及可复用基础组件,沿用既有设计与请求层,按本轮验收分工留存所需截图
|
||||
确定页面方案或审查结论前,读取[前端职责](../../../../docs/architecture.md#34-前端模块职责)、[文案与信息层级](../../../../docs/theme.md#界面文案与信息层级)和[界面验证](../../../../CONTRIBUTING.md#界面验证)的完整章节,局部修改同样读取。新增或移动文件时,页面与布局按同一套目录规则,根据调用范围和导出内容区分组件私有实现、共享常量和共享纯函数
|
||||
|
||||
明确本次用户操作、原页面、最接近的同类实现及可复用基础组件,沿用既有设计与请求层,按本轮验收分工留存所需截图
|
||||
|
||||
## 按改动补齐规范
|
||||
|
||||
@@ -21,10 +23,15 @@
|
||||
|
||||
普通维护和新增业务页面沿用现有设计;设计技能中的配色、字体、布局探索不覆盖项目规范,主题算法只在涉及时读取
|
||||
|
||||
- 页面和组件不添加浏览器原生提示的 `title` 属性。确需补充说明时,按内容复用已有的 Tooltip 或 Popover
|
||||
- 列表行需要快速展示少量字段时,先核对列表接口已返回的字段和后端查询已读取的数据。能随当前页低成本返回的字段直接用于展示,完整详情在用户打开详情时加载
|
||||
|
||||
## 验收范围与收尾
|
||||
|
||||
验证前按[界面验证](../../../../CONTRIBUTING.md#界面验证)明确本次受影响的用户路径、状态和通过条件。局部修改围绕受影响区域及相关操作验收;主题、窗口尺寸和空/加载/错误状态仅在受影响时补充,共用主题或基础组件变更按主题规范扩大范围
|
||||
|
||||
沿实际操作验证待确认、执行中、完成、失败与取消等受影响阶段,同时检查当前弹层和背景区域,核对应该出现的反馈与不应出现的状态。必要时延迟模拟响应以观察过渡状态,不能仅凭请求成功或截图齐全判定交互通过
|
||||
|
||||
通过后按[验证停止条件](../../../../CONTRIBUTING.md#验证)收尾;只有新改动、失败或未解疑点时补验相关部分。补交截图或 PR 材料时复用仍有效的运行证据
|
||||
|
||||
## 交付前
|
||||
@@ -37,7 +44,7 @@
|
||||
- **样式与状态**:是否使用对应 Token 与 utility,局部样式是否符合适用边界,受影响的主题、窄屏及交互状态是否正确
|
||||
- **模块归属**从调用方核对公开入口。页面或多文件组件通过 `index.vue` 提供界面,其他页面复用整页时引用所属模块的布局入口,独立复用的业务组件按领域放置
|
||||
- **Provider 边界**涉及账号操作、身份配置或定价时,沿接口响应、控件和提交载荷追踪同一条规则。服务端决定的能力使用接口字段,Provider 专属表单解释自己的字段,多个页面共用的编辑流程只维护一份。按[前端职责](../../../../docs/architecture.md#34-前端模块职责)核对归属
|
||||
- **查询与动作**:区分首次加载、刷新、分页、单行与批量操作,核对 loading、禁用状态的影响范围;沿用请求层错误处理,不在页面叠加同一错误的提示
|
||||
- **查询与动作**:区分首次加载、刷新、分页、单行与批量操作,明确当前动作的反馈归属及其他控件的禁用范围,避免同一动作在前后景重复显示执行反馈。待确认不等于已提交,复用交互时重新核对 loading、进度与结果的显示条件是否适用于当前动作;沿用请求层错误处理,不在页面叠加同一错误的提示
|
||||
- **运行证据**:按界面验证核对截图与实际交互,证据对应当前实现;页面 PR 的可访问图片和 Draft 条件按该节执行
|
||||
|
||||
交付简述所复用的页面或组件、实际验证范围及缺口;环境不足时如实说明,不能仅凭构建、源码或截图推断未验证的行为
|
||||
@@ -20,7 +20,7 @@
|
||||
|
||||
调用入口前重新核对当前脚本的副作用、目标版本和待推送提交,保留无关工作区内容,不自动清理或暂存用户文件。
|
||||
先编辑 `release/notes.md`,保留为未提交改动(已暂存或未暂存均可);其他已跟踪文件的改动应先单独提交。
|
||||
脚本只改 `release/version.yaml` 的顶层 `version`,按[接口弃用规则](../../../../backend/crates/gateway-plugin/sdk/docs/manifest.md#接口弃用)校验并维护 `plugin-api-deprecations.json`,将这些差异与最终工作区中的发布说明一起提交为 `chore: bump version to <version>`。
|
||||
脚本更新 `release/version.yaml` 的顶层 `version`,按[接口弃用规则](../../../../backend/crates/gateway-plugin/sdk/docs/manifest.md#接口弃用)校验并维护 `plugin-api-deprecations.json`,与手写发布说明一起提交为 `chore: bump version to <version>`。
|
||||
不要提前单独提交说明或把版本文件改成目标版本;脚本要求说明相对 HEAD 有改动,并自行更新版本号。
|
||||
本任务需要的提交按[项目约定](../../../../CONTRIBUTING.md#项目约定)保留英文 Conventional Commits 与相应署名。
|
||||
|
||||
@@ -31,7 +31,7 @@ release/publish "$release_version"
|
||||
```
|
||||
|
||||
该命令会创建上述版本提交与 annotated tag,原子推送分支和 tag,再从长期分支手动触发 `release.yml`。
|
||||
只读预检使用 `release/publish --check "$release_version"`。发布工作流读取 tag 中的说明,修改 tag 之后的本地文件不会改变该次构建。
|
||||
只读预检使用 `release/publish --check "$release_version"`。发布工作流读取 tag 中的手写说明,为常规版本追加安装入口、文档和 GitHub 变更列表。
|
||||
|
||||
只调整已发布页面的标题或正文时,编辑对应 GitHub Release 的 `name` 或 `body` 并回读核对;
|
||||
保持已有 tag、源码提交、附件和预发行状态,不重新执行发布入口。
|
||||
@@ -46,7 +46,9 @@ release/publish "$release_version"
|
||||
|
||||
- 尚未推送:补齐缺失的步骤,按入口原子推送分支和 tag
|
||||
- 已推送但未触发:使用入口提示的 dispatch 命令
|
||||
- 已有 run:跟踪对应提交的任务,失败时重跑失败任务。构建产物保留 7 天,过期后从原 tag 重跑完整工作流
|
||||
- Release 尚未公开时,跟踪原 run 并重跑失败任务。构建产物保留 7 天,过期后从原 tag 重跑工作流
|
||||
- 正式版已公开,GitHub Latest 或镜像 `latest` 提升中断时,在已有恢复授权下执行 `gh workflow run release.yml --ref main -f tag="v$release_version" -f recover_latest=true`。任务核对公开附件、版本镜像与 tag 提交对应的镜像摘要,补齐稳定入口后同步通道表。若任一稳定入口已经指向更新版本,则保留现有入口
|
||||
- 仅通道表写入失败时,确认工作流能写入 `main`,按已有授权执行 `gh workflow run release.yml --ref main -f tag="v$release_version" -f index_only=true`。各通道均可用此入口重新核对公开附件并合并通道表
|
||||
|
||||
### 修复源码后同版本重发
|
||||
|
||||
@@ -58,9 +60,10 @@ release/publish "$release_version"
|
||||
### 验收
|
||||
|
||||
- 发布完成后核对 GitHub Release 的版本、正式版/预发行状态和中文变更正文;对照平台清单与工作流确认归档、校验和及镜像产物。
|
||||
工作流附加的安装说明和自动提交列表按其当前配置处理,不用它们替代手写的中文变更说明。
|
||||
手写正文应与 tag 内的说明一致,核对安装入口和 `Full Changelog` 指向目标版本,正式版的比较范围从上一正式版开始
|
||||
- 核对 `backend-validation` 的结果。复用时检查摘要中的源码提交和成功 CI 链接,确认发行提交仅修改版本与说明;未满足复用条件时检查本次完整后端任务,不能把 `quality / backend` 的跳过单独记为测试通过
|
||||
- 回读 `main:release/version.yaml` 的 `published`。正式版参与同一大版本四个普通通道的比较;RC 参与 RC、Beta、Alpha,Beta 参与 Beta、Alpha,Alpha 只参与自身。实验版只推进 `exp["X.Y.Z"]`。有通道推进时应有 `chore(release): update release channels to <version>` 提交;重复执行或较旧版本未推进任何通道时无提交
|
||||
- 通道表写入失败时,确认该版本已公开、工作流能写入 `main`,再按已有授权执行 `gh workflow run release.yml --ref main -f tag="v$release_version" -f index_only=true`。恢复任务重新校验公开附件、读取并合并当前清单,不重新打包或改 tag
|
||||
- 正式版提升或恢复后,回读 GitHub Latest 的 tag 与镜像 `latest` 的摘要,核对两者均指向预期正式版
|
||||
- 保留 v3.42.0 在线升级使用的 `update-index` 页面和 v3.42.1 的 `version.yaml` 附件
|
||||
- 返回版本、tag 对应提交、Release/工作流链接及实际结果。失败、仍在构建或缺失产物时明确说明,不能称为发布成功;
|
||||
Release 和镜像已生成也不表示用户的运行实例已经升级。
|
||||
@@ -9,12 +9,20 @@
|
||||
3. 使用用户确定的目标版本,建议版本时说明兼容性、能力或修复依据;同名 tag 先区分重试与新发行,不递增版本掩盖冲突
|
||||
4. 命名与晋级按[版本命名与升级规则](../../../../deploy/README.md#版本命名与升级规则),实验版另读[实验流程](experimental.md#分支与版本)
|
||||
|
||||
对比基线选自已公开且 tag 位于目标提交历史内的 GitHub Release
|
||||
|
||||
- 推荐正式版号和编写发布说明时,都核对上一正式版到目标提交的最终差异,覆盖期间全部预发行。对于向后兼容的变更,只要有用户可用的新功能,就从上一正式版递增 minor 并将 patch 归零,仅含修复则递增 patch
|
||||
- alpha、beta、rc 优先对比同一 `X.Y.Z` 的上一常规预发行,没有时对比上一正式版
|
||||
- exp 对比同一 `X.Y.Z` 的上一实验版,首次实验对比同号正式版
|
||||
- 没有前序发行的首次发布从仓库起点核对
|
||||
|
||||
## 发布说明
|
||||
|
||||
读取当前 [notes.md](../../../../release/notes.md)与[项目约定](../../../../CONTRIBUTING.md#项目约定)中的发布说明条目
|
||||
|
||||
- 只在发布说明任务中修改 `release/notes.md`,替换为本次版本内容,首行为目标 tag,正文使用中文
|
||||
- 常规版本按「新增功能」「优化改进」「问题修复」「升级须知」归类,省略空章节;单一改动可直接写一句。安装命令和文档入口由工作流附加
|
||||
- 常规版本的手写正文按「新增功能」「优化改进」「问题修复」「升级须知」归类,省略空章节;单一改动可直接写一句
|
||||
- 常规版本的安装入口、文档链接和 GitHub 变更列表由工作流在发版时追加
|
||||
- 每条用一句短语讲清一个用户可感知的结果,不加句号,例如「系统更新:确认当前平台有安装包后才提示升级」
|
||||
- 同一变化只写一次,保留会影响使用或升级的默认值和限制,不展开实现过程、逐条翻译提交或写未经验证的承诺
|
||||
- 剔除回退、重复及未进入发行范围的内容,升级事项须能追溯到实际迁移、配置或兼容变化
|
||||
@@ -31,7 +39,7 @@
|
||||
在上一发行基线到 HEAD 的提交中检查是否已有目标版本的备版提交(`chore: bump version to <version>`;查历史时也匹配 `chore(release): prepare v<version>` 和 `chore(release): v<version>`),即使同名 tag 已不存在也要查。命中时先核对该提交对应的发行状态,按[失败恢复](operations.md#恢复与验收)处理,不在旧提交上再叠一个同名提交
|
||||
|
||||
发布说明准备好、其他代码已提交后,执行 `release/publish --check <version>`,检查版本、说明、工作区、远端分支与 tag、工具链和插件兼容窗口。
|
||||
预检不修改文件、Git 引用或远端状态;远端存在本地未知提交时先同步再检查。它不替代 CI、发行物验证或实际发布授权
|
||||
预检不修改文件、Git 引用或远端状态;远端存在本地未知提交时,先同步再检查。它不替代 CI、发行物验证或实际发布授权
|
||||
|
||||
按[验证要求](../../../../CONTRIBUTING.md#验证)核对目标提交的证据,区分通过、失败、跳过与未执行
|
||||
数据库变更同时读取[迁移冻结规则](../../../../backend/migrations/README.md#冻结规则):
|
||||
|
||||
@@ -27,6 +27,7 @@ updates:
|
||||
# 按官方 Codex 锁文件、协议指纹或已审计 fork 固定;完成对应核对与实测后再手动升级。
|
||||
ignore:
|
||||
- dependency-name: aws-lc-rs
|
||||
- dependency-name: h2
|
||||
- dependency-name: hyper
|
||||
- dependency-name: hyper-rustls
|
||||
- dependency-name: hyper-tls
|
||||
@@ -71,6 +72,8 @@ updates:
|
||||
directories:
|
||||
- /deploy
|
||||
labels: []
|
||||
ignore:
|
||||
- dependency-name: rust
|
||||
schedule:
|
||||
interval: weekly
|
||||
day: monday
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
require_relative 'release-metadata'
|
||||
require_relative 'published-channels'
|
||||
|
||||
# 构建和验证可以并行;调用方必须在仓库级发布锁内执行本脚本
|
||||
module ReleasePublication
|
||||
@@ -39,44 +39,69 @@ module ReleasePublication
|
||||
end
|
||||
end
|
||||
|
||||
def self.image_digest(ref)
|
||||
digest = run('docker', 'buildx', 'imagetools', 'inspect', ref, '--format', '{{.Manifest.Digest}}')
|
||||
raise "Invalid image digest for #{ref}" unless digest.match?(/\Asha256:[a-f0-9]{64}\z/)
|
||||
digest
|
||||
end
|
||||
|
||||
def self.tag(image, digest, name)
|
||||
ref = "#{image}:#{name}"
|
||||
run('docker', 'buildx', 'imagetools', 'create', '-t', ref, "#{image}@#{digest}")
|
||||
actual = run('docker', 'buildx', 'imagetools', 'inspect', ref, '--format', '{{.Manifest.Digest}}')
|
||||
raise "Promoted image digest changed: #{ref}" unless actual == digest
|
||||
raise "Promoted image digest changed: #{ref}" unless image_digest(ref) == digest
|
||||
end
|
||||
|
||||
def self.publish(version:, image:, digest:, repository:, release_id:)
|
||||
version = ReleaseMetadata.version(version)
|
||||
version = ReleaseMetadata.release_version(version)
|
||||
raise 'Invalid image digest' unless digest.match?(/\Asha256:[a-f0-9]{64}\z/)
|
||||
raise 'Invalid GitHub release ID' unless release_id.match?(/\A\d+\z/)
|
||||
endpoint = "repos/#{repository}/releases/#{release_id}"
|
||||
|
||||
# 附件上传及镜像证明、签名已完成,再公开版本入口;失败可从本 job 重跑
|
||||
tag(image, digest, version.tr('+', '-'))
|
||||
# 附件、签名和证明就绪后才公开版本入口
|
||||
tag(image, digest, version)
|
||||
run('gh', 'api', '--method', 'PATCH', endpoint, '-F', 'draft=false', '-f', 'make_latest=false')
|
||||
return if ReleaseMetadata.prerelease?(version)
|
||||
promote_latest(version, image, digest, repository, endpoint) unless ReleaseMetadata.prerelease?(version)
|
||||
end
|
||||
|
||||
current_versions = [latest_release(repository), latest_image(image)]
|
||||
def self.recover_latest(tag:, image:, repository:, ref:)
|
||||
version = ReleaseMetadata.release_version(tag)
|
||||
raise 'Latest recovery requires a stable release' if ReleaseMetadata.prerelease?(version)
|
||||
commit = ReleaseMetadata.tag_commit(tag, ref)
|
||||
release = PublishedChannels::Publisher.new(repository).verify_assets(version)
|
||||
digest = image_digest("#{image}:#{version}")
|
||||
raise "Version image differs from the image built for #{commit}" unless image_digest("#{image}:sha-#{commit}") == digest
|
||||
promote_latest(version, image, digest, repository, "repos/#{repository}/releases/#{release.fetch('id')}")
|
||||
end
|
||||
|
||||
def self.promote_latest(version, image, digest, repository, endpoint)
|
||||
github_latest = latest_release(repository)
|
||||
docker_latest = latest_image(image)
|
||||
current_versions = [github_latest, docker_latest]
|
||||
unless can_promote?(version, current_versions)
|
||||
puts "Published #{version}; latest remains at #{current_versions.compact.join(', ')}"
|
||||
return
|
||||
end
|
||||
|
||||
# 两个服务不能原子更新;同时检查两侧版本,让失败重试可以补齐而旧版不能回退
|
||||
tag(image, digest, 'latest')
|
||||
run('gh', 'api', '--method', 'PATCH', endpoint, '-f', 'make_latest=true')
|
||||
tag(image, digest, 'latest') unless docker_latest == version && image_digest("#{image}:latest") == digest
|
||||
run('gh', 'api', '--method', 'PATCH', endpoint, '-f', 'make_latest=true') unless github_latest == "v#{version}"
|
||||
puts "Published #{version} and promoted latest"
|
||||
end
|
||||
end
|
||||
|
||||
if $PROGRAM_NAME == __FILE__
|
||||
begin
|
||||
ReleasePublication.publish(
|
||||
version: ENV.fetch('VERSION'), image: "#{ENV.fetch('REGISTRY')}/#{ENV.fetch('IMAGE_NAME')}",
|
||||
digest: ENV.fetch('DIGEST'), repository: ENV.fetch('GITHUB_REPOSITORY'),
|
||||
release_id: ENV.fetch('RELEASE_ID')
|
||||
)
|
||||
image = "#{ENV.fetch('REGISTRY')}/#{ENV.fetch('IMAGE_NAME')}"
|
||||
repository = ENV.fetch('GITHUB_REPOSITORY')
|
||||
case ARGV
|
||||
when []
|
||||
ReleasePublication.publish(version: ENV.fetch('VERSION'), image: image, digest: ENV.fetch('DIGEST'),
|
||||
repository: repository, release_id: ENV.fetch('RELEASE_ID'))
|
||||
when ['recover-latest']
|
||||
ReleasePublication.recover_latest(tag: ENV.fetch('TAG'), image: image, repository: repository, ref: ENV.fetch('GITHUB_REF'))
|
||||
else
|
||||
raise 'usage: publish-release.rb [recover-latest]'
|
||||
end
|
||||
rescue StandardError => error
|
||||
warn "error: #{error.message}"
|
||||
exit 1
|
||||
|
||||
@@ -67,11 +67,12 @@ module PublishedChannels
|
||||
end
|
||||
missing = expected - uploaded
|
||||
raise "Incomplete release #{tag}: #{missing.join(', ')}" unless missing.empty?
|
||||
release
|
||||
end
|
||||
|
||||
def check_unpublished(version)
|
||||
existing = find_release(version)
|
||||
raise "Release v#{version} already public; use index-only recovery" if existing && !existing.fetch('draft')
|
||||
raise "Release v#{version} already public; use recover_latest or index_only" if existing && !existing.fetch('draft')
|
||||
end
|
||||
|
||||
def publish(version)
|
||||
|
||||
@@ -20,6 +20,31 @@ module ReleaseMetadata
|
||||
version(value).split('+', 2).first.include?('-')
|
||||
end
|
||||
|
||||
def self.release_version(raw)
|
||||
value = version(raw)
|
||||
raise "Release versions cannot contain build metadata: #{raw}" if value.include?('+')
|
||||
value
|
||||
end
|
||||
|
||||
def self.validate_branch(raw, ref)
|
||||
value = release_version(raw)
|
||||
if value.include?('-exp.')
|
||||
raise "Experimental releases require an experimental/<purpose> branch" unless ref.match?(%r{\Arefs/heads/experimental/.+\z})
|
||||
elsif ref != 'refs/heads/main'
|
||||
raise "Release #{value} requires the main branch"
|
||||
end
|
||||
value
|
||||
end
|
||||
|
||||
# 从触发工作流的提交核对 tag,允许分支前进后重试同一发行
|
||||
def self.tag_commit(tag, ref)
|
||||
value = validate_branch(tag, ref)
|
||||
raise "Expected release tag v#{value}" unless tag == "v#{value}"
|
||||
commit = git('rev-parse', '--verify', "refs/tags/#{tag}^{commit}")
|
||||
raise "#{tag} is outside #{ref}" unless git('merge-base', commit, 'HEAD') == commit
|
||||
commit
|
||||
end
|
||||
|
||||
def self.sort_key(value)
|
||||
Gem::Version.new(version(value).split('+', 2).first)
|
||||
end
|
||||
@@ -66,21 +91,39 @@ module ReleaseMetadata
|
||||
"#{APP_NAME}_#{version}_#{platform.fetch('os')}_#{platform.fetch('arch')}.#{platform.fetch('archive')}"
|
||||
end
|
||||
|
||||
# 正式版始终对比上一正式版,常规预发行优先对比同一目标版本的上一预发行
|
||||
def self.previous_tag(value)
|
||||
return if value.include?('-exp.')
|
||||
|
||||
endpoint = "repos/#{ENV.fetch('GITHUB_REPOSITORY')}/releases?per_page=100"
|
||||
output, status = Open3.capture2('gh', 'api', '--paginate', endpoint, '--jq',
|
||||
'.[] | select(.draft == false) | [.tag_name, .prerelease] | @tsv')
|
||||
raise 'Failed to read published releases' unless status.success?
|
||||
|
||||
reachable = git('tag', '--list', 'v*', '--merged', 'HEAD').lines.map(&:strip)
|
||||
candidates = output.each_line.each_with_object([]) do |line, tags|
|
||||
tag, prerelease = line.chomp.split("\t")
|
||||
next unless reachable.include?(tag) && tag.delete_prefix('v').match?(SEMVER) && !tag.include?('+')
|
||||
next unless prerelease?(tag) == (prerelease == 'true') && sort_key(tag) < sort_key(value)
|
||||
tags << tag
|
||||
end
|
||||
if prerelease?(value)
|
||||
prefix = "v#{value.split('-', 2).first}-"
|
||||
previous = candidates.select { |tag| tag.start_with?(prefix) && !tag.include?('-exp.') }.max_by { |tag| sort_key(tag) }
|
||||
return previous if previous
|
||||
end
|
||||
candidates.reject { |tag| prerelease?(tag) }.max_by { |tag| sort_key(tag) }
|
||||
end
|
||||
|
||||
def self.outputs(tag)
|
||||
value = version(YAML.load_file('release/version.yaml').fetch('version'))
|
||||
value = release_version(YAML.load_file('release/version.yaml').fetch('version'))
|
||||
raise "Release tag #{tag} does not match v#{value}" unless tag == "v#{value}"
|
||||
validate_notes(value)
|
||||
entries = platforms
|
||||
docker, native = entries.partition { |entry| entry['docker'] == true }
|
||||
previous = git('tag', '--list', 'v*', '--merged', 'HEAD').lines.map(&:strip).filter_map do |candidate|
|
||||
next unless candidate.delete_prefix('v').match?(SEMVER)
|
||||
key = sort_key(candidate)
|
||||
[key, candidate] if key < sort_key(value)
|
||||
end.max_by(&:first)&.last
|
||||
{
|
||||
'tag' => tag,
|
||||
'version' => value,
|
||||
'docker_version' => value.tr('+', '-'),
|
||||
'build_time' => Time.now.utc.iso8601,
|
||||
'git_sha' => git('rev-parse', 'HEAD'),
|
||||
'platform_matrix' => JSON.generate('include' => entries),
|
||||
@@ -88,7 +131,7 @@ module ReleaseMetadata
|
||||
'non_docker_matrix' => JSON.generate('include' => native),
|
||||
'windows_matrix' => JSON.generate('include' => entries.select { |entry| entry['os'] == 'windows' }),
|
||||
'docker_platforms' => docker.map { |entry| entry['dockerPlatform'] }.join(','),
|
||||
'previous_tag' => previous,
|
||||
'previous_tag' => previous_tag(value),
|
||||
'prerelease' => prerelease?(value),
|
||||
'build_type' => value.split('+', 2).first.include?('-exp.') ? 'experimental' : 'release'
|
||||
}
|
||||
@@ -113,13 +156,16 @@ end
|
||||
|
||||
if $PROGRAM_NAME == __FILE__
|
||||
begin
|
||||
command, value = ARGV
|
||||
raise 'usage: release-metadata.rb validate VERSION | outputs TAG' unless ARGV.length == 2
|
||||
command, value, ref = ARGV
|
||||
arity = command == 'outputs' ? 2 : 3
|
||||
raise 'usage: release-metadata.rb validate VERSION REF | tag-commit TAG REF | outputs TAG' unless ARGV.length == arity
|
||||
case command
|
||||
when 'validate'
|
||||
value = ReleaseMetadata.version(value)
|
||||
value = ReleaseMetadata.validate_branch(value, ref)
|
||||
ReleaseMetadata.validate_notes(value)
|
||||
puts value
|
||||
when 'tag-commit'
|
||||
puts ReleaseMetadata.tag_commit(value, ref)
|
||||
when 'outputs'
|
||||
metadata = ReleaseMetadata.outputs(value)
|
||||
ReleaseMetadata.seal_manifest(metadata)
|
||||
|
||||
@@ -25,7 +25,7 @@ module ReleaseQuality
|
||||
rows = capture('gh', 'api', '--paginate', "repos/#{repository}/actions/runs/#{run.fetch('id')}/jobs?per_page=100", '--jq', '.jobs[] | @json')
|
||||
job = rows.lines.map { |line| JSON.parse(line) }.find { |entry| entry.fetch('name') == 'quality / backend' }
|
||||
return nil unless job && job.fetch('conclusion') == 'success'
|
||||
job.fetch('html_url')
|
||||
{ 'sha' => parent, 'url' => job.fetch('html_url') }
|
||||
end
|
||||
end
|
||||
|
||||
@@ -37,8 +37,10 @@ if $PROGRAM_NAME == __FILE__
|
||||
evidence = nil
|
||||
end
|
||||
puts "run_backend=#{evidence.nil?}"
|
||||
puts "backend_source_sha=#{evidence ? evidence.fetch('sha') : ReleaseQuality.capture('git', 'rev-parse', 'HEAD').strip}"
|
||||
puts "backend_evidence_url=#{evidence ? evidence.fetch('url') : ''}"
|
||||
if ENV['GITHUB_STEP_SUMMARY']
|
||||
message = evidence ? "后端质量检查复用版本提交父提交的 [CI 结果](#{evidence});仅版本与发布说明不同" : '未找到可复用的后端 CI 结果,完整检查发行提交'
|
||||
message = evidence ? "后端质量检查复用 `#{evidence.fetch('sha')}` 的[成功 CI](#{evidence.fetch('url')});仅版本与发布说明不同" : '未找到可复用的后端 CI 结果,完整检查发行提交'
|
||||
File.open(ENV.fetch('GITHUB_STEP_SUMMARY'), 'a') { |file| file.puts(message) }
|
||||
end
|
||||
end
|
||||
@@ -125,7 +125,7 @@ jobs:
|
||||
run: cargo clippy --all-targets --all-features --locked -- -D warnings
|
||||
|
||||
- name: Setup nextest
|
||||
uses: taiki-e/install-action@75a7c0f87bd666af3cdb75c5b9e9d03ab6044e6f # v2.90.6
|
||||
uses: taiki-e/install-action@073e1fd0bc889c9aee68dbaaa927cde1b5653a83 # v2.90.11
|
||||
with:
|
||||
tool: cargo-nextest@0.9.143
|
||||
fallback: none
|
||||
|
||||
@@ -11,6 +11,10 @@ on:
|
||||
description: 'Recover the index for an already public release without rebuilding'
|
||||
type: boolean
|
||||
default: false
|
||||
recover_latest:
|
||||
description: 'Recover latest and the channel index for an already public stable release'
|
||||
type: boolean
|
||||
default: false
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -25,7 +29,7 @@ env:
|
||||
|
||||
jobs:
|
||||
release-info:
|
||||
if: ${{ !inputs.index_only }}
|
||||
if: ${{ !inputs.index_only && !inputs.recover_latest }}
|
||||
runs-on: ubuntu-26.04
|
||||
timeout-minutes: 10
|
||||
permissions:
|
||||
@@ -34,7 +38,6 @@ jobs:
|
||||
outputs:
|
||||
tag: ${{ steps.version.outputs.tag }}
|
||||
version: ${{ steps.version.outputs.version }}
|
||||
docker_version: ${{ steps.version.outputs.docker_version }}
|
||||
build_time: ${{ steps.version.outputs.build_time }}
|
||||
git_sha: ${{ steps.version.outputs.git_sha }}
|
||||
platform_matrix: ${{ steps.version.outputs.platform_matrix }}
|
||||
@@ -48,17 +51,26 @@ jobs:
|
||||
rust: ${{ steps.toolchains.outputs.rust }}
|
||||
rust_image: ${{ steps.toolchains.outputs.rust_image }}
|
||||
run_backend: ${{ steps.quality.outputs.run_backend }}
|
||||
backend_source_sha: ${{ steps.quality.outputs.backend_source_sha }}
|
||||
backend_evidence_url: ${{ steps.quality.outputs.backend_evidence_url }}
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
ref: ${{ inputs.tag }}
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Verify release branch and check out the tagged commit
|
||||
env:
|
||||
RELEASE_TAG: ${{ inputs.tag }}
|
||||
run: |
|
||||
commit="$(ruby .github/scripts/release-metadata.rb tag-commit "$RELEASE_TAG" "$GITHUB_REF")"
|
||||
git checkout --detach "$commit"
|
||||
|
||||
- name: Read release metadata and seal plugin manifest
|
||||
id: version
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
RELEASE_TAG: ${{ inputs.tag }}
|
||||
run: ruby .github/scripts/release-metadata.rb outputs "$RELEASE_TAG" >> "$GITHUB_OUTPUT"
|
||||
|
||||
@@ -88,6 +100,31 @@ jobs:
|
||||
run_backend: ${{ needs.release-info.outputs.run_backend == 'true' }}
|
||||
run_frontend: false
|
||||
|
||||
backend-validation:
|
||||
name: backend-validation (${{ needs.release-info.outputs.run_backend == 'true' && 'current release' || 'reused CI' }})
|
||||
needs: [release-info, quality]
|
||||
if: ${{ !cancelled() && needs.release-info.result == 'success' }}
|
||||
runs-on: ubuntu-26.04
|
||||
timeout-minutes: 5
|
||||
steps:
|
||||
- name: Report backend validation evidence
|
||||
env:
|
||||
QUALITY_RESULT: ${{ needs.quality.result }}
|
||||
RUN_BACKEND: ${{ needs.release-info.outputs.run_backend }}
|
||||
SOURCE_SHA: ${{ needs.release-info.outputs.backend_source_sha }}
|
||||
EVIDENCE_URL: ${{ needs.release-info.outputs.backend_evidence_url }}
|
||||
run: |
|
||||
if [ "$QUALITY_RESULT" != success ]; then
|
||||
echo "后端质量检查未通过:$QUALITY_RESULT" | tee -a "$GITHUB_STEP_SUMMARY"
|
||||
exit 1
|
||||
fi
|
||||
if [ "$RUN_BACKEND" = true ]; then
|
||||
echo "后端质量检查已执行并通过,提交:\`$SOURCE_SHA\`" | tee -a "$GITHUB_STEP_SUMMARY"
|
||||
else
|
||||
test -n "$EVIDENCE_URL"
|
||||
echo "后端质量检查复用 \`$SOURCE_SHA\` 的[成功 CI]($EVIDENCE_URL);发行提交仅版本与发布说明不同" | tee -a "$GITHUB_STEP_SUMMARY"
|
||||
fi
|
||||
|
||||
windows:
|
||||
needs: release-info
|
||||
name: windows-tests (${{ matrix.arch }})
|
||||
@@ -115,7 +152,7 @@ jobs:
|
||||
cache-bin: false
|
||||
save-if: ${{ github.event_name != 'pull_request' }}
|
||||
- name: Setup nextest
|
||||
uses: taiki-e/install-action@75a7c0f87bd666af3cdb75c5b9e9d03ab6044e6f # v2.90.6
|
||||
uses: taiki-e/install-action@073e1fd0bc889c9aee68dbaaa927cde1b5653a83 # v2.90.11
|
||||
with:
|
||||
tool: cargo-nextest@0.9.143
|
||||
fallback: none
|
||||
@@ -273,7 +310,7 @@ jobs:
|
||||
shell: bash
|
||||
env:
|
||||
VERSION: ${{ needs.release-info.outputs.version }}
|
||||
DOCKER_VERSION: ${{ needs.release-info.outputs.docker_version }}
|
||||
DOCKER_VERSION: ${{ needs.release-info.outputs.version }}
|
||||
PLATFORM_MATRIX: ${{ needs.release-info.outputs.platform_matrix }}
|
||||
run: ruby .github/scripts/package-release.rb archives
|
||||
|
||||
@@ -402,7 +439,7 @@ jobs:
|
||||
group: release-publication
|
||||
queue: max
|
||||
# 产物准备可与测试重叠,版本标签和 GitHub Release 必须等全部质量与镜像验证通过
|
||||
needs: [release-info, quality, windows, security, package-assets, build-docker-image]
|
||||
needs: [release-info, backend-validation, windows, security, package-assets, build-docker-image]
|
||||
runs-on: ubuntu-26.04
|
||||
timeout-minutes: 20
|
||||
permissions:
|
||||
@@ -434,7 +471,7 @@ jobs:
|
||||
uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1
|
||||
|
||||
- name: Install Cosign
|
||||
uses: sigstore/cosign-installer@756fe2d284c7292c4e9b62c8a28f1e5629c59532 # v4.1.3
|
||||
uses: sigstore/cosign-installer@881c63bd87e38389154debd8331404ce7ca8a3ab # v4.1.4
|
||||
|
||||
- name: Login to GHCR
|
||||
uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0
|
||||
@@ -443,6 +480,12 @@ jobs:
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Check that the release is unpublished
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
VERSION: ${{ needs.release-info.outputs.version }}
|
||||
run: ruby .github/scripts/published-channels.rb check "$VERSION"
|
||||
|
||||
- name: Assemble candidate image manifest
|
||||
id: manifest
|
||||
shell: bash
|
||||
@@ -507,6 +550,9 @@ jobs:
|
||||
- name: Prepare release notes
|
||||
shell: bash
|
||||
env:
|
||||
PREVIOUS_TAG: ${{ needs.release-info.outputs.previous_tag }}
|
||||
RELEASE_TAG: ${{ needs.release-info.outputs.tag }}
|
||||
BUILD_TYPE: ${{ needs.release-info.outputs.build_type }}
|
||||
INSTALLATION_NOTES: |
|
||||
## Linux 一键安装(Docker Compose)
|
||||
|
||||
@@ -521,17 +567,16 @@ jobs:
|
||||
run: |
|
||||
ruby <<'RUBY'
|
||||
notes = File.readlines('release/notes.md').drop(1).join.strip
|
||||
installation = ENV.fetch('INSTALLATION_NOTES').strip
|
||||
unless ENV.fetch('BUILD_TYPE') == 'experimental'
|
||||
notes += "\n\n#{ENV.fetch('INSTALLATION_NOTES').strip}"
|
||||
if ENV.fetch('PREVIOUS_TAG').empty?
|
||||
notes += "\n\n**Full Changelog**: https://github.com/#{ENV.fetch('GITHUB_REPOSITORY')}/commits/#{ENV.fetch('RELEASE_TAG')}"
|
||||
end
|
||||
end
|
||||
output = File.join(ENV.fetch('RUNNER_TEMP'), 'release-notes.md')
|
||||
File.write(output, "#{notes}\n\n#{installation}\n")
|
||||
File.write(output, "#{notes}\n")
|
||||
RUBY
|
||||
|
||||
- name: Check that the release is unpublished
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
VERSION: ${{ needs.release-info.outputs.version }}
|
||||
run: ruby .github/scripts/published-channels.rb check "$VERSION"
|
||||
|
||||
- name: Generate release asset provenance
|
||||
uses: actions/attest@1e69f48acb82d1966a394da916b4c1698aa569d6 # v4.2.2
|
||||
with:
|
||||
@@ -542,7 +587,7 @@ jobs:
|
||||
uses: softprops/action-gh-release@8a0cd651e5b2365bd640854a3fa5dfc70e4875f3 # v3.0.4
|
||||
with:
|
||||
tag_name: ${{ needs.release-info.outputs.tag }}
|
||||
generate_release_notes: true
|
||||
generate_release_notes: ${{ needs.release-info.outputs.build_type != 'experimental' && needs.release-info.outputs.previous_tag != '' }}
|
||||
previous_tag: ${{ needs.release-info.outputs.previous_tag }}
|
||||
prerelease: ${{ needs.release-info.outputs.prerelease == 'true' }}
|
||||
# action 保留已公开 Release 的状态,新 Release 上传完成后仍保持草稿
|
||||
@@ -567,8 +612,34 @@ jobs:
|
||||
VERSION: ${{ needs.release-info.outputs.version }}
|
||||
run: ruby .github/scripts/published-channels.rb publish "$VERSION"
|
||||
|
||||
recover-latest:
|
||||
if: inputs.recover_latest
|
||||
runs-on: ubuntu-26.04
|
||||
concurrency:
|
||||
group: release-publication
|
||||
queue: max
|
||||
permissions:
|
||||
contents: write
|
||||
packages: write
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1
|
||||
- uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0
|
||||
with:
|
||||
registry: ${{ env.REGISTRY }}
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ github.token }}
|
||||
- name: Restore latest from the verified version image
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
TAG: ${{ inputs.tag }}
|
||||
run: ruby .github/scripts/publish-release.rb recover-latest
|
||||
|
||||
recover-index:
|
||||
if: inputs.index_only
|
||||
needs: recover-latest
|
||||
if: ${{ !cancelled() && (needs.recover-latest.result == 'success' || (inputs.index_only && !inputs.recover_latest)) }}
|
||||
runs-on: ubuntu-26.04
|
||||
concurrency:
|
||||
group: release-publication
|
||||
|
||||
@@ -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@75a7c0f87bd666af3cdb75c5b9e9d03ab6044e6f # v2.90.6
|
||||
uses: taiki-e/install-action@073e1fd0bc889c9aee68dbaaa927cde1b5653a83 # v2.90.11
|
||||
with:
|
||||
tool: cargo-audit@0.22.2
|
||||
fallback: none
|
||||
|
||||
@@ -4,13 +4,13 @@
|
||||
|
||||
| 任务意图与常见说法 | 必用技能 |
|
||||
| --- | --- |
|
||||
| 需求评估、排障、开发、修复、代码审查、改文档,包括“看下这个 Issue”“改弹窗/样式/文案”“修接口/调度/数据库” | [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 加载插件边界 |
|
||||
| 发版、准备版本、发布 beta/实验版、整理发布说明、打发行 tag | [cpr-release](.agents/skills/cpr-release/SKILL.md) |
|
||||
|
||||
结合上下文识别“提交吧”“看看这个问题”等省略说法:普通 Git 提交不自动变成 PR,代码排查不自动变成 Issue;审查与发版准备不代表获准远程写入
|
||||
结合当前任务判断“继续”“验收一下”等省略说法。验收代码或文档改动时执行开发指南;核对发布产物时走发版技能。普通 Git 提交不自动变成 PR,代码排查不自动变成 Issue;审查与发版准备不代表获准远程写入
|
||||
|
||||
首次命中技能时完整读取其 `SKILL.md`,再读取领域必读规范,之后按当前步骤补充实现、命令和示例。技能名称、描述或入口摘要不能代替首次读取的正文与必读引用;引用中明确要求“先读”“必须读取”或“执行”的规范也要落实,其他资料按需读取
|
||||
|
||||
@@ -26,7 +26,7 @@ Issue 和 PR 回复统一按 [GitHub 回复口吻](CONTRIBUTING.md#github-回复
|
||||
### 任务延续与收尾
|
||||
|
||||
- 在任务上下文和压缩摘要中保留目标、授权、当前阶段、已读规范的路径与关键约束、验证命令与结果及对应代码状态、剩余事项
|
||||
- 同一任务可复用实际完成的读取与验证记录;仅在规范变更、进入未覆盖领域或具体决策缺少条款时补读对应内容。输出截断只补缺失部分,上下文压缩与阶段切换本身不触发重读或重验
|
||||
- 续接任务时,从记录中恢复当前步骤适用的规范与待查项,核对已有证据对应的实现。规范变更、进入新领域或缺少具体约束时补读对应条款,输出截断只补缺失部分。已有证据仍适用的检查直接复用
|
||||
- 远端更新或合并冲突后,按实际变更及其依赖影响补充自审和验证,复用未受影响的证据
|
||||
- 实现、自审与必要验证完成后,按[验证停止条件](CONTRIBUTING.md#验证)停止扩围;完成已获授权的剩余交付步骤并确认结果后结束
|
||||
|
||||
|
||||
+5
-5
@@ -55,7 +55,7 @@ AI 开发和审查入口是根目录的 [AGENTS.md](AGENTS.md)。在仓库上下
|
||||
### 项目技能
|
||||
|
||||
仓库技能位于 `.agents/skills/`,随代码共享。技能提供执行流程,协作与审查标准仍以本文和 `AGENTS.md` 为准。
|
||||
AI 开发、排查、代码审查和文档修改必须执行 `cpr-dev-guide`;准备、创建、更新及审查 PR 必须执行 `cpr-github-pr`,不以用户是否显式点名技能为条件。PR 内修复仍须经过开发流程,不能用填写 PR 正文代替实现自审与验证
|
||||
AI 开发、排查、代码审查、文档修改及对这些改动的验收必须执行 `cpr-dev-guide`;准备、创建、更新及审查 PR 必须执行 `cpr-github-pr`,不以用户是否显式点名技能为条件。PR 内修复仍须经过开发流程,不能用填写 PR 正文代替实现自审与验证
|
||||
|
||||
| 技能 | 用途 | 调用示例 |
|
||||
| --- | --- | --- |
|
||||
@@ -122,7 +122,7 @@ PR 不接受以下协作规则文件的新增、修改、删除或重命名:
|
||||
- 业务数据的解析、校验和展示优先复用已有逻辑。新增抽象放在拥有该职责的模块,避免重复事实源或无实际需求的通用层
|
||||
- 新增代码注释使用中文。提交信息使用英文 Conventional Commits,参考近期历史,按完整功能归并
|
||||
- AI 参与的提交按实际助手添加 `Co-authored-by: 名称 <邮箱>`,名称与邮箱采用该助手已知的署名身份,并保留其他实际共同作者署名;PR 的 AI 使用披露不替代提交署名
|
||||
- 发布说明写入 `release/notes.md`,标题首行为目标版本的 `# vX.Y.Z`,章节标题和正文使用中文;命令、配置键、协议名等保留原文。只说明本次版本的实际变化,按影响交代升级事项
|
||||
- 发布说明写入 `release/notes.md`,标题首行为目标版本的 `# vX.Y.Z`,手写章节标题和正文使用中文;命令、配置键、协议名等保留原文。只说明本次版本的实际变化,按影响交代升级事项。常规版本由发布工作流追加安装入口、文档链接和 GitHub 变更列表,比较基线见[版本与说明准备](.agents/skills/cpr-release/references/preparation.md)
|
||||
- PR 聚焦目标;无关格式化、重构和依赖升级单独处理
|
||||
|
||||
## 文档职责与更新条件
|
||||
@@ -144,8 +144,8 @@ PR 不接受以下协作规则文件的新增、修改、删除或重命名:
|
||||
| [插件使用](docs/plugins.md) | 如何安装、授权、配置和使用插件 | 管理员操作与影响,不展开 SDK 调用或宿主事务实现 |
|
||||
| [插件 SDK](backend/crates/gateway-plugin/sdk/README.md) / [CLI](backend/apps/plugin-cli/README.md) | 如何编写和打包插件 | 作者合同、权限边界、示例与打包验证 |
|
||||
| [数据库迁移](backend/migrations/README.md) | 如何维护 schema 和准备测试库 | 冻结规则、升级约束和测试环境,不罗列迁移历史 |
|
||||
| [共用组件](modules/ui/README.md)及其组件参考 | 如何安装、使用和开发独立 UI 库 | 组件公开 API、主题能力与库内开发;宿主页面约定归管理端主题,跨仓库联调归开发文档 |
|
||||
| [官方插件示例](modules/plugins/README.md)及其示例说明 | 如何构建、使用和维护示例插件 | 示例自身的功能、配置与验证;通用协议归 SDK,宿主安装操作归插件使用文档 |
|
||||
| [共用组件](https://github.com/zyycn/codex-proxy-ui/blob/main/README.md)及其组件参考 | 如何安装、使用和开发独立 UI 库 | 组件公开 API、主题能力与库内开发;宿主页面约定归管理端主题,跨仓库联调归开发文档 |
|
||||
| [官方插件示例](https://github.com/zyycn/codex-proxy-plugins/blob/main/README.md)及其示例说明 | 如何构建、使用和维护示例插件 | 示例自身的功能、配置与验证;通用协议归 SDK,宿主安装操作归插件使用文档 |
|
||||
| [AGENTS.md](AGENTS.md) 与[项目技能](.agents/skills/cpr-dev-guide/SKILL.md) | AI 如何选择并执行任务流程 | 任务匹配、执行步骤和规范入口,不另建模块合同、版本表或协作标准 |
|
||||
| 本文 | 如何协作、审查和交付 | 流程、判断标准与验证要求,任务入口由 [开发技能](.agents/skills/cpr-dev-guide/SKILL.md) 串联 |
|
||||
|
||||
@@ -229,7 +229,7 @@ git diff --check
|
||||
|
||||
常规容器检查与发行构建共用二进制构建入口,并复用已检查的前端产物;Dockerfile、工具链、依赖或构建配置变化时执行完整源码镜像构建,定期安全检查也覆盖源码构建。两条路径均验证容器运行、安全扫描与关闭行为
|
||||
|
||||
发行构建与质量检查并行,Windows 两种架构的插件与系统更新测试独立运行。仅当发行提交只修改版本与发布说明,且其父提交有本仓库主分支成功的后端 CI 时复用该结果;缺少证据则完整重跑。对外发布等待质量、Windows 测试、依赖审计和镜像验证全部成功,构建耗时与测试报告保留 7 天
|
||||
发行构建与质量检查并行,Windows 两种架构的插件与系统更新测试独立运行。仅当发行提交只修改版本与发布说明,且其父提交有本仓库主分支成功的后端 CI 时复用该结果;缺少证据则完整重跑。`backend-validation` 明确报告本次执行或复用结果,复用时列出被验证的源码提交和 CI 链接。对外发布等待质量、Windows 测试、依赖审计和镜像验证全部成功,构建耗时与测试报告保留 7 天
|
||||
|
||||
新增自动规则优先使用现有工具,要求依据明确、结果稳定、误报可控;无法可靠判定的设计与视觉问题保留审查判断,避免把具体源码写法锁成测试
|
||||
|
||||
|
||||
@@ -5,14 +5,14 @@
|
||||
|
||||
# Codex Proxy RS
|
||||
|
||||
面向 Codex 的自托管多账号 AI 网关
|
||||
多平台自托管多账号 AI 网关
|
||||
|
||||
[](https://github.com/zyycn/codex-proxy-rs/actions/workflows/ci.yml)
|
||||
[](https://github.com/zyycn/codex-proxy-rs/releases)
|
||||
[](https://github.com/zyycn/codex-proxy-rs/releases)
|
||||
[](https://github.com/zyycn/codex-proxy-rs/pkgs/container/codex-proxy-rs)
|
||||
[](LICENSE)
|
||||
|
||||
[快速预览](#快速预览) · [快速开始](#快速开始) · [文档](#文档) · [社区](#社区) · [贡献者](#贡献者) · [Star History](#star-history) · [支持项目](#支持项目) · [许可证](#许可证)
|
||||
[快速预览](#快速预览) · [快速开始](#快速开始) · [文档](#文档) · [贡献者](#贡献者) · [Star History](#star-history) · [社区](#社区) · [支持项目](#支持项目) · [许可证](#许可证)
|
||||
|
||||
</div>
|
||||
|
||||
@@ -49,12 +49,6 @@ curl -fsSL https://raw.githubusercontent.com/zyycn/codex-proxy-rs/main/deploy/in
|
||||
| 开发宿主 | [开发与源码联调](docs/development.md) · [系统架构](docs/architecture.md) · [管理端主题](docs/theme.md) · [数据库迁移](backend/migrations/README.md) |
|
||||
| 参与协作 | [贡献、审查与验证](CONTRIBUTING.md) |
|
||||
|
||||
## 社区
|
||||
|
||||
问题反馈与功能建议请使用 [GitHub Issues](https://github.com/zyycn/codex-proxy-rs/issues),填写要求见 [贡献说明](CONTRIBUTING.md#提交-issue)
|
||||
|
||||
感谢 [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)
|
||||
@@ -68,6 +62,18 @@ curl -fsSL https://raw.githubusercontent.com/zyycn/codex-proxy-rs/main/deploy/in
|
||||
</picture>
|
||||
</a>
|
||||
|
||||
## 社区
|
||||
|
||||
点击或扫码加入 Telegram 群 [小酒馆][telegram-group]
|
||||
|
||||
[<img src="docs/community/telegram-qr.png" alt="扫码加入小酒馆 Telegram 群" width="138">][telegram-group]
|
||||
|
||||
[telegram-group]: https://t.me/+9tk761zbNAMyNWY9
|
||||
|
||||
问题反馈与功能建议请使用 [GitHub Issues](https://github.com/zyycn/codex-proxy-rs/issues),填写要求见 [贡献说明](CONTRIBUTING.md#提交-issue)
|
||||
|
||||
感谢 [LINUX DO](https://linux.do) 社区提供开放、友善的技术交流平台
|
||||
|
||||
## 支持项目
|
||||
|
||||
如果 Codex Proxy RS 帮助到你了,欢迎请我喝杯咖啡 ☕
|
||||
|
||||
Generated
+64
-40
@@ -153,9 +153,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "async-compression"
|
||||
version = "0.4.52"
|
||||
version = "0.4.54"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6ad47a740fb906fffdd891e8b6d5fde2511600f7bfaebd68939fa08a14999459"
|
||||
checksum = "0c31224bd2c09447484a1143f2fc1d871eb405789859c8e5470a3e7f95f40a18"
|
||||
dependencies = [
|
||||
"compression-codecs",
|
||||
"compression-core",
|
||||
@@ -292,9 +292,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "aws-sdk-s3"
|
||||
version = "1.161.0"
|
||||
version = "1.162.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d9c63e3ca6e56670513469e992759f4a51041603fde329471b29c5c1f5eaeefe"
|
||||
checksum = "4ffd93a622eaef65d9dee213b1c8afb8b5d999aa2020fe1c9ba6a94ec5e973e4"
|
||||
dependencies = [
|
||||
"arc-swap",
|
||||
"aws-credential-types",
|
||||
@@ -483,9 +483,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "aws-smithy-runtime-api"
|
||||
version = "1.22.0"
|
||||
version = "1.22.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c0b79dbb5331ccd297686df811d50ab3f39db171f5c765372a69272a0990b014"
|
||||
checksum = "20b0ce5fd8f8ec576f6737cf9a3a02172fddad2b90b8874577a4647fab11425c"
|
||||
dependencies = [
|
||||
"aws-smithy-async",
|
||||
"aws-smithy-runtime-api-macros",
|
||||
@@ -522,9 +522,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "aws-smithy-types"
|
||||
version = "1.9.4"
|
||||
version = "1.9.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "aff4bf014c512840b2bba80a20417b723cbd6a0a65c02e2d81f50b4268aedfc7"
|
||||
checksum = "2085f9721fb3755821f8db7611a67ed15f4d6fdba6785b4db8ed7cd18eebee0f"
|
||||
dependencies = [
|
||||
"base64-simd",
|
||||
"bytes",
|
||||
@@ -842,9 +842,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "clap"
|
||||
version = "4.6.8"
|
||||
version = "4.6.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ac230478587d0269d8d6998b82ae69ea51509d55df66d9e92edd1f986904cd4a"
|
||||
checksum = "50066ca966813ca8957ee15361752f19424a8ff620dbe9c8993d9f99d99b04b3"
|
||||
dependencies = [
|
||||
"clap_builder",
|
||||
"clap_derive",
|
||||
@@ -852,9 +852,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "clap_builder"
|
||||
version = "4.6.7"
|
||||
version = "4.6.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d"
|
||||
checksum = "a0ed97c96ef4efb3cc84e09fa388df4463e7cc3224ec38d7b1d9e45749333590"
|
||||
dependencies = [
|
||||
"anstream",
|
||||
"anstyle",
|
||||
@@ -864,9 +864,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "clap_derive"
|
||||
version = "4.6.8"
|
||||
version = "4.6.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "895c9d8d2ac2dd8b8a29f3724a14e72aaaa6debcf8c38c82f97305c6a172767a"
|
||||
checksum = "b4c174f11f949b9ca8c60580925e282b9cbd5454750e506f08648b2038080cd7"
|
||||
dependencies = [
|
||||
"heck",
|
||||
"proc-macro2",
|
||||
@@ -961,9 +961,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "compression-codecs"
|
||||
version = "0.4.47"
|
||||
version = "0.4.49"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "84f840cff84d10085260e460023934d0af699e71212b09b2a41452e8bd9cda43"
|
||||
checksum = "f938fc0d88fbe2c8d6f0e1ba96ba1165d89ff698e98468cd019d92cff2ecd367"
|
||||
dependencies = [
|
||||
"compression-core",
|
||||
"flate2",
|
||||
@@ -1109,9 +1109,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "crc32fast"
|
||||
version = "1.5.5"
|
||||
version = "1.5.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2b929dd2a135771f40afabd1073f85eed59c800b7c61901e5c254270497dad64"
|
||||
checksum = "fd9ae8fcb3ea71b0b26338b4ffb13006bb175de8fd07921089a906ce7e5e6945"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
]
|
||||
@@ -1762,6 +1762,7 @@ dependencies = [
|
||||
"thiserror",
|
||||
"tokio",
|
||||
"tracing",
|
||||
"url",
|
||||
"uuid",
|
||||
]
|
||||
|
||||
@@ -1819,6 +1820,7 @@ dependencies = [
|
||||
"gateway-protocol",
|
||||
"http",
|
||||
"http-body-util",
|
||||
"regex-automata",
|
||||
"semver",
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -1885,8 +1887,9 @@ dependencies = [
|
||||
"tracing",
|
||||
"tracing-appender",
|
||||
"tracing-subscriber",
|
||||
"uuid",
|
||||
"wiremock",
|
||||
"yaml-rust2 0.13.0",
|
||||
"yaml-rust2 0.13.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2071,9 +2074,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "h2"
|
||||
version = "0.4.20"
|
||||
version = "0.4.19"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7d29020232d6aa3fb1daca64c1127cf662cf97f254ae16c18c05b8ab635fc118"
|
||||
checksum = "ef8e5e5a340588f4452631496976cf8636d4a7ecf600239fdc27615d2530bc16"
|
||||
dependencies = [
|
||||
"atomic-waker",
|
||||
"bytes",
|
||||
@@ -2549,9 +2552,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "jsonschema"
|
||||
version = "0.61.2"
|
||||
version = "0.63.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0e37f27df77c7887edbc5f5a59ecd8e5ec4a669319266ec1b61068667a603183"
|
||||
checksum = "b0802aebc749a4ef12e76aee083622b100249be0dc6d2103d84bbb2f7936a1ae"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"bytecount",
|
||||
@@ -2577,18 +2580,18 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "jsonschema-regex"
|
||||
version = "0.61.2"
|
||||
version = "0.63.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7e41151614b6c927e21982be8bef5a26741ae5a0ae6a781eedee2aa930a980e6"
|
||||
checksum = "ba1527289dfcb1400df61b5c591218e8e30031376671f611faecb5b9a1ff4987"
|
||||
dependencies = [
|
||||
"regex-syntax",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "jsonschema-value"
|
||||
version = "0.61.2"
|
||||
version = "0.63.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1515b9a91134ef67d7bac95c2d76fbc7e383c4c55ee544204ceec8088f881fef"
|
||||
checksum = "a95285ab129d630f01cf2f1345c28662116340fac1a35eb0795e5dbbf0ef990d"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"bytecount",
|
||||
@@ -2692,9 +2695,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lru"
|
||||
version = "0.19.0"
|
||||
version = "0.19.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4a9f71e3591c7ec44d3e563e87bf14ddc2bada8519dca046e5b0e560cd004e2d"
|
||||
checksum = "d4e2a1b977b42ee8b53a2a4adbd1183431c493f1d1960b7ccd893e2f0b9407ba"
|
||||
dependencies = [
|
||||
"hashbrown 0.17.1",
|
||||
]
|
||||
@@ -2705,6 +2708,12 @@ version = "0.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154"
|
||||
|
||||
[[package]]
|
||||
name = "lzma-rust2"
|
||||
version = "0.26.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4c7861572250348d13073a9035c6a83f3e583ec9a76a65ce92f338fe1107d8f5"
|
||||
|
||||
[[package]]
|
||||
name = "lzma-sys"
|
||||
version = "0.1.20"
|
||||
@@ -3402,6 +3411,7 @@ dependencies = [
|
||||
"reqwest",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sevenz-rust2",
|
||||
"sha2",
|
||||
"tar",
|
||||
"tempfile",
|
||||
@@ -3442,7 +3452,7 @@ dependencies = [
|
||||
"hyper",
|
||||
"hyper-rustls",
|
||||
"hyper-util",
|
||||
"lru 0.19.0",
|
||||
"lru 0.19.2",
|
||||
"native-tls",
|
||||
"openssl",
|
||||
"openssl-sys",
|
||||
@@ -3497,6 +3507,8 @@ dependencies = [
|
||||
"jsonwebtoken",
|
||||
"p256",
|
||||
"reqwest",
|
||||
"rustls",
|
||||
"rustls-native-certs",
|
||||
"semver",
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -3690,9 +3702,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "redis"
|
||||
version = "1.8.2"
|
||||
version = "1.8.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4bef8fa589dd53a8a379a7856de1365d0a1be50c6b8aebb5c01c1ec441a2c509"
|
||||
checksum = "c85db9332bbc47e826283f0a6058d747c478ed2278976279cefd22154d541b98"
|
||||
dependencies = [
|
||||
"arc-swap",
|
||||
"arcstr",
|
||||
@@ -3746,9 +3758,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "referencing"
|
||||
version = "0.61.2"
|
||||
version = "0.63.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a028057ef852c58a42d75e09da87b5e733f4030f4c7411728955e4f87203a577"
|
||||
checksum = "858eb92e3a3c1d120695a04d5c6e8861915ee4394b8f77c90adbf686d6ddbf6e"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"fluent-uri",
|
||||
@@ -4181,6 +4193,18 @@ dependencies = [
|
||||
"stable_deref_trait",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sevenz-rust2"
|
||||
version = "0.27.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2e668242e054ba8b7360918104c30c6685bdedf847909a784cf267d002f40a6a"
|
||||
dependencies = [
|
||||
"crc32fast",
|
||||
"js-sys",
|
||||
"lzma-rust2",
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sha1"
|
||||
version = "0.10.7"
|
||||
@@ -4211,9 +4235,9 @@ checksum = "bbfa15b3dddfee50a0fff136974b3e1bde555604ba463834a7eb7deb6417705d"
|
||||
|
||||
[[package]]
|
||||
name = "sha2"
|
||||
version = "0.11.1"
|
||||
version = "0.11.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19"
|
||||
checksum = "5b0e5c7d67bc53f435386b2130fdc900488c5703770f6d8a4633060e34288a27"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cpufeatures 0.3.0",
|
||||
@@ -5647,9 +5671,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "yaml-rust2"
|
||||
version = "0.13.0"
|
||||
version = "0.13.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "57e5b818a27a4cd30884ea380857a5e56f7ec3ba24a3990a3cc0b95af3238e18"
|
||||
checksum = "4a8af4469040402b7fe43c26575bab9a3069f0717c4a2931ecf4fb8728ee4cec"
|
||||
dependencies = [
|
||||
"arraydeque",
|
||||
"encoding_rs",
|
||||
@@ -5775,9 +5799,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "zip"
|
||||
version = "9.8.0"
|
||||
version = "9.8.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "721c8158b9503b2660291ad3056a20f722deaeed21bb908a9a363d7e17b34f0e"
|
||||
checksum = "2d8dbe089cf6b0448b78f5fc50139ab5aaa40d08ac07cdc1baf2c13add35fcce"
|
||||
dependencies = [
|
||||
"constant_time_eq",
|
||||
"crc32fast",
|
||||
|
||||
+1
-1
@@ -45,7 +45,7 @@ opt-level = 2
|
||||
[profile.dev.package.blake2]
|
||||
opt-level = 2
|
||||
|
||||
[profile.dev.package."sha2@0.11.1"]
|
||||
[profile.dev.package.sha2]
|
||||
opt-level = 2
|
||||
|
||||
[profile.dev.package."miniz_oxide@0.9.1"]
|
||||
|
||||
@@ -135,6 +135,7 @@ async fn execute(
|
||||
store.admin_ports().settings(),
|
||||
timezone,
|
||||
providers.admin.clone(),
|
||||
core.snapshots(),
|
||||
core.snapshot_control(),
|
||||
core.account_probe(),
|
||||
Some(providers.peer.service()),
|
||||
|
||||
@@ -79,7 +79,11 @@ impl Providers {
|
||||
)
|
||||
.await?;
|
||||
environment.host.report_startup_ready("OpenAI Provider");
|
||||
let antigravity = provider_antigravity::initialize(ports.clone())?;
|
||||
let antigravity = provider_antigravity::initialize(
|
||||
ports.clone(),
|
||||
environment.host.runtime_data_dir().join("antigravity"),
|
||||
)
|
||||
.await?;
|
||||
environment
|
||||
.host
|
||||
.report_startup_ready("Antigravity Provider");
|
||||
|
||||
@@ -76,7 +76,9 @@ fn core_value_owners_do_not_depend_on_execution_or_routing() {
|
||||
let reexports = read_root_reexport_owners(&root);
|
||||
for relative in super::rust_files(&root) {
|
||||
let allowed: Option<&[&str]> = match relative.to_str().expect("source path") {
|
||||
"validation.rs" => Some(&[]),
|
||||
"validation.rs" | "time.rs" => Some(&[]),
|
||||
// 每日排班使用部署日历换算;时间值模块自身不得依赖路由、执行或其他业务
|
||||
"account/duty.rs" => Some(&["account", "time"]),
|
||||
"identity.rs" => Some(&["validation"]),
|
||||
"upstream.rs" => Some(&["validation"]),
|
||||
"event.rs" => Some(&["metering", "operation", "upstream", "validation"]),
|
||||
|
||||
@@ -131,6 +131,7 @@ fn config_loader_should_ignore_unknown_fields_in_configuration_sections() {
|
||||
let mut document = valid_config_document();
|
||||
document["host"]["system_update"] = serde_json::json!({});
|
||||
document["store"]["pool"] = serde_json::json!({});
|
||||
document["openai"] = serde_json::json!({});
|
||||
for path in [
|
||||
"",
|
||||
"/host",
|
||||
@@ -369,31 +370,6 @@ fn config_loader_should_reject_zero_server_port() {
|
||||
assert_rejected(valid_config().replace("port: 8080", "port: 0"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn config_loader_should_accept_optional_openai_routing_strings() {
|
||||
for value in [
|
||||
serde_json::Value::Null,
|
||||
serde_json::json!("us"),
|
||||
serde_json::json!("custom-value"),
|
||||
serde_json::json!(""),
|
||||
] {
|
||||
let mut document = valid_config_document();
|
||||
document["openai"]["residency"] = value.clone();
|
||||
document["openai"]["account_routing_override"] = value;
|
||||
parse_config(&document.to_string()).expect("optional routing strings");
|
||||
}
|
||||
let mut document = valid_config_document();
|
||||
document["openai"]
|
||||
.as_object_mut()
|
||||
.unwrap()
|
||||
.remove("residency");
|
||||
document["openai"]
|
||||
.as_object_mut()
|
||||
.unwrap()
|
||||
.remove("account_routing_override");
|
||||
parse_config(&document.to_string()).expect("omitted routing strings");
|
||||
}
|
||||
|
||||
fn assert_rejected(config: String) {
|
||||
assert!(parse_config(&config).is_err());
|
||||
}
|
||||
|
||||
@@ -32,6 +32,7 @@ sha2 = "0.11"
|
||||
subtle = "2.6.1"
|
||||
thiserror = "2.0.18"
|
||||
tracing = "0.1.44"
|
||||
url = "2.5.8"
|
||||
uuid = { version = "1.23.3", features = ["v4", "v7"] }
|
||||
cron = "0.17"
|
||||
chrono-tz = "0.10"
|
||||
|
||||
@@ -99,6 +99,7 @@ async fn initialize_inner(
|
||||
store.settings(),
|
||||
timezone,
|
||||
providers.clone(),
|
||||
published_snapshot.clone(),
|
||||
snapshot.clone(),
|
||||
probe.clone(),
|
||||
upstream_info.clone(),
|
||||
@@ -194,6 +195,12 @@ async fn initialize_inner(
|
||||
)),
|
||||
auth,
|
||||
accounts: accounts.clone(),
|
||||
account_schedules: Arc::new(crate::AccountScheduleService {
|
||||
timezone,
|
||||
store: store.account_schedules(),
|
||||
providers: providers.clone(),
|
||||
snapshot: snapshot.clone(),
|
||||
}),
|
||||
account_groups: Arc::new(DefaultAccountGroupService::new(
|
||||
upstream_info.clone(),
|
||||
store.account_groups(),
|
||||
@@ -304,6 +311,7 @@ pub fn initialize_accounts(
|
||||
settings: Arc<dyn ports::store::SettingsStore>,
|
||||
timezone: gateway_core::time::DeploymentTimeZone,
|
||||
providers: ProviderAdminRegistry,
|
||||
published: gateway_core::runtime::RuntimeSnapshotHandle,
|
||||
snapshot: Arc<dyn SnapshotControl>,
|
||||
probe: Arc<dyn AccountProbe>,
|
||||
upstream_info: Option<Arc<dyn ports::peer::PeerUpstreamService>>,
|
||||
@@ -314,6 +322,7 @@ pub fn initialize_accounts(
|
||||
settings,
|
||||
timezone,
|
||||
providers,
|
||||
published,
|
||||
snapshot,
|
||||
probe,
|
||||
upstream_info,
|
||||
|
||||
@@ -263,10 +263,11 @@ impl ScheduledTask for FreezeRecoveryTask {
|
||||
context: WorkerCycleContext,
|
||||
) -> futures::future::BoxFuture<'_, Result<(), WorkerTaskError>> {
|
||||
Box::pin(async move {
|
||||
if context.cancellation().is_cancelled() {
|
||||
return Ok(());
|
||||
}
|
||||
self.run_cycle_inner().await;
|
||||
// 中止在途探测,避免把停机当成探测失败而延长冻结
|
||||
context
|
||||
.cancellation()
|
||||
.run_until_cancelled(self.run_cycle_inner())
|
||||
.await;
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
@@ -26,6 +26,7 @@ pub use use_case::peer_link::{PeerLinkError, PeerLinkService};
|
||||
|
||||
pub use use_case::{
|
||||
account_groups::AccountGroupService,
|
||||
account_schedules::AccountScheduleService,
|
||||
accounts::AccountsService,
|
||||
auth::AuthService,
|
||||
backup::BackupService,
|
||||
@@ -209,6 +210,7 @@ pub struct AdminServices {
|
||||
peer_link: Arc<dyn PeerLinkService>,
|
||||
accounts: Arc<dyn AccountsService>,
|
||||
account_groups: Arc<dyn AccountGroupService>,
|
||||
account_schedules: Arc<AccountScheduleService>,
|
||||
client_keys: Arc<dyn ClientKeyService>,
|
||||
client_distribution: Arc<dyn ClientDistributionService>,
|
||||
observability: Arc<dyn ObservabilityService>,
|
||||
@@ -272,6 +274,11 @@ impl AdminServices {
|
||||
self.accounts.as_ref()
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn account_schedules(&self) -> &AccountScheduleService {
|
||||
self.account_schedules.as_ref()
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn account_groups(&self) -> &dyn AccountGroupService {
|
||||
self.account_groups.as_ref()
|
||||
|
||||
@@ -0,0 +1,262 @@
|
||||
//! 账号排班的轻量目录与批量变更合同
|
||||
|
||||
use super::AdminError;
|
||||
use chrono::{DateTime, Offset, TimeDelta, Utc};
|
||||
use gateway_core::account::duty::{DailyShift, SchedulePolicy};
|
||||
use gateway_core::time::DeploymentTimeZone;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ScheduleAccount {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
#[serde(skip)]
|
||||
pub provider_kind: String,
|
||||
#[serde(skip)]
|
||||
pub has_cached_quota: bool,
|
||||
pub authentication_kind: String,
|
||||
pub plan_type: Option<String>,
|
||||
pub plan_type_display: Option<String>,
|
||||
pub group_ids: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct ScheduleGroup {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct ScheduleChange {
|
||||
#[serde(default)]
|
||||
pub clear: bool,
|
||||
pub revision: u64,
|
||||
pub policy: Option<SchedulePolicy>,
|
||||
pub targets: Vec<TargetChange>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum TargetKind {
|
||||
Account,
|
||||
Group,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct TargetChange {
|
||||
pub kind: TargetKind,
|
||||
pub id: String,
|
||||
pub action: ScheduleAction,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum ScheduleAction {
|
||||
Remove,
|
||||
Set(Vec<DailyShift>),
|
||||
}
|
||||
|
||||
impl ScheduleChange {
|
||||
pub fn validate(&self) -> Result<(), AdminError> {
|
||||
if self.revision == 0
|
||||
|| !self.clear && self.policy.is_none() && self.targets.is_empty()
|
||||
|| self
|
||||
.policy
|
||||
.is_some_and(|p| !(1..=100).contains(&p.limit_percent))
|
||||
{
|
||||
return Err(AdminError::invalid("排班策略或版本无效"));
|
||||
}
|
||||
validate_targets(&self.targets)
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_targets(changes: &[TargetChange]) -> Result<(), AdminError> {
|
||||
let mut targets = BTreeSet::new();
|
||||
for target in changes {
|
||||
if !targets.insert((target.kind, &target.id)) || target.id.is_empty() {
|
||||
return Err(AdminError::invalid("排班对象重复或无效"));
|
||||
}
|
||||
if let ScheduleAction::Set(shifts) = &target.action {
|
||||
let mut ids = BTreeSet::new();
|
||||
let mut spans = Vec::new();
|
||||
for shift in shifts {
|
||||
if shift.start >= 1440
|
||||
|| shift.end >= 1440
|
||||
|| uuid::Uuid::parse_str(&shift.id).is_err()
|
||||
|| !ids.insert(&shift.id)
|
||||
{
|
||||
return Err(AdminError::invalid("班次标识或时间无效"));
|
||||
}
|
||||
if shift.start < shift.end {
|
||||
spans.push((shift.start, shift.end));
|
||||
} else {
|
||||
spans.push((shift.start, 1440));
|
||||
if shift.end > 0 {
|
||||
spans.push((0, shift.end));
|
||||
}
|
||||
}
|
||||
}
|
||||
spans.sort_unstable();
|
||||
if spans.windows(2).any(|w| w[0].1 > w[1].0) {
|
||||
return Err(AdminError::invalid("同一排班对象的班次时间重叠"));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum ScheduleScope {
|
||||
Roster,
|
||||
Account,
|
||||
Group,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct ScheduleQuery {
|
||||
pub scope: ScheduleScope,
|
||||
pub page: u32,
|
||||
pub page_size: u32,
|
||||
pub revision: Option<u64>,
|
||||
#[serde(default)]
|
||||
pub search: String,
|
||||
#[serde(default)]
|
||||
pub group_id: String,
|
||||
#[serde(default)]
|
||||
pub targets: Vec<TargetChange>,
|
||||
#[serde(default)]
|
||||
pub clear: bool,
|
||||
pub summary_minute: Option<u16>,
|
||||
#[serde(default)]
|
||||
pub include_summary: bool,
|
||||
}
|
||||
|
||||
impl ScheduleQuery {
|
||||
pub fn validate(&self) -> Result<(), AdminError> {
|
||||
if self.page == 0
|
||||
|| !(1..=100).contains(&self.page_size)
|
||||
|| self.summary_minute.is_some_and(|minute| minute >= 1440)
|
||||
{
|
||||
return Err(AdminError::invalid("排班查询页码、每页数量或时间无效"));
|
||||
}
|
||||
validate_targets(&self.targets)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(tag = "kind", rename_all = "camelCase")]
|
||||
pub enum ScheduleItem {
|
||||
Account {
|
||||
#[serde(flatten)]
|
||||
account: ScheduleAccount,
|
||||
shifts: Option<Vec<DailyShift>>,
|
||||
},
|
||||
Group {
|
||||
#[serde(flatten)]
|
||||
group: ScheduleGroup,
|
||||
shifts: Option<Vec<DailyShift>>,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct ScheduleBand {
|
||||
pub start: u16,
|
||||
pub end: u16,
|
||||
pub count: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ScheduleSummary {
|
||||
pub target_count: u64,
|
||||
pub pool_count: u64,
|
||||
pub available: u64,
|
||||
pub off_duty: Option<String>,
|
||||
pub visible: u64,
|
||||
pub current: u64,
|
||||
pub bands: Vec<ScheduleBand>,
|
||||
pub editing: ScheduleEditingBasis,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ScheduleEditingBasis {
|
||||
pub bands: Vec<ScheduleBand>,
|
||||
pub available: u64,
|
||||
pub off_duty: Option<String>,
|
||||
pub cohorts: Vec<ScheduleCohort>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct ScheduleCohort {
|
||||
pub targets: Vec<String>,
|
||||
pub fixed: Vec<(u16, u16)>,
|
||||
pub count: u64,
|
||||
pub example: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct ScheduleList {
|
||||
pub revision: u64,
|
||||
pub policy: SchedulePolicy,
|
||||
pub items: Vec<ScheduleItem>,
|
||||
pub total: i64,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub groups: Option<Vec<ScheduleGroup>>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub summary: Option<ScheduleSummary>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct ScheduleQueryResult {
|
||||
#[serde(flatten)]
|
||||
pub page: ScheduleList,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub clock: Option<ScheduleClock>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ScheduleClock {
|
||||
pub valid_for_millis: i64,
|
||||
pub unix_millis: i64,
|
||||
pub minute: u16,
|
||||
}
|
||||
|
||||
impl ScheduleClock {
|
||||
#[must_use]
|
||||
pub fn at(now: DateTime<Utc>, timezone: DeploymentTimeZone) -> Self {
|
||||
let offset = |minutes| {
|
||||
timezone
|
||||
.local(now + TimeDelta::minutes(minutes))
|
||||
.offset()
|
||||
.fix()
|
||||
};
|
||||
let current = offset(0);
|
||||
let mut end = 24 * 60;
|
||||
// 同一偏移下可用经过的分钟推进本地时钟;遇到夏令时跳变就在边界重新采样
|
||||
if offset(end) != current {
|
||||
let mut start = 0;
|
||||
while end - start > 1 {
|
||||
let mid = (start + end) / 2;
|
||||
if offset(mid) == current {
|
||||
start = mid;
|
||||
} else {
|
||||
end = mid;
|
||||
}
|
||||
}
|
||||
}
|
||||
let unix_millis = now.timestamp_millis();
|
||||
Self {
|
||||
valid_for_millis: end * 60_000 - unix_millis.rem_euclid(60_000),
|
||||
unix_millis,
|
||||
minute: timezone.minute_of_day(now),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -42,6 +42,7 @@ pub struct ProviderAccountCapabilities {
|
||||
/// 导入时应用的账号设置;名称只覆盖单账号导入,其余设置统一应用
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct AccountImportSettings {
|
||||
pub platform_icon: Option<String>,
|
||||
pub name: Option<String>,
|
||||
pub notes: Option<String>,
|
||||
pub enabled: bool,
|
||||
@@ -54,7 +55,7 @@ pub struct AccountImportSettings {
|
||||
/// 账号列表排序字段
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum AccountSortField {
|
||||
Email,
|
||||
Name,
|
||||
Status,
|
||||
PlanType,
|
||||
Usage,
|
||||
@@ -91,6 +92,9 @@ pub struct AccountListQuery {
|
||||
/// Admin query service 从运行态存储取得的当前账号冷却快照
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct AccountRuntimeSnapshot {
|
||||
/// 模型维度冷却独立于整账号冷却,不能据此阻断其他模型
|
||||
pub model_cooldowns:
|
||||
BTreeMap<String, Vec<gateway_core::provider_ports::ProviderScopedCooldown>>,
|
||||
pub protection_rules: BTreeMap<String, Vec<gateway_core::account::AccountProtectionMatch>>,
|
||||
pub cooldown: BTreeMap<String, gateway_core::account::AccountCooldown>,
|
||||
/// `None` 表示实时 lease 存储不可用;`Some` 中未出现的账号当前使用量为零
|
||||
@@ -222,6 +226,8 @@ pub struct AccountPage {
|
||||
/// 同一状态快照下的账号事实与唯一状态投影
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct AccountPageItem {
|
||||
pub model_cooldowns: Vec<gateway_core::provider_ports::ProviderScopedCooldown>,
|
||||
pub platform_icon: Option<String>,
|
||||
pub protection_rules: Vec<gateway_core::account::AccountProtectionMatch>,
|
||||
pub account: AccountRecord,
|
||||
pub projection: AccountStatusProjection,
|
||||
@@ -240,6 +246,7 @@ pub struct AccountCapacity {
|
||||
/// 账号可编辑事实的一次性替换命令
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct UpdateAccount {
|
||||
pub platform_icon: Option<String>,
|
||||
pub account_id: String,
|
||||
/// 缺省保留名称,空字符串清除名称并使用邮箱展示
|
||||
pub name: Option<String>,
|
||||
|
||||
@@ -13,6 +13,7 @@ pub enum MutationAuditOperation {
|
||||
AdminApiKeyChanged { exists: bool },
|
||||
AccountGroupCreate,
|
||||
AccountGroupUpdate,
|
||||
AccountScheduleUpdate,
|
||||
AccountGroupEnabled { enabled: bool },
|
||||
AccountGroupDelete,
|
||||
ClientApiKeyResetBudget,
|
||||
@@ -47,6 +48,7 @@ pub enum MutationAuditOperation {
|
||||
OutboundProxyUpdate,
|
||||
OutboundProxyDelete,
|
||||
OutboundProxyTest,
|
||||
ProxyTestTargetsUpdate,
|
||||
AccountGroupPluginReconcile,
|
||||
ClientApiKeyPluginReconcile,
|
||||
ProviderAccountImportDocument,
|
||||
@@ -72,6 +74,7 @@ impl MutationAuditOperation {
|
||||
"runtime_settings",
|
||||
),
|
||||
Self::AccountGroupCreate => ("create", "account_group"),
|
||||
Self::AccountScheduleUpdate => ("update", "account_schedule"),
|
||||
Self::AccountGroupUpdate => ("update", "account_group"),
|
||||
Self::AccountGroupEnabled { enabled } => {
|
||||
(if enabled { "enable" } else { "disable" }, "account_group")
|
||||
@@ -110,6 +113,7 @@ impl MutationAuditOperation {
|
||||
Self::OutboundProxyCreate => ("create", "outbound_proxy"),
|
||||
Self::OutboundProxyUpdate => ("update", "outbound_proxy"),
|
||||
Self::OutboundProxyDelete => ("delete", "outbound_proxy"),
|
||||
Self::ProxyTestTargetsUpdate => ("update", "proxy_test_targets"),
|
||||
Self::OutboundProxyTest => ("test", "outbound_proxy"),
|
||||
Self::AccountGroupPluginReconcile => ("plugin_reconcile", "account_group"),
|
||||
Self::ClientApiKeyPluginReconcile => ("plugin_reconcile", "client_api_key"),
|
||||
|
||||
@@ -108,6 +108,7 @@ pub struct ClientKeyListQuery {
|
||||
/// 不含完整明文 Key 的管理投影
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ClientKeyRecord {
|
||||
pub validity: gateway_core::policy::ClientKeyValidity,
|
||||
pub peer_sharing: gateway_core::policy::ClientPeerSharing,
|
||||
pub request_profile_overrides: ProviderRequestProfileOverrides,
|
||||
pub id: ClientApiKeyId,
|
||||
@@ -124,6 +125,13 @@ pub struct ClientKeyRecord {
|
||||
pub updated_at: DateTime<Utc>,
|
||||
}
|
||||
|
||||
impl ClientKeyRecord {
|
||||
#[must_use]
|
||||
pub fn is_active(&self) -> bool {
|
||||
self.enabled && self.validity.is_active()
|
||||
}
|
||||
}
|
||||
|
||||
/// Client Key 列表页
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ClientKeyPage {
|
||||
@@ -168,6 +176,7 @@ impl fmt::Debug for ClientKeySecret {
|
||||
/// API 提交的 Client Key 创建命令
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct CreateClientKey {
|
||||
pub validity: gateway_core::policy::ClientKeyValidity,
|
||||
pub peer_sharing: gateway_core::policy::ClientPeerSharing,
|
||||
pub request_profile_overrides: ProviderRequestProfileOverrides,
|
||||
pub custom_key: Option<PlaintextClientApiKey>,
|
||||
@@ -181,6 +190,7 @@ pub struct CreateClientKey {
|
||||
/// 管理用例生成 ID 与明文后的持久化命令
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
pub struct NewClientKey {
|
||||
pub validity: gateway_core::policy::ClientKeyValidity,
|
||||
pub peer_sharing: gateway_core::policy::ClientPeerSharing,
|
||||
pub request_profile_overrides: ProviderRequestProfileOverrides,
|
||||
pub id: ClientApiKeyId,
|
||||
@@ -207,6 +217,7 @@ impl fmt::Debug for NewClientKey {
|
||||
/// 修改 Client Key 的公开策略字段
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct UpdateClientKey {
|
||||
pub validity: Option<gateway_core::policy::ClientKeyValidity>,
|
||||
pub peer_sharing: Option<gateway_core::policy::ClientPeerSharing>,
|
||||
pub request_profile_override_updates: ProviderRequestProfileOverrideUpdates,
|
||||
pub id: ClientApiKeyId,
|
||||
@@ -293,13 +304,33 @@ pub enum ClientKeyBudgetPeriod {
|
||||
All,
|
||||
}
|
||||
|
||||
/// 清零所选窗口并恢复日历规则,保留限额与历史费用
|
||||
/// 清零所选窗口,保留限额与历史费用
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ResetClientKeyBudget {
|
||||
pub id: ClientApiKeyId,
|
||||
pub period: ClientKeyBudgetPeriod,
|
||||
}
|
||||
|
||||
impl ResetClientKeyBudget {
|
||||
/// 返回所选日、周窗口的终点;插件重置以起止相同表示等待下次使用
|
||||
#[must_use]
|
||||
pub fn window_ends(
|
||||
&self,
|
||||
origin: &ClientKeyBudgetMutationOrigin,
|
||||
start: DateTime<Utc>,
|
||||
) -> (Option<DateTime<Utc>>, Option<DateTime<Utc>>) {
|
||||
let end = |days| match origin {
|
||||
ClientKeyBudgetMutationOrigin::Admin => start + chrono::Duration::days(days),
|
||||
ClientKeyBudgetMutationOrigin::Plugin(_) => start,
|
||||
};
|
||||
match self.period {
|
||||
ClientKeyBudgetPeriod::Daily => (Some(end(1)), None),
|
||||
ClientKeyBudgetPeriod::Weekly => (None, Some(end(7))),
|
||||
ClientKeyBudgetPeriod::All => (Some(end(1)), Some(end(7))),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 显式窗口复用已有日/周金额上限,外部周期的选择归调用方
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ClientKeyBudgetWindowPeriod {
|
||||
@@ -319,7 +350,9 @@ impl ClientKeyBudgetWindowPeriod {
|
||||
|
||||
/// 手动对齐只需要账号身份,列表不读取凭据、额度或用量
|
||||
#[derive(serde::Serialize, Debug)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct BudgetReferenceAccount {
|
||||
pub platform_icon: Option<String>,
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub email: Option<String>,
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
use std::num::{NonZeroU16, NonZeroU64};
|
||||
|
||||
pub mod account_groups;
|
||||
pub mod account_schedules;
|
||||
pub mod accounts;
|
||||
pub mod analytics;
|
||||
pub mod audit;
|
||||
|
||||
@@ -783,6 +783,7 @@ pub struct AccountRequestBucket {
|
||||
/// Dashboard 中一个账号的完整用量事实
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct DashboardAccountUsage {
|
||||
pub platform_icon: Option<String>,
|
||||
pub upstream: Option<super::upstream_info::ProviderUpstreamInfo>,
|
||||
pub account_id: String,
|
||||
pub provider_kind: String,
|
||||
@@ -888,11 +889,14 @@ impl UsageErrorOrigin {
|
||||
}
|
||||
|
||||
/// 使用记录表格的窄读模型
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
#[derive(Clone, PartialEq)]
|
||||
pub struct UsageListRecord {
|
||||
pub platform_icon: Option<String>,
|
||||
pub outcome: RequestOutcome,
|
||||
/// 已保存的上游错误对象含非空字符串 code、type 或 message
|
||||
pub has_upstream_error: bool,
|
||||
pub upstream_error_message: Option<String>,
|
||||
pub retry_after_ms: Option<u64>,
|
||||
pub error_code: Option<String>,
|
||||
pub error_message: Option<String>,
|
||||
pub error_kind: Option<String>,
|
||||
@@ -959,6 +963,17 @@ pub struct UsageListRecord {
|
||||
pub started_at: DateTime<Utc>,
|
||||
}
|
||||
|
||||
// 上游错误原文只交付给管理端,避免整行调试输出带出正文
|
||||
impl std::fmt::Debug for UsageListRecord {
|
||||
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
formatter
|
||||
.debug_struct("UsageListRecord")
|
||||
.field("id", &self.id)
|
||||
.field("outcome", &self.outcome)
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
/// 受控请求详情中的上游错误字段,不参与错误分类或普通日志输出
|
||||
#[derive(Clone, PartialEq)]
|
||||
pub struct UsageUpstreamError {
|
||||
@@ -1167,9 +1182,12 @@ pub struct DiagnosticsObservation {
|
||||
pub struct DiagnosticObservation {
|
||||
pub key: String,
|
||||
pub name: String,
|
||||
pub account_provider_kind: Option<String>,
|
||||
pub account_email: Option<String>,
|
||||
pub providers: Vec<String>,
|
||||
pub platform_icon: Option<String>,
|
||||
pub account_authentication_kind: Option<String>,
|
||||
pub account_plan_type: Option<String>,
|
||||
pub account_plan_type_display: Option<String>,
|
||||
pub request_count: u64,
|
||||
pub success_count: u64,
|
||||
pub failure_count: u64,
|
||||
@@ -1639,8 +1657,11 @@ pub struct UsageInsight {
|
||||
/// 已完成分母计算的诊断项
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct DiagnosticsItem {
|
||||
pub providers: Vec<String>,
|
||||
pub platform_icon: Option<String>,
|
||||
pub key: String,
|
||||
pub name: String,
|
||||
pub account_email: Option<String>,
|
||||
pub account_authentication_kind: Option<String>,
|
||||
pub account_plan_type: Option<String>,
|
||||
/// 仅账号维度补充当前互联识别结果
|
||||
|
||||
@@ -78,6 +78,8 @@ impl fmt::Debug for ImportCredentials {
|
||||
/// 批量导入提交结果
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct CredentialImportResult {
|
||||
/// 本次事务首次创建的账号,同身份重新导入沿用已有账号
|
||||
pub created_ids: std::collections::BTreeSet<ProviderAccountId>,
|
||||
pub config_revision: Revision,
|
||||
pub credential_ids: Vec<ProviderAccountId>,
|
||||
}
|
||||
@@ -540,10 +542,18 @@ impl fmt::Debug for AuthorizationReceiptKey {
|
||||
}
|
||||
}
|
||||
|
||||
/// 凭据事务对账号的实际影响,同身份授权可以更新既有账号
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum CredentialChange {
|
||||
Created,
|
||||
Updated,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct AuthorizationCommitResult {
|
||||
pub result: CredentialMutationResult,
|
||||
pub newly_committed: bool,
|
||||
/// 重放已提交回执时没有新的账号变更
|
||||
pub change: Option<CredentialChange>,
|
||||
}
|
||||
|
||||
/// OAuth 准备结果拆解后的 Store 命令与两个结算 guard
|
||||
@@ -698,7 +708,9 @@ pub struct PreparedCredentialRotationFacts {
|
||||
pub plan_type: Option<String>,
|
||||
/// Token 刷新保留提交时的资料,不以准备阶段的副本覆盖新套餐
|
||||
pub preserve_profile: bool,
|
||||
/// 连接配置变更保留当前凭据健康状态与错误事实
|
||||
/// 已核实同一身份续期时,允许把匹配此标识的目录续接至新凭据版本
|
||||
pub preserve_catalog_etag: Option<String>,
|
||||
/// 凭据或连接配置更新保留提交时的健康状态与错误事实
|
||||
pub preserve_credential_state: bool,
|
||||
pub preserve_access_token_expiry: bool,
|
||||
pub provider_material: ProviderDocument,
|
||||
@@ -722,13 +734,19 @@ impl PreparedCredentialRotation {
|
||||
Self { facts, guard }
|
||||
}
|
||||
|
||||
/// 仅修改连接配置时,不把配置更新视为凭据恢复成功
|
||||
/// 更新本身不能证明账号已恢复时,保留提交时的状态
|
||||
#[must_use]
|
||||
pub fn preserving_credential_state(mut self) -> Self {
|
||||
self.facts.preserve_credential_state = true;
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn preserving_catalog(mut self, etag: String) -> Self {
|
||||
self.facts.preserve_catalog_etag = Some(etag);
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn facts(&self) -> &PreparedCredentialRotationFacts {
|
||||
&self.facts
|
||||
@@ -890,6 +908,8 @@ pub struct ProviderQuotaReadRequest<'a> {
|
||||
/// Provider 已解析的 quota 结果及其不透明差异字段
|
||||
#[derive(Debug, Default, Clone, PartialEq)]
|
||||
pub struct ProviderQuota {
|
||||
/// 与 Provider 选号使用同一日额度观测,仅在其有效期内提供
|
||||
pub daily_used_percent: Option<u8>,
|
||||
pub paused_windows: Vec<String>,
|
||||
pub upstream: Option<super::upstream_info::ProviderUpstreamInfo>,
|
||||
/// 上游额度响应明确提供的套餐,可用于补全账号展示
|
||||
@@ -1052,14 +1072,23 @@ pub struct ProviderResetCreditResult {
|
||||
pub credit: Option<ProviderResetCredit>,
|
||||
}
|
||||
|
||||
impl ProviderQuota {
|
||||
/// 保留账号已有的套餐子类型,仅在缺失时使用上游额度快照补全
|
||||
pub(crate) fn fill_missing_plan_type(&self, account_plan_type: &mut Option<String>) {
|
||||
if explicit_plan_type(account_plan_type.as_deref()).is_none() {
|
||||
*account_plan_type = explicit_plan_type(self.plan_type.as_deref()).map(str::to_owned);
|
||||
}
|
||||
/// 用额度观测补齐缺失的套餐 ID,只采用与账号套餐相符的描述
|
||||
pub fn resolve_observed_plan<'a>(
|
||||
account_plan_type: &mut Option<String>,
|
||||
observed_type: Option<&str>,
|
||||
observed_display: Option<&'a str>,
|
||||
) -> Option<&'a str> {
|
||||
let observed_type = explicit_plan_type(observed_type);
|
||||
if explicit_plan_type(account_plan_type.as_deref()).is_none() {
|
||||
*account_plan_type = observed_type.map(str::to_owned);
|
||||
}
|
||||
observed_display.filter(|_| {
|
||||
observed_type
|
||||
.is_none_or(|id| Some(id.trim()) == account_plan_type.as_deref().map(str::trim))
|
||||
})
|
||||
}
|
||||
|
||||
impl ProviderQuota {
|
||||
/// 选择账号用量统计窗口,同时返回展示所需的周期事实
|
||||
///
|
||||
/// 周/月额度使用边界完整、可归属到整个账号的窗口
|
||||
@@ -1310,6 +1339,9 @@ impl fmt::Debug for ProviderExport {
|
||||
/// 统一账号目录的一行完整结果
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct AccountDirectoryItem {
|
||||
pub schedule_duty: Option<gateway_core::account::duty::ScheduleDuty>,
|
||||
pub model_cooldowns: Vec<gateway_core::provider_ports::ProviderScopedCooldown>,
|
||||
pub platform_icon: Option<String>,
|
||||
pub protection_rules: Vec<gateway_core::account::AccountProtectionMatch>,
|
||||
pub account: AccountRecord,
|
||||
pub capacity: super::accounts::AccountCapacity,
|
||||
|
||||
@@ -27,6 +27,7 @@ pub struct ProxyListQuery {
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ProxyAccountRef {
|
||||
pub platform_icon: Option<String>,
|
||||
pub upstream: Option<super::upstream_info::ProviderUpstreamInfo>,
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
@@ -56,6 +57,41 @@ pub struct ProxyAccountPage {
|
||||
pub page_size: u16,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct ProxyTestTarget {
|
||||
pub name: String,
|
||||
pub url: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct ProxyTestTargets {
|
||||
pub revision: Revision,
|
||||
pub targets: Vec<ProxyTestTarget>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct TargetProbeResult {
|
||||
pub latency_ms: u64,
|
||||
#[serde(flatten)]
|
||||
pub outcome: TargetProbeOutcome,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(tag = "kind", rename_all = "camelCase")]
|
||||
pub enum TargetProbeOutcome {
|
||||
Http {
|
||||
status: u16,
|
||||
#[serde(rename = "exitIp")]
|
||||
exit_ip: Option<std::net::IpAddr>,
|
||||
},
|
||||
Failed {
|
||||
message: String,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ProxyTestResult {
|
||||
pub location: ProxyLocationDetection,
|
||||
|
||||
@@ -45,8 +45,9 @@ 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 antigravity_background_refresh: bool,
|
||||
pub openai_websocket_pool: gateway_core::settings::OpenAiWebSocketPoolSettings,
|
||||
pub openai_request_settings: gateway_core::settings::OpenAiRequestSettings,
|
||||
pub codex_privacy_policy: gateway_core::settings::privacy::CodexPrivacyPolicy,
|
||||
pub request_location_enabled: bool,
|
||||
pub request_location: gateway_core::account::RequestLocation,
|
||||
@@ -71,6 +72,7 @@ pub struct RuntimeSettingsValues {
|
||||
pub usage_retention_days: u32,
|
||||
pub ops_event_retention_days: u32,
|
||||
pub audit_retention_days: u32,
|
||||
pub prompt_rewrite_rules: Vec<gateway_core::settings::prompt_rewrite::PromptRewriteRule>,
|
||||
pub account_error_protection: gateway_core::account::AccountErrorProtection,
|
||||
pub account_warmup_enabled: bool,
|
||||
pub account_warmup_cron: String,
|
||||
@@ -192,6 +194,9 @@ impl From<RuntimeSettings> for ReplaceRuntimeSettings {
|
||||
impl RuntimeSettingsValues {
|
||||
/// 校验共同事实,返回字段名供边界转换错误;SQL 类型转换仍由 Store 处理
|
||||
pub fn validate(&self) -> Result<(), &'static str> {
|
||||
for rule in &self.prompt_rewrite_rules {
|
||||
rule.validate().map_err(|_| "prompt_rewrite_rules")?;
|
||||
}
|
||||
if !(1..=1440).contains(&self.reset_credit_lead_minutes) {
|
||||
return Err("reset_credit_lead_minutes");
|
||||
}
|
||||
@@ -201,9 +206,8 @@ impl RuntimeSettingsValues {
|
||||
{
|
||||
return Err("reset_credit_max_weekly_remaining_percent");
|
||||
}
|
||||
self.openai_request_country
|
||||
.validate()
|
||||
.map_err(|_| "openai_request_country")?;
|
||||
self.openai_websocket_pool.validate()?;
|
||||
self.openai_request_settings.validate()?;
|
||||
self.request_location
|
||||
.validate()
|
||||
.map_err(|_| "request_location")?;
|
||||
|
||||
@@ -50,11 +50,13 @@ pub struct SystemUpdatePolicy {
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct SystemVersion {
|
||||
pub version: String,
|
||||
pub instance_id: String,
|
||||
pub restart_supported: bool,
|
||||
pub git_sha: String,
|
||||
pub build_time: String,
|
||||
pub deployment_mode: String,
|
||||
pub update_channel: String,
|
||||
pub latest_version: String,
|
||||
pub latest_version: Option<String>,
|
||||
pub has_update: bool,
|
||||
pub update_cached: bool,
|
||||
pub update_warning: Option<String>,
|
||||
@@ -67,7 +69,7 @@ pub struct SystemVersion {
|
||||
pub struct SystemUpdateDetail {
|
||||
pub policy: SystemUpdatePolicy,
|
||||
pub current_version: String,
|
||||
pub latest_version: String,
|
||||
pub latest_version: Option<String>,
|
||||
pub has_update: bool,
|
||||
pub deployment_mode: String,
|
||||
pub build_type: String,
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
//! 账号排班的事务存储边界
|
||||
|
||||
use super::store::AdminStoreResult;
|
||||
use crate::model::{
|
||||
MutationContext, Revision,
|
||||
account_schedules::{ScheduleChange, ScheduleList, ScheduleQuery},
|
||||
};
|
||||
use async_trait::async_trait;
|
||||
|
||||
#[async_trait]
|
||||
pub trait AccountScheduleStore: Send + Sync {
|
||||
async fn query(&self, query: &ScheduleQuery) -> AdminStoreResult<ScheduleList>;
|
||||
async fn save(
|
||||
&self,
|
||||
change: ScheduleChange,
|
||||
context: &MutationContext,
|
||||
) -> AdminStoreResult<Revision>;
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
//! 管理用例依赖的外部能力端口
|
||||
|
||||
pub mod account_schedules;
|
||||
pub mod backup;
|
||||
pub mod client_distribution;
|
||||
pub mod peer;
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
//! 原生 Provider 管理能力与启动时注册表
|
||||
|
||||
use std::{collections::BTreeMap, sync::Arc};
|
||||
use std::{
|
||||
collections::{BTreeMap, BTreeSet},
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
use async_trait::async_trait;
|
||||
use gateway_core::{
|
||||
@@ -20,7 +23,7 @@ use crate::model::provider_credentials::{
|
||||
ProviderExport, ProviderExportCredentialInput, ProviderModelCatalogDocument, ProviderModels,
|
||||
ProviderProfileAvatar, ProviderProfileStatistics, ProviderQuota, ProviderQuotaReadRequest,
|
||||
ProviderQuotaRequest, ProviderResetCreditResult, ProviderResetCredits, ProviderSubscription,
|
||||
explicit_plan_type,
|
||||
explicit_plan_type, resolve_observed_plan,
|
||||
};
|
||||
use crate::model::{
|
||||
provider_credentials::{ProviderDocument, ProviderQuotaWindow},
|
||||
@@ -145,6 +148,24 @@ struct ProviderAdminDiagnostic {
|
||||
source: Option<gateway_core::error::ErrorSource>,
|
||||
}
|
||||
|
||||
/// 区分新账号首查与既有账号变更后的后台观察
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct AccountFactsChange<'a> {
|
||||
pub ids: &'a [ProviderAccountId],
|
||||
pub created_ids: &'a BTreeSet<ProviderAccountId>,
|
||||
}
|
||||
|
||||
impl<'a> AccountFactsChange<'a> {
|
||||
#[must_use]
|
||||
pub const fn updated(ids: &'a [ProviderAccountId]) -> Self {
|
||||
static EMPTY: BTreeSet<ProviderAccountId> = BTreeSet::new();
|
||||
Self {
|
||||
ids,
|
||||
created_ids: &EMPTY,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 一个具体 Provider 对管理控制面提供的解析、验证、上游交互与运行时资源回收能力
|
||||
///
|
||||
/// 数据变更由 Provider 返回 prepared facts;config revision、审计与 PostgreSQL 事务
|
||||
@@ -297,7 +318,12 @@ pub trait ProviderAdmin: Send + Sync {
|
||||
/// 该通知发生在 Store 事务成功之后、下一份 RuntimeSnapshot 编译之前;通知
|
||||
/// 不参与已提交事务成败
|
||||
/// 没有账号派生状态的 Provider 可使用默认空实现
|
||||
async fn account_facts_changed(&self, _account_ids: &[ProviderAccountId]) {}
|
||||
async fn account_facts_changed(&self, _change: AccountFactsChange<'_>) {}
|
||||
|
||||
/// 既有账号变更后是否主动查额,手动刷新与新账号首查独立执行
|
||||
async fn background_quota_refresh_enabled(&self) -> Result<bool, ProviderAdminError> {
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// 生成一次连接测试所需的 Provider-owned operation;Core 负责实际执行与落账
|
||||
async fn connection_test_operation(
|
||||
@@ -558,15 +584,14 @@ impl ProviderAdminRegistry {
|
||||
plan_type: &mut Option<String>,
|
||||
quota: Option<&ProviderQuota>,
|
||||
) -> Option<String> {
|
||||
if let Some(quota) = quota {
|
||||
quota.fill_missing_plan_type(plan_type);
|
||||
// 保留账号已知的套餐,不能给它配上另一档快照的描述
|
||||
let quota_id = explicit_plan_type(quota.plan_type.as_deref()).map(str::trim);
|
||||
if let Some(display) = "a.plan_type_display
|
||||
&& quota_id.is_none_or(|id| Some(id) == plan_type.as_deref().map(str::trim))
|
||||
{
|
||||
return Some(display.clone());
|
||||
}
|
||||
if let Some(quota) = quota
|
||||
&& let Some(display) = resolve_observed_plan(
|
||||
plan_type,
|
||||
quota.plan_type.as_deref(),
|
||||
quota.plan_type_display.as_deref(),
|
||||
)
|
||||
{
|
||||
return Some(display.to_owned());
|
||||
}
|
||||
self.plan_type_display(provider_kind, plan_type.as_deref())
|
||||
}
|
||||
|
||||
@@ -8,7 +8,8 @@ use crate::model::{
|
||||
AdminError, MutationContext, Revision,
|
||||
proxies::{
|
||||
ImportProxyBinding, NewProxy, ProxyAccountListQuery, ProxyAccountPage, ProxyListQuery,
|
||||
ProxyMutation, ProxyPage, ProxyRecord, ProxyTestResult, UpdateProxy,
|
||||
ProxyMutation, ProxyPage, ProxyRecord, ProxyTestResult, ProxyTestTargets,
|
||||
TargetProbeResult, UpdateProxy,
|
||||
},
|
||||
};
|
||||
|
||||
@@ -21,6 +22,12 @@ pub trait PluginProxyAccess: Send + Sync {
|
||||
|
||||
#[async_trait]
|
||||
pub trait ProxyStore: Send + Sync {
|
||||
async fn test_targets(&self) -> AdminStoreResult<ProxyTestTargets>;
|
||||
async fn replace_test_targets(
|
||||
&self,
|
||||
settings: &ProxyTestTargets,
|
||||
context: &MutationContext,
|
||||
) -> AdminStoreResult<Revision>;
|
||||
/// 在凭据交换到提交期间保护选定代理的连接配置和测试结果
|
||||
async fn reserve_import(&self, id: &str) -> AdminStoreResult<ProxyImportReservation>;
|
||||
async fn list(&self, query: ProxyListQuery) -> AdminStoreResult<ProxyPage>;
|
||||
@@ -78,5 +85,6 @@ pub enum ProbeRoute<'a> {
|
||||
|
||||
#[async_trait]
|
||||
pub trait ProxyProbe: Send + Sync {
|
||||
async fn test_target(&self, proxy: &OutboundProxy, endpoint: &str) -> TargetProbeResult;
|
||||
async fn test(&self, proxy: ProbeRoute<'_>, detect_location: bool) -> ProxyTestResult;
|
||||
}
|
||||
@@ -655,6 +655,7 @@ pub struct AdminAccountStorePorts {
|
||||
accounts: Arc<dyn AccountStore>,
|
||||
runtime: Arc<dyn AccountRuntimeStore>,
|
||||
groups: Arc<dyn AccountGroupStore>,
|
||||
schedules: Arc<dyn super::account_schedules::AccountScheduleStore>,
|
||||
proxies: Arc<dyn super::proxy::ProxyStore>,
|
||||
}
|
||||
|
||||
@@ -664,12 +665,14 @@ impl AdminAccountStorePorts {
|
||||
accounts: Arc<dyn AccountStore>,
|
||||
runtime: Arc<dyn AccountRuntimeStore>,
|
||||
groups: Arc<dyn AccountGroupStore>,
|
||||
schedules: Arc<dyn super::account_schedules::AccountScheduleStore>,
|
||||
proxies: Arc<dyn super::proxy::ProxyStore>,
|
||||
) -> Self {
|
||||
Self {
|
||||
accounts,
|
||||
runtime,
|
||||
groups,
|
||||
schedules,
|
||||
proxies,
|
||||
}
|
||||
}
|
||||
@@ -755,6 +758,11 @@ impl AdminStorePorts {
|
||||
self.accounts.runtime.clone()
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn account_schedules(&self) -> Arc<dyn super::account_schedules::AccountScheduleStore> {
|
||||
self.accounts.schedules.clone()
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn account_groups(&self) -> Arc<dyn AccountGroupStore> {
|
||||
self.accounts.groups.clone()
|
||||
|
||||
@@ -25,6 +25,13 @@ pub(super) fn register(
|
||||
}};
|
||||
}
|
||||
register!(Load, load, (), ());
|
||||
register!(
|
||||
PreviewPromptRewrite,
|
||||
preview_prompt_rewrite,
|
||||
gateway_core::settings::prompt_rewrite::PromptRewritePreviewRequest,
|
||||
request,
|
||||
request
|
||||
);
|
||||
register!(
|
||||
PreviewPrivacyPolicy,
|
||||
preview_privacy_policy,
|
||||
|
||||
@@ -55,37 +55,44 @@ impl ScheduledTask for ResetCreditAutomationTask {
|
||||
context: WorkerCycleContext,
|
||||
) -> futures::future::BoxFuture<'_, Result<(), WorkerTaskError>> {
|
||||
Box::pin(async move {
|
||||
let settings = self
|
||||
.settings
|
||||
.load_runtime_settings()
|
||||
context
|
||||
.cancellation()
|
||||
.run_until_cancelled(self.run_due())
|
||||
.await
|
||||
.map_err(|_| WorkerTaskError::safe("重置卡设置读取失败"))?;
|
||||
// 单轮有界,积压沿到期顺序继续;并发复用已有账号刷新配置
|
||||
let due = self
|
||||
.store
|
||||
.due_reset_credit_automations(Utc::now(), 100)
|
||||
.await
|
||||
.map_err(|_| WorkerTaskError::safe("重置卡计划读取失败"))?;
|
||||
let work = futures::stream::iter(due)
|
||||
.map(|account_id| async move {
|
||||
let id = ProviderAccountId::new(account_id.clone())
|
||||
.map_err(|_| WorkerTaskError::safe("重置卡账号 ID 不合法"))?;
|
||||
if let Err(error) = self.accounts.reconcile_reset_credit_automation(id).await {
|
||||
tracing::warn!(
|
||||
account_id,
|
||||
error_kind = error.kind().as_str(),
|
||||
"自动重置卡任务失败"
|
||||
);
|
||||
}
|
||||
Ok::<_, WorkerTaskError>(())
|
||||
})
|
||||
.buffer_unordered(settings.values.refresh_concurrency.max(1) as usize)
|
||||
.collect::<Vec<_>>();
|
||||
tokio::select! {
|
||||
() = context.cancellation().cancelled() => {},
|
||||
_ = tokio::time::timeout(Duration::from_secs(30), work) => {},
|
||||
}
|
||||
Ok(())
|
||||
.unwrap_or(Ok(()))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl ResetCreditAutomationTask {
|
||||
async fn run_due(&self) -> Result<(), WorkerTaskError> {
|
||||
let settings = self
|
||||
.settings
|
||||
.load_runtime_settings()
|
||||
.await
|
||||
.map_err(|_| WorkerTaskError::safe("重置卡设置读取失败"))?;
|
||||
// 单轮有界,积压沿到期顺序继续;并发复用已有账号刷新配置
|
||||
let due = self
|
||||
.store
|
||||
.due_reset_credit_automations(Utc::now(), 100)
|
||||
.await
|
||||
.map_err(|_| WorkerTaskError::safe("重置卡计划读取失败"))?;
|
||||
let work = futures::stream::iter(due)
|
||||
.map(|account_id| async move {
|
||||
let id = ProviderAccountId::new(account_id.clone())
|
||||
.map_err(|_| WorkerTaskError::safe("重置卡账号 ID 不合法"))?;
|
||||
if let Err(error) = self.accounts.reconcile_reset_credit_automation(id).await {
|
||||
tracing::warn!(
|
||||
account_id,
|
||||
error_kind = error.kind().as_str(),
|
||||
"自动重置卡任务失败"
|
||||
);
|
||||
}
|
||||
Ok::<_, WorkerTaskError>(())
|
||||
})
|
||||
.buffer_unordered(settings.values.refresh_concurrency.max(1) as usize)
|
||||
.collect::<Vec<_>>();
|
||||
let _ = tokio::time::timeout(Duration::from_secs(30), work).await;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
//! 批量排班校验与已提交配置的发布
|
||||
|
||||
use super::{map_store_error, publish_committed};
|
||||
use crate::{
|
||||
model::{
|
||||
AdminError, MutationContext,
|
||||
account_schedules::{
|
||||
ScheduleAccount, ScheduleChange, ScheduleClock, ScheduleItem, ScheduleQuery,
|
||||
ScheduleQueryResult,
|
||||
},
|
||||
provider_credentials::ProviderQuotaRequest,
|
||||
},
|
||||
ports::{account_schedules::AccountScheduleStore, provider::ProviderAdminRegistry},
|
||||
};
|
||||
use futures::{StreamExt, stream};
|
||||
use gateway_core::{account::ProviderAccountId, routing::ProviderKind, runtime::SnapshotControl};
|
||||
use std::sync::Arc;
|
||||
|
||||
pub struct AccountScheduleService {
|
||||
pub(crate) timezone: gateway_core::time::DeploymentTimeZone,
|
||||
pub(crate) providers: ProviderAdminRegistry,
|
||||
pub(crate) store: Arc<dyn AccountScheduleStore>,
|
||||
pub(crate) snapshot: Arc<dyn SnapshotControl>,
|
||||
}
|
||||
|
||||
impl AccountScheduleService {
|
||||
pub async fn query(&self, mut query: ScheduleQuery) -> Result<ScheduleQueryResult, AdminError> {
|
||||
query.validate()?;
|
||||
let clock = query.include_summary.then(|| {
|
||||
let clock = ScheduleClock::at(chrono::Utc::now(), self.timezone);
|
||||
query.summary_minute.get_or_insert(clock.minute);
|
||||
clock
|
||||
});
|
||||
let mut page = self
|
||||
.store
|
||||
.query(&query)
|
||||
.await
|
||||
.map_err(|e| map_store_error(e, "账号排班"))?;
|
||||
stream::iter(page.items.iter_mut().filter_map(|item| match item {
|
||||
ScheduleItem::Account { account, .. } => Some(account),
|
||||
ScheduleItem::Group { .. } => None,
|
||||
}))
|
||||
.for_each_concurrent(8, |account| self.fill_plan(account))
|
||||
.await;
|
||||
Ok(ScheduleQueryResult { page, clock })
|
||||
}
|
||||
|
||||
async fn fill_plan(&self, account: &mut ScheduleAccount) {
|
||||
account.plan_type_display = self
|
||||
.providers
|
||||
.plan_type_display(&account.provider_kind, account.plan_type.as_deref());
|
||||
// 有些套餐名来自上游额度观测,只在目录缺少展示名时读取已保存的快照
|
||||
if account.plan_type_display.is_some()
|
||||
|| !account.has_cached_quota
|
||||
|| account.authentication_kind == "api_key"
|
||||
{
|
||||
return;
|
||||
}
|
||||
let (Ok(kind), Ok(account_id)) = (
|
||||
ProviderKind::new(account.provider_kind.clone()),
|
||||
ProviderAccountId::new(account.id.clone()),
|
||||
) else {
|
||||
return;
|
||||
};
|
||||
let Ok(provider) = self.providers.require(&kind) else {
|
||||
return;
|
||||
};
|
||||
if let Ok(quota) = provider
|
||||
.quota(ProviderQuotaRequest {
|
||||
account_id,
|
||||
refresh: false,
|
||||
rolling_usage: None,
|
||||
})
|
||||
.await
|
||||
{
|
||||
account.plan_type_display = self.providers.resolve_account_plan(
|
||||
&account.provider_kind,
|
||||
&mut account.plan_type,
|
||||
Some("a),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn save(
|
||||
&self,
|
||||
change: ScheduleChange,
|
||||
context: &MutationContext,
|
||||
) -> Result<u64, AdminError> {
|
||||
change.validate()?;
|
||||
let revision = self
|
||||
.store
|
||||
.save(change, context)
|
||||
.await
|
||||
.map_err(|e| map_store_error(e, "账号排班"))?;
|
||||
publish_committed(self.snapshot.as_ref(), revision).await?;
|
||||
Ok(revision.get())
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
mod reset_credit_automation;
|
||||
|
||||
use crate::ports::provider::AccountFactsChange;
|
||||
use std::{
|
||||
collections::{BTreeMap, BTreeSet},
|
||||
sync::Arc,
|
||||
@@ -197,6 +198,7 @@ pub(crate) struct DefaultAccountsService {
|
||||
settings: Arc<dyn crate::ports::store::SettingsStore>,
|
||||
timezone: gateway_core::time::DeploymentTimeZone,
|
||||
providers: ProviderAdminRegistry,
|
||||
published: gateway_core::runtime::RuntimeSnapshotHandle,
|
||||
snapshot: Arc<dyn SnapshotControl>,
|
||||
probe: Arc<dyn AccountProbe>,
|
||||
upstream_info: Option<Arc<dyn crate::ports::peer::PeerUpstreamService>>,
|
||||
@@ -216,6 +218,7 @@ impl DefaultAccountsService {
|
||||
settings: Arc<dyn crate::ports::store::SettingsStore>,
|
||||
timezone: gateway_core::time::DeploymentTimeZone,
|
||||
providers: ProviderAdminRegistry,
|
||||
published: gateway_core::runtime::RuntimeSnapshotHandle,
|
||||
snapshot: Arc<dyn SnapshotControl>,
|
||||
probe: Arc<dyn AccountProbe>,
|
||||
upstream_info: Option<Arc<dyn crate::ports::peer::PeerUpstreamService>>,
|
||||
@@ -226,6 +229,7 @@ impl DefaultAccountsService {
|
||||
settings,
|
||||
timezone,
|
||||
providers,
|
||||
published,
|
||||
snapshot,
|
||||
probe,
|
||||
upstream_info,
|
||||
@@ -513,6 +517,18 @@ impl DefaultAccountsService {
|
||||
lookback,
|
||||
);
|
||||
Ok(AccountDirectoryItem {
|
||||
schedule_duty: self
|
||||
.published
|
||||
.snapshot_for_diagnostics()
|
||||
.and_then(|snapshot| {
|
||||
snapshot.account_schedule_duty(
|
||||
account_id,
|
||||
std::time::SystemTime::now(),
|
||||
quota.daily_used_percent,
|
||||
)
|
||||
}),
|
||||
model_cooldowns: stored.model_cooldowns,
|
||||
platform_icon: stored.platform_icon,
|
||||
protection_rules: stored.protection_rules,
|
||||
capacity: super::peer_link::upstream::account_capacity(
|
||||
&stored.account,
|
||||
@@ -623,6 +639,7 @@ impl AccountsService for DefaultAccountsService {
|
||||
self.attach_quota_local_usage(&page.items, &mut quotas)
|
||||
.await?;
|
||||
let mut api_key_usage = self.load_api_key_usage(&page.items, "as).await?;
|
||||
let published = self.published.snapshot_for_diagnostics();
|
||||
let items = page
|
||||
.items
|
||||
.into_iter()
|
||||
@@ -647,6 +664,11 @@ impl AccountsService for DefaultAccountsService {
|
||||
lookback,
|
||||
);
|
||||
Ok(AccountDirectoryItem {
|
||||
schedule_duty: published.as_ref().and_then(|snapshot| {
|
||||
snapshot.account_schedule_duty(&id, now.into(), quota.daily_used_percent)
|
||||
}),
|
||||
model_cooldowns: item.model_cooldowns,
|
||||
platform_icon: item.platform_icon,
|
||||
protection_rules: item.protection_rules,
|
||||
capacity: crate::model::accounts::AccountCapacity {
|
||||
used_slots: in_flight
|
||||
@@ -755,7 +777,7 @@ impl AccountsService for DefaultAccountsService {
|
||||
super::notify_account_facts_changed(
|
||||
self.upstream_info.as_deref(),
|
||||
provider.as_ref(),
|
||||
std::slice::from_ref(&result.account_id),
|
||||
AccountFactsChange::updated(std::slice::from_ref(&result.account_id)),
|
||||
)
|
||||
.await;
|
||||
publish_committed(self.snapshot.as_ref(), result.config_revision).await?;
|
||||
@@ -803,7 +825,7 @@ impl AccountsService for DefaultAccountsService {
|
||||
super::notify_account_facts_changed(
|
||||
self.upstream_info.as_deref(),
|
||||
provider.as_ref(),
|
||||
std::slice::from_ref(&account_id),
|
||||
AccountFactsChange::updated(std::slice::from_ref(&account_id)),
|
||||
)
|
||||
.await;
|
||||
publish_committed(self.snapshot.as_ref(), config_revision).await?;
|
||||
@@ -839,7 +861,7 @@ impl AccountsService for DefaultAccountsService {
|
||||
super::notify_account_facts_changed(
|
||||
self.upstream_info.as_deref(),
|
||||
provider.as_ref(),
|
||||
std::slice::from_ref(&account_id),
|
||||
AccountFactsChange::updated(std::slice::from_ref(&account_id)),
|
||||
)
|
||||
.await;
|
||||
publish_committed(self.snapshot.as_ref(), result.config_revision).await?;
|
||||
@@ -957,7 +979,7 @@ impl AccountsService for DefaultAccountsService {
|
||||
super::notify_account_facts_changed(
|
||||
self.upstream_info.as_deref(),
|
||||
provider.as_ref(),
|
||||
provider_ids,
|
||||
AccountFactsChange::updated(provider_ids),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
@@ -970,7 +992,7 @@ impl AccountsService for DefaultAccountsService {
|
||||
self.upstream_info.as_ref(),
|
||||
&provider,
|
||||
&self.accounts,
|
||||
&exhausted,
|
||||
AccountFactsChange::updated(&exhausted),
|
||||
context.request_id.as_str(),
|
||||
);
|
||||
}
|
||||
@@ -1340,7 +1362,8 @@ impl AccountsService for DefaultAccountsService {
|
||||
.map(ToOwned::to_owned);
|
||||
let upstream_body = error
|
||||
.upstream_response()
|
||||
.map(|response| String::from_utf8_lossy(response.body()).into_owned());
|
||||
.and_then(gateway_core::engine::probe::AccountProbeUpstreamResponse::body)
|
||||
.map(|body| String::from_utf8_lossy(body).into_owned());
|
||||
let message = error.client_message().to_owned();
|
||||
vec![AccountConnectionTestEvent::Failed {
|
||||
source: error.source(),
|
||||
|
||||
@@ -337,6 +337,11 @@ impl ClientKeyService for DefaultClientKeyService {
|
||||
context: &MutationContext,
|
||||
command: CreateClientKey,
|
||||
) -> Result<CreatedClientKey, AdminError> {
|
||||
if !command.validity.is_valid() {
|
||||
return Err(AdminError::invalid(
|
||||
"请填写完整有效期,到期时间须晚于生效时间",
|
||||
));
|
||||
}
|
||||
crate::model::client_keys::validate_group_ids(&command.group_ids)
|
||||
.map_err(|_| AdminError::invalid("API Key 分组不合法"))?;
|
||||
for (provider, profile) in &command.request_profile_overrides {
|
||||
@@ -354,6 +359,7 @@ impl ClientKeyService for DefaultClientKeyService {
|
||||
.store
|
||||
.create_client_key(
|
||||
NewClientKey {
|
||||
validity: command.validity,
|
||||
peer_sharing: command.peer_sharing,
|
||||
request_profile_overrides: command.request_profile_overrides,
|
||||
id,
|
||||
@@ -382,6 +388,11 @@ impl ClientKeyService for DefaultClientKeyService {
|
||||
) -> Result<ClientKeyMutation, AdminError> {
|
||||
crate::model::client_keys::validate_group_ids(&command.group_ids)
|
||||
.map_err(|_| AdminError::invalid("API Key 分组不合法"))?;
|
||||
if command.validity.is_some_and(|range| !range.is_valid()) {
|
||||
return Err(AdminError::invalid(
|
||||
"请填写完整有效期,到期时间须晚于生效时间",
|
||||
));
|
||||
}
|
||||
for (provider, profile) in &command.request_profile_override_updates {
|
||||
self.validate_profile(provider, profile.as_ref())?;
|
||||
}
|
||||
|
||||
@@ -12,7 +12,10 @@ use crate::{
|
||||
ProviderQuotaRequest, StartAuthorization,
|
||||
},
|
||||
},
|
||||
ports::{provider::ProviderAdmin, store::AccountStore},
|
||||
ports::{
|
||||
provider::{AccountFactsChange, ProviderAdmin},
|
||||
store::AccountStore,
|
||||
},
|
||||
};
|
||||
use gateway_core::{account::ProviderAccountId, routing::ProviderKind, runtime::SnapshotControl};
|
||||
|
||||
@@ -24,13 +27,13 @@ pub(super) async fn publish_credentials_and_observe_quota(
|
||||
accounts: &std::sync::Arc<dyn AccountStore>,
|
||||
snapshot: &dyn SnapshotControl,
|
||||
revision: crate::model::Revision,
|
||||
account_ids: &[ProviderAccountId],
|
||||
change: AccountFactsChange<'_>,
|
||||
request_id: &str,
|
||||
) -> Result<(), AdminError> {
|
||||
notify_account_facts_changed(peer.map(AsRef::as_ref), provider.as_ref(), account_ids).await;
|
||||
notify_account_facts_changed(peer.map(AsRef::as_ref), provider.as_ref(), change).await;
|
||||
publish_committed(snapshot, revision).await?;
|
||||
|
||||
observe_account_quotas(peer, provider, accounts, account_ids, request_id);
|
||||
observe_account_quotas(peer, provider, accounts, change, request_id);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -38,16 +41,32 @@ pub(super) fn observe_account_quotas(
|
||||
peer: Option<&std::sync::Arc<dyn crate::ports::peer::PeerUpstreamService>>,
|
||||
provider: &std::sync::Arc<dyn ProviderAdmin>,
|
||||
accounts: &std::sync::Arc<dyn AccountStore>,
|
||||
account_ids: &[ProviderAccountId],
|
||||
change: AccountFactsChange<'_>,
|
||||
request_id: &str,
|
||||
) {
|
||||
// 配置已提交,额度查询失败不回滚配置
|
||||
let provider = provider.clone();
|
||||
let peer = peer.cloned();
|
||||
let accounts = accounts.clone();
|
||||
let account_ids = account_ids.to_vec();
|
||||
let mut seen = std::collections::BTreeSet::new();
|
||||
let (initial, updated): (Vec<_>, Vec<_>) = change
|
||||
.ids
|
||||
.iter()
|
||||
.filter(|id| seen.insert(*id))
|
||||
.cloned()
|
||||
.partition(|id| change.created_ids.contains(id));
|
||||
let request_id = request_id.to_owned();
|
||||
tokio::spawn(async move {
|
||||
let mut account_ids = initial;
|
||||
if !updated.is_empty() {
|
||||
match provider.background_quota_refresh_enabled().await {
|
||||
Ok(true) => account_ids.extend(updated),
|
||||
Ok(false) => {}
|
||||
Err(error) => {
|
||||
tracing::warn!(request_id, error = %error, "读取后台额度查询设置失败")
|
||||
}
|
||||
}
|
||||
}
|
||||
for account_id in account_ids {
|
||||
let request = ProviderQuotaRequest {
|
||||
account_id: account_id.clone(),
|
||||
@@ -292,7 +311,7 @@ pub(super) async fn commit_authorization(
|
||||
match accounts.commit_authorization(command, context).await {
|
||||
Ok(result) => {
|
||||
if let Some(guard) = credential_guard
|
||||
&& result.newly_committed
|
||||
&& result.change.is_some()
|
||||
{
|
||||
guard.finish();
|
||||
}
|
||||
@@ -405,7 +424,7 @@ pub(super) async fn delete_credentials(
|
||||
for account_id in &account_ids {
|
||||
notify_account_unavailable(peer, provider, account_id).await;
|
||||
}
|
||||
notify_account_facts_changed(peer, provider, &account_ids).await;
|
||||
notify_account_facts_changed(peer, provider, AccountFactsChange::updated(&account_ids)).await;
|
||||
Ok(CredentialDeletionResult {
|
||||
config_revision: revision,
|
||||
account_ids,
|
||||
@@ -415,11 +434,11 @@ pub(super) async fn delete_credentials(
|
||||
pub(super) async fn notify_account_facts_changed(
|
||||
peer: Option<&dyn crate::ports::peer::PeerUpstreamService>,
|
||||
provider: &dyn ProviderAdmin,
|
||||
ids: &[ProviderAccountId],
|
||||
change: AccountFactsChange<'_>,
|
||||
) {
|
||||
provider.account_facts_changed(ids).await;
|
||||
provider.account_facts_changed(change).await;
|
||||
if let Some(peer) = peer {
|
||||
for id in ids {
|
||||
for id in change.ids {
|
||||
if let Err(error) = peer.account_changed(id).await {
|
||||
tracing::warn!(account_id = %id, error = %error, "upstream information cache invalidation failed");
|
||||
}
|
||||
|
||||
@@ -9,13 +9,16 @@ use crate::{
|
||||
AdminError,
|
||||
provider_credentials::{
|
||||
AuthorizationCommitResult, AuthorizationReceiptKey, AuthorizationStarted,
|
||||
CompleteAuthorization, CredentialDeletion, CredentialDeletionResult,
|
||||
CompleteAuthorization, CredentialChange, CredentialDeletion, CredentialDeletionResult,
|
||||
CredentialImportCommit, CredentialImportResult, CredentialMutationResult,
|
||||
ImportCredentials, PrepareCredentialImport, PrepareCredentialRotation,
|
||||
RotateCredential, StartAuthorization,
|
||||
},
|
||||
},
|
||||
ports::{provider::ProviderAdmin, store::AccountStore},
|
||||
ports::{
|
||||
provider::{AccountFactsChange, ProviderAdmin},
|
||||
store::AccountStore,
|
||||
},
|
||||
};
|
||||
|
||||
use super::super::{
|
||||
@@ -97,7 +100,10 @@ impl ProviderCredentials {
|
||||
&self.accounts,
|
||||
self.snapshot.as_ref(),
|
||||
result.config_revision,
|
||||
&result.credential_ids,
|
||||
AccountFactsChange {
|
||||
ids: &result.credential_ids,
|
||||
created_ids: &result.created_ids,
|
||||
},
|
||||
&context.request_id,
|
||||
)
|
||||
.await?;
|
||||
@@ -175,7 +181,7 @@ impl ProviderCredentials {
|
||||
super::super::notify_account_facts_changed(
|
||||
self.upstream_info.as_deref(),
|
||||
self.provider.as_ref(),
|
||||
std::slice::from_ref(&result.account_id),
|
||||
AccountFactsChange::updated(std::slice::from_ref(&result.account_id)),
|
||||
)
|
||||
.await;
|
||||
publish_committed(self.snapshot.as_ref(), result.config_revision).await?;
|
||||
@@ -248,14 +254,23 @@ impl super::CredentialsService {
|
||||
request_id: &str,
|
||||
) -> Result<CredentialMutationResult, AdminError> {
|
||||
let result = outcome.result;
|
||||
if outcome.newly_committed {
|
||||
if let Some(change) = outcome.change {
|
||||
let ids = std::slice::from_ref(&result.account_id);
|
||||
let created_ids = (change == CredentialChange::Created)
|
||||
.then(|| result.account_id.clone())
|
||||
.into_iter()
|
||||
.collect();
|
||||
let change = AccountFactsChange {
|
||||
ids,
|
||||
created_ids: &created_ids,
|
||||
};
|
||||
publish_credentials_and_observe_quota(
|
||||
self.upstream_info.as_ref(),
|
||||
provider,
|
||||
&self.accounts,
|
||||
self.snapshot.as_ref(),
|
||||
result.config_revision,
|
||||
std::slice::from_ref(&result.account_id),
|
||||
change,
|
||||
request_id,
|
||||
)
|
||||
.await?;
|
||||
|
||||
@@ -4,7 +4,7 @@ mod flow;
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use gateway_core::{routing::ProviderKind, runtime::SnapshotControl};
|
||||
use gateway_core::{account::ProviderAccountId, routing::ProviderKind, runtime::SnapshotControl};
|
||||
|
||||
use crate::{
|
||||
model::AdminError,
|
||||
@@ -40,6 +40,20 @@ impl CredentialsService {
|
||||
}
|
||||
}
|
||||
|
||||
/// 已有账号的凭据操作按已保存的归属选择 Provider
|
||||
pub async fn for_account(
|
||||
&self,
|
||||
account_id: &ProviderAccountId,
|
||||
) -> Result<ProviderCredentials, AdminError> {
|
||||
let account = self
|
||||
.accounts
|
||||
.load_account_record(account_id)
|
||||
.await
|
||||
.map_err(|error| super::map_store_error(error, "provider credentials"))?
|
||||
.ok_or_else(|| AdminError::not_found("账号不存在"))?;
|
||||
self.for_provider(&account.provider_kind)
|
||||
}
|
||||
|
||||
pub fn for_provider(&self, kind: &ProviderKind) -> Result<ProviderCredentials, AdminError> {
|
||||
let provider = self
|
||||
.providers
|
||||
|
||||
@@ -137,7 +137,7 @@ impl KeyUsageService for DefaultKeyUsageService {
|
||||
self.keys
|
||||
.get_client_key(id)
|
||||
.await
|
||||
.map(|key| key.filter(|key| key.enabled).map(|key| key.budget))
|
||||
.map(|key| key.filter(|key| key.is_active()).map(|key| key.budget))
|
||||
.map_err(|error| map_store_error(error, "key usage budget"))
|
||||
}
|
||||
|
||||
@@ -159,7 +159,7 @@ impl KeyUsageService for DefaultKeyUsageService {
|
||||
self.keys
|
||||
.reveal_client_key(&id)
|
||||
.await
|
||||
.map(|secret| secret.filter(|secret| secret.record.enabled))
|
||||
.map(|secret| secret.filter(|secret| secret.record.is_active()))
|
||||
.map_err(|error| map_store_error(error, "key usage config"))
|
||||
}
|
||||
|
||||
@@ -176,7 +176,7 @@ impl KeyUsageService for DefaultKeyUsageService {
|
||||
.get_client_key(&id)
|
||||
.await
|
||||
.map_err(|error| map_store_error(error, "key usage profile"))?
|
||||
.filter(|key| key.enabled)
|
||||
.filter(|key| key.is_active())
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! 管理控制面的用例实现
|
||||
|
||||
pub mod account_groups;
|
||||
pub mod account_schedules;
|
||||
pub mod accounts;
|
||||
pub mod auth;
|
||||
pub mod backup;
|
||||
|
||||
@@ -109,6 +109,9 @@ impl UsageErrorOrigin {
|
||||
"no_available_provider",
|
||||
"no_eligible_account",
|
||||
"account_capacity_unavailable",
|
||||
"account_pool_quota_exhausted",
|
||||
"key_rate_limited",
|
||||
"key_concurrency_limited",
|
||||
"middleware_capacity_unavailable",
|
||||
"concurrency_queue_full",
|
||||
"concurrency_queue_timeout",
|
||||
|
||||
@@ -379,13 +379,15 @@ impl ObservabilityService for DefaultObservabilityService {
|
||||
account_upstream_peer: peers.get(&item.key).copied(),
|
||||
key: item.key,
|
||||
name: item.name,
|
||||
account_email: item.account_email,
|
||||
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_display: self.historical_plan_display(
|
||||
item.account_plan_type_display,
|
||||
item.providers.first().map(String::as_str),
|
||||
item.account_plan_type.as_deref(),
|
||||
),
|
||||
providers: item.providers,
|
||||
platform_icon: item.platform_icon,
|
||||
account_plan_type: item.account_plan_type,
|
||||
request_count: item.request_count,
|
||||
success_count: item.success_count,
|
||||
@@ -422,17 +424,26 @@ impl ObservabilityService for DefaultObservabilityService {
|
||||
.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())
|
||||
});
|
||||
error.provider_account_plan_type_display = self.historical_plan_display(
|
||||
error.provider_account_plan_type_display.take(),
|
||||
error.provider_kind.as_deref(),
|
||||
error.provider_account_plan_type.as_deref(),
|
||||
);
|
||||
}
|
||||
Ok(page)
|
||||
}
|
||||
}
|
||||
|
||||
impl DefaultObservabilityService {
|
||||
fn historical_plan_display(
|
||||
&self,
|
||||
display: Option<String>,
|
||||
provider: Option<&str>,
|
||||
plan_type: Option<&str>,
|
||||
) -> Option<String> {
|
||||
display.or_else(|| self.providers.plan_type_display(provider?, plan_type))
|
||||
}
|
||||
|
||||
async fn current_upstream_peers<'a>(
|
||||
&self,
|
||||
ids: impl Iterator<Item = &'a str>,
|
||||
@@ -540,11 +551,11 @@ impl DefaultObservabilityService {
|
||||
.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())
|
||||
});
|
||||
record.provider_account_plan_type_display = self.historical_plan_display(
|
||||
record.provider_account_plan_type_display.take(),
|
||||
record.provider_kind.as_deref(),
|
||||
record.provider_account_plan_type.as_deref(),
|
||||
);
|
||||
let Some(UsageBilling::Total { source, total }) = record.billing.as_ref() else {
|
||||
continue;
|
||||
};
|
||||
|
||||
@@ -104,7 +104,7 @@ impl PeerLinkService for DefaultPeerLinkService {
|
||||
.get_client_key(client.policy().key_id())
|
||||
.await
|
||||
.map_err(|error| map_store_error(error, "client API key"))?
|
||||
.filter(|key| key.enabled)
|
||||
.filter(|key| key.is_active())
|
||||
.ok_or(PeerLinkError::Unauthorized)?;
|
||||
let budget_observed_at = Utc::now();
|
||||
let sharing = intersect_sharing(frozen_sharing, key.peer_sharing);
|
||||
|
||||
@@ -320,6 +320,13 @@ fn model_observation(
|
||||
reset.min(observed_at + TimeDelta::minutes(30))
|
||||
})
|
||||
.min(now + TimeDelta::minutes(5));
|
||||
let expires_at = if let Some(deadline) = account.quota.exhaustion_deadline()
|
||||
&& account.quota.is_exhausted()
|
||||
{
|
||||
expires_at.min(deadline.into())
|
||||
} else {
|
||||
expires_at
|
||||
};
|
||||
if observed_at > now || expires_at <= now {
|
||||
return None;
|
||||
}
|
||||
|
||||
@@ -11,10 +11,10 @@ use gateway_core::{
|
||||
use std::{collections::BTreeMap, sync::Arc, time::SystemTime};
|
||||
|
||||
impl PeerInfoService {
|
||||
pub(crate) async fn read_summaries(
|
||||
pub(super) async fn hydrate(
|
||||
&self,
|
||||
connections: &[UpstreamConnection],
|
||||
) -> Result<Vec<(UpstreamConnection, ProviderQuota)>, StoreError> {
|
||||
) -> Result<(), StoreError> {
|
||||
let _refresh = self.cache_refresh.lock().await;
|
||||
let ids = connections
|
||||
.iter()
|
||||
@@ -78,6 +78,15 @@ impl PeerInfoService {
|
||||
self.cache(connection, observation);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) async fn read_summaries(
|
||||
&self,
|
||||
connections: &[UpstreamConnection],
|
||||
) -> Result<Vec<(UpstreamConnection, ProviderQuota)>, StoreError> {
|
||||
self.hydrate(connections).await?;
|
||||
let now = SystemTime::now();
|
||||
let summaries = {
|
||||
let observations = self
|
||||
.observations
|
||||
|
||||
@@ -214,6 +214,7 @@ impl PeerInfoService {
|
||||
}
|
||||
}
|
||||
ProviderQuota {
|
||||
daily_used_percent: None,
|
||||
paused_windows: Vec::new(),
|
||||
upstream: Some(info),
|
||||
plan_type: None,
|
||||
|
||||
@@ -42,13 +42,15 @@ impl PeerInfoService {
|
||||
.clone()
|
||||
}
|
||||
|
||||
pub(super) fn refresh_due(&self, connection: &UpstreamConnection) -> bool {
|
||||
if self.unsupported(connection) {
|
||||
return false;
|
||||
}
|
||||
let state = self.refresh_state(connection);
|
||||
state.try_lock().is_ok_and(|state| {
|
||||
state.connection != *connection || Instant::now() >= state.next_attempt
|
||||
pub(super) fn retry_ready(&self, connection: &UpstreamConnection) -> bool {
|
||||
let attempts = self
|
||||
.attempts
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
attempts.get(&connection.account_id).is_none_or(|slot| {
|
||||
slot.try_lock().is_ok_and(|state| {
|
||||
state.connection != *connection || Instant::now() >= state.next_attempt
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
@@ -128,8 +130,9 @@ impl PeerInfoService {
|
||||
};
|
||||
let now = SystemTime::now();
|
||||
let failure = result.as_ref().err().copied();
|
||||
let min_delay = Duration::from_secs(15);
|
||||
let delay = match failure {
|
||||
None => Duration::from_secs(240 + stable_jitter(id.as_str())),
|
||||
None => min_delay,
|
||||
Some(UpstreamInfoFailure::Unauthorized | UpstreamInfoFailure::SharingDisabled) => {
|
||||
Duration::from_secs(1800)
|
||||
}
|
||||
@@ -138,8 +141,7 @@ impl PeerInfoService {
|
||||
.max(retry_after.unwrap_or_default());
|
||||
state.next_attempt = Instant::now() + delay;
|
||||
// 管理员修复授权后可主动复核,不继承自动重试的长退避,仍遵守上游限流
|
||||
state.manual_after =
|
||||
Instant::now() + Duration::from_secs(15).max(retry_after.unwrap_or_default());
|
||||
state.manual_after = Instant::now() + min_delay.max(retry_after.unwrap_or_default());
|
||||
state.last_error = failure;
|
||||
let document = match result {
|
||||
Ok(document) => Some(document),
|
||||
@@ -170,6 +172,7 @@ impl PeerInfoService {
|
||||
.and_then(|peer| quota::observe(&peer, started_at, now))
|
||||
.unwrap_or(QuotaState::unknown());
|
||||
let observation = QuotaObservation {
|
||||
merge_base: None,
|
||||
quota_pause: None,
|
||||
expected_connection: Some(connection.clone()),
|
||||
account_id: id.clone(),
|
||||
@@ -214,12 +217,6 @@ impl PeerInfoService {
|
||||
}
|
||||
}
|
||||
|
||||
fn stable_jitter(id: &str) -> u64 {
|
||||
id.bytes().fold(0_u64, |hash, byte| {
|
||||
hash.wrapping_mul(31).wrapping_add(u64::from(byte))
|
||||
}) % 60
|
||||
}
|
||||
|
||||
fn refresh_error(error: UpstreamInfoFailure) -> Option<ProviderAdminError> {
|
||||
let message = match error {
|
||||
UpstreamInfoFailure::Unauthorized => "上游未授权读取互联信息",
|
||||
|
||||
@@ -12,7 +12,8 @@ use futures::{StreamExt as _, stream};
|
||||
use gateway_core::{
|
||||
account::{
|
||||
LoadedCredential, ProviderAccount, ProviderAccountId, ProviderAccountStore,
|
||||
UpstreamConnection, UpstreamInfoFailure, UpstreamInfoSource, UpstreamSchedulingSignal,
|
||||
QuotaObservationVersion, UpstreamConnection, UpstreamInfoFailure, UpstreamInfoSource,
|
||||
UpstreamSchedulingSignal,
|
||||
},
|
||||
error::{StoreError, StoreErrorKind},
|
||||
routing::ProviderKind,
|
||||
@@ -22,11 +23,12 @@ use gateway_protocol::peer::PeerLink;
|
||||
use std::{
|
||||
collections::{BTreeMap, HashMap},
|
||||
sync::{Arc, Mutex, RwLock},
|
||||
time::SystemTime,
|
||||
time::{Duration, SystemTime},
|
||||
};
|
||||
use tokio::sync::Semaphore;
|
||||
|
||||
const REFRESH_CONCURRENCY: usize = 4;
|
||||
const REFRESH_INTERVAL: Duration = Duration::from_secs(5 * 60);
|
||||
|
||||
pub(super) struct CachedObservation {
|
||||
pub connection: UpstreamConnection,
|
||||
@@ -209,56 +211,35 @@ impl PeerInfoService {
|
||||
if context.cancellation().is_cancelled() {
|
||||
break;
|
||||
}
|
||||
let accounts = match self.accounts.list_for_provider(provider, false).await {
|
||||
let mut accounts = match self.accounts.list_for_provider(provider, false).await {
|
||||
Ok(accounts) => accounts,
|
||||
Err(error) => {
|
||||
failure.get_or_insert(error);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let connections = accounts
|
||||
.iter()
|
||||
.filter(|account| self.supported(account))
|
||||
.map(UpstreamConnection::for_account)
|
||||
.collect::<Vec<_>>();
|
||||
active.extend(
|
||||
connections
|
||||
.iter()
|
||||
.map(|connection| connection.account_id.clone()),
|
||||
);
|
||||
let connections = {
|
||||
accounts.retain(|account| self.supported(account));
|
||||
active.extend(accounts.iter().map(|account| account.id().clone()));
|
||||
if accounts.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let batch = {
|
||||
let mut cursors = self
|
||||
.cursors
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let offset = cursors.entry(provider.clone()).or_default();
|
||||
if *offset >= connections.len() {
|
||||
if *offset >= accounts.len() {
|
||||
*offset = 0;
|
||||
}
|
||||
let batch = connections
|
||||
.iter()
|
||||
.skip(*offset)
|
||||
.take(100)
|
||||
.cloned()
|
||||
.collect::<Vec<_>>();
|
||||
*offset += batch.len();
|
||||
let end = (*offset + 100).min(accounts.len());
|
||||
let batch = &accounts[*offset..end];
|
||||
*offset = end;
|
||||
batch
|
||||
};
|
||||
if let Err(error) = self.read_summaries(&connections).await {
|
||||
if let Err(error) = self.refresh_batch(batch).await {
|
||||
failure.get_or_insert(error);
|
||||
continue;
|
||||
}
|
||||
// 每轮有界并发,运行期到期记录在请求开始时预留,取消后可按普通重试恢复
|
||||
let pending = connections
|
||||
.into_iter()
|
||||
.filter(|connection| self.refresh_due(connection))
|
||||
.take(100)
|
||||
.collect::<Vec<_>>();
|
||||
stream::iter(pending).map(|connection| async move {
|
||||
if let Err(error) = self.refresh(&connection.account_id, false).await {
|
||||
tracing::warn!(account_id = %connection.account_id, error = %error, "Upstream quota refresh failed");
|
||||
}
|
||||
}).buffer_unordered(REFRESH_CONCURRENCY).collect::<Vec<_>>().await;
|
||||
}
|
||||
// 查询失败时保留该轮无法核对的账号,避免错误风暴清空所有节流记录
|
||||
if failure.is_none() && !context.cancellation().is_cancelled() {
|
||||
@@ -279,6 +260,74 @@ impl PeerInfoService {
|
||||
drop(removed);
|
||||
failure.map_or(Ok(()), Err)
|
||||
}
|
||||
|
||||
async fn refresh_batch(&self, accounts: &[ProviderAccount]) -> Result<(), StoreError> {
|
||||
let connections: Vec<_> = accounts
|
||||
.iter()
|
||||
.map(UpstreamConnection::for_account)
|
||||
.collect();
|
||||
self.hydrate(&connections).await?;
|
||||
let now = SystemTime::now();
|
||||
let mut due = Vec::new();
|
||||
let mut stale = Vec::new();
|
||||
{
|
||||
let observations = self
|
||||
.observations
|
||||
.read()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
for (account, connection) in accounts.iter().zip(connections) {
|
||||
let cached = observations
|
||||
.get(account.id())
|
||||
.filter(|c| c.connection == connection);
|
||||
if cached
|
||||
.is_some_and(|c| c.stored_failure == Some(UpstreamInfoFailure::Unsupported))
|
||||
|| !self.retry_ready(&connection)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
// 只有成功识别的快照参与惰性刷新,授权失败等识别记录仍按退避复查
|
||||
let Some(observed_at) = cached
|
||||
.filter(|c| c.summary.is_some())
|
||||
.and_then(|c| c.observed_at)
|
||||
else {
|
||||
due.push(connection.account_id);
|
||||
continue;
|
||||
};
|
||||
let aged = now.duration_since(observed_at).unwrap_or_default() >= REFRESH_INTERVAL;
|
||||
let quota = account.quota();
|
||||
if quota.is_exhausted() {
|
||||
// 已在重置后查过但未获恢复证据时,等下一个复查周期
|
||||
if quota.exhaustion_refresh_due(now, REFRESH_INTERVAL)
|
||||
&& (aged || quota.reset_at().is_some_and(|reset| observed_at < reset))
|
||||
{
|
||||
due.push(connection.account_id);
|
||||
}
|
||||
} else if aged {
|
||||
stale.push(QuotaObservationVersion {
|
||||
account_id: connection.account_id,
|
||||
credential_revision: connection.credential_revision,
|
||||
observed_at,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
// 用量查询失败只影响正常账号,首查与耗尽复查仍可执行
|
||||
let mut outcome = Ok(());
|
||||
if !stale.is_empty() {
|
||||
match self.accounts.accounts_used_since_quota(&stale).await {
|
||||
Ok(active) => due.extend(active),
|
||||
Err(error) => outcome = Err(error),
|
||||
}
|
||||
}
|
||||
stream::iter(due)
|
||||
.for_each_concurrent(REFRESH_CONCURRENCY, |id| async move {
|
||||
if let Err(error) = self.refresh(&id, false).await {
|
||||
tracing::warn!(account_id = %id, error = %error, "Upstream quota refresh failed");
|
||||
}
|
||||
})
|
||||
.await;
|
||||
outcome
|
||||
}
|
||||
}
|
||||
|
||||
impl UpstreamInfoSource for PeerInfoService {
|
||||
|
||||
@@ -19,6 +19,8 @@ use crate::{
|
||||
},
|
||||
};
|
||||
|
||||
use crate::ports::provider::AccountFactsChange;
|
||||
|
||||
use super::{
|
||||
map_provider_error, map_store_error, publish_credentials_and_observe_quota,
|
||||
required_credential, required_plugin_credential, validate_prepared_import,
|
||||
@@ -218,7 +220,10 @@ impl PluginAccountAccess for DefaultPluginAccountAccess {
|
||||
&self.accounts,
|
||||
self.snapshot.as_ref(),
|
||||
result.config_revision,
|
||||
std::slice::from_ref(&account_id),
|
||||
AccountFactsChange {
|
||||
ids: &result.credential_ids,
|
||||
created_ids: &result.created_ids,
|
||||
},
|
||||
&context.request_id,
|
||||
)
|
||||
.await?;
|
||||
@@ -263,7 +268,7 @@ impl PluginAccountAccess for DefaultPluginAccountAccess {
|
||||
&self.accounts,
|
||||
self.snapshot.as_ref(),
|
||||
result.config_revision,
|
||||
std::slice::from_ref(&result.account_id),
|
||||
AccountFactsChange::updated(std::slice::from_ref(&result.account_id)),
|
||||
&context.request_id,
|
||||
)
|
||||
.await?;
|
||||
|
||||
@@ -85,6 +85,7 @@ impl PluginResourceAccess for DefaultPluginResourceAccess {
|
||||
resource_key,
|
||||
groups,
|
||||
NewClientKey {
|
||||
validity: Default::default(),
|
||||
peer_sharing: Default::default(),
|
||||
id,
|
||||
name: command.name,
|
||||
|
||||
@@ -69,6 +69,18 @@ async fn list_proxies(
|
||||
|
||||
#[async_trait]
|
||||
pub trait ProxiesService: Send + Sync {
|
||||
async fn test_targets(&self) -> Result<ProxyTestTargets, AdminError>;
|
||||
async fn replace_test_targets(
|
||||
&self,
|
||||
settings: ProxyTestTargets,
|
||||
context: &MutationContext,
|
||||
) -> Result<ProxyTestTargets, AdminError>;
|
||||
async fn test_target(
|
||||
&self,
|
||||
proxy_id: &str,
|
||||
name: &str,
|
||||
revision: Revision,
|
||||
) -> Result<(String, TargetProbeResult), AdminError>;
|
||||
async fn create_batch(
|
||||
&self,
|
||||
commands: Vec<Result<NewProxy, AdminError>>,
|
||||
@@ -131,6 +143,12 @@ pub(crate) struct DefaultProxiesService {
|
||||
}
|
||||
|
||||
impl DefaultProxiesService {
|
||||
fn test_slot(&self) -> Result<tokio::sync::SemaphorePermit<'_>, AdminError> {
|
||||
self.test_slots
|
||||
.try_acquire()
|
||||
.map_err(|_| AdminError::new(AdminErrorKind::RateLimited, "代理测试已达并发上限"))
|
||||
}
|
||||
|
||||
pub(crate) fn new(
|
||||
store: Arc<dyn ProxyStore>,
|
||||
probe: Arc<dyn ProxyProbe>,
|
||||
@@ -151,6 +169,84 @@ impl DefaultProxiesService {
|
||||
|
||||
#[async_trait]
|
||||
impl ProxiesService for DefaultProxiesService {
|
||||
async fn test_targets(&self) -> Result<ProxyTestTargets, AdminError> {
|
||||
self.store
|
||||
.test_targets()
|
||||
.await
|
||||
.map_err(|error| map_store_error(error, "proxy test targets"))
|
||||
}
|
||||
|
||||
async fn replace_test_targets(
|
||||
&self,
|
||||
mut settings: ProxyTestTargets,
|
||||
context: &MutationContext,
|
||||
) -> Result<ProxyTestTargets, AdminError> {
|
||||
if settings.targets.len() > 32 {
|
||||
return Err(AdminError::invalid("最多可配置 32 个测试目标"));
|
||||
}
|
||||
let mut names = std::collections::HashSet::new();
|
||||
for target in &mut settings.targets {
|
||||
target.name = target.name.trim().to_owned();
|
||||
if target.name.is_empty()
|
||||
|| target.name.chars().count() > 100
|
||||
|| target.name.chars().any(char::is_control)
|
||||
{
|
||||
return Err(AdminError::invalid("目标名称需要 1 至 100 个字符"));
|
||||
}
|
||||
if !names.insert(target.name.as_str()) {
|
||||
return Err(AdminError::invalid("测试目标名称重复"));
|
||||
}
|
||||
let raw = target.url.trim();
|
||||
let url = url::Url::parse(raw)
|
||||
.ok()
|
||||
.filter(|url| {
|
||||
!raw.chars().any(char::is_control)
|
||||
&& url.scheme() == "https"
|
||||
&& url.has_host()
|
||||
&& url.username().is_empty()
|
||||
&& url.password().is_none()
|
||||
&& url.fragment().is_none()
|
||||
})
|
||||
.ok_or_else(|| AdminError::invalid("请输入不含凭据和片段的 HTTPS 目标地址"))?;
|
||||
if raw.len() > 2048 || url.as_str().len() > 2048 {
|
||||
return Err(AdminError::invalid("目标地址不能超过 2048 字节"));
|
||||
}
|
||||
target.url = url.into();
|
||||
}
|
||||
settings.revision = self
|
||||
.store
|
||||
.replace_test_targets(&settings, context)
|
||||
.await
|
||||
.map_err(|error| map_store_error(error, "proxy test targets"))?;
|
||||
publish_committed(self.snapshot.as_ref(), settings.revision).await?;
|
||||
Ok(settings)
|
||||
}
|
||||
|
||||
async fn test_target(
|
||||
&self,
|
||||
proxy_id: &str,
|
||||
name: &str,
|
||||
revision: Revision,
|
||||
) -> Result<(String, TargetProbeResult), AdminError> {
|
||||
let _permit = self.test_slot()?;
|
||||
let settings = self.test_targets().await?;
|
||||
if settings.revision != revision {
|
||||
return Err(AdminError::conflict("测试目标已更新,请重新选择"));
|
||||
}
|
||||
let target = settings
|
||||
.targets
|
||||
.iter()
|
||||
.find(|target| target.name == name)
|
||||
.ok_or_else(|| AdminError::not_found("测试目标不存在"))?;
|
||||
let record = self
|
||||
.store
|
||||
.get(proxy_id)
|
||||
.await
|
||||
.map_err(|error| map_store_error(error, "proxy"))?;
|
||||
let result = self.probe.test_target(&record.proxy, &target.url).await;
|
||||
Ok((record.name, result))
|
||||
}
|
||||
|
||||
async fn create_batch(
|
||||
&self,
|
||||
commands: Vec<Result<NewProxy, AdminError>>,
|
||||
@@ -394,10 +490,7 @@ impl ProxiesService for DefaultProxiesService {
|
||||
proxy: ProbeRoute<'_>,
|
||||
detect_location: bool,
|
||||
) -> Result<ProxyTestResult, AdminError> {
|
||||
let _permit = self
|
||||
.test_slots
|
||||
.try_acquire()
|
||||
.map_err(|_| AdminError::new(AdminErrorKind::RateLimited, "代理测试已达并发上限"))?;
|
||||
let _permit = self.test_slot()?;
|
||||
Ok(self.probe.test(proxy, detect_location).await)
|
||||
}
|
||||
|
||||
@@ -408,10 +501,7 @@ impl ProxiesService for DefaultProxiesService {
|
||||
detect_location: bool,
|
||||
context: &MutationContext,
|
||||
) -> Result<ProxyRecord, AdminError> {
|
||||
let _permit = self
|
||||
.test_slots
|
||||
.try_acquire()
|
||||
.map_err(|_| AdminError::new(AdminErrorKind::RateLimited, "代理测试已达并发上限"))?;
|
||||
let _permit = self.test_slot()?;
|
||||
let record = self
|
||||
.store
|
||||
.get(id)
|
||||
|
||||
@@ -22,6 +22,17 @@ use super::{map_store_error, publish_committed};
|
||||
/// API 消费的 Runtime settings 管理服务
|
||||
#[async_trait]
|
||||
pub trait SettingsService: Send + Sync {
|
||||
async fn preview_prompt_rewrite(
|
||||
&self,
|
||||
request: gateway_core::settings::prompt_rewrite::PromptRewritePreviewRequest,
|
||||
) -> Result<gateway_core::settings::prompt_rewrite::PromptRewritePreviewResult, AdminError>
|
||||
{
|
||||
request
|
||||
.rule
|
||||
.preview(&request.text)
|
||||
.map_err(|_| AdminError::invalid("正则表达式无效或超出编译大小限制"))
|
||||
}
|
||||
|
||||
async fn preview_privacy_policy(
|
||||
&self,
|
||||
_request: gateway_core::settings::privacy::PrivacyPreviewRequest,
|
||||
@@ -117,7 +128,22 @@ fn validate_settings(command: &ReplaceRuntimeSettings) -> Result<(), AdminError>
|
||||
)
|
||||
.map_err(|_| AdminError::invalid("运行时设置不满足约束"))?;
|
||||
command.values.validate().map_err(|field| match field {
|
||||
"openai_request_country" => AdminError::invalid("请求国家必须是两位大写 ASCII 字母"),
|
||||
"prompt_rewrite_rules" => AdminError::invalid("正则表达式无效或超出编译大小限制"),
|
||||
"openai_websocket_pool.fast_path_budget_ms" => {
|
||||
AdminError::invalid("WS 建连等待时间须为 1–15000 毫秒")
|
||||
}
|
||||
"openai_websocket_pool.max_age_ms"
|
||||
| "openai_websocket_pool.idle_timeout_ms"
|
||||
| "openai_websocket_pool.max_connecting" => {
|
||||
AdminError::invalid("WS 连接寿命、空闲回收时间和最大并发建连数必须大于零")
|
||||
}
|
||||
"openai_request_settings.residency"
|
||||
| "openai_request_settings.account_routing_override" => {
|
||||
AdminError::invalid("数据驻留和账号路由必须是有效的单行请求头值")
|
||||
}
|
||||
"openai_request_settings.request_country" => {
|
||||
AdminError::invalid("请求国家必须是两位大写 ASCII 字母")
|
||||
}
|
||||
_ => AdminError::invalid("运行时设置不满足约束"),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -106,6 +106,7 @@ fn provider_document_debug_should_not_expose_opaque_material() {
|
||||
#[test]
|
||||
fn representative_quota_should_prefer_short_window_and_highest_usage() {
|
||||
let quota = ProviderQuota {
|
||||
daily_used_percent: None,
|
||||
paused_windows: Vec::new(),
|
||||
upstream: None,
|
||||
credits: None,
|
||||
@@ -131,6 +132,7 @@ fn representative_quota_should_prefer_account_wide_window_over_model_specific_wi
|
||||
let mut model_specific = quota_window("shortTerm", Some(18_000), Some(64.0));
|
||||
model_specific.local_usage_attribution = QuotaLocalUsageAttribution::Unavailable;
|
||||
let quota = ProviderQuota {
|
||||
daily_used_percent: None,
|
||||
paused_windows: Vec::new(),
|
||||
upstream: None,
|
||||
credits: None,
|
||||
@@ -152,6 +154,7 @@ fn representative_quota_should_prefer_account_wide_window_over_model_specific_wi
|
||||
#[test]
|
||||
fn account_exhaustion_preserves_measured_and_unknown_window_usage() {
|
||||
let mut quota = ProviderQuota {
|
||||
daily_used_percent: None,
|
||||
paused_windows: Vec::new(),
|
||||
upstream: None,
|
||||
credits: None,
|
||||
@@ -183,6 +186,7 @@ fn exhausted_quota_should_preserve_the_provider_identified_reached_window() {
|
||||
let mut reached = quota_window("monthly", Some(2_592_000), Some(98.0));
|
||||
reached.limit_reached = true;
|
||||
let mut quota = ProviderQuota {
|
||||
daily_used_percent: None,
|
||||
paused_windows: Vec::new(),
|
||||
upstream: None,
|
||||
credits: None,
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
//! 排班分钟采样在部署时区的跳时和重复时刻重新对齐
|
||||
|
||||
use chrono::{DateTime, TimeDelta, Utc};
|
||||
use gateway_admin::model::account_schedules::ScheduleClock;
|
||||
|
||||
#[test]
|
||||
fn clock_expires_at_both_dst_boundaries() {
|
||||
let zone = "America/New_York".parse().unwrap();
|
||||
for (sample, before, after) in [
|
||||
("2026-03-08T06:59:44.500Z", 119, 180),
|
||||
("2026-11-01T05:59:44.500Z", 119, 60),
|
||||
] {
|
||||
let at: DateTime<Utc> = sample.parse().unwrap();
|
||||
let clock = ScheduleClock::at(at, zone);
|
||||
assert_eq!(clock.minute, before);
|
||||
assert_eq!(clock.valid_for_millis, 15_500);
|
||||
let next = ScheduleClock::at(at + TimeDelta::milliseconds(clock.valid_for_millis), zone);
|
||||
assert_eq!(next.minute, after);
|
||||
assert_eq!(next.valid_for_millis, 86_400_000);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
//! 模型模块测试:镜像 src/model/ 中带逻辑的模块
|
||||
|
||||
mod account_groups;
|
||||
mod account_schedules;
|
||||
mod audit;
|
||||
mod backup;
|
||||
mod client_keys;
|
||||
|
||||
@@ -116,6 +116,7 @@ fn selected_usage_window(quota: &ProviderQuota) -> Option<(&str, AccountUsagePer
|
||||
|
||||
fn usage_quota(windows: Vec<ProviderQuotaWindow>) -> ProviderQuota {
|
||||
ProviderQuota {
|
||||
daily_used_percent: None,
|
||||
paused_windows: Vec::new(),
|
||||
upstream: None,
|
||||
credits: None,
|
||||
@@ -170,6 +171,7 @@ fn usage_window(key: &str, group: &str, seconds: u64) -> ProviderQuotaWindow {
|
||||
#[test]
|
||||
fn dashboard_quota_should_preserve_unknown_and_actual_window_facts() {
|
||||
let mut quota = ProviderQuota {
|
||||
daily_used_percent: None,
|
||||
paused_windows: Vec::new(),
|
||||
upstream: None,
|
||||
credits: None,
|
||||
|
||||
@@ -59,6 +59,7 @@ fn window(key: &str, days: u64) -> ProviderQuotaWindow {
|
||||
|
||||
fn quota(windows: Vec<ProviderQuotaWindow>) -> ProviderQuota {
|
||||
ProviderQuota {
|
||||
daily_used_percent: None,
|
||||
paused_windows: Vec::new(),
|
||||
upstream: None,
|
||||
credits: None,
|
||||
|
||||
@@ -315,6 +315,7 @@ impl AccountRuntimeStore for FakeRuntimeStore {
|
||||
) -> AdminStoreResult<AccountRuntimeSnapshot> {
|
||||
*self.requested_accounts.lock().expect("requested accounts") = account_ids.to_vec();
|
||||
Ok(AccountRuntimeSnapshot {
|
||||
model_cooldowns: BTreeMap::new(),
|
||||
protection_rules: std::collections::BTreeMap::new(),
|
||||
cooldown: BTreeMap::from([(
|
||||
"acct_limited".to_owned(),
|
||||
|
||||
@@ -40,7 +40,7 @@ use gateway_admin::{
|
||||
provider_credentials::{
|
||||
AuthorizationCommit, AuthorizationCommitGuard, AuthorizationCredentialCommit,
|
||||
AuthorizationMutationTarget, AuthorizationStarted, CompleteAuthorization,
|
||||
ConsumeProviderResetCredit, CredentialCommitGuard, CredentialDetails,
|
||||
ConsumeProviderResetCredit, CredentialChange, CredentialCommitGuard, CredentialDetails,
|
||||
CredentialImportCommit, CredentialImportResult, CredentialMutationResult,
|
||||
CredentialRotationCommit, PendingAuthorizationMutation, PrepareCredentialImport,
|
||||
PrepareCredentialRefresh, PrepareCredentialRotation, PreparedAuthorizationCommit,
|
||||
@@ -267,6 +267,7 @@ impl FakeProviderAdmin {
|
||||
email: account.email.clone(),
|
||||
plan_type: account.plan_type.clone(),
|
||||
preserve_profile: false,
|
||||
preserve_catalog_etag: None,
|
||||
preserve_credential_state: false,
|
||||
preserve_access_token_expiry: false,
|
||||
provider_material: document(),
|
||||
@@ -346,7 +347,10 @@ impl ProviderAdmin for FakeProviderAdmin {
|
||||
self.record("provider.account_unavailable");
|
||||
}
|
||||
|
||||
async fn account_facts_changed(&self, _: &[ProviderAccountId]) {
|
||||
async fn account_facts_changed(
|
||||
&self,
|
||||
_: gateway_admin::ports::provider::AccountFactsChange<'_>,
|
||||
) {
|
||||
self.record("provider.account_facts_changed");
|
||||
}
|
||||
|
||||
@@ -740,6 +744,8 @@ impl FakeAccountStore {
|
||||
last_error_message: account.last_error_message.clone(),
|
||||
};
|
||||
AccountPageItem {
|
||||
model_cooldowns: Vec::new(),
|
||||
platform_icon: None,
|
||||
protection_rules: Vec::new(),
|
||||
capacity: gateway_admin::model::accounts::AccountCapacity {
|
||||
used_slots: None,
|
||||
@@ -992,6 +998,12 @@ impl AccountStore for FakeAccountStore {
|
||||
self.record_context(context);
|
||||
self.require_commit()?;
|
||||
Ok(CredentialImportResult {
|
||||
created_ids: command
|
||||
.prepared
|
||||
.credentials
|
||||
.iter()
|
||||
.map(|c| c.account_id.clone())
|
||||
.collect(),
|
||||
config_revision: revision(2),
|
||||
credential_ids: command
|
||||
.prepared
|
||||
@@ -1016,18 +1028,21 @@ impl AccountStore for FakeAccountStore {
|
||||
return Ok(
|
||||
gateway_admin::model::provider_credentials::AuthorizationCommitResult {
|
||||
result,
|
||||
newly_committed: false,
|
||||
change: None,
|
||||
},
|
||||
);
|
||||
}
|
||||
self.record("store.commit_authorization");
|
||||
self.record_context(context);
|
||||
self.require_commit()?;
|
||||
let (account_id, credential_revision) = match command.credential {
|
||||
AuthorizationCredentialCommit::Create(credential) => (credential.account_id, None),
|
||||
let (account_id, credential_revision, change) = match command.credential {
|
||||
AuthorizationCredentialCommit::Create(credential) => {
|
||||
(credential.account_id, None, CredentialChange::Created)
|
||||
}
|
||||
AuthorizationCredentialCommit::Reauthorize(credential) => (
|
||||
credential.account_id,
|
||||
Some(revision(credential.expected_credential_revision.get() + 1)),
|
||||
CredentialChange::Updated,
|
||||
),
|
||||
};
|
||||
let result = CredentialMutationResult {
|
||||
@@ -1042,7 +1057,7 @@ impl AccountStore for FakeAccountStore {
|
||||
Ok(
|
||||
gateway_admin::model::provider_credentials::AuthorizationCommitResult {
|
||||
result,
|
||||
newly_committed: true,
|
||||
change: Some(change),
|
||||
},
|
||||
)
|
||||
}
|
||||
@@ -1200,8 +1215,12 @@ 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(),
|
||||
antigravity_background_refresh: true,
|
||||
openai_websocket_pool: Default::default(),
|
||||
openai_request_settings: gateway_core::settings::OpenAiRequestSettings {
|
||||
oauth_guardian_review_model: false,
|
||||
..Default::default()
|
||||
},
|
||||
codex_privacy_policy: Default::default(),
|
||||
request_location_enabled: false,
|
||||
request_location: Default::default(),
|
||||
@@ -1226,6 +1245,7 @@ impl SettingsStore for StaticSettingsStore {
|
||||
usage_retention_days: 30,
|
||||
ops_event_retention_days: 30,
|
||||
audit_retention_days: 30,
|
||||
prompt_rewrite_rules: Vec::new(),
|
||||
account_error_protection: gateway_core::account::AccountErrorProtection::default(),
|
||||
account_warmup_enabled: false,
|
||||
account_warmup_cron: "0 8 * * *".to_owned(),
|
||||
@@ -1891,6 +1911,7 @@ async fn accounts_update_should_commit_then_release_disabled_account_and_publish
|
||||
.update(
|
||||
&context("update-request"),
|
||||
UpdateAccount {
|
||||
platform_icon: None,
|
||||
name: None,
|
||||
notes: None,
|
||||
model_access: Default::default(),
|
||||
@@ -1931,6 +1952,7 @@ async fn accounts_update_should_not_notify_provider_when_store_commit_fails() {
|
||||
.update(
|
||||
&context("update-failure"),
|
||||
UpdateAccount {
|
||||
platform_icon: None,
|
||||
name: None,
|
||||
notes: None,
|
||||
model_access: Default::default(),
|
||||
@@ -2141,6 +2163,7 @@ async fn accounts_list_should_degrade_quota_failure_to_empty_window_without_drop
|
||||
let events = events();
|
||||
let openai = FakeProviderAdmin::new("openai", events.clone());
|
||||
openai.set_quota(ProviderQuota {
|
||||
daily_used_percent: None,
|
||||
paused_windows: Vec::new(),
|
||||
upstream: None,
|
||||
credits: None,
|
||||
@@ -2303,6 +2326,7 @@ async fn accounts_list_should_map_unknown_credential_to_error_not_normal() {
|
||||
async fn accounts_list_should_not_derive_rate_limited_from_provider_quota_view() {
|
||||
let provider = FakeProviderAdmin::new("openai", events());
|
||||
provider.set_quota(ProviderQuota {
|
||||
daily_used_percent: None,
|
||||
paused_windows: Vec::new(),
|
||||
upstream: None,
|
||||
credits: None,
|
||||
@@ -2356,6 +2380,7 @@ async fn accounts_list_should_not_derive_rate_limited_from_provider_quota_view()
|
||||
async fn accounts_list_should_not_derive_exhaustion_from_provider_quota_view() {
|
||||
let provider = FakeProviderAdmin::new("openai", events());
|
||||
provider.set_quota(ProviderQuota {
|
||||
daily_used_percent: None,
|
||||
paused_windows: Vec::new(),
|
||||
upstream: None,
|
||||
credits: None,
|
||||
@@ -3122,6 +3147,7 @@ async fn accounts_list_should_attach_local_usage_to_quota_windows() {
|
||||
let provider = FakeProviderAdmin::new("openai", events());
|
||||
let reset_at = Utc::now() + TimeDelta::hours(1);
|
||||
provider.set_quota(ProviderQuota {
|
||||
daily_used_percent: None,
|
||||
paused_windows: Vec::new(),
|
||||
upstream: None,
|
||||
credits: None,
|
||||
@@ -3288,6 +3314,7 @@ async fn account_windows_attach_only_the_usage_allowed_by_the_provider() {
|
||||
let provider = FakeProviderAdmin::new("openai", events());
|
||||
let reset_at = Utc::now() + TimeDelta::days(7);
|
||||
let mut quota = ProviderQuota {
|
||||
daily_used_percent: None,
|
||||
paused_windows: Vec::new(),
|
||||
upstream: None,
|
||||
credits: None,
|
||||
@@ -3611,6 +3638,7 @@ pub(super) fn document() -> ProviderDocument {
|
||||
|
||||
fn empty_quota() -> ProviderQuota {
|
||||
ProviderQuota {
|
||||
daily_used_percent: None,
|
||||
paused_windows: Vec::new(),
|
||||
upstream: None,
|
||||
credits: None,
|
||||
@@ -3739,6 +3767,7 @@ fn plugin_rotation_facts(account: &AccountRecord) -> PreparedCredentialRotationF
|
||||
email: account.email.clone(),
|
||||
plan_type: account.plan_type.clone(),
|
||||
preserve_profile: true,
|
||||
preserve_catalog_etag: None,
|
||||
preserve_credential_state: false,
|
||||
preserve_access_token_expiry: false,
|
||||
provider_material: document(),
|
||||
@@ -4013,6 +4042,7 @@ fn unsupported() -> ProviderAdminError {
|
||||
|
||||
pub(super) fn import_settings() -> gateway_admin::model::accounts::AccountImportSettings {
|
||||
gateway_admin::model::accounts::AccountImportSettings {
|
||||
platform_icon: None,
|
||||
name: None,
|
||||
notes: Some("团队备用".to_owned()),
|
||||
model_access: Default::default(),
|
||||
|
||||
@@ -151,6 +151,7 @@ impl ClientKeyStore for TestClientKeyStore {
|
||||
}
|
||||
self.plaintexts.lock().unwrap().push(key.plaintext);
|
||||
let record = ClientKeyRecord {
|
||||
validity: Default::default(),
|
||||
peer_sharing: key.peer_sharing,
|
||||
request_profile_overrides: Default::default(),
|
||||
id: key.id,
|
||||
@@ -318,6 +319,7 @@ async fn plugin_client_key_list_projects_only_public_identity_and_uses_stable_na
|
||||
list_response: Mutex::new(Some(ClientKeyPage {
|
||||
config_revision: Revision::new(7).expect("revision"),
|
||||
items: vec![ClientKeyRecord {
|
||||
validity: Default::default(),
|
||||
peer_sharing: Default::default(),
|
||||
request_profile_overrides: Default::default(),
|
||||
id: key_id.clone(),
|
||||
@@ -455,6 +457,7 @@ async fn duplicate_names_report_the_same_actionable_conflict_on_create_and_updat
|
||||
.update(
|
||||
&mutation_context(),
|
||||
UpdateClientKey {
|
||||
validity: Default::default(),
|
||||
peer_sharing: None,
|
||||
request_profile_override_updates: Default::default(),
|
||||
id: ClientApiKeyId::new("key_existing").unwrap(),
|
||||
@@ -476,6 +479,7 @@ async fn duplicate_names_report_the_same_actionable_conflict_on_create_and_updat
|
||||
|
||||
fn create_command(key: Option<&str>) -> CreateClientKey {
|
||||
CreateClientKey {
|
||||
validity: Default::default(),
|
||||
peer_sharing: Default::default(),
|
||||
request_profile_overrides: Default::default(),
|
||||
custom_key: key.map(|value| PlaintextClientApiKey::new(value).unwrap()),
|
||||
@@ -570,6 +574,7 @@ async fn duplicate_group_ids_are_rejected_before_key_creation_or_update() {
|
||||
.update(
|
||||
&mutation_context(),
|
||||
UpdateClientKey {
|
||||
validity: Default::default(),
|
||||
peer_sharing: None,
|
||||
request_profile_override_updates: Default::default(),
|
||||
id: ClientApiKeyId::new("key_existing").unwrap(),
|
||||
@@ -592,6 +597,7 @@ async fn duplicate_group_ids_are_rejected_before_key_creation_or_update() {
|
||||
async fn clearing_an_unregistered_provider_profile_is_rejected_before_writing() {
|
||||
let services = super::AdminHarness::new().build().await;
|
||||
let command = UpdateClientKey {
|
||||
validity: None,
|
||||
id: ClientApiKeyId::new("key_existing").unwrap(),
|
||||
name: "test".to_owned(),
|
||||
label: None,
|
||||
|
||||
@@ -1,5 +1,108 @@
|
||||
//! 按 Provider 组织凭据导入、授权与提交边界测试
|
||||
//! 验证账号归属分派,并组织凭据导入、授权与提交边界测试
|
||||
|
||||
mod openai;
|
||||
mod peer;
|
||||
mod xai;
|
||||
|
||||
use gateway_admin::model::{
|
||||
AdminErrorKind,
|
||||
provider_credentials::{CredentialMutation, RotateCredential},
|
||||
};
|
||||
use gateway_core::account::ProviderAccountId;
|
||||
|
||||
use super::{
|
||||
AdminHarness,
|
||||
accounts::{
|
||||
FakeAccountStore, FakeProviderAdmin, account_record, context, document, events, recorded,
|
||||
revision,
|
||||
},
|
||||
};
|
||||
|
||||
#[tokio::test]
|
||||
async fn account_rotation_should_dispatch_by_saved_provider_for_each_authentication_kind() {
|
||||
for kind in ["openai", "xai", "antigravity"] {
|
||||
for authentication in ["oauth", "api_key"] {
|
||||
let store_events = events();
|
||||
let mut account = account_record(kind);
|
||||
account.authentication_kind = authentication.to_owned();
|
||||
if authentication == "api_key" {
|
||||
account.upstream_user_id = None;
|
||||
account.has_refresh_token = false;
|
||||
account.access_token_expires_at = None;
|
||||
account.next_refresh_at = None;
|
||||
}
|
||||
let account_id = ProviderAccountId::new(account.id.clone()).unwrap();
|
||||
let store = FakeAccountStore::with_account(account, store_events.clone());
|
||||
let mut harness = AdminHarness::new().accounts(store.clone());
|
||||
let mut provider_events = Vec::new();
|
||||
for registered_kind in ["openai", "xai", "antigravity"] {
|
||||
let calls = events();
|
||||
harness = harness.provider(FakeProviderAdmin::new(registered_kind, calls.clone()));
|
||||
provider_events.push((registered_kind, calls));
|
||||
}
|
||||
let services = harness.build().await;
|
||||
let result = services
|
||||
.credentials()
|
||||
.for_account(&account_id)
|
||||
.await
|
||||
.expect("select saved provider")
|
||||
.rotate(RotateCredential {
|
||||
mutation: CredentialMutation {
|
||||
context: context("rotate-account-connection"),
|
||||
account_id: account_id.clone(),
|
||||
},
|
||||
settings: None,
|
||||
provider_material: document(),
|
||||
})
|
||||
.await
|
||||
.expect("rotate selected account");
|
||||
|
||||
assert_eq!(result.account_id, account_id);
|
||||
assert_eq!(result.credential_revision, Some(revision(2)));
|
||||
assert_eq!(store.audit_requests(), ["rotate-account-connection"]);
|
||||
assert_eq!(
|
||||
recorded(&store_events),
|
||||
[
|
||||
"store.load_account_record",
|
||||
"store.credential_details",
|
||||
"store.commit_rotation",
|
||||
]
|
||||
);
|
||||
for (registered_kind, calls) in provider_events {
|
||||
let expected: &[&str] = if registered_kind == kind {
|
||||
&[
|
||||
"provider.prepare_rotation",
|
||||
"guard.finish",
|
||||
"provider.account_facts_changed",
|
||||
]
|
||||
} else {
|
||||
&[]
|
||||
};
|
||||
assert_eq!(recorded(&calls), expected, "{kind}/{authentication}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn missing_account_should_stop_credential_dispatch_before_provider_or_store_mutation() {
|
||||
let store_events = events();
|
||||
let provider_events = events();
|
||||
let store = FakeAccountStore::new("openai", store_events.clone());
|
||||
let mut harness = AdminHarness::new().accounts(store.clone());
|
||||
for kind in ["openai", "xai", "antigravity"] {
|
||||
harness = harness.provider(FakeProviderAdmin::new(kind, provider_events.clone()));
|
||||
}
|
||||
let services = harness.build().await;
|
||||
let error = services
|
||||
.credentials()
|
||||
.for_account(&ProviderAccountId::new("acct_missing").unwrap())
|
||||
.await
|
||||
.err()
|
||||
.expect("missing account must fail before selecting a provider");
|
||||
|
||||
assert_eq!(error.kind(), AdminErrorKind::NotFound);
|
||||
assert_eq!(recorded(&store_events), ["store.load_account_record"]);
|
||||
assert!(recorded(&provider_events).is_empty());
|
||||
assert!(store.audit_requests().is_empty());
|
||||
}
|
||||
@@ -33,8 +33,12 @@ fn runtime_settings(enabled: bool, probe_enabled: bool) -> RuntimeSettings {
|
||||
rotation_strategy: gateway_admin::model::settings::RotationStrategy::Smart,
|
||||
updated_at: Utc::now(),
|
||||
values: gateway_admin::model::settings::RuntimeSettingsValues {
|
||||
openai_oauth_guardian_review_model: false,
|
||||
openai_request_country: Default::default(),
|
||||
antigravity_background_refresh: true,
|
||||
openai_websocket_pool: Default::default(),
|
||||
openai_request_settings: gateway_core::settings::OpenAiRequestSettings {
|
||||
oauth_guardian_review_model: false,
|
||||
..Default::default()
|
||||
},
|
||||
codex_privacy_policy: Default::default(),
|
||||
request_location_enabled: false,
|
||||
request_location: Default::default(),
|
||||
@@ -59,6 +63,7 @@ fn runtime_settings(enabled: bool, probe_enabled: bool) -> RuntimeSettings {
|
||||
usage_retention_days: 31,
|
||||
ops_event_retention_days: 30,
|
||||
audit_retention_days: 90,
|
||||
prompt_rewrite_rules: Vec::new(),
|
||||
account_error_protection: gateway_core::account::AccountErrorProtection {
|
||||
enabled,
|
||||
probe_enabled,
|
||||
|
||||
@@ -283,6 +283,7 @@ impl AdminHarness {
|
||||
self.accounts,
|
||||
self.account_runtime,
|
||||
self.account_groups,
|
||||
Arc::new(UnavailableStore),
|
||||
self.proxies,
|
||||
),
|
||||
self.auth,
|
||||
@@ -1381,3 +1382,20 @@ impl gateway_admin::ports::reset_credit_automation::ResetCreditAutomationStore
|
||||
Err(unavailable("reset-credit automation"))
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl gateway_admin::ports::account_schedules::AccountScheduleStore for UnavailableStore {
|
||||
async fn query(
|
||||
&self,
|
||||
_: &gateway_admin::model::account_schedules::ScheduleQuery,
|
||||
) -> AdminStoreResult<gateway_admin::model::account_schedules::ScheduleList> {
|
||||
unreachable!()
|
||||
}
|
||||
async fn save(
|
||||
&self,
|
||||
_: gateway_admin::model::account_schedules::ScheduleChange,
|
||||
_: &gateway_admin::model::MutationContext,
|
||||
) -> AdminStoreResult<gateway_admin::model::Revision> {
|
||||
unreachable!()
|
||||
}
|
||||
}
|
||||
@@ -516,6 +516,7 @@ async fn dashboard_should_preserve_provider_plan_names() {
|
||||
*store.account_usage.lock().unwrap() = plans
|
||||
.iter()
|
||||
.map(|(plan, _)| DashboardAccountUsage {
|
||||
platform_icon: None,
|
||||
upstream: None,
|
||||
account_id: format!("account-{plan}"),
|
||||
provider_kind: "openai".to_owned(),
|
||||
|
||||
@@ -43,6 +43,9 @@ fn usage_error_origin_recognizes_unambiguous_failure_kinds() {
|
||||
("no_available_provider", Proxy),
|
||||
("no_eligible_account", Proxy),
|
||||
("account_capacity_unavailable", Proxy),
|
||||
("account_pool_quota_exhausted", Proxy),
|
||||
("key_rate_limited", Proxy),
|
||||
("key_concurrency_limited", Proxy),
|
||||
("middleware_capacity_unavailable", Proxy),
|
||||
("concurrency_queue_full", Proxy),
|
||||
("concurrency_queue_timeout", Proxy),
|
||||
|
||||
@@ -337,8 +337,12 @@ impl SettingsStore for FixtureSettingsStore {
|
||||
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(),
|
||||
antigravity_background_refresh: true,
|
||||
openai_websocket_pool: Default::default(),
|
||||
openai_request_settings: gateway_core::settings::OpenAiRequestSettings {
|
||||
oauth_guardian_review_model: false,
|
||||
..Default::default()
|
||||
},
|
||||
codex_privacy_policy: Default::default(),
|
||||
request_location_enabled: false,
|
||||
request_location: Default::default(),
|
||||
@@ -363,6 +367,7 @@ impl SettingsStore for FixtureSettingsStore {
|
||||
usage_retention_days: 31,
|
||||
ops_event_retention_days: 30,
|
||||
audit_retention_days: 30,
|
||||
prompt_rewrite_rules: Vec::new(),
|
||||
account_error_protection: gateway_core::account::AccountErrorProtection::default(),
|
||||
account_warmup_enabled: false,
|
||||
account_warmup_cron: "0 8 * * *".to_owned(),
|
||||
@@ -447,8 +452,11 @@ fn total_record(
|
||||
now: DateTime<Utc>,
|
||||
) -> UsageListRecord {
|
||||
UsageListRecord {
|
||||
platform_icon: None,
|
||||
provider_account_upstream_peer: None,
|
||||
has_upstream_error: false,
|
||||
upstream_error_message: None,
|
||||
retry_after_ms: None,
|
||||
error_code: None,
|
||||
error_message: None,
|
||||
error_kind: None,
|
||||
@@ -538,11 +546,14 @@ fn diagnostic(name: &str, request_count: u64) -> DiagnosticObservation {
|
||||
caller_error_count: 0,
|
||||
retry_count: 0,
|
||||
retried_request_count: 0,
|
||||
account_provider_kind: None,
|
||||
providers: vec![],
|
||||
platform_icon: None,
|
||||
account_authentication_kind: None,
|
||||
account_plan_type: None,
|
||||
account_plan_type_display: None,
|
||||
key: name.to_owned(),
|
||||
name: name.to_owned(),
|
||||
account_email: None,
|
||||
request_count,
|
||||
success_count: request_count,
|
||||
failure_count: 0,
|
||||
|
||||
@@ -49,6 +49,7 @@ async fn manual_and_periodic_refreshes_share_capacity_and_release_it_after_failu
|
||||
let accounts = Arc::new(TestAccounts {
|
||||
accounts: Mutex::new(records.clone()),
|
||||
records: Mutex::default(),
|
||||
last_generation: Mutex::default(),
|
||||
failed_provider: None,
|
||||
});
|
||||
let transport = Arc::new(GatedTransport::new());
|
||||
@@ -113,6 +114,7 @@ async fn queued_refresh_reads_current_account_after_capacity_becomes_available()
|
||||
let accounts = Arc::new(TestAccounts {
|
||||
accounts: Mutex::new(records.clone()),
|
||||
records: Mutex::default(),
|
||||
last_generation: Mutex::default(),
|
||||
failed_provider: None,
|
||||
});
|
||||
let transport = Arc::new(GatedTransport::new());
|
||||
@@ -232,6 +234,7 @@ async fn discovery_uses_provider_capabilities_and_publishes_neutral_signals() {
|
||||
account("acct_native", "xai", "oauth"),
|
||||
]),
|
||||
records: Mutex::default(),
|
||||
last_generation: Mutex::default(),
|
||||
failed_provider,
|
||||
});
|
||||
let transport = Arc::new(TestTransport(Mutex::new(Vec::new())));
|
||||
@@ -329,6 +332,7 @@ async fn account_edits_preserve_observation_and_refresh_budget_until_connection_
|
||||
let accounts = Arc::new(TestAccounts {
|
||||
accounts: Mutex::new(vec![initial.clone()]),
|
||||
records: Mutex::default(),
|
||||
last_generation: Mutex::default(),
|
||||
failed_provider: None,
|
||||
});
|
||||
let transport = Arc::new(TestTransport(Mutex::new(Vec::new())));
|
||||
@@ -403,22 +407,29 @@ impl PeerTransport for TestTransport {
|
||||
.lock()
|
||||
.unwrap()
|
||||
.push(account.id().as_str().to_owned());
|
||||
let now = Utc::now();
|
||||
Ok(serde_json::to_vec(&serde_json::json!({
|
||||
"object":"cpr.peer", "schema_version":3,
|
||||
"observed_at":now.to_rfc3339(),
|
||||
"expires_at":(now + chrono::Duration::minutes(5)).to_rfc3339(),
|
||||
"capabilities":["key_usage"],
|
||||
"usage":{"status":"available","observed_at":now.to_rfc3339(),"data":{"unit":"USD","allowed":false,
|
||||
"windows":[{"key":"daily","total":"1","used":"1","remaining":"0","reset_at":(now + chrono::Duration::days(1)).to_rfc3339()}]}},
|
||||
"models":[]
|
||||
})).unwrap())
|
||||
Ok(peer_snapshot(false))
|
||||
}
|
||||
}
|
||||
|
||||
fn peer_snapshot(allowed: bool) -> Vec<u8> {
|
||||
let now = Utc::now();
|
||||
let (used, remaining) = if allowed { ("0", "1") } else { ("1", "0") };
|
||||
serde_json::to_vec(&serde_json::json!({
|
||||
"object":"cpr.peer", "schema_version":3,
|
||||
"observed_at":now.to_rfc3339(),
|
||||
"expires_at":(now + chrono::Duration::minutes(5)).to_rfc3339(),
|
||||
"capabilities":["key_usage", "key_limits"],
|
||||
"key_limits":{"max_concurrency":4},
|
||||
"usage":{"status":"available","observed_at":now.to_rfc3339(),"data":{"unit":"USD","allowed":allowed,
|
||||
"windows":[{"key":"daily","total":"1","used":used,"remaining":remaining,"reset_at":(now + chrono::Duration::days(1)).to_rfc3339()}]}},
|
||||
"models":[]
|
||||
})).unwrap()
|
||||
}
|
||||
|
||||
struct TestAccounts {
|
||||
accounts: Mutex<Vec<ProviderAccount>>,
|
||||
records: Mutex<BTreeMap<ProviderAccountId, QuotaObservation>>,
|
||||
last_generation: Mutex<BTreeMap<ProviderAccountId, SystemTime>>,
|
||||
failed_provider: Option<&'static str>,
|
||||
}
|
||||
|
||||
@@ -549,6 +560,22 @@ impl ProviderAccountStore for TestAccounts {
|
||||
.filter_map(|id| stored.get(id).cloned())
|
||||
.collect())
|
||||
}
|
||||
async fn accounts_used_since_quota(
|
||||
&self,
|
||||
snapshots: &[QuotaObservationVersion],
|
||||
) -> Result<Vec<ProviderAccountId>, StoreError> {
|
||||
let completed = self.last_generation.lock().unwrap();
|
||||
Ok(snapshots
|
||||
.iter()
|
||||
.filter(|s| {
|
||||
completed
|
||||
.get(&s.account_id)
|
||||
.is_some_and(|at| *at > s.observed_at)
|
||||
})
|
||||
.map(|s| s.account_id.clone())
|
||||
.collect())
|
||||
}
|
||||
|
||||
async fn compare_and_swap_quota(
|
||||
&self,
|
||||
observation: QuotaObservation,
|
||||
|
||||
@@ -48,11 +48,94 @@ async fn unsupported_detection_survives_restart_until_manual_rediscovery() {
|
||||
let discovered = restarted.service().refresh_quota(&id).await.unwrap();
|
||||
assert!(discovered.upstream.unwrap().discovered);
|
||||
assert_eq!(transport.requests.load(Ordering::SeqCst), 2);
|
||||
tokio::time::advance(Duration::from_secs(360)).await;
|
||||
cycle(&resumed_worker).await;
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn healthy_peer_refresh_requires_generation_after_an_aged_local_snapshot() {
|
||||
let (mut bundle, accounts, transport, id) = fixture(UpstreamInfoFailure::Unavailable);
|
||||
*transport.failure.lock().unwrap() = None;
|
||||
cycle(&worker(&mut bundle)).await;
|
||||
let initial = accounts.records.lock().unwrap()[&id].observed_at;
|
||||
|
||||
let mut restarted = initialize(accounts.clone(), transport.clone());
|
||||
let worker = worker(&mut restarted);
|
||||
accounts
|
||||
.last_generation
|
||||
.lock()
|
||||
.unwrap()
|
||||
.insert(id.clone(), initial + Duration::from_secs(1));
|
||||
cycle(&worker).await;
|
||||
assert_eq!(transport.requests.load(Ordering::SeqCst), 1);
|
||||
assert!(
|
||||
restarted
|
||||
.scheduling_source()
|
||||
.is_peer(&accounts.accounts.lock().unwrap()[0])
|
||||
);
|
||||
|
||||
let old = initial - Duration::from_secs(600);
|
||||
accounts
|
||||
.records
|
||||
.lock()
|
||||
.unwrap()
|
||||
.get_mut(&id)
|
||||
.unwrap()
|
||||
.observed_at = old;
|
||||
accounts
|
||||
.last_generation
|
||||
.lock()
|
||||
.unwrap()
|
||||
.insert(id.clone(), old);
|
||||
cycle(&worker).await;
|
||||
assert_eq!(transport.requests.load(Ordering::SeqCst), 1);
|
||||
|
||||
accounts
|
||||
.last_generation
|
||||
.lock()
|
||||
.unwrap()
|
||||
.insert(id.clone(), old + Duration::from_secs(1));
|
||||
cycle(&worker).await;
|
||||
tokio::time::advance(Duration::from_secs(600)).await;
|
||||
cycle(&worker).await;
|
||||
assert_eq!(transport.requests.load(Ordering::SeqCst), 2);
|
||||
restarted.service().refresh_quota(&id).await.unwrap();
|
||||
assert_eq!(transport.requests.load(Ordering::SeqCst), 3);
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn exhausted_peer_rechecks_at_reset_or_after_five_minutes_without_usage() {
|
||||
let (mut bundle, accounts, transport, id) = fixture(UpstreamInfoFailure::Unavailable);
|
||||
*transport.failure.lock().unwrap() = None;
|
||||
let worker = worker(&mut bundle);
|
||||
cycle(&worker).await;
|
||||
let now = SystemTime::now();
|
||||
let old = now - Duration::from_secs(600);
|
||||
let account = accounts.accounts.lock().unwrap()[0].clone();
|
||||
for (exhausted_at, reset_at, expected) in [
|
||||
(old, Some(now + Duration::from_secs(600)), 1),
|
||||
(old, Some(now), 2),
|
||||
(now, None, 2),
|
||||
(old, None, 3),
|
||||
] {
|
||||
accounts
|
||||
.records
|
||||
.lock()
|
||||
.unwrap()
|
||||
.get_mut(&id)
|
||||
.unwrap()
|
||||
.observed_at = old;
|
||||
accounts.accounts.lock().unwrap()[0] = account.clone().with_account_facts(
|
||||
true,
|
||||
CredentialState::Ready,
|
||||
QuotaState::exhausted(QuotaEvidence::ProviderDenied, exhausted_at, reset_at),
|
||||
None,
|
||||
None,
|
||||
);
|
||||
tokio::time::advance(Duration::from_secs(30)).await;
|
||||
cycle(&worker).await;
|
||||
assert_eq!(transport.requests.load(Ordering::SeqCst), expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn unsupported_detection_keeps_manual_refresh_throttling() {
|
||||
for retry_after in [None, Some(Duration::from_secs(90))] {
|
||||
@@ -382,12 +465,12 @@ fn fixture(
|
||||
let accounts = Arc::new(TestAccounts {
|
||||
accounts: Mutex::new(vec![record]),
|
||||
records: Mutex::default(),
|
||||
last_generation: Mutex::default(),
|
||||
failed_provider: None,
|
||||
});
|
||||
let transport = Arc::new(DetectionTransport {
|
||||
requests: AtomicUsize::new(0),
|
||||
failure: Mutex::new(Some(failure.into())),
|
||||
success: TestTransport(Mutex::default()),
|
||||
});
|
||||
(
|
||||
initialize(accounts.clone(), transport.clone()),
|
||||
@@ -432,15 +515,14 @@ async fn cycle(worker: &WorkerRegistration) {
|
||||
struct DetectionTransport {
|
||||
requests: AtomicUsize,
|
||||
failure: Mutex<Option<PeerFetchFailure>>,
|
||||
success: TestTransport,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl PeerTransport for DetectionTransport {
|
||||
async fn fetch(
|
||||
&self,
|
||||
account: &ProviderAccount,
|
||||
connection: &PeerConnection,
|
||||
_account: &ProviderAccount,
|
||||
_connection: &PeerConnection,
|
||||
) -> Result<Vec<u8>, PeerFetchFailure> {
|
||||
self.requests.fetch_add(1, Ordering::SeqCst);
|
||||
if let Some(failure) = self.failure.lock().unwrap().as_ref() {
|
||||
@@ -449,6 +531,6 @@ impl PeerTransport for DetectionTransport {
|
||||
retry_after: failure.retry_after,
|
||||
});
|
||||
}
|
||||
self.success.fetch(account, connection).await
|
||||
Ok(peer_snapshot(true))
|
||||
}
|
||||
}
|
||||
@@ -100,6 +100,20 @@ impl SnapshotControl for Fixture {
|
||||
|
||||
#[async_trait]
|
||||
impl ProxyStore for Fixture {
|
||||
async fn test_targets(
|
||||
&self,
|
||||
) -> gateway_admin::ports::store::AdminStoreResult<
|
||||
gateway_admin::model::proxies::ProxyTestTargets,
|
||||
> {
|
||||
unreachable!()
|
||||
}
|
||||
async fn replace_test_targets(
|
||||
&self,
|
||||
_: &gateway_admin::model::proxies::ProxyTestTargets,
|
||||
_: &gateway_admin::model::MutationContext,
|
||||
) -> gateway_admin::ports::store::AdminStoreResult<gateway_admin::model::Revision> {
|
||||
unreachable!()
|
||||
}
|
||||
async fn reserve_import(&self, _: &str) -> AdminStoreResult<ProxyImportReservation> {
|
||||
unreachable!()
|
||||
}
|
||||
|
||||
@@ -39,6 +39,20 @@ pub(super) struct TestPluginPorts;
|
||||
|
||||
#[async_trait]
|
||||
impl gateway_admin::ports::proxy::ProxyStore for TestPluginPorts {
|
||||
async fn test_targets(
|
||||
&self,
|
||||
) -> gateway_admin::ports::store::AdminStoreResult<
|
||||
gateway_admin::model::proxies::ProxyTestTargets,
|
||||
> {
|
||||
unreachable!()
|
||||
}
|
||||
async fn replace_test_targets(
|
||||
&self,
|
||||
_: &gateway_admin::model::proxies::ProxyTestTargets,
|
||||
_: &gateway_admin::model::MutationContext,
|
||||
) -> gateway_admin::ports::store::AdminStoreResult<gateway_admin::model::Revision> {
|
||||
unreachable!()
|
||||
}
|
||||
async fn reserve_import(
|
||||
&self,
|
||||
_: &str,
|
||||
|
||||
@@ -39,6 +39,20 @@ impl ProxyStore for TestProxies {
|
||||
Err(super::unavailable("proxy"))
|
||||
}
|
||||
|
||||
async fn test_targets(
|
||||
&self,
|
||||
) -> gateway_admin::ports::store::AdminStoreResult<
|
||||
gateway_admin::model::proxies::ProxyTestTargets,
|
||||
> {
|
||||
unreachable!()
|
||||
}
|
||||
async fn replace_test_targets(
|
||||
&self,
|
||||
_: &gateway_admin::model::proxies::ProxyTestTargets,
|
||||
_: &gateway_admin::model::MutationContext,
|
||||
) -> gateway_admin::ports::store::AdminStoreResult<gateway_admin::model::Revision> {
|
||||
unreachable!()
|
||||
}
|
||||
async fn reserve_import(
|
||||
&self,
|
||||
id: &str,
|
||||
@@ -194,6 +208,14 @@ async fn plugin_proxy_resolution_requires_enabled_configuration_without_account_
|
||||
|
||||
#[async_trait]
|
||||
impl ProxyProbe for TestProxies {
|
||||
async fn test_target(
|
||||
&self,
|
||||
_: &gateway_core::account::OutboundProxy,
|
||||
_: &str,
|
||||
) -> gateway_admin::model::proxies::TargetProbeResult {
|
||||
unreachable!()
|
||||
}
|
||||
|
||||
async fn test(&self, _: ProbeRoute<'_>, _: bool) -> ProxyTestResult {
|
||||
panic!("unexpected proxy probe")
|
||||
}
|
||||
@@ -318,6 +340,7 @@ async fn linked_accounts_share_plan_resolution_and_only_read_cached_quota() {
|
||||
] {
|
||||
let provider = FakeProviderAdmin::new(kind, events());
|
||||
provider.set_quota(ProviderQuota {
|
||||
daily_used_percent: None,
|
||||
paused_windows: Vec::new(),
|
||||
upstream: None,
|
||||
credits: None,
|
||||
@@ -333,6 +356,7 @@ async fn linked_accounts_share_plan_resolution_and_only_read_cached_quota() {
|
||||
.provider(provider.clone())
|
||||
.proxies(Arc::new(TestProxies {
|
||||
accounts: Some(vec![ProxyAccountRef {
|
||||
platform_icon: None,
|
||||
upstream: None,
|
||||
id: "acct_plan".to_owned(),
|
||||
name: "套餐测试".to_owned(),
|
||||
@@ -487,6 +511,14 @@ impl Drop for ActiveProbe<'_> {
|
||||
|
||||
#[async_trait]
|
||||
impl ProxyProbe for GatedProxyProbe {
|
||||
async fn test_target(
|
||||
&self,
|
||||
_: &gateway_core::account::OutboundProxy,
|
||||
_: &str,
|
||||
) -> gateway_admin::model::proxies::TargetProbeResult {
|
||||
unreachable!()
|
||||
}
|
||||
|
||||
async fn test(&self, _: ProbeRoute<'_>, _: bool) -> ProxyTestResult {
|
||||
self.active
|
||||
.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
|
||||
@@ -56,7 +56,10 @@ impl VisitMut for WireTypes {
|
||||
}
|
||||
let last = path.path.segments.last().unwrap().clone();
|
||||
*ty = match last.ident.to_string().as_str() {
|
||||
"DateTime" | "Tz" | "TokenPrice" | "AdminApiKey" => parse_quote!(String),
|
||||
"DateTime" | "Tz" | "TokenPrice" | "AdminApiKey" | "ProviderKind"
|
||||
| "PromptPattern" => {
|
||||
parse_quote!(String)
|
||||
}
|
||||
"Value" => parse_quote!(serde_json::Value),
|
||||
"OpaqueProviderData" => parse_quote!(serde_json::Map<String, serde_json::Value>),
|
||||
_ => Type::Path(syn::TypePath {
|
||||
@@ -80,6 +83,9 @@ fn contract_type(mut item: Item, name: &str) -> Item {
|
||||
| "ReplaceRuntimeSettings"
|
||||
| "AdminApiKeyMutation"
|
||||
| "RegeneratedAdminApiKey"
|
||||
| "PromptRewriteRule"
|
||||
| "PromptRewritePreviewRequest"
|
||||
| "PromptRewritePreviewResult"
|
||||
| "CodexPrivacyPolicy"
|
||||
| "PrivacyRule"
|
||||
| "PrivacyStep"
|
||||
@@ -113,6 +119,15 @@ fn contract_type(mut item: Item, name: &str) -> Item {
|
||||
if let Some(fields) = fields {
|
||||
for field in fields {
|
||||
field.vis = parse_quote!(pub);
|
||||
// 非空名称与前缀由宿主在接收设置时校验,SDK 只描述字符串合同
|
||||
if name == "PromptRewriteRule"
|
||||
&& field
|
||||
.ident
|
||||
.as_ref()
|
||||
.is_some_and(|id| id == "pattern" || id == "name")
|
||||
{
|
||||
field.attrs.retain(|attr| !attr.path().is_ident("serde"));
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Item::Enum(item) = &mut item {
|
||||
@@ -225,6 +240,23 @@ fn sdk_settings_contract_matches_host_declarations() {
|
||||
"AccountErrorOperator",
|
||||
][..],
|
||||
),
|
||||
(
|
||||
"../gateway-core/src/settings/prompt_rewrite.rs",
|
||||
&[
|
||||
"PromptRewriteRule",
|
||||
"PromptMatchMode",
|
||||
"PromptRewritePreviewRequest",
|
||||
"PromptRewritePreviewResult",
|
||||
][..],
|
||||
),
|
||||
(
|
||||
"../gateway-core/src/settings/websocket.rs",
|
||||
&["OpenAiWebSocketPoolSettings"][..],
|
||||
),
|
||||
(
|
||||
"../gateway-core/src/settings/openai.rs",
|
||||
&["OpenAiRequestSettings", "OpenAiRequestCountry"][..],
|
||||
),
|
||||
(
|
||||
"../gateway-core/src/settings/privacy.rs",
|
||||
&[
|
||||
@@ -254,7 +286,7 @@ fn sdk_settings_contract_matches_host_declarations() {
|
||||
),
|
||||
(
|
||||
"../gateway-core/src/account/location.rs",
|
||||
&["RequestLocation", "OpenAiRequestCountry"][..],
|
||||
&["RequestLocation"][..],
|
||||
),
|
||||
(
|
||||
"../gateway-core/src/account/scheduling.rs",
|
||||
|
||||
@@ -349,8 +349,9 @@ async fn settings_should_reject_zero_refresh_margin_before_store_call() {
|
||||
model_mappings: Default::default(),
|
||||
rotation_strategy: RotationStrategy::Smart,
|
||||
values: gateway_admin::model::settings::RuntimeSettingsValues {
|
||||
openai_oauth_guardian_review_model: true,
|
||||
openai_request_country: Default::default(),
|
||||
antigravity_background_refresh: true,
|
||||
openai_websocket_pool: Default::default(),
|
||||
openai_request_settings: Default::default(),
|
||||
codex_privacy_policy: Default::default(),
|
||||
request_location_enabled: false,
|
||||
request_location: Default::default(),
|
||||
@@ -376,6 +377,7 @@ async fn settings_should_reject_zero_refresh_margin_before_store_call() {
|
||||
usage_retention_days: 31,
|
||||
ops_event_retention_days: 30,
|
||||
audit_retention_days: 30,
|
||||
prompt_rewrite_rules: Vec::new(),
|
||||
account_error_protection:
|
||||
gateway_core::account::AccountErrorProtection::default(),
|
||||
account_warmup_enabled: false,
|
||||
|
||||
@@ -27,12 +27,14 @@ impl SystemOperations for RecordingSystemOperations {
|
||||
}
|
||||
Ok(SystemVersion {
|
||||
version: "1.0.0".to_owned(),
|
||||
instance_id: "test-instance".to_owned(),
|
||||
restart_supported: false,
|
||||
git_sha: "unknown".to_owned(),
|
||||
build_time: "unknown".to_owned(),
|
||||
deployment_mode: "source".to_owned(),
|
||||
update_channel: "stable".to_owned(),
|
||||
|
||||
latest_version: "1.0.0".to_owned(),
|
||||
latest_version: None,
|
||||
has_update: false,
|
||||
update_cached: false,
|
||||
update_warning: None,
|
||||
@@ -50,7 +52,7 @@ impl SystemOperations for RecordingSystemOperations {
|
||||
available_channels: vec![gateway_admin::model::system::SystemUpdateChannel::Stable],
|
||||
},
|
||||
current_version: "1.0.0".to_owned(),
|
||||
latest_version: "1.0.0".to_owned(),
|
||||
latest_version: None,
|
||||
has_update: false,
|
||||
deployment_mode: "source".to_owned(),
|
||||
build_type: "source".to_owned(),
|
||||
|
||||
@@ -2,6 +2,25 @@
|
||||
|
||||
use super::*;
|
||||
|
||||
pub(super) async fn validate_platform_icons(
|
||||
state: &impl crate::SessionState,
|
||||
names: &[&str],
|
||||
) -> Result<(), AdminError> {
|
||||
if names.iter().any(|name| !name.is_empty()) {
|
||||
let catalog = state
|
||||
.platform_icon_names()
|
||||
.await
|
||||
.map_err(|_| AdminError::service_unavailable())?;
|
||||
if names
|
||||
.iter()
|
||||
.any(|&name| !name.is_empty() && !catalog.contains(name))
|
||||
{
|
||||
return Err(map_wire_error(WireValidationError::new("platformIcon")));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_account_notes(notes: Option<&str>) -> Result<(), WireValidationError> {
|
||||
if notes.is_some_and(|notes| {
|
||||
notes.chars().count() > 500
|
||||
@@ -22,6 +41,8 @@ fn parse_provider(value: &str) -> Result<ProviderKind, WireValidationError> {
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct AccountImportSettingsRequest {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub platform_icon: Option<String>,
|
||||
pub name: Option<String>,
|
||||
pub notes: Option<String>,
|
||||
pub enabled: bool,
|
||||
@@ -52,6 +73,7 @@ impl AccountImportSettingsRequest {
|
||||
.name
|
||||
.map(|name| name.trim().to_owned())
|
||||
.filter(|name| !name.is_empty()),
|
||||
platform_icon: self.platform_icon,
|
||||
notes: self.notes,
|
||||
enabled: self.enabled,
|
||||
concurrency_limit: parse_concurrency_limit(self.concurrency_limit)?,
|
||||
@@ -213,6 +235,7 @@ fn validate_authorization_flow(
|
||||
#[derive(Clone, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct UpdateAccountRequest {
|
||||
pub platform_icon: Option<String>,
|
||||
pub connection: Option<AccountConnectionUpdateRequest>,
|
||||
pub outbound_proxy_id: Option<String>,
|
||||
pub account_id: String,
|
||||
@@ -253,6 +276,7 @@ impl UpdateAccountRequest {
|
||||
outbound_proxy: super::wire::proxy_selection(self.outbound_proxy_id)?,
|
||||
account_id: self.account_id,
|
||||
name: self.name.map(|name| name.trim().to_owned()),
|
||||
platform_icon: self.platform_icon,
|
||||
notes: self.notes,
|
||||
enabled: self.enabled,
|
||||
concurrency_limit: parse_concurrency_limit(self.concurrency_limit)?,
|
||||
@@ -264,13 +288,13 @@ impl UpdateAccountRequest {
|
||||
}
|
||||
}
|
||||
|
||||
/// 编辑 OpenAI 账号的连接设置;OAuth 仅接受传输方式
|
||||
/// 连接字段由 Provider 按账号类型校验,未提供的选项不注入凭据文档
|
||||
#[derive(Clone, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct AccountConnectionUpdateRequest {
|
||||
pub protocol: Option<String>,
|
||||
pub base_url: Option<String>,
|
||||
pub transport: String,
|
||||
pub transport: Option<String>,
|
||||
pub api_key: Option<String>,
|
||||
}
|
||||
|
||||
@@ -286,7 +310,11 @@ impl AccountConnectionUpdateRequest {
|
||||
if let Some(base_url) = &self.base_url {
|
||||
require_text(base_url, 2048, "connection.baseUrl")?;
|
||||
}
|
||||
if !matches!(self.transport.as_str(), "http" | "prefer_websocket") {
|
||||
if self
|
||||
.transport
|
||||
.as_deref()
|
||||
.is_some_and(|transport| !matches!(transport, "http" | "prefer_websocket"))
|
||||
{
|
||||
return Err(WireValidationError::new("connection.transport"));
|
||||
}
|
||||
if self.api_key.as_ref().is_some_and(|key| {
|
||||
@@ -300,8 +328,10 @@ impl AccountConnectionUpdateRequest {
|
||||
}
|
||||
|
||||
fn into_document(self) -> ProviderDocument {
|
||||
let mut material =
|
||||
Map::from_iter([("transport".to_owned(), Value::String(self.transport))]);
|
||||
let mut material = Map::new();
|
||||
if let Some(transport) = self.transport {
|
||||
material.insert("transport".to_owned(), Value::String(transport));
|
||||
}
|
||||
if let Some(protocol) = self.protocol {
|
||||
material.insert("protocol".to_owned(), Value::String(protocol));
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@ where
|
||||
S: SessionState + Clone + Send + Sync + 'static,
|
||||
{
|
||||
Router::new()
|
||||
.merge(super::schedules::router::<S>())
|
||||
.merge(super::import_tasks::router::<S>())
|
||||
.route("/api/admin/accounts", get(list_accounts::<S>))
|
||||
.route(
|
||||
@@ -182,6 +183,15 @@ async fn import_accounts<S>(
|
||||
where
|
||||
S: SessionState + Send + Sync,
|
||||
{
|
||||
super::credentials::validate_platform_icons(
|
||||
&state,
|
||||
request
|
||||
.settings
|
||||
.as_ref()
|
||||
.and_then(|settings| settings.platform_icon.as_deref())
|
||||
.as_slice(),
|
||||
)
|
||||
.await?;
|
||||
let (provider, command) = request
|
||||
.into_command(auth.context().mutation_context())
|
||||
.map_err(map_wire_error)?;
|
||||
@@ -232,6 +242,15 @@ async fn complete_account_authorization<S>(
|
||||
where
|
||||
S: SessionState + Send + Sync,
|
||||
{
|
||||
super::credentials::validate_platform_icons(
|
||||
&state,
|
||||
request
|
||||
.settings
|
||||
.as_ref()
|
||||
.and_then(|settings| settings.platform_icon.as_deref())
|
||||
.as_slice(),
|
||||
)
|
||||
.await?;
|
||||
let (provider, command) = request
|
||||
.into_command(auth.context().mutation_context())
|
||||
.map_err(map_wire_error)?;
|
||||
@@ -255,16 +274,21 @@ async fn update_account<S>(
|
||||
where
|
||||
S: SessionState + Send + Sync,
|
||||
{
|
||||
super::credentials::validate_platform_icons(
|
||||
&state,
|
||||
request.platform_icon.as_deref().as_slice(),
|
||||
)
|
||||
.await?;
|
||||
let (command, connection) = request.into_command().map_err(map_wire_error)?;
|
||||
let context = auth.context().mutation_context();
|
||||
let result = if let Some(provider_material) = connection {
|
||||
let provider = ProviderKind::new("openai").map_err(|_| AdminError::internal())?;
|
||||
let account_id = ProviderAccountId::new(command.account_id.clone())
|
||||
.map_err(|_| AdminError::internal())?;
|
||||
let result = state
|
||||
.admin_services()
|
||||
.credentials()
|
||||
.for_provider(&provider)
|
||||
.for_account(&account_id)
|
||||
.await
|
||||
.map_err(map_service_error)?
|
||||
.rotate(RotateCredential {
|
||||
mutation: CredentialMutation {
|
||||
|
||||
@@ -149,6 +149,12 @@ where
|
||||
if request.items.is_empty() || request.items.len() > MAX_IMPORT_TASK_ITEMS {
|
||||
return Err(map_wire_error(WireValidationError::new("items")));
|
||||
}
|
||||
let icons: Vec<_> = request
|
||||
.items
|
||||
.iter()
|
||||
.filter_map(|item| item.settings.as_ref()?.platform_icon.as_deref())
|
||||
.collect();
|
||||
super::credentials::validate_platform_icons(&state, &icons).await?;
|
||||
let encoded = serde_json::to_vec(&request.items)
|
||||
.map_err(|_| map_wire_error(WireValidationError::new("items")))?;
|
||||
let fingerprint = Sha256::digest(&encoded).into();
|
||||
|
||||
@@ -68,6 +68,7 @@ mod credentials;
|
||||
mod handlers;
|
||||
mod import_tasks;
|
||||
mod presenter;
|
||||
mod schedules;
|
||||
mod upstream_info;
|
||||
mod wire;
|
||||
|
||||
|
||||
@@ -67,6 +67,9 @@ pub(super) fn account_view(
|
||||
time: crate::time::TimePresenter,
|
||||
) -> AccountView {
|
||||
let AccountDirectoryItem {
|
||||
schedule_duty,
|
||||
model_cooldowns,
|
||||
platform_icon,
|
||||
account,
|
||||
capacity,
|
||||
capabilities,
|
||||
@@ -110,7 +113,20 @@ pub(super) fn account_view(
|
||||
.map(|value| super::upstream_info::view(value, now, time));
|
||||
let (mut quota, refresh_token_expires_at) = account_quota_view(quota, cooldown, now, time);
|
||||
quota.protection_rules = protection_rules;
|
||||
quota.model_rate_limits = model_cooldowns
|
||||
.into_iter()
|
||||
.map(|cooldown| {
|
||||
let until: DateTime<Utc> = cooldown.until().into();
|
||||
AccountModelRateLimitView {
|
||||
model: cooldown.scope().value().to_owned(),
|
||||
until: time.rfc3339(&until),
|
||||
until_display: time.datetime(&until),
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
AccountView {
|
||||
schedule_duty,
|
||||
platform_icon,
|
||||
quota_settings: account.quota_settings,
|
||||
auto_use_quota_credits: account.auto_use_quota_credits,
|
||||
upstream,
|
||||
@@ -269,6 +285,7 @@ pub(super) fn account_quota_view(
|
||||
let recovery_probe_required = cooldown.is_some_and(|value| value.kind.requires_probe());
|
||||
(
|
||||
AccountQuotaView {
|
||||
model_rate_limits: Vec::new(),
|
||||
paused_windows: quota.paused_windows,
|
||||
refreshed_at: quota.observed_at.map(|value| time.rfc3339(&value)),
|
||||
refreshed_at_relative: quota
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
//! 管理端账号排班的读取与原子保存
|
||||
|
||||
use crate::SessionState;
|
||||
use crate::admin::{
|
||||
AdminAuth, AdminEnvelope, AdminError, AdminJson, AdminResponse, wire::map_admin_service_error,
|
||||
};
|
||||
use axum::{Router, extract::State, http::StatusCode, response::IntoResponse, routing::post};
|
||||
use gateway_admin::model::account_schedules::{ScheduleChange, ScheduleQuery};
|
||||
|
||||
pub fn router<S: SessionState + Clone + Send + Sync + 'static>() -> Router<S> {
|
||||
Router::new()
|
||||
.route("/api/admin/accounts/schedules/query", post(query::<S>))
|
||||
.route("/api/admin/accounts/schedules/update", post(save::<S>))
|
||||
}
|
||||
|
||||
async fn query<S: SessionState + Send + Sync>(
|
||||
_auth: AdminAuth,
|
||||
State(state): State<S>,
|
||||
AdminJson(query): AdminJson<ScheduleQuery>,
|
||||
) -> Result<impl IntoResponse, AdminError> {
|
||||
let page = state
|
||||
.admin_services()
|
||||
.account_schedules()
|
||||
.query(query)
|
||||
.await
|
||||
.map_err(map_admin_service_error)?;
|
||||
Ok(AdminResponse::new(StatusCode::OK, AdminEnvelope::ok(page)))
|
||||
}
|
||||
|
||||
async fn save<S: SessionState + Send + Sync>(
|
||||
auth: AdminAuth,
|
||||
State(state): State<S>,
|
||||
AdminJson(change): AdminJson<ScheduleChange>,
|
||||
) -> Result<impl IntoResponse, AdminError> {
|
||||
let revision = state
|
||||
.admin_services()
|
||||
.account_schedules()
|
||||
.save(change, &auth.context().mutation_context())
|
||||
.await
|
||||
.map_err(map_admin_service_error)?;
|
||||
Ok(AdminResponse::new(
|
||||
StatusCode::OK,
|
||||
AdminEnvelope::ok(revision),
|
||||
))
|
||||
}
|
||||
@@ -203,7 +203,7 @@ fn parse_provider(value: &str) -> Result<Option<ProviderKind>, WireValidationErr
|
||||
|
||||
fn parse_sort_field(value: &str) -> Option<AccountSortField> {
|
||||
match value.trim() {
|
||||
"email" => Some(AccountSortField::Email),
|
||||
"name" => Some(AccountSortField::Name),
|
||||
"status" => Some(AccountSortField::Status),
|
||||
"planType" => Some(AccountSortField::PlanType),
|
||||
"usage" => Some(AccountSortField::Usage),
|
||||
@@ -247,6 +247,9 @@ pub struct AccountSummaryView {
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AccountView {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub schedule_duty: Option<gateway_core::account::duty::ScheduleDuty>,
|
||||
pub platform_icon: Option<String>,
|
||||
pub quota_settings: gateway_core::account::AccountQuotaSettings,
|
||||
pub auto_use_quota_credits: bool,
|
||||
pub upstream: Option<super::AccountUpstreamInfoView>,
|
||||
@@ -381,6 +384,7 @@ pub use crate::admin::account_groups::AccountGroupRefView;
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AccountQuotaView {
|
||||
pub model_rate_limits: Vec<AccountModelRateLimitView>,
|
||||
pub paused_windows: Vec<String>,
|
||||
pub refreshed_at: Option<String>,
|
||||
pub refreshed_at_relative: Option<crate::time::RelativeTimeView>,
|
||||
@@ -396,6 +400,14 @@ pub struct AccountQuotaView {
|
||||
pub credits: Option<AccountQuotaCreditsView>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AccountModelRateLimitView {
|
||||
pub model: String,
|
||||
pub until: String,
|
||||
pub until_display: String,
|
||||
}
|
||||
|
||||
/// 上游点数安全视图,不透出额度响应中的其他 Provider 字段
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
|
||||
@@ -153,6 +153,8 @@ impl ClientKeySort {
|
||||
#[derive(Clone, PartialEq, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct CreateClientKeyRequest {
|
||||
#[serde(default)]
|
||||
validity: gateway_core::policy::ClientKeyValidity,
|
||||
#[serde(default)]
|
||||
peer_sharing: gateway_core::policy::ClientPeerSharing,
|
||||
#[serde(default)]
|
||||
@@ -188,6 +190,7 @@ impl CreateClientKeyRequest {
|
||||
let request_profile_overrides =
|
||||
normalize_request_profile_overrides(self.provider_request_profile_overrides)?;
|
||||
Ok(CreateClientKey {
|
||||
validity: self.validity,
|
||||
peer_sharing: self.peer_sharing,
|
||||
request_profile_overrides,
|
||||
custom_key: self
|
||||
@@ -216,6 +219,7 @@ impl CreateClientKeyRequest {
|
||||
#[derive(Debug, Clone, PartialEq, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct UpdateClientKeyRequest {
|
||||
validity: Option<gateway_core::policy::ClientKeyValidity>,
|
||||
peer_sharing: Option<gateway_core::policy::ClientPeerSharing>,
|
||||
#[serde(default)]
|
||||
provider_request_profile_overrides: ProviderRequestProfileOverrideUpdates,
|
||||
@@ -241,6 +245,7 @@ impl UpdateClientKeyRequest {
|
||||
let request_profile_override_updates =
|
||||
normalize_request_profile_override_updates(self.provider_request_profile_overrides)?;
|
||||
Ok(UpdateClientKey {
|
||||
validity: self.validity,
|
||||
peer_sharing: self.peer_sharing,
|
||||
request_profile_override_updates,
|
||||
id: client_key_id(self.id, "clientKeyMutationNotFound")?,
|
||||
@@ -370,6 +375,10 @@ impl
|
||||
#[derive(Debug, Clone, PartialEq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ClientKeyView {
|
||||
validity: gateway_core::policy::ClientKeyValidity,
|
||||
validity_status: gateway_core::policy::ClientKeyValidityStatus,
|
||||
starts_at_display: Option<String>,
|
||||
expires_at_display: Option<String>,
|
||||
peer_sharing: gateway_core::policy::ClientPeerSharing,
|
||||
provider_request_profile_overrides: ProviderRequestProfileOverrides,
|
||||
id: String,
|
||||
@@ -407,6 +416,10 @@ impl From<(ClientKeyRecord, crate::time::TimePresenter)> for ClientKeyView {
|
||||
.collect::<ProviderRequestProfileOverrides>();
|
||||
Self {
|
||||
provider_request_profile_overrides,
|
||||
validity: record.validity,
|
||||
validity_status: record.validity.status_at(time.now()),
|
||||
starts_at_display: record.validity.starts_at.map(|start| time.datetime(&start)),
|
||||
expires_at_display: record.validity.expires_at.map(|end| time.datetime(&end)),
|
||||
peer_sharing: record.peer_sharing,
|
||||
id: record.id.to_string(),
|
||||
name: record.name,
|
||||
@@ -471,7 +484,6 @@ impl TryFrom<(ClientKeyPage, crate::time::TimePresenter)> for ClientKeyListData
|
||||
let next_cursor = page
|
||||
.next_cursor
|
||||
.map(wire_cursor)
|
||||
.transpose()?
|
||||
.as_ref()
|
||||
.map(encode_client_key_cursor)
|
||||
.transpose()?;
|
||||
@@ -584,7 +596,8 @@ impl From<ClientKeyMutation> for MutatedClientKeyData {
|
||||
}
|
||||
|
||||
/// 解码后的 Client Key 游标字段
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct ClientKeyCursorData {
|
||||
pub sort: ClientKeySort,
|
||||
pub value: ClientKeyCursorValue,
|
||||
@@ -601,25 +614,12 @@ pub enum ClientKeyCursorValue {
|
||||
LastUsedAt(Option<DateTime<Utc>>),
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
struct CursorWire {
|
||||
sort: ClientKeySort,
|
||||
value: ClientKeyCursorValue,
|
||||
id: String,
|
||||
}
|
||||
|
||||
/// 把 owner 游标编码为不透明 wire 值
|
||||
pub fn encode_client_key_cursor(
|
||||
cursor: &ClientKeyCursorData,
|
||||
) -> Result<String, WireValidationError> {
|
||||
validate_client_key_cursor(cursor)?;
|
||||
let bytes = serde_json::to_vec(&CursorWire {
|
||||
sort: cursor.sort,
|
||||
value: cursor.value.clone(),
|
||||
id: cursor.id.clone(),
|
||||
})
|
||||
.map_err(|_| WireValidationError::new("cursor"))?;
|
||||
let bytes = serde_json::to_vec(cursor).map_err(|_| WireValidationError::new("cursor"))?;
|
||||
Ok(URL_SAFE_NO_PAD.encode(bytes))
|
||||
}
|
||||
|
||||
@@ -631,13 +631,8 @@ pub fn decode_client_key_cursor(encoded: &str) -> Result<ClientKeyCursorData, Wi
|
||||
let bytes = URL_SAFE_NO_PAD
|
||||
.decode(encoded)
|
||||
.map_err(|_| WireValidationError::new("cursor"))?;
|
||||
let cursor: CursorWire =
|
||||
let cursor: ClientKeyCursorData =
|
||||
serde_json::from_slice(&bytes).map_err(|_| WireValidationError::new("cursor"))?;
|
||||
let cursor = ClientKeyCursorData {
|
||||
sort: cursor.sort,
|
||||
value: cursor.value,
|
||||
id: cursor.id,
|
||||
};
|
||||
validate_client_key_cursor(&cursor)?;
|
||||
Ok(cursor)
|
||||
}
|
||||
@@ -711,20 +706,18 @@ fn domain_cursor(cursor: ClientKeyCursorData) -> Result<ClientKeyCursor, WireVal
|
||||
})
|
||||
}
|
||||
|
||||
fn wire_cursor(cursor: ClientKeyCursor) -> Result<ClientKeyCursorData, WireValidationError> {
|
||||
fn wire_cursor(cursor: ClientKeyCursor) -> ClientKeyCursorData {
|
||||
let value = match cursor.value {
|
||||
DomainCursorValue::Name(value) => ClientKeyCursorValue::Name(value),
|
||||
DomainCursorValue::Enabled(value) => ClientKeyCursorValue::Enabled(value),
|
||||
DomainCursorValue::CreatedAt(value) => ClientKeyCursorValue::CreatedAt(value),
|
||||
DomainCursorValue::LastUsedAt(value) => ClientKeyCursorValue::LastUsedAt(value),
|
||||
};
|
||||
let cursor = ClientKeyCursorData {
|
||||
ClientKeyCursorData {
|
||||
sort: wire_sort(cursor.sort),
|
||||
value,
|
||||
id: cursor.id.to_string(),
|
||||
};
|
||||
validate_client_key_cursor(&cursor)?;
|
||||
Ok(cursor)
|
||||
}
|
||||
}
|
||||
|
||||
fn client_key_id(
|
||||
|
||||
@@ -263,6 +263,8 @@ pub(crate) fn usage_list_record_view(
|
||||
upstream_status_code: record.upstream_status_code,
|
||||
error_code: record.error_code,
|
||||
error_message: record.error_message,
|
||||
upstream_error_message: record.upstream_error_message,
|
||||
retry_after_ms: record.retry_after_ms,
|
||||
error_kind: record.error_kind,
|
||||
websocket_close_code: record.websocket_close_code,
|
||||
continuation_unavailable_reason: record.continuation_unavailable_reason,
|
||||
@@ -276,6 +278,7 @@ pub(crate) fn usage_list_record_view(
|
||||
account_id: record.provider_account_ref,
|
||||
account_email: record.provider_account_email,
|
||||
account_name: record.provider_account_name,
|
||||
platform_icon: record.platform_icon,
|
||||
account_notes: record.provider_account_notes,
|
||||
account_plan_type: record.provider_account_plan_type,
|
||||
account_plan_type_display: record.provider_account_plan_type_display,
|
||||
@@ -940,6 +943,7 @@ pub(crate) fn dashboard_view(
|
||||
.email
|
||||
.clone()
|
||||
.unwrap_or_else(|| credential.name.clone()),
|
||||
platform_icon: credential.platform_icon,
|
||||
notes: credential.notes,
|
||||
plan_type: credential.plan_type.clone(),
|
||||
plan_type_display: credential
|
||||
@@ -1350,13 +1354,16 @@ pub(crate) fn diagnostics_view(
|
||||
.items
|
||||
.into_iter()
|
||||
.map(|item| DiagnosticItemView {
|
||||
key: item.key,
|
||||
providers: item.providers,
|
||||
platform_icon: item.platform_icon,
|
||||
account_email: item.account_email,
|
||||
authentication_kind: item.account_authentication_kind,
|
||||
name: if item.name == "__none__" {
|
||||
name: if item.key == "__none__" {
|
||||
"未知".to_owned()
|
||||
} else {
|
||||
item.name
|
||||
},
|
||||
key: item.key,
|
||||
request_count: item.request_count,
|
||||
account_plan_type: item.account_plan_type,
|
||||
account_plan_type_display: item.account_plan_type_display,
|
||||
|
||||
@@ -86,11 +86,14 @@ pub struct ImageBillingView {
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct UsageListRecordView {
|
||||
pub platform_icon: Option<String>,
|
||||
pub error_origin: &'static str,
|
||||
pub client_status_code: Option<u16>,
|
||||
pub upstream_status_code: Option<u16>,
|
||||
pub error_code: Option<String>,
|
||||
pub error_message: Option<String>,
|
||||
pub upstream_error_message: Option<String>,
|
||||
pub retry_after_ms: Option<u64>,
|
||||
pub error_kind: Option<String>,
|
||||
pub websocket_close_code: Option<u16>,
|
||||
pub continuation_unavailable_reason: Option<String>,
|
||||
@@ -432,6 +435,7 @@ pub enum DashboardAccountMetric {
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DashboardAccountUsageView {
|
||||
pub platform_icon: Option<String>,
|
||||
pub upstream: Option<crate::admin::accounts::AccountUpstreamInfoView>,
|
||||
pub id: String,
|
||||
pub provider: String,
|
||||
@@ -872,8 +876,11 @@ pub struct UsageCacheView {
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DiagnosticItemView {
|
||||
pub providers: Vec<String>,
|
||||
pub platform_icon: Option<String>,
|
||||
pub key: String,
|
||||
pub name: String,
|
||||
pub account_email: Option<String>,
|
||||
pub authentication_kind: Option<String>,
|
||||
pub account_plan_type: Option<String>,
|
||||
pub account_plan_type_display: Option<String>,
|
||||
|
||||
@@ -13,7 +13,7 @@ use gateway_admin::model::{
|
||||
AdminError as ServiceError, PageSize, Revision,
|
||||
proxies::{
|
||||
NewProxy, ProxyAccountListQuery, ProxyBatchResult, ProxyListQuery, ProxyMutation,
|
||||
ProxyRecord, ProxyTestResult, TestProxy, UpdateProxy,
|
||||
ProxyRecord, ProxyTestResult, ProxyTestTargets, TestProxy, UpdateProxy,
|
||||
},
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -152,6 +152,7 @@ impl From<ProxyTestResult> for ProxyTestView {
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct ProxyAccountView {
|
||||
platform_icon: Option<String>,
|
||||
upstream: Option<super::accounts::AccountUpstreamInfoView>,
|
||||
id: String,
|
||||
name: String,
|
||||
@@ -260,6 +261,11 @@ where
|
||||
.route("/api/admin/proxies/delete", post(delete::<S>))
|
||||
.route("/api/admin/proxies/test", post(test::<S>))
|
||||
.route("/api/admin/proxies/probe", post(probe::<S>))
|
||||
.route(
|
||||
"/api/admin/proxies/targets",
|
||||
get(test_targets::<S>).post(replace_test_targets::<S>),
|
||||
)
|
||||
.route("/api/admin/proxies/targets/test", post(test_target::<S>))
|
||||
}
|
||||
|
||||
fn revision(value: u64) -> Result<Revision, AdminError> {
|
||||
@@ -340,6 +346,7 @@ where
|
||||
.items
|
||||
.into_iter()
|
||||
.map(|account| ProxyAccountView {
|
||||
platform_icon: account.platform_icon,
|
||||
upstream: account.upstream.map(|info| {
|
||||
super::accounts::upstream_info_view(
|
||||
info,
|
||||
@@ -546,6 +553,75 @@ where
|
||||
))
|
||||
}
|
||||
|
||||
async fn test_targets<S>(
|
||||
_: AdminAuth,
|
||||
State(state): State<S>,
|
||||
) -> Result<impl IntoResponse, AdminError>
|
||||
where
|
||||
S: SessionState + Send + Sync,
|
||||
{
|
||||
let targets = state
|
||||
.admin_services()
|
||||
.proxies()
|
||||
.test_targets()
|
||||
.await
|
||||
.map_err(map_error)?;
|
||||
Ok(AdminResponse::new(
|
||||
StatusCode::OK,
|
||||
AdminEnvelope::ok(targets),
|
||||
))
|
||||
}
|
||||
|
||||
async fn replace_test_targets<S>(
|
||||
auth: AdminAuth,
|
||||
State(state): State<S>,
|
||||
AdminJson(settings): AdminJson<ProxyTestTargets>,
|
||||
) -> Result<impl IntoResponse, AdminError>
|
||||
where
|
||||
S: SessionState + Send + Sync,
|
||||
{
|
||||
let targets = state
|
||||
.admin_services()
|
||||
.proxies()
|
||||
.replace_test_targets(settings, &auth.context().mutation_context())
|
||||
.await
|
||||
.map_err(map_error)?;
|
||||
Ok(AdminResponse::new(
|
||||
StatusCode::OK,
|
||||
AdminEnvelope::ok(targets),
|
||||
))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
struct TargetTestRequest {
|
||||
proxy_id: String,
|
||||
target_name: String,
|
||||
revision: Revision,
|
||||
}
|
||||
|
||||
async fn test_target<S>(
|
||||
_: AdminAuth,
|
||||
State(state): State<S>,
|
||||
AdminJson(request): AdminJson<TargetTestRequest>,
|
||||
) -> Result<impl IntoResponse, AdminError>
|
||||
where
|
||||
S: SessionState + Send + Sync,
|
||||
{
|
||||
let (proxy_name, result) = state
|
||||
.admin_services()
|
||||
.proxies()
|
||||
.test_target(&request.proxy_id, &request.target_name, request.revision)
|
||||
.await
|
||||
.map_err(map_error)?;
|
||||
Ok(AdminResponse::new(
|
||||
StatusCode::OK,
|
||||
AdminEnvelope::ok(serde_json::json!({
|
||||
"proxyName": proxy_name, "result": result,
|
||||
})),
|
||||
))
|
||||
}
|
||||
|
||||
async fn probe<S>(
|
||||
_: AdminAuth,
|
||||
State(state): State<S>,
|
||||
|
||||
@@ -36,8 +36,9 @@ pub type ProviderRequestProfileUpdates =
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct RuntimeSettingsFields {
|
||||
pub openai_oauth_guardian_review_model: bool,
|
||||
pub openai_request_country: gateway_core::account::OpenAiRequestCountry,
|
||||
pub antigravity_background_refresh: bool,
|
||||
pub openai_websocket_pool: gateway_core::settings::OpenAiWebSocketPoolSettings,
|
||||
pub openai_request_settings: gateway_core::settings::OpenAiRequestSettings,
|
||||
pub codex_privacy_policy: gateway_core::settings::privacy::CodexPrivacyPolicy,
|
||||
pub request_location_enabled: bool,
|
||||
pub request_location: gateway_core::account::RequestLocation,
|
||||
@@ -62,6 +63,7 @@ pub struct RuntimeSettingsFields {
|
||||
pub usage_retention_days: u64,
|
||||
pub ops_event_retention_days: u64,
|
||||
pub audit_retention_days: u64,
|
||||
pub prompt_rewrite_rules: Vec<gateway_core::settings::prompt_rewrite::PromptRewriteRule>,
|
||||
pub account_error_protection: gateway_core::account::AccountErrorProtection,
|
||||
pub account_warmup_enabled: bool,
|
||||
pub account_warmup_cron: String,
|
||||
@@ -283,6 +285,10 @@ where
|
||||
post(preview_privacy::<S>),
|
||||
)
|
||||
.route("/api/admin/settings/update", post(update_settings::<S>))
|
||||
.route(
|
||||
"/api/admin/settings/prompt-rewrite/preview",
|
||||
post(preview_prompt_rewrite::<S>),
|
||||
)
|
||||
.route(
|
||||
"/api/admin/settings/client-downloads/codex-desktop/windows",
|
||||
get(codex_desktop_windows_downloads::<S>),
|
||||
@@ -581,7 +587,12 @@ fn map_wire_error(error: WireValidationError) -> AdminError {
|
||||
"settingsUsageRetentionOverflow" => "用量记录保留天数不合法".to_owned(),
|
||||
"settingsOpsRetentionOverflow" => "运维事件保留天数不合法".to_owned(),
|
||||
"settingsAuditRetentionOverflow" => "审计记录保留天数不合法".to_owned(),
|
||||
"openaiRequestCountry" => "自定义请求国家必须是两位大写 ASCII 字母".to_owned(),
|
||||
"openaiRequestSettings.residency" | "openaiRequestSettings.accountRoutingOverride" => {
|
||||
"数据驻留和账号路由必须是有效的单行请求头值".to_owned()
|
||||
}
|
||||
"openaiRequestSettings.requestCountry" => {
|
||||
"自定义请求国家必须是两位大写 ASCII 字母".to_owned()
|
||||
}
|
||||
"requestLocation" => "请求位置的国家代码、地区或城市不合法".to_owned(),
|
||||
"providerRequestProfiles" => "服务商客户端身份配置无效".to_owned(),
|
||||
"minCodexDesktopVersion" => "Codex Desktop 最低版本格式不合法".to_owned(),
|
||||
@@ -705,8 +716,9 @@ impl RuntimeSettingsFields {
|
||||
self,
|
||||
) -> Result<gateway_admin::model::settings::RuntimeSettingsValues, WireValidationError> {
|
||||
let values = gateway_admin::model::settings::RuntimeSettingsValues {
|
||||
openai_oauth_guardian_review_model: self.openai_oauth_guardian_review_model,
|
||||
openai_request_country: self.openai_request_country,
|
||||
antigravity_background_refresh: self.antigravity_background_refresh,
|
||||
openai_websocket_pool: self.openai_websocket_pool,
|
||||
openai_request_settings: self.openai_request_settings,
|
||||
codex_privacy_policy: self.codex_privacy_policy,
|
||||
request_location_enabled: self.request_location_enabled,
|
||||
request_location: self
|
||||
@@ -739,6 +751,7 @@ impl RuntimeSettingsFields {
|
||||
.map_err(|_| WireValidationError::new("settingsOpsRetentionOverflow"))?,
|
||||
audit_retention_days: u32::try_from(self.audit_retention_days)
|
||||
.map_err(|_| WireValidationError::new("settingsAuditRetentionOverflow"))?,
|
||||
prompt_rewrite_rules: self.prompt_rewrite_rules,
|
||||
account_error_protection: self.account_error_protection,
|
||||
account_warmup_enabled: self.account_warmup_enabled,
|
||||
account_warmup_cron: self.account_warmup_cron,
|
||||
@@ -756,8 +769,9 @@ impl RuntimeSettingsFields {
|
||||
impl From<gateway_admin::model::settings::RuntimeSettingsValues> for RuntimeSettingsFields {
|
||||
fn from(settings: gateway_admin::model::settings::RuntimeSettingsValues) -> Self {
|
||||
crate::admin::settings::RuntimeSettingsFields {
|
||||
openai_oauth_guardian_review_model: settings.openai_oauth_guardian_review_model,
|
||||
openai_request_country: settings.openai_request_country,
|
||||
antigravity_background_refresh: settings.antigravity_background_refresh,
|
||||
openai_websocket_pool: settings.openai_websocket_pool,
|
||||
openai_request_settings: settings.openai_request_settings,
|
||||
codex_privacy_policy: settings.codex_privacy_policy,
|
||||
request_location_enabled: settings.request_location_enabled,
|
||||
request_location: settings.request_location,
|
||||
@@ -782,6 +796,7 @@ impl From<gateway_admin::model::settings::RuntimeSettingsValues> for RuntimeSett
|
||||
usage_retention_days: u64::from(settings.usage_retention_days),
|
||||
ops_event_retention_days: u64::from(settings.ops_event_retention_days),
|
||||
audit_retention_days: u64::from(settings.audit_retention_days),
|
||||
prompt_rewrite_rules: settings.prompt_rewrite_rules,
|
||||
account_error_protection: settings.account_error_protection,
|
||||
account_warmup_enabled: settings.account_warmup_enabled,
|
||||
account_warmup_cron: settings.account_warmup_cron,
|
||||
@@ -796,6 +811,7 @@ impl From<gateway_admin::model::settings::RuntimeSettingsValues> for RuntimeSett
|
||||
|
||||
fn settings_validation_error(field: &'static str) -> WireValidationError {
|
||||
WireValidationError::new(match field {
|
||||
"prompt_rewrite_rules" => "promptRewriteRules",
|
||||
"account_error_protection" => "accountErrorProtection",
|
||||
"account_warmup_enabled" => "accountWarmupEnabled",
|
||||
"account_warmup_model" => "accountWarmupModel",
|
||||
@@ -811,7 +827,15 @@ fn settings_validation_error(field: &'static str) -> WireValidationError {
|
||||
"max_waiting_per_key" => "maxWaitingPerKey",
|
||||
"min_codex_cli_version" => "minCodexCliVersion",
|
||||
"min_codex_desktop_version" => "minCodexDesktopVersion",
|
||||
"openai_request_country" => "openaiRequestCountry",
|
||||
"openai_websocket_pool.max_age_ms" => "openaiWebsocketPool.maxAgeMs",
|
||||
"openai_websocket_pool.max_connecting" => "openaiWebsocketPool.maxConnecting",
|
||||
"openai_websocket_pool.fast_path_budget_ms" => "openaiWebsocketPool.fastPathBudgetMs",
|
||||
"openai_websocket_pool.idle_timeout_ms" => "openaiWebsocketPool.idleTimeoutMs",
|
||||
"openai_request_settings.request_country" => "openaiRequestSettings.requestCountry",
|
||||
"openai_request_settings.residency" => "openaiRequestSettings.residency",
|
||||
"openai_request_settings.account_routing_override" => {
|
||||
"openaiRequestSettings.accountRoutingOverride"
|
||||
}
|
||||
"account_affinity" => "accountAffinity",
|
||||
"openai_guardian_reserved_concurrency" => "openaiGuardianReservedConcurrency",
|
||||
"session_affinity_ttl_hours" => "sessionAffinityTtlHours",
|
||||
@@ -846,3 +870,25 @@ where
|
||||
AdminEnvelope::ok(result),
|
||||
))
|
||||
}
|
||||
|
||||
async fn preview_prompt_rewrite<S>(
|
||||
State(state): State<S>,
|
||||
_auth: AdminAuth,
|
||||
AdminJson(request): AdminJson<
|
||||
gateway_core::settings::prompt_rewrite::PromptRewritePreviewRequest,
|
||||
>,
|
||||
) -> Result<impl IntoResponse, AdminError>
|
||||
where
|
||||
S: SessionState + Send + Sync,
|
||||
{
|
||||
let result = state
|
||||
.admin_services()
|
||||
.settings()
|
||||
.preview_prompt_rewrite(request)
|
||||
.await
|
||||
.map_err(map_service_error)?;
|
||||
Ok(AdminResponse::new(
|
||||
StatusCode::OK,
|
||||
AdminEnvelope::ok(result),
|
||||
))
|
||||
}
|
||||
@@ -81,12 +81,14 @@ impl UpdateRequest {
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct SystemVersionView {
|
||||
version: String,
|
||||
instance_id: String,
|
||||
restart_supported: bool,
|
||||
git_sha: String,
|
||||
build_time: String,
|
||||
deployment_mode: String,
|
||||
deployment_mode_label: String,
|
||||
update_channel: String,
|
||||
latest_version: String,
|
||||
latest_version: Option<String>,
|
||||
has_update: bool,
|
||||
update_cached: bool,
|
||||
update_warning: Option<String>,
|
||||
@@ -97,6 +99,8 @@ impl From<SystemVersion> for SystemVersionView {
|
||||
Self {
|
||||
deployment_mode_label: deployment_mode_label(&version.deployment_mode).to_owned(),
|
||||
version: version.version,
|
||||
instance_id: version.instance_id,
|
||||
restart_supported: version.restart_supported,
|
||||
git_sha: version.git_sha,
|
||||
build_time: version.build_time,
|
||||
deployment_mode: version.deployment_mode,
|
||||
@@ -114,7 +118,7 @@ impl From<SystemVersion> for SystemVersionView {
|
||||
struct SystemUpdateDetailView {
|
||||
policy: SystemUpdatePolicy,
|
||||
current_version: String,
|
||||
latest_version: String,
|
||||
latest_version: Option<String>,
|
||||
has_update: bool,
|
||||
deployment_mode: String,
|
||||
deployment_mode_label: String,
|
||||
|
||||
@@ -72,10 +72,6 @@ pub(crate) fn client_error_code(code: &str) -> &str {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn is_retry_after_header(name: &str) -> bool {
|
||||
name.eq_ignore_ascii_case("retry-after") || name.eq_ignore_ascii_case("retry-after-ms")
|
||||
}
|
||||
|
||||
/// 为 HTTP 错误或流内失败保留原有字段,仅投影客户端需要的重试信号
|
||||
pub(crate) fn capacity_error_for_client(data: &Value) -> Option<Value> {
|
||||
const CODE_PATHS: [&str; 2] = ["/error/code", "/response/error/code"];
|
||||
@@ -91,12 +87,6 @@ pub(crate) fn capacity_error_for_client(data: &Value) -> Option<Value> {
|
||||
return None;
|
||||
}
|
||||
let mut projected = data.clone();
|
||||
// 容量等待与换号已由网关执行;旧账号的等待提示不能再次阻塞客户端的新一轮路由
|
||||
for path in ["/headers", "/error/headers", "/response/error/headers"] {
|
||||
if let Some(Value::Object(headers)) = projected.pointer_mut(path) {
|
||||
headers.retain(|name, _| !is_retry_after_header(name));
|
||||
}
|
||||
}
|
||||
for path in CODE_PATHS {
|
||||
if let Some(code) = projected.pointer_mut(path)
|
||||
&& capacity_code(code)
|
||||
@@ -129,22 +119,24 @@ pub fn gateway_error_response(error: &GatewayError) -> Response {
|
||||
}
|
||||
let mut response = (status, Json(body)).into_response();
|
||||
response.extensions_mut().insert(error.clone());
|
||||
if let Some(delay) = error.retry_after()
|
||||
&& let Ok(value) = HeaderValue::from_str(
|
||||
&delay
|
||||
.as_secs()
|
||||
.saturating_add(u64::from(delay.subsec_nanos() > 0))
|
||||
.max(1)
|
||||
.to_string(),
|
||||
)
|
||||
{
|
||||
if let Some(seconds) = retry_after_seconds(error) {
|
||||
response
|
||||
.headers_mut()
|
||||
.insert(axum::http::header::RETRY_AFTER, value);
|
||||
.insert(axum::http::header::RETRY_AFTER, HeaderValue::from(seconds));
|
||||
}
|
||||
response
|
||||
}
|
||||
|
||||
/// HTTP 和 WS 的等待秒数均向上取整,避免客户端在冷却到期前重新发起请求
|
||||
pub(crate) fn retry_after_seconds(error: &GatewayError) -> Option<u64> {
|
||||
error.retry_after().map(|delay| {
|
||||
delay
|
||||
.as_secs()
|
||||
.saturating_add(u64::from(delay.subsec_nanos() > 0))
|
||||
.max(1)
|
||||
})
|
||||
}
|
||||
|
||||
/// Gateway 错误稳定映射,供 HTTP、SSE 和 WebSocket 共用
|
||||
#[must_use]
|
||||
pub const fn gateway_error_contract(
|
||||
@@ -211,12 +203,15 @@ pub const fn gateway_error_contract(
|
||||
"rate_limit_error",
|
||||
"concurrency_queue_timeout",
|
||||
),
|
||||
GatewayErrorKind::RateLimited => (
|
||||
GatewayErrorKind::RateLimited
|
||||
| GatewayErrorKind::QuotaExhausted
|
||||
| GatewayErrorKind::KeyRateLimited
|
||||
| GatewayErrorKind::KeyConcurrencyLimited => (
|
||||
StatusCode::TOO_MANY_REQUESTS,
|
||||
"rate_limit_error",
|
||||
"rate_limit_exceeded",
|
||||
),
|
||||
GatewayErrorKind::BudgetExhausted => (
|
||||
GatewayErrorKind::AccountPoolQuotaExhausted | GatewayErrorKind::BudgetExhausted => (
|
||||
StatusCode::TOO_MANY_REQUESTS,
|
||||
"usage_limit_reached",
|
||||
"usage_limit_reached",
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Antigravity 桌面端与 CLI 的模型选择器识别及菜单投影
|
||||
//! Antigravity 桌面端与 CLI 的模型发现请求识别及目录投影
|
||||
|
||||
use axum::http::{HeaderMap, header::USER_AGENT};
|
||||
use gateway_core::routing::{AgentModelListing, ExecutableModelMetadata, PublicModelId};
|
||||
|
||||
Loaded 100 of 841 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user