mirror of
https://github.com/zyycn/codex-proxy-rs.git
synced 2026-12-06 16:00:54 +00:00
Compare commits
24
Commits
v3.62.0
...
v3.62.1-rc.4
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2336d73d6d | ||
|
|
ad7209f180 | ||
|
|
9d30e17d7d | ||
|
|
1ee50b4e61 | ||
|
|
2473d88efd | ||
|
|
6f6b8dd3a0 | ||
|
|
8fc756ffec | ||
|
|
efd5357fac | ||
|
|
2bb7679b1b | ||
|
|
f2c1de1568 | ||
|
|
a77d38dd77 | ||
|
|
9a14263f1a | ||
|
|
177679a13c | ||
|
|
195c51c06c | ||
|
|
745bd15d3d | ||
|
|
3170b92d47 | ||
|
|
8b40e707fd | ||
|
|
15aabfc861 | ||
|
|
0ebf6739e2 | ||
|
|
b987cca4aa | ||
|
|
72e82c565e | ||
|
|
47ccdeb737 | ||
|
|
b20b0e2013 | ||
|
|
16fc302d46 |
No files matched your search
@@ -11,11 +11,16 @@ description: Codex Proxy RS 的需求评估、排障、开发、代码审查与
|
||||
|
||||
- 先写读者需要知道的事实或动作。删掉一句不影响理解、判断或操作,就删;标题、正文和通知不重复同一信息
|
||||
- 保留会改变决定的条件、权限、后果和恢复步骤。错误通知只说已知问题,有明确办法才补一句;后端返回的提示在后端改,前端不重复解释。上游原文、用户内容和诊断事实保持原样
|
||||
- 包括 `SKILL.md` 及其引用文档在内,所有常规文档只写当前有效的行为、规则和操作。变更时就地改写所属条目,只有[发版日志](../../../release/notes.md)记录版本变迁
|
||||
|
||||
## 核实问题根因与宿主职责
|
||||
|
||||
评估功能建议、排障、开发和审查时,先按[问题与方案依据](../../../CONTRIBUTING.md#问题与方案依据)核实使用者要完成什么、当前行为造成了什么影响。反馈直接给出改法时,先弄清提出这个改法的原因
|
||||
|
||||
改动共享调用链前,对照现有调用方和同类入口,找出谁提供事实、谁作决定、谁执行。涉及平台策略时,由所属 Provider 解释设置并给出决定,共享层沿用已有入口分派。需要改变共享合同时,说明调用方需要传递什么事实或结果
|
||||
|
||||
替换合同时同步更新仓内调用方。只有能指出仍需独立支持的调用方或明确的版本承诺,才保留旧入口。已部署数据库按[迁移冻结规则](../../../backend/migrations/README.md#冻结规则)验证升级路径,旧配置值的去留按功能需求决定
|
||||
|
||||
先确定正常使用时应得到的结果。设计校验、回退或故障恢复时,同时看它防住的具体风险和它可能挡住的正常用法。按协议、隔离要求和实际部署条件选择对正常路径影响最小的做法。只在假设的部署场景下才需要的处理,留到有相应需求时再做
|
||||
|
||||
排查故障时,从症状沿实际调用链回溯,定位行为最早偏离预期的环节,用源码、诊断或对照复现说明触发条件如何导致结果。原因尚未确定时,区分已知事实与假设,指出哪项证据能区分可能原因。确认根因后,在负责该行为的模块修复,用原触发场景验证
|
||||
@@ -30,11 +35,10 @@ description: Codex Proxy RS 的需求评估、排障、开发、代码审查与
|
||||
| --- | --- |
|
||||
| 调整页面、弹窗、表单、按钮、文案、样式或交互;目标在 `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) |
|
||||
| 开发、排查或审查服务端接口、路由、调度、账号与用量规则、持久化、后台任务或协议行为;目标是 `backend/` 中的实现、配置、迁移,或 Rust 源码 | [Workspace 边界](../../../docs/architecture.md#3-workspace-边界)的模块与依赖规则、所属模块及[后端自审](../../../docs/architecture.md#后端自审);Rust 使用 `$rust-best-practices` 和下方后端注释要求,宿主 Rust 同时读取 [Rust 模块组织约定](../../../docs/architecture.md#32-rust-模块组织约定) |
|
||||
| 后端行为、配置或迁移(含后端模块、目录与调用链调整),或 Rust 源码 | [Workspace 边界](../../../docs/architecture.md#3-workspace-边界)及所属模块章节。后端按[后端自审](../../../docs/architecture.md#后端自审)检查,Rust 使用 `$rust-best-practices` 和[后端注释](#后端注释),宿主 Rust 遵循 [Rust 模块组织约定](../../../docs/architecture.md#32-rust-模块组织约定) |
|
||||
| 修改页面接口调用,或开发、排查、审查面向管理端或模型客户端的 HTTP/WS API 合同 | [API](../../../docs/api.md)对应章节;优先复用已有接口,核对调用方 → 服务端解析 → 实际查询或执行,不能只凭前端类型认定参数生效;按实际改动叠加前后端规范 |
|
||||
| 新增、修改或审查客户端可见错误、失败提示、后台任务状态文案 | 下方[错误文案](#错误文案),并按实际出口核对[错误与诊断三层边界](../../../docs/architecture.md#错误与诊断三层边界) |
|
||||
| 模块或调用链变更,包括目录整理 | [Workspace 边界](../../../docs/architecture.md#3-workspace-边界)及所属模块章节;并排核对任务范围内同类实现的职责归属、公开入口与依赖方向,再决定目录与共享合同的位置 |
|
||||
| 新增内置 Provider、接入客户端协议,或让已有入口支持另一种实现 | 对照[Provider 与协议边界](../../../docs/architecture.md#5-provider-与协议边界),并排追踪新旧实现从入口到执行的路径。沿用目录或类型前,确认名称仍能描述扩展后的职责。共享层按厂商分支时,核实哪个接口合同指定了上游。按能力选择时,核对谁声明能力、谁匹配候选,用同名模型支持不同协议等场景验证。涉及选号时,对照已有实现的满载与取消行为 |
|
||||
| 内置 Provider 或客户端协议变更,包括单个平台调整设置或后台任务 | 对照 [Provider 与协议边界](../../../docs/architecture.md#5-provider-与协议边界)。固定上游须有端点合同依据,按能力选路须验证协议与账号范围,选号变更还要核对满载与取消 |
|
||||
| 新增、调整、清理或审查测试 | 下方[测试维护](#测试维护),按当前行为、职责归属与已有覆盖判断保留、合并或删除 |
|
||||
| 修改部署行为、`deploy/` 配置或数据库迁移 | 按范围读取[部署](../../../deploy/README.md)、[迁移](../../../backend/migrations/README.md)对应章节 |
|
||||
| 修改或审查文档;实现或审查用法、公开合同、职责、约束或运维操作的变化 | [文档检查](references/documentation.md),按最终行为核对是否漏更;纯文档任务只补读核实所述事实需要的领域条款 |
|
||||
@@ -45,12 +49,12 @@ description: Codex Proxy RS 的需求评估、排障、开发、代码审查与
|
||||
|
||||
长任务按 [任务延续与收尾](../../../AGENTS.md#任务延续与收尾)恢复已匹配的领域、具体约束与验证进度。单独收到验收请求时,先确认待验收版本和范围,发现偏差按当前授权处理
|
||||
|
||||
1. 遵守已提供的 [AGENTS.md](../../../AGENTS.md),按其 CodeGraph 约定定位代码;确认工作区、任务范围与已有改动,找到事实归属、同类实现和调用链,补齐上表命中规范及[项目约定](../../../CONTRIBUTING.md#项目约定)对应条目后再修改
|
||||
2. 按最终差异与受影响行为重新匹配上表,逐项对照适用条款检查实际实现。处理本次引入的职责越界、重复规则、冗余状态与无依据分支;删除或替换功能时一并清理失效的配置、类型、调用、测试与文档,已部署数据和公开合同仍遵守所属迁移及兼容规则;仅审查时报告,不自行修复
|
||||
1. 确认工作区、任务范围与已有改动,按 [CodeGraph 约定](../../../AGENTS.md#codegraph)定位代码,执行适用的[项目约定](../../../CONTRIBUTING.md#项目约定)
|
||||
2. 沿最终差异回查受影响的调用链及适用规范。删除或替换功能时,一并清理失效的配置、类型、调用、测试与文档
|
||||
3. 模块移动或重命名时,同步核对源码、测试、公开导出及配置、脚本中的名称和路径引用;在本任务内更新受影响的文档、示例和引用
|
||||
4. 按变更范围执行[验证](../../../CONTRIBUTING.md#验证)及其停止条件,后端命令见[验证命令](../../../docs/architecture.md#验证命令);复用仍适用的验证证据与用户已确定的验收分工,区分通过、失败、跳过与未执行
|
||||
5. 交付前按[首要写作要求](#首要写作要求言简意赅)通读本次新增或修改的文字。验收结论同时依据规范核对结果与行为验证证据;有规范偏差或缺少必要证据时,指出具体位置或未验证场景。前端按[前端流程](references/frontend.md)核对运行证据,后端按上表检查生命周期
|
||||
6. 按授权完成提交与交付;提交前按[提交约定](../../../CONTRIBUTING.md#项目约定)准备提交信息与实际共同作者署名,提交后核对实际提交消息,PR 的 AI 披露不能替代提交署名
|
||||
5. 按[写作要求](#首要写作要求言简意赅)通读变更文字,交付时指出仍存在的规范偏差或未验证场景
|
||||
6. 获准提交时按[提交约定](../../../CONTRIBUTING.md#项目约定)组织差异。一个功能及其回归测试一起提交,可独立验证和回退的修复分开提交。核对实际提交消息与共同作者署名
|
||||
|
||||
## 测试维护
|
||||
|
||||
@@ -60,7 +64,7 @@ description: Codex Proxy RS 的需求评估、排障、开发、代码审查与
|
||||
- 同一层对同一行为的重复覆盖合并为清晰的场景矩阵,复用相邻测试夹具;跨层测试确有不同职责或失败路径时保留,不为统一而扩大测试辅助抽象
|
||||
- 断言可观察的行为与业务不变量,避免复述实现细节。验收上游兼容行为时,先从对应版本的上游实现确定预期,再核对网关对同一输入的处理。例如历史应增量续接时,要看出站请求是否只含预期的增量,因为回退全量也可能返回成功
|
||||
- 维护项目明确要求的架构边界检查;发现漏检时,对照规则核实扫描范围、排除项与被检查的依赖关系,优先补齐现有检查中能稳定判定的缺口
|
||||
- 当前协议兼容、数据读取兼容、安全边界、并发和资源生命周期仍需覆盖,不按 `old`、`legacy` 等名称机械删除,也不能用改名代替无效用例清理
|
||||
- 按仍受支持的协议与数据、安全边界、并发和资源生命周期判断测试去留
|
||||
- 不在仓库中新增或保留迁移 SQL 专项测试,包括迁移文本、schema 演变与指定版本升级用例;需要验证迁移执行、数据保留或回滚时,在临时目录编写一次性验证并使用隔离数据库,测试通过即可,临时脚本不纳入维护测试集
|
||||
- 持久化功能测试使用当前完整 schema,验证现行读写、事务与数据约束;插件运行时状态迁移等业务能力按当前功能测试,不归为迁移 SQL 专项测试
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
- 以当前目标分支及任务内工作区的实现、配置和有效运行证据核实行为;提交记录用于发现待核实的主题,不能直接当作现行事实或按提交顺序组织正文。按 [CodeGraph 约定](../../../../AGENTS.md#codegraph)同步索引后定位,证据不足时报告缺口,不把计划或推测写成已支持能力
|
||||
- 开发任务按最终行为检查哪些用法、合同、职责、约束或运维操作需要同步,即使尚无 Markdown 差异也要检查;独立文档更新按用户范围核对现行说明,不等到发版时再补普通开发所需的文档
|
||||
- 沿同一事实查找所属正文及相关概述、示例和引用,重点核对“支持/不支持”等能力声明、默认值、配置模板和命令。概述保留必要摘要并链接详细合同;不能只更新详细章节,留下 README 或示例中的矛盾说明,也不扩展为无关全仓改写
|
||||
- 涉及合同或职责时核对所属架构、API 或 SDK 条款,在所属章节就地修订。审计记录、旧数据兼容和回滚仍是现行能力时,保留读者需要的说明
|
||||
- 涉及合同或职责时,在所属架构、API 或 SDK 章节就地修订。核对文中每个版本号、旧字段名和迁移编号,只保留解释现行合同或执行当前操作所需的内容。版本差异与一次性升级说明按[内容归属](../../../../CONTRIBUTING.md#内容归属)处理
|
||||
|
||||
## 交付检查
|
||||
|
||||
|
||||
@@ -1,15 +1,8 @@
|
||||
# 插件职责边界
|
||||
|
||||
开发、排查或审查插件接入、SDK、Runtime、宿主扩展接口及独立网关插件时完整读取,不以文件位于插件目录或正在选择能力为条件
|
||||
确定方案前读取[职责与源码入口](../../../../docs/architecture.md#职责与源码入口)、[发布与执行边界](../../../../docs/architecture.md#发布与执行边界)及[信任与资源边界](../../../../docs/architecture.md#信任与资源边界),明确问题归属、必要宿主保护与插件责任
|
||||
开发或审查插件接入、SDK、Runtime 和独立插件时,先按[职责与源码入口](../../../../docs/architecture.md#职责与源码入口)、[发布与执行边界](../../../../docs/architecture.md#发布与执行边界)及[信任与资源边界](../../../../docs/architecture.md#信任与资源边界)定位行为归属
|
||||
|
||||
**宿主提供可组合能力,守住自身合同、资源与稳定性;插件业务正确性和兼容修复由插件负责**
|
||||
|
||||
- 宿主提供可独立组合的受控原生能力,负责授权、资源隔离、事务与审计,复用已有服务与状态归属
|
||||
- 插件自身的触发条件、跨资源关联、策略和流程编排由插件实现,不能把某个使用场景做成宿主专属流程、状态或补偿逻辑
|
||||
- 插件行为不可预测,只保留宿主安全解码、权限、资源限制及一致性所需的检查,不为插件业务正确性增加语义校验、未知字段拒绝或重复检查;失败按已有调用、会话、实例边界及能力策略拒绝、隔离和回收,不把单次业务错误扩大为全局停用
|
||||
- 不靠猜测插件意图、补造业务字段、修正业务结果、重放操作或增加插件专属兼容分支让错误插件继续工作;问题归插件时在插件侧修复,不把补偿搬进宿主 SDK 或 Runtime
|
||||
- 通用协议与会话辅助、公开合同规定的默认值和失败恢复仍按既有合同执行,不能因拒绝业务兜底而删掉必要的宿主保护;故障隔离按[信任与资源边界](../../../../docs/architecture.md#信任与资源边界)评估,不假定完整信任的插件具有安全沙箱
|
||||
- 开放已有能力时复用宿主服务与数据模型,不为插件的导入、修正、重算等编排新增表、字段、账本或任务系统;确有宿主能力缺口时,界定可独立使用的基础接口及输入输出、权限、事务、失败和重复调用语义,不夹带插件私有模型与工作流
|
||||
- 新增防御、兼容、重试、缓存或状态前,说明要保护的宿主不变量、触发依据和最小处理范围;仅为迁就某个插件或猜测未来行为时不加入宿主
|
||||
- 自审调用链、合同、测试与文档中的业务判断、自动串联和专属状态,仅换成通用名称不算解除耦合;验证失败与取消后的资源释放、状态一致性和其他调用受影响范围,不以插件恢复成功代替宿主边界验证
|
||||
- 选择实现位置时,沿触发条件、跨资源关联和状态写入追到最后作决定的一方。插件拥有自己的业务编排和兼容修复,优先组合宿主已有服务
|
||||
- 扩展宿主时,先指出缺少哪项可独立使用的能力,再界定输入输出、权限、事务、失败和重复调用语义。插件可通过宿主的私有状态服务持久化数据,无需为这一流程增设专用表或后台任务
|
||||
- 增加校验、回退或重试前,说明要保护的协议、授权或资源约束。按公开合同处理字段、默认值和恢复,避免宿主猜测插件意图、改写业务结果或重放操作
|
||||
- 验收失败与取消路径时,检查资源释放、事务状态和受影响的调用、会话或实例。完整信任的进程仍须遵守宿主资源合同
|
||||
@@ -27,9 +27,7 @@ description: 准备、创建、更新或审查 GitHub PR,含回复讨论与处
|
||||
| 创建或更新 PR | [创建流程](references/create.md)、[PR 流程](../../../CONTRIBUTING.md#pr-流程)与[规则文件保护](../../../CONTRIBUTING.md#规则文件保护) |
|
||||
| 审查 PR | [审查流程](references/review.md)、[审查标准](../../../CONTRIBUTING.md#审查标准) |
|
||||
| 回复讨论或审查意见 | 读取目标评论和相关上下文,按[GitHub 回复口吻](../../../CONTRIBUTING.md#github-回复口吻)答复实际处理结果 |
|
||||
| 实现自审、审查或修改代码与文档 | 执行 [cpr-dev-guide](../cpr-dev-guide/SKILL.md)的领域必读与对应检查,包括后端、插件、测试和 API 等命中项;只读审查同样执行,不能仅核对 PR 正文与 CI |
|
||||
| 含前端改动 | [前端流程](../cpr-dev-guide/references/frontend.md),核对适用规范与当前实现的运行证据 |
|
||||
| 含文档改动 | [文档检查](../cpr-dev-guide/references/documentation.md) |
|
||||
| 实现自审、只读审查或修改代码与文档 | 按 [cpr-dev-guide](../cpr-dev-guide/SKILL.md#先确定领域与必读规范)选择受影响的领域,检查实现和运行证据 |
|
||||
|
||||
## 创建与审查的公共核对
|
||||
|
||||
|
||||
@@ -25,14 +25,14 @@
|
||||
|
||||
- `exp.N` 产生 `experimental` 构建类型,所有平台的二进制与镜像使用同一版本和源码提交。
|
||||
应用内更新仅允许同一轮实验,规则见[版本命名与升级规则](../../../../deploy/README.md#版本命名与升级规则)。
|
||||
发版前核对上一实验版是否已包含该更新器;仍禁用在线更新的旧构建需要先手动升级。
|
||||
发版前核对起始构建能否检查同一实验线的更新。起始构建未启用在线更新时,在发版日志中说明手动升级方式。
|
||||
- GitHub Release 标为 Pre-release,且不设为 Latest;Docker 发布版本标签,不覆盖稳定版 `latest`。
|
||||
发布任务应将该基线的最高公开实验版写入`main:release/version.yaml` 的 `published[大版本].exp[基线]`,不推进普通通道。
|
||||
- 复用正式版平台清单、质量检查、完整安装包与多架构镜像,以及部署文件、校验和和现有产物证明。
|
||||
对照本次清单确认平台,不以“实验版”为由仅发布单架构镜像。
|
||||
- 部署说明交代与稳定实例并存的目录、配置、端口和数据库要求;需要 Compose 隔离配置时,
|
||||
核对发布附件确实包含它,不能只在文案中承诺。
|
||||
- 实验版正文使用下方完整文案,不再由工作流重复追加安装章节或自动生成混入正式版基线的提交列表。
|
||||
- 实验版正文使用下方模板,安装步骤只写一次,变更范围以同一实验线为准。
|
||||
- Release 的 `name` 使用上述展示标题。工作流若默认以 tag 为标题,发布成功后用 `gh release edit --title` 设置标题,
|
||||
再通过 `gh api` 回读核对;仅修改 `name`,保留 tag、产物、正文和预发行状态。
|
||||
|
||||
|
||||
@@ -20,7 +20,7 @@
|
||||
|
||||
调用入口前重新核对当前脚本的副作用、目标版本和待推送提交,保留无关工作区内容,不自动清理或暂存用户文件。
|
||||
先编辑 `release/notes.md`,保留为未提交改动(已暂存或未暂存均可);其他已跟踪文件的改动应先单独提交。
|
||||
脚本只改 `release/version.yaml` 的顶层 `version`,按[接口弃用规则](../../../../backend/crates/gateway-plugin/sdk/docs/manifest.md#接口弃用)校验并维护 `plugin-api-deprecations.json`,将这些差异与最终工作区中的发布说明一起提交为 `chore: bump version to <version>`。
|
||||
脚本更新 `release/version.yaml` 的顶层 `version`,按[接口弃用规则](../../../../backend/crates/gateway-plugin/sdk/docs/manifest.md#接口弃用)校验并维护 `plugin-api-deprecations.json`,与手写发布说明一起提交为 `chore: bump version to <version>`。
|
||||
不要提前单独提交说明或把版本文件改成目标版本;脚本要求说明相对 HEAD 有改动,并自行更新版本号。
|
||||
本任务需要的提交按[项目约定](../../../../CONTRIBUTING.md#项目约定)保留英文 Conventional Commits 与相应署名。
|
||||
|
||||
@@ -31,7 +31,7 @@ release/publish "$release_version"
|
||||
```
|
||||
|
||||
该命令会创建上述版本提交与 annotated tag,原子推送分支和 tag,再从长期分支手动触发 `release.yml`。
|
||||
只读预检使用 `release/publish --check "$release_version"`。发布工作流读取 tag 中的说明,修改 tag 之后的本地文件不会改变该次构建。
|
||||
只读预检使用 `release/publish --check "$release_version"`。发布工作流读取 tag 中的手写说明,为常规版本追加安装入口、文档和 GitHub 变更列表。
|
||||
|
||||
只调整已发布页面的标题或正文时,编辑对应 GitHub Release 的 `name` 或 `body` 并回读核对;
|
||||
保持已有 tag、源码提交、附件和预发行状态,不重新执行发布入口。
|
||||
@@ -60,7 +60,8 @@ release/publish "$release_version"
|
||||
### 验收
|
||||
|
||||
- 发布完成后核对 GitHub Release 的版本、正式版/预发行状态和中文变更正文;对照平台清单与工作流确认归档、校验和及镜像产物。
|
||||
工作流附加的安装说明和自动提交列表按其当前配置处理,不用它们替代手写的中文变更说明。
|
||||
手写正文应与 tag 内的说明一致,核对安装入口和 `Full Changelog` 指向目标版本,正式版的比较范围从上一正式版开始
|
||||
- 核对 `backend-validation` 的结果。复用时检查摘要中的源码提交和成功 CI 链接,确认发行提交仅修改版本与说明;未满足复用条件时检查本次完整后端任务,不能把 `quality / backend` 的跳过单独记为测试通过
|
||||
- 回读 `main:release/version.yaml` 的 `published`。正式版参与同一大版本四个普通通道的比较;RC 参与 RC、Beta、Alpha,Beta 参与 Beta、Alpha,Alpha 只参与自身。实验版只推进 `exp["X.Y.Z"]`。有通道推进时应有 `chore(release): update release channels to <version>` 提交;重复执行或较旧版本未推进任何通道时无提交
|
||||
- 正式版提升或恢复后,回读 GitHub Latest 的 tag 与镜像 `latest` 的摘要,核对两者均指向预期正式版
|
||||
- 保留 v3.42.0 在线升级使用的 `update-index` 页面和 v3.42.1 的 `version.yaml` 附件
|
||||
|
||||
@@ -9,12 +9,20 @@
|
||||
3. 使用用户确定的目标版本,建议版本时说明兼容性、能力或修复依据;同名 tag 先区分重试与新发行,不递增版本掩盖冲突
|
||||
4. 命名与晋级按[版本命名与升级规则](../../../../deploy/README.md#版本命名与升级规则),实验版另读[实验流程](experimental.md#分支与版本)
|
||||
|
||||
对比基线选自已公开且 tag 位于目标提交历史内的 GitHub Release
|
||||
|
||||
- 推荐正式版号和编写发布说明时,都核对上一正式版到目标提交的最终差异,覆盖期间全部预发行。对于向后兼容的变更,只要有用户可用的新功能,就从上一正式版递增 minor 并将 patch 归零,仅含修复则递增 patch
|
||||
- alpha、beta、rc 优先对比同一 `X.Y.Z` 的上一常规预发行,没有时对比上一正式版
|
||||
- exp 对比同一 `X.Y.Z` 的上一实验版,首次实验对比同号正式版
|
||||
- 没有前序发行的首次发布从仓库起点核对
|
||||
|
||||
## 发布说明
|
||||
|
||||
读取当前 [notes.md](../../../../release/notes.md)与[项目约定](../../../../CONTRIBUTING.md#项目约定)中的发布说明条目
|
||||
|
||||
- 只在发布说明任务中修改 `release/notes.md`,替换为本次版本内容,首行为目标 tag,正文使用中文
|
||||
- 常规版本按「新增功能」「优化改进」「问题修复」「升级须知」归类,省略空章节;单一改动可直接写一句。安装命令和文档入口由工作流附加
|
||||
- 常规版本的手写正文按「新增功能」「优化改进」「问题修复」「升级须知」归类,省略空章节;单一改动可直接写一句
|
||||
- 常规版本的安装入口、文档链接和 GitHub 变更列表由工作流在发版时追加
|
||||
- 每条用一句短语讲清一个用户可感知的结果,不加句号,例如「系统更新:确认当前平台有安装包后才提示升级」
|
||||
- 同一变化只写一次,保留会影响使用或升级的默认值和限制,不展开实现过程、逐条翻译提交或写未经验证的承诺
|
||||
- 剔除回退、重复及未进入发行范围的内容,升级事项须能追溯到实际迁移、配置或兼容变化
|
||||
@@ -31,7 +39,7 @@
|
||||
在上一发行基线到 HEAD 的提交中检查是否已有目标版本的备版提交(`chore: bump version to <version>`;查历史时也匹配 `chore(release): prepare v<version>` 和 `chore(release): v<version>`),即使同名 tag 已不存在也要查。命中时先核对该提交对应的发行状态,按[失败恢复](operations.md#恢复与验收)处理,不在旧提交上再叠一个同名提交
|
||||
|
||||
发布说明准备好、其他代码已提交后,执行 `release/publish --check <version>`,检查版本、说明、工作区、远端分支与 tag、工具链和插件兼容窗口。
|
||||
预检不修改文件、Git 引用或远端状态;远端存在本地未知提交时先同步再检查。它不替代 CI、发行物验证或实际发布授权
|
||||
预检不修改文件、Git 引用或远端状态;远端存在本地未知提交时,先同步再检查。它不替代 CI、发行物验证或实际发布授权
|
||||
|
||||
按[验证要求](../../../../CONTRIBUTING.md#验证)核对目标提交的证据,区分通过、失败、跳过与未执行
|
||||
数据库变更同时读取[迁移冻结规则](../../../../backend/migrations/README.md#冻结规则):
|
||||
|
||||
@@ -91,17 +91,36 @@ module ReleaseMetadata
|
||||
"#{APP_NAME}_#{version}_#{platform.fetch('os')}_#{platform.fetch('arch')}.#{platform.fetch('archive')}"
|
||||
end
|
||||
|
||||
# 正式版始终对比上一正式版,常规预发行优先对比同一目标版本的上一预发行
|
||||
def self.previous_tag(value)
|
||||
return if value.include?('-exp.')
|
||||
|
||||
endpoint = "repos/#{ENV.fetch('GITHUB_REPOSITORY')}/releases?per_page=100"
|
||||
output, status = Open3.capture2('gh', 'api', '--paginate', endpoint, '--jq',
|
||||
'.[] | select(.draft == false) | [.tag_name, .prerelease] | @tsv')
|
||||
raise 'Failed to read published releases' unless status.success?
|
||||
|
||||
reachable = git('tag', '--list', 'v*', '--merged', 'HEAD').lines.map(&:strip)
|
||||
candidates = output.each_line.each_with_object([]) do |line, tags|
|
||||
tag, prerelease = line.chomp.split("\t")
|
||||
next unless reachable.include?(tag) && tag.delete_prefix('v').match?(SEMVER) && !tag.include?('+')
|
||||
next unless prerelease?(tag) == (prerelease == 'true') && sort_key(tag) < sort_key(value)
|
||||
tags << tag
|
||||
end
|
||||
if prerelease?(value)
|
||||
prefix = "v#{value.split('-', 2).first}-"
|
||||
previous = candidates.select { |tag| tag.start_with?(prefix) && !tag.include?('-exp.') }.max_by { |tag| sort_key(tag) }
|
||||
return previous if previous
|
||||
end
|
||||
candidates.reject { |tag| prerelease?(tag) }.max_by { |tag| sort_key(tag) }
|
||||
end
|
||||
|
||||
def self.outputs(tag)
|
||||
value = release_version(YAML.load_file('release/version.yaml').fetch('version'))
|
||||
raise "Release tag #{tag} does not match v#{value}" unless tag == "v#{value}"
|
||||
validate_notes(value)
|
||||
entries = platforms
|
||||
docker, native = entries.partition { |entry| entry['docker'] == true }
|
||||
previous = git('tag', '--list', 'v*', '--merged', 'HEAD').lines.map(&:strip).filter_map do |candidate|
|
||||
next unless candidate.delete_prefix('v').match?(SEMVER)
|
||||
key = sort_key(candidate)
|
||||
[key, candidate] if key < sort_key(value)
|
||||
end.max_by(&:first)&.last
|
||||
{
|
||||
'tag' => tag,
|
||||
'version' => value,
|
||||
@@ -112,7 +131,7 @@ module ReleaseMetadata
|
||||
'non_docker_matrix' => JSON.generate('include' => native),
|
||||
'windows_matrix' => JSON.generate('include' => entries.select { |entry| entry['os'] == 'windows' }),
|
||||
'docker_platforms' => docker.map { |entry| entry['dockerPlatform'] }.join(','),
|
||||
'previous_tag' => previous,
|
||||
'previous_tag' => previous_tag(value),
|
||||
'prerelease' => prerelease?(value),
|
||||
'build_type' => value.split('+', 2).first.include?('-exp.') ? 'experimental' : 'release'
|
||||
}
|
||||
|
||||
@@ -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
|
||||
@@ -51,6 +51,8 @@ jobs:
|
||||
rust: ${{ steps.toolchains.outputs.rust }}
|
||||
rust_image: ${{ steps.toolchains.outputs.rust_image }}
|
||||
run_backend: ${{ steps.quality.outputs.run_backend }}
|
||||
backend_source_sha: ${{ steps.quality.outputs.backend_source_sha }}
|
||||
backend_evidence_url: ${{ steps.quality.outputs.backend_evidence_url }}
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
@@ -68,6 +70,7 @@ jobs:
|
||||
- name: Read release metadata and seal plugin manifest
|
||||
id: version
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
RELEASE_TAG: ${{ inputs.tag }}
|
||||
run: ruby .github/scripts/release-metadata.rb outputs "$RELEASE_TAG" >> "$GITHUB_OUTPUT"
|
||||
|
||||
@@ -97,6 +100,31 @@ jobs:
|
||||
run_backend: ${{ needs.release-info.outputs.run_backend == 'true' }}
|
||||
run_frontend: false
|
||||
|
||||
backend-validation:
|
||||
name: backend-validation (${{ needs.release-info.outputs.run_backend == 'true' && 'current release' || 'reused CI' }})
|
||||
needs: [release-info, quality]
|
||||
if: ${{ !cancelled() && needs.release-info.result == 'success' }}
|
||||
runs-on: ubuntu-26.04
|
||||
timeout-minutes: 5
|
||||
steps:
|
||||
- name: Report backend validation evidence
|
||||
env:
|
||||
QUALITY_RESULT: ${{ needs.quality.result }}
|
||||
RUN_BACKEND: ${{ needs.release-info.outputs.run_backend }}
|
||||
SOURCE_SHA: ${{ needs.release-info.outputs.backend_source_sha }}
|
||||
EVIDENCE_URL: ${{ needs.release-info.outputs.backend_evidence_url }}
|
||||
run: |
|
||||
if [ "$QUALITY_RESULT" != success ]; then
|
||||
echo "后端质量检查未通过:$QUALITY_RESULT" | tee -a "$GITHUB_STEP_SUMMARY"
|
||||
exit 1
|
||||
fi
|
||||
if [ "$RUN_BACKEND" = true ]; then
|
||||
echo "后端质量检查已执行并通过,提交:\`$SOURCE_SHA\`" | tee -a "$GITHUB_STEP_SUMMARY"
|
||||
else
|
||||
test -n "$EVIDENCE_URL"
|
||||
echo "后端质量检查复用 \`$SOURCE_SHA\` 的[成功 CI]($EVIDENCE_URL);发行提交仅版本与发布说明不同" | tee -a "$GITHUB_STEP_SUMMARY"
|
||||
fi
|
||||
|
||||
windows:
|
||||
needs: release-info
|
||||
name: windows-tests (${{ matrix.arch }})
|
||||
@@ -411,7 +439,7 @@ jobs:
|
||||
group: release-publication
|
||||
queue: max
|
||||
# 产物准备可与测试重叠,版本标签和 GitHub Release 必须等全部质量与镜像验证通过
|
||||
needs: [release-info, quality, windows, security, package-assets, build-docker-image]
|
||||
needs: [release-info, backend-validation, windows, security, package-assets, build-docker-image]
|
||||
runs-on: ubuntu-26.04
|
||||
timeout-minutes: 20
|
||||
permissions:
|
||||
@@ -522,6 +550,8 @@ jobs:
|
||||
- name: Prepare release notes
|
||||
shell: bash
|
||||
env:
|
||||
PREVIOUS_TAG: ${{ needs.release-info.outputs.previous_tag }}
|
||||
RELEASE_TAG: ${{ needs.release-info.outputs.tag }}
|
||||
BUILD_TYPE: ${{ needs.release-info.outputs.build_type }}
|
||||
INSTALLATION_NOTES: |
|
||||
## Linux 一键安装(Docker Compose)
|
||||
@@ -537,7 +567,12 @@ jobs:
|
||||
run: |
|
||||
ruby <<'RUBY'
|
||||
notes = File.readlines('release/notes.md').drop(1).join.strip
|
||||
notes += "\n\n#{ENV.fetch('INSTALLATION_NOTES').strip}" unless ENV.fetch('BUILD_TYPE') == 'experimental'
|
||||
unless ENV.fetch('BUILD_TYPE') == 'experimental'
|
||||
notes += "\n\n#{ENV.fetch('INSTALLATION_NOTES').strip}"
|
||||
if ENV.fetch('PREVIOUS_TAG').empty?
|
||||
notes += "\n\n**Full Changelog**: https://github.com/#{ENV.fetch('GITHUB_REPOSITORY')}/commits/#{ENV.fetch('RELEASE_TAG')}"
|
||||
end
|
||||
end
|
||||
output = File.join(ENV.fetch('RUNNER_TEMP'), 'release-notes.md')
|
||||
File.write(output, "#{notes}\n")
|
||||
RUBY
|
||||
@@ -552,7 +587,7 @@ jobs:
|
||||
uses: softprops/action-gh-release@8a0cd651e5b2365bd640854a3fa5dfc70e4875f3 # v3.0.4
|
||||
with:
|
||||
tag_name: ${{ needs.release-info.outputs.tag }}
|
||||
generate_release_notes: ${{ needs.release-info.outputs.build_type != 'experimental' }}
|
||||
generate_release_notes: ${{ needs.release-info.outputs.build_type != 'experimental' && needs.release-info.outputs.previous_tag != '' }}
|
||||
previous_tag: ${{ needs.release-info.outputs.previous_tag }}
|
||||
prerelease: ${{ needs.release-info.outputs.prerelease == 'true' }}
|
||||
# action 保留已公开 Release 的状态,新 Release 上传完成后仍保持草稿
|
||||
|
||||
+9
-9
@@ -122,12 +122,12 @@ 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 聚焦目标;无关格式化、重构和依赖升级单独处理
|
||||
|
||||
## 文档职责与更新条件
|
||||
|
||||
**文档只描述当前有效状态,不记录变更历史**,在所属章节就地修订,不追加“本次新增”“此前行为”或修复经过
|
||||
**除发版日志外,所有文档只描述当前有效状态。** 功能或合同变化时,直接修订所属章节的说明与示例
|
||||
|
||||
只有用法、合同、职责、约束或读者需要执行的操作发生变化时才更新,内部重构和界面微调不默认附带文档改动
|
||||
|
||||
@@ -150,8 +150,8 @@ PR 不接受以下协作规则文件的新增、修改、删除或重命名:
|
||||
| 本文 | 如何协作、审查和交付 | 流程、判断标准与验证要求,任务入口由 [开发技能](.agents/skills/cpr-dev-guide/SKILL.md) 串联 |
|
||||
|
||||
- 同一事实只在所属文档完整说明,其他位置按读者任务保留必要摘要和链接
|
||||
- 改动原因、前后对比、排查经过和验证结果放在 PR、Issue 或任务报告;`release/notes.md` 是发版时使用的发布说明,不作为常规文档的历史章节,也不随普通开发任务自动追加
|
||||
- 仍影响升级、恢复或兼容使用的内容,写成明确的适用条件与操作,保留必要限制,不叙述演变过程
|
||||
- PR、Issue 或任务报告说明改动原因、排查经过和验证结果。版本间的差异以及某次升级专属的一次性操作,在发版时写入 `release/notes.md`
|
||||
- 部署、迁移和接口文档写明当前支持范围、配置和操作。排障按可观察条件给出处理办法,例如根据数据库迁移校验失败定位冲突
|
||||
|
||||
### 层次与行文
|
||||
|
||||
@@ -197,9 +197,9 @@ AI 进行前端开发或审查时,执行[前端流程](.agents/skills/cpr-dev-
|
||||
|
||||
| 范围 | 现有检查 | 仍需提供的证据 |
|
||||
| --- | --- | --- |
|
||||
| Rust | Rustfmt、严格 Clippy、后端测试、架构边界检查 | 相关失败场景和集成行为 |
|
||||
| Rust | [Rustfmt、严格 Clippy、后端测试与架构检查](docs/architecture.md#验证命令) | 相关失败场景和集成行为 |
|
||||
| 前端 | ESLint、类型检查与构建 | 页面一致性、交互和实际数据状态 |
|
||||
| 数据库迁移 | 冻结清单校验与 PR 基线比对 | 升级行为及兼容说明 |
|
||||
| 数据库迁移 | [冻结清单校验与 PR 基线比对](backend/migrations/README.md#冻结规则) | 支持的发行线从已部署版本升级后的行为 |
|
||||
| 依赖安全 | Cargo Audit、pnpm Audit | 本次变更的权限、数据与信任边界 |
|
||||
| 工作流与容器 | Actionlint、相关容器检查 | 改动涉及的运行行为 |
|
||||
|
||||
@@ -215,7 +215,7 @@ pnpm --dir frontend build
|
||||
git diff --check
|
||||
```
|
||||
|
||||
`build` 已包含类型检查;不维护独立前端测试代码。后端的工具链、命令与线程栈设置统一见 [修改与验收](docs/architecture.md#12-修改与验收)
|
||||
`build` 已包含类型检查;不维护独立前端测试代码
|
||||
|
||||
依赖 PostgreSQL / Redis 的测试使用 [专用测试环境](backend/migrations/README.md#本地测试库),未配置导致跳过时明确记录。CI 中已有对应服务和检查,见 [质量工作流](.github/workflows/_quality.yml) 与 [安全扫描](.github/workflows/security.yml)
|
||||
|
||||
@@ -225,11 +225,11 @@ git diff --check
|
||||
|
||||
[CI](.github/workflows/ci.yml) 按变更范围调用质量检查,Markdown 不触发后端、前端和容器任务,工作流语法检查独立执行
|
||||
|
||||
后端 CI 使用 nextest 执行 `main` 集成测试,默认 Redis 密码模式执行完整测试集,ACL 用户模式复用同一批构建产物执行 Store 的 Redis 测试;本地验证命令见 [架构文档](docs/architecture.md#验证命令)
|
||||
后端 CI 使用 nextest 执行 `main` 集成测试。Redis 默认用户密码模式运行全量,ACL 用户模式复用同一批构建产物运行 Store 的 Redis 测试
|
||||
|
||||
常规容器检查与发行构建共用二进制构建入口,并复用已检查的前端产物;Dockerfile、工具链、依赖或构建配置变化时执行完整源码镜像构建,定期安全检查也覆盖源码构建。两条路径均验证容器运行、安全扫描与关闭行为
|
||||
|
||||
发行构建与质量检查并行,Windows 两种架构的插件与系统更新测试独立运行。仅当发行提交只修改版本与发布说明,且其父提交有本仓库主分支成功的后端 CI 时复用该结果;缺少证据则完整重跑。对外发布等待质量、Windows 测试、依赖审计和镜像验证全部成功,构建耗时与测试报告保留 7 天
|
||||
发行构建与质量检查并行,Windows 两种架构的插件与系统更新测试独立运行。仅当发行提交只修改版本与发布说明,且其父提交有本仓库主分支成功的后端 CI 时复用该结果;缺少证据则完整重跑。`backend-validation` 明确报告本次执行或复用结果,复用时列出被验证的源码提交和 CI 链接。对外发布等待质量、Windows 测试、依赖审计和镜像验证全部成功,构建耗时与测试报告保留 7 天
|
||||
|
||||
新增自动规则优先使用现有工具,要求依据明确、结果稳定、误报可控;无法可靠判定的设计与视觉问题保留审查判断,避免把具体源码写法锁成测试
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
</div>
|
||||
|
||||
> [!NOTE]
|
||||
> 支持 OpenAI(Codex)、xAI(Grok)和 Google Antigravity 账号,以及兼容 OpenAI Responses 或 Anthropic Messages 的 API Key 服务,详见[账号接入](docs/api.md#账号能力导入与-oauth)
|
||||
> 支持 OpenAI(Codex)、xAI(Grok)和 Google Antigravity 账号。API Key 上游可使用 OpenAI Responses、Anthropic Messages 或 Google GenAI,支持的协议取决于所选平台。详见[账号接入](docs/api.md#账号能力导入与-oauth)
|
||||
|
||||
## 快速预览
|
||||
|
||||
|
||||
@@ -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()),
|
||||
|
||||
@@ -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"]),
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Codex Proxy Plugin CLI
|
||||
|
||||
`cpr-plugin` 按 [SDK 合同](../../crates/gateway-plugin/sdk/README.md)校验清单,将插件可执行文件与声明的资源打包,并输出 SHA-256 校验文件
|
||||
`cpr-plugin package` 将已构建的插件二进制和声明资源打成安装包,同时生成 SHA-256 校验文件。作者清单须省略 `package`,CLI 会写入协议版本、目标平台和文件摘要。清单格式见 [SDK 清单](../../crates/gateway-plugin/sdk/docs/manifest.md)。
|
||||
|
||||
## 安装
|
||||
|
||||
@@ -14,7 +14,7 @@ cargo +1.99.1 install --locked --path backend/apps/plugin-cli --root /path/to/lo
|
||||
|
||||
## 打包
|
||||
|
||||
先构建目标平台的二进制;有管理页面时,也构建静态资源。全部参数见 `cpr-plugin package --help`
|
||||
先构建目标平台的二进制。有管理页面时,还需构建其静态资源。支持的目标为 `x86_64-unknown-linux-gnu`、`aarch64-unknown-linux-gnu` 和 `aarch64-apple-darwin`。全部参数见 `cpr-plugin package --help`。
|
||||
|
||||
```bash
|
||||
cpr-plugin package \
|
||||
@@ -25,20 +25,14 @@ cpr-plugin package \
|
||||
--output-dir /path/to/output
|
||||
```
|
||||
|
||||
资源文件须在 `resources` 中声明,默认从清单所在目录按相对路径读取。
|
||||
`--resource-map web=web/dist` 从项目内的 `web/dist/` 读取包内 `web/` 资源。可为不同前缀重复传参,未匹配任何资源的映射会报错
|
||||
`--binary` 指定的文件会写入清单的 `main` 路径。`resources` 中每项默认从清单所在目录按包内路径读取。清单、二进制和各资源均须是普通文件,不能以符号链接作输入文件。
|
||||
|
||||
例如,清单声明 `web/index.html` 时,`--resource-map web=web/dist` 改从 `<清单目录>/web/dist/index.html` 读取,包内仍为 `web/index.html`。映射只匹配资源路径的第一段,可为不同前缀重复传参。源目录须为项目相对路径,资源解析后须在清单目录内。重复前缀、未匹配任何资源或映射前缀本身被用作资源文件时,打包失败。包内命名规则见[包内路径](../../crates/gateway-plugin/sdk/docs/manifest.md#包内路径)。
|
||||
|
||||
输出为 `<插件 ID>-<版本>-<目标 triple>.tar.gz` 及对应的 `.tar.gz.sha256`。归档根目录包含 `plugin.json`、可执行文件和声明资源。
|
||||
输入清单及生成后的清单均不得超过 64 KiB,压缩包上限为 32 MiB,展开归档上限为 128 MiB
|
||||
|
||||
作者清单须省略 `package`。CLI 将协议版本、目标平台和文件摘要写入 `plugin.json`。可省略的声明字段见 [SDK 扩展项声明](../../crates/gateway-plugin/sdk/docs/manifest.md#扩展项简写)
|
||||
|
||||
支持 `x86_64-unknown-linux-gnu`、`aarch64-unknown-linux-gnu` 和 `aarch64-apple-darwin`。
|
||||
打包后在目标宿主验证启动和插件功能。完整示例见插件[子模块](../../../docs/development.md#源码联调)的 `examples/workbench`
|
||||
|
||||
### 图标资源
|
||||
|
||||
按 [SDK 插件图标](../../crates/gateway-plugin/sdk/docs/manifest.md#插件图标)填写 `icon` 和 `resources`。CLI 自动打包原文件并计算摘要,宿主在安装时校验
|
||||
图标与其他资源一样按原文件打包,图像内容由宿主在安装时校验。打包后在目标宿主验证启动和插件功能。参见[图标要求](../../crates/gateway-plugin/sdk/docs/manifest.md#插件图标)、[安装步骤](../../../docs/plugins.md#安装)及插件[子模块](../../../docs/development.md#源码联调)的 `examples/workbench`。
|
||||
|
||||
## 开发
|
||||
|
||||
|
||||
@@ -182,11 +182,7 @@ fn package(options: &Options) -> Result<PackageOutput, PackagerError> {
|
||||
source.display()
|
||||
)));
|
||||
}
|
||||
if sources.insert(package_path.clone(), source).is_some() {
|
||||
return Err(PackagerError::Invalid(format!(
|
||||
"plugin main and resource share package path {package_path}"
|
||||
)));
|
||||
}
|
||||
sources.insert(package_path.clone(), source);
|
||||
}
|
||||
if used_maps.len() != resource_maps.len() {
|
||||
let unused = resource_maps
|
||||
@@ -199,8 +195,6 @@ fn package(options: &Options) -> Result<PackageOutput, PackagerError> {
|
||||
unused.join(", ")
|
||||
)));
|
||||
}
|
||||
reject_case_folded_paths(sources.keys())?;
|
||||
|
||||
let mut files = BTreeMap::new();
|
||||
let mut source_bytes = 0u64;
|
||||
for (package_path, source) in sources {
|
||||
@@ -301,20 +295,6 @@ fn resource_source(
|
||||
}
|
||||
}
|
||||
|
||||
fn reject_case_folded_paths<'a>(
|
||||
paths: impl IntoIterator<Item = &'a String>,
|
||||
) -> Result<(), PackagerError> {
|
||||
let mut folded = BTreeSet::new();
|
||||
for path in paths {
|
||||
if !folded.insert(path.to_ascii_lowercase()) {
|
||||
return Err(PackagerError::Invalid(format!(
|
||||
"package path collides case-insensitively: {path}"
|
||||
)));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn write_archive(
|
||||
output: &mut File,
|
||||
manifest: &[u8],
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -26,6 +26,7 @@ pub use use_case::peer_link::{PeerLinkError, PeerLinkService};
|
||||
|
||||
pub use use_case::{
|
||||
account_groups::AccountGroupService,
|
||||
account_schedules::AccountScheduleService,
|
||||
accounts::AccountsService,
|
||||
auth::AuthService,
|
||||
backup::BackupService,
|
||||
@@ -209,6 +210,7 @@ pub struct AdminServices {
|
||||
peer_link: Arc<dyn PeerLinkService>,
|
||||
accounts: Arc<dyn AccountsService>,
|
||||
account_groups: Arc<dyn AccountGroupService>,
|
||||
account_schedules: Arc<AccountScheduleService>,
|
||||
client_keys: Arc<dyn ClientKeyService>,
|
||||
client_distribution: Arc<dyn ClientDistributionService>,
|
||||
observability: Arc<dyn ObservabilityService>,
|
||||
@@ -272,6 +274,11 @@ impl AdminServices {
|
||||
self.accounts.as_ref()
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn account_schedules(&self) -> &AccountScheduleService {
|
||||
self.account_schedules.as_ref()
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn account_groups(&self) -> &dyn AccountGroupService {
|
||||
self.account_groups.as_ref()
|
||||
|
||||
@@ -0,0 +1,262 @@
|
||||
//! 账号排班的轻量目录与批量变更合同
|
||||
|
||||
use super::AdminError;
|
||||
use chrono::{DateTime, Offset, TimeDelta, Utc};
|
||||
use gateway_core::account::duty::{DailyShift, SchedulePolicy};
|
||||
use gateway_core::time::DeploymentTimeZone;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ScheduleAccount {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
#[serde(skip)]
|
||||
pub provider_kind: String,
|
||||
#[serde(skip)]
|
||||
pub has_cached_quota: bool,
|
||||
pub authentication_kind: String,
|
||||
pub plan_type: Option<String>,
|
||||
pub plan_type_display: Option<String>,
|
||||
pub group_ids: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct ScheduleGroup {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct ScheduleChange {
|
||||
#[serde(default)]
|
||||
pub clear: bool,
|
||||
pub revision: u64,
|
||||
pub policy: Option<SchedulePolicy>,
|
||||
pub targets: Vec<TargetChange>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum TargetKind {
|
||||
Account,
|
||||
Group,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct TargetChange {
|
||||
pub kind: TargetKind,
|
||||
pub id: String,
|
||||
pub action: ScheduleAction,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum ScheduleAction {
|
||||
Remove,
|
||||
Set(Vec<DailyShift>),
|
||||
}
|
||||
|
||||
impl ScheduleChange {
|
||||
pub fn validate(&self) -> Result<(), AdminError> {
|
||||
if self.revision == 0
|
||||
|| !self.clear && self.policy.is_none() && self.targets.is_empty()
|
||||
|| self
|
||||
.policy
|
||||
.is_some_and(|p| !(1..=100).contains(&p.limit_percent))
|
||||
{
|
||||
return Err(AdminError::invalid("排班策略或版本无效"));
|
||||
}
|
||||
validate_targets(&self.targets)
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_targets(changes: &[TargetChange]) -> Result<(), AdminError> {
|
||||
let mut targets = BTreeSet::new();
|
||||
for target in changes {
|
||||
if !targets.insert((target.kind, &target.id)) || target.id.is_empty() {
|
||||
return Err(AdminError::invalid("排班对象重复或无效"));
|
||||
}
|
||||
if let ScheduleAction::Set(shifts) = &target.action {
|
||||
let mut ids = BTreeSet::new();
|
||||
let mut spans = Vec::new();
|
||||
for shift in shifts {
|
||||
if shift.start >= 1440
|
||||
|| shift.end >= 1440
|
||||
|| uuid::Uuid::parse_str(&shift.id).is_err()
|
||||
|| !ids.insert(&shift.id)
|
||||
{
|
||||
return Err(AdminError::invalid("班次标识或时间无效"));
|
||||
}
|
||||
if shift.start < shift.end {
|
||||
spans.push((shift.start, shift.end));
|
||||
} else {
|
||||
spans.push((shift.start, 1440));
|
||||
if shift.end > 0 {
|
||||
spans.push((0, shift.end));
|
||||
}
|
||||
}
|
||||
}
|
||||
spans.sort_unstable();
|
||||
if spans.windows(2).any(|w| w[0].1 > w[1].0) {
|
||||
return Err(AdminError::invalid("同一排班对象的班次时间重叠"));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum ScheduleScope {
|
||||
Roster,
|
||||
Account,
|
||||
Group,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct ScheduleQuery {
|
||||
pub scope: ScheduleScope,
|
||||
pub page: u32,
|
||||
pub page_size: u32,
|
||||
pub revision: Option<u64>,
|
||||
#[serde(default)]
|
||||
pub search: String,
|
||||
#[serde(default)]
|
||||
pub group_id: String,
|
||||
#[serde(default)]
|
||||
pub targets: Vec<TargetChange>,
|
||||
#[serde(default)]
|
||||
pub clear: bool,
|
||||
pub summary_minute: Option<u16>,
|
||||
#[serde(default)]
|
||||
pub include_summary: bool,
|
||||
}
|
||||
|
||||
impl ScheduleQuery {
|
||||
pub fn validate(&self) -> Result<(), AdminError> {
|
||||
if self.page == 0
|
||||
|| !(1..=100).contains(&self.page_size)
|
||||
|| self.summary_minute.is_some_and(|minute| minute >= 1440)
|
||||
{
|
||||
return Err(AdminError::invalid("排班查询页码、每页数量或时间无效"));
|
||||
}
|
||||
validate_targets(&self.targets)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(tag = "kind", rename_all = "camelCase")]
|
||||
pub enum ScheduleItem {
|
||||
Account {
|
||||
#[serde(flatten)]
|
||||
account: ScheduleAccount,
|
||||
shifts: Option<Vec<DailyShift>>,
|
||||
},
|
||||
Group {
|
||||
#[serde(flatten)]
|
||||
group: ScheduleGroup,
|
||||
shifts: Option<Vec<DailyShift>>,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct ScheduleBand {
|
||||
pub start: u16,
|
||||
pub end: u16,
|
||||
pub count: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ScheduleSummary {
|
||||
pub target_count: u64,
|
||||
pub pool_count: u64,
|
||||
pub available: u64,
|
||||
pub off_duty: Option<String>,
|
||||
pub visible: u64,
|
||||
pub current: u64,
|
||||
pub bands: Vec<ScheduleBand>,
|
||||
pub editing: ScheduleEditingBasis,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ScheduleEditingBasis {
|
||||
pub bands: Vec<ScheduleBand>,
|
||||
pub available: u64,
|
||||
pub off_duty: Option<String>,
|
||||
pub cohorts: Vec<ScheduleCohort>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct ScheduleCohort {
|
||||
pub targets: Vec<String>,
|
||||
pub fixed: Vec<(u16, u16)>,
|
||||
pub count: u64,
|
||||
pub example: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct ScheduleList {
|
||||
pub revision: u64,
|
||||
pub policy: SchedulePolicy,
|
||||
pub items: Vec<ScheduleItem>,
|
||||
pub total: i64,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub groups: Option<Vec<ScheduleGroup>>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub summary: Option<ScheduleSummary>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct ScheduleQueryResult {
|
||||
#[serde(flatten)]
|
||||
pub page: ScheduleList,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub clock: Option<ScheduleClock>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ScheduleClock {
|
||||
pub valid_for_millis: i64,
|
||||
pub unix_millis: i64,
|
||||
pub minute: u16,
|
||||
}
|
||||
|
||||
impl ScheduleClock {
|
||||
#[must_use]
|
||||
pub fn at(now: DateTime<Utc>, timezone: DeploymentTimeZone) -> Self {
|
||||
let offset = |minutes| {
|
||||
timezone
|
||||
.local(now + TimeDelta::minutes(minutes))
|
||||
.offset()
|
||||
.fix()
|
||||
};
|
||||
let current = offset(0);
|
||||
let mut end = 24 * 60;
|
||||
// 同一偏移下可用经过的分钟推进本地时钟;遇到夏令时跳变就在边界重新采样
|
||||
if offset(end) != current {
|
||||
let mut start = 0;
|
||||
while end - start > 1 {
|
||||
let mid = (start + end) / 2;
|
||||
if offset(mid) == current {
|
||||
start = mid;
|
||||
} else {
|
||||
end = mid;
|
||||
}
|
||||
}
|
||||
}
|
||||
let unix_millis = now.timestamp_millis();
|
||||
Self {
|
||||
valid_for_millis: end * 60_000 - unix_millis.rem_euclid(60_000),
|
||||
unix_millis,
|
||||
minute: timezone.minute_of_day(now),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,7 @@ pub enum MutationAuditOperation {
|
||||
AdminApiKeyChanged { exists: bool },
|
||||
AccountGroupCreate,
|
||||
AccountGroupUpdate,
|
||||
AccountScheduleUpdate,
|
||||
AccountGroupEnabled { enabled: bool },
|
||||
AccountGroupDelete,
|
||||
ClientApiKeyResetBudget,
|
||||
@@ -73,6 +74,7 @@ impl MutationAuditOperation {
|
||||
"runtime_settings",
|
||||
),
|
||||
Self::AccountGroupCreate => ("create", "account_group"),
|
||||
Self::AccountScheduleUpdate => ("update", "account_schedule"),
|
||||
Self::AccountGroupUpdate => ("update", "account_group"),
|
||||
Self::AccountGroupEnabled { enabled } => {
|
||||
(if enabled { "enable" } else { "disable" }, "account_group")
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
use std::num::{NonZeroU16, NonZeroU64};
|
||||
|
||||
pub mod account_groups;
|
||||
pub mod account_schedules;
|
||||
pub mod accounts;
|
||||
pub mod analytics;
|
||||
pub mod audit;
|
||||
|
||||
@@ -78,6 +78,8 @@ impl fmt::Debug for ImportCredentials {
|
||||
/// 批量导入提交结果
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct CredentialImportResult {
|
||||
/// 本次事务首次创建的账号,同身份重新导入沿用已有账号
|
||||
pub created_ids: std::collections::BTreeSet<ProviderAccountId>,
|
||||
pub config_revision: Revision,
|
||||
pub credential_ids: Vec<ProviderAccountId>,
|
||||
}
|
||||
@@ -100,6 +102,8 @@ impl fmt::Debug for PrepareCredentialImport {
|
||||
/// Provider 已验证、可由 Store 原子创建的一份 credential
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct PreparedCredentialCreate {
|
||||
/// 同身份重复导入时,允许沿用与此标识匹配的本地目录
|
||||
pub preserve_catalog_etag: Option<String>,
|
||||
pub model_access: Option<gateway_core::account::AccountModelAccess>,
|
||||
pub outbound_proxy: Option<gateway_core::account::OutboundProxy>,
|
||||
pub account_id: ProviderAccountId,
|
||||
@@ -540,10 +544,18 @@ impl fmt::Debug for AuthorizationReceiptKey {
|
||||
}
|
||||
}
|
||||
|
||||
/// 凭据事务对账号的实际影响,同身份授权可以更新既有账号
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum CredentialChange {
|
||||
Created,
|
||||
Updated,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct AuthorizationCommitResult {
|
||||
pub result: CredentialMutationResult,
|
||||
pub newly_committed: bool,
|
||||
/// 重放已提交回执时没有新的账号变更
|
||||
pub change: Option<CredentialChange>,
|
||||
}
|
||||
|
||||
/// OAuth 准备结果拆解后的 Store 命令与两个结算 guard
|
||||
@@ -698,6 +710,8 @@ pub struct PreparedCredentialRotationFacts {
|
||||
pub plan_type: Option<String>,
|
||||
/// Token 刷新保留提交时的资料,不以准备阶段的副本覆盖新套餐
|
||||
pub preserve_profile: bool,
|
||||
/// 已核实同一身份续期时,允许把匹配此标识的目录续接至新凭据版本
|
||||
pub preserve_catalog_etag: Option<String>,
|
||||
/// 凭据或连接配置更新保留提交时的健康状态与错误事实
|
||||
pub preserve_credential_state: bool,
|
||||
pub preserve_access_token_expiry: bool,
|
||||
@@ -890,6 +904,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>,
|
||||
/// 上游额度响应明确提供的套餐,可用于补全账号展示
|
||||
@@ -1298,6 +1314,13 @@ pub struct ProviderExport {
|
||||
pub document: ProviderDocument,
|
||||
}
|
||||
|
||||
/// 判断账号能否导出凭据所需的公开事实
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct CredentialExportScope {
|
||||
pub provider_kind: ProviderKind,
|
||||
pub authentication_kind: String,
|
||||
}
|
||||
|
||||
/// Store 为 Provider 导出序列化准备的最小输入;material 对公共层保持不透明
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct ProviderExportCredentialInput {
|
||||
@@ -1319,6 +1342,7 @@ impl fmt::Debug for ProviderExport {
|
||||
/// 统一账号目录的一行完整结果
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct AccountDirectoryItem {
|
||||
pub schedule_duty: Option<gateway_core::account::duty::ScheduleDuty>,
|
||||
pub model_cooldowns: Vec<gateway_core::provider_ports::ProviderScopedCooldown>,
|
||||
pub platform_icon: Option<String>,
|
||||
pub protection_rules: Vec<gateway_core::account::AccountProtectionMatch>,
|
||||
|
||||
@@ -31,6 +31,9 @@ pub fn validate_model_mappings<'a>(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 平台运行设置,字段由对应 Provider 定义
|
||||
pub type ProviderSettings = BTreeMap<ProviderKind, gateway_core::account::OpaqueProviderData>;
|
||||
|
||||
/// Provider-owned 请求画像选择;Provider ID 是唯一命名空间
|
||||
pub type ProviderRequestProfiles =
|
||||
BTreeMap<ProviderKind, gateway_core::account::OpaqueProviderData>;
|
||||
@@ -45,6 +48,9 @@ pub use gateway_core::account::RotationStrategy;
|
||||
/// 运行设置的共同值;版本、Provider 画像更新和数据库秘密由外层类型拥有
|
||||
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct RuntimeSettingsValues {
|
||||
/// 平台运行设置按 Provider 更新,省略的平台保留已提交值
|
||||
#[serde(default)]
|
||||
pub provider_settings: ProviderSettings,
|
||||
pub openai_websocket_pool: gateway_core::settings::OpenAiWebSocketPoolSettings,
|
||||
pub openai_request_settings: gateway_core::settings::OpenAiRequestSettings,
|
||||
pub codex_privacy_policy: gateway_core::settings::privacy::CodexPrivacyPolicy,
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
//! 账号排班的事务存储边界
|
||||
|
||||
use super::store::AdminStoreResult;
|
||||
use crate::model::{
|
||||
MutationContext, Revision,
|
||||
account_schedules::{ScheduleChange, ScheduleList, ScheduleQuery},
|
||||
};
|
||||
use async_trait::async_trait;
|
||||
|
||||
#[async_trait]
|
||||
pub trait AccountScheduleStore: Send + Sync {
|
||||
async fn query(&self, query: &ScheduleQuery) -> AdminStoreResult<ScheduleList>;
|
||||
async fn save(
|
||||
&self,
|
||||
change: ScheduleChange,
|
||||
context: &MutationContext,
|
||||
) -> AdminStoreResult<Revision>;
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
//! 管理用例依赖的外部能力端口
|
||||
|
||||
pub mod account_schedules;
|
||||
pub mod backup;
|
||||
pub mod client_distribution;
|
||||
pub mod peer;
|
||||
|
||||
@@ -2,17 +2,61 @@
|
||||
|
||||
use crate::model::{AdminError, pricing::PricingSyncPreview};
|
||||
use async_trait::async_trait;
|
||||
use gateway_core::metering::{ModelPriceOverride, TokenPriceOverride};
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
/// 文本参考价保留来源的上下文阈值和独立音频输入计价事实
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ExternalModelPrice {
|
||||
pub standard: TokenPriceOverride,
|
||||
pub long_context: Option<(u64, TokenPriceOverride)>,
|
||||
pub has_audio_input_price: bool,
|
||||
}
|
||||
|
||||
/// 外层键为来源目录,内层键为模型;无法解析为文本参考价的条目保留为 None
|
||||
pub type ExternalPrices = BTreeMap<String, BTreeMap<String, Option<ExternalModelPrice>>>;
|
||||
|
||||
/// 消费方可导入的上下文阈值,以及是否可以独立采用文本输入单价
|
||||
#[derive(Default, Clone, Copy)]
|
||||
pub struct PricingSourcePolicy {
|
||||
pub long_context_tokens: Option<u64>,
|
||||
pub text_only_input: bool,
|
||||
}
|
||||
|
||||
impl PricingSourcePolicy {
|
||||
fn accepts(self, source: &ExternalModelPrice) -> bool {
|
||||
(!source.has_audio_input_price || self.text_only_input)
|
||||
&& source
|
||||
.long_context
|
||||
.as_ref()
|
||||
.is_none_or(|(threshold, _)| self.long_context_tokens == Some(*threshold))
|
||||
}
|
||||
|
||||
fn price(self, source: &ExternalModelPrice) -> Option<ModelPriceOverride> {
|
||||
if !self.accepts(source) {
|
||||
return None;
|
||||
}
|
||||
let mut bands = BTreeMap::from([("standard".to_owned(), source.standard.clone())]);
|
||||
if let Some((_, rates)) = &source.long_context {
|
||||
bands.insert("long_standard".to_owned(), rates.clone());
|
||||
}
|
||||
Some(ModelPriceOverride {
|
||||
multiplier_bps: 10_000,
|
||||
bands,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Provider 明确登记的外部参考模型,不按名称前缀猜测不同产品的对应关系
|
||||
pub struct PricingSourceModel {
|
||||
pub provider: String,
|
||||
pub model: String,
|
||||
pub policy: PricingSourcePolicy,
|
||||
}
|
||||
|
||||
/// 同名外部目录可直接同步,跨平台模型只采用 Provider 登记的参考价
|
||||
pub enum PricingCatalogSource {
|
||||
Direct,
|
||||
Direct(PricingSourcePolicy),
|
||||
References(BTreeMap<String, PricingSourceModel>),
|
||||
}
|
||||
|
||||
@@ -26,7 +70,7 @@ impl PricingSourceScope {
|
||||
let mut vendors = BTreeSet::new();
|
||||
for (kind, source) in &self.catalogs {
|
||||
match source {
|
||||
PricingCatalogSource::Direct => {
|
||||
PricingCatalogSource::Direct(_) => {
|
||||
vendors.insert(kind.as_str());
|
||||
}
|
||||
PricingCatalogSource::References(models) => {
|
||||
@@ -40,56 +84,74 @@ impl PricingSourceScope {
|
||||
pub fn requires_catalog(&self, vendor: &str) -> bool {
|
||||
matches!(
|
||||
self.catalogs.get(vendor),
|
||||
Some(PricingCatalogSource::Direct)
|
||||
Some(PricingCatalogSource::Direct(_))
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn project(self, source: PricingSyncPreview) -> PricingSyncPreview {
|
||||
pub(crate) fn project(&self, source: ExternalPrices) -> Result<PricingSyncPreview, AdminError> {
|
||||
let mut result = PricingSyncPreview {
|
||||
prices: BTreeMap::new(),
|
||||
skipped: Vec::new(),
|
||||
};
|
||||
for (kind, catalog) in self.catalogs {
|
||||
let prices = match catalog {
|
||||
PricingCatalogSource::Direct => {
|
||||
let prefix = format!("{kind}/");
|
||||
result.skipped.extend(
|
||||
source
|
||||
.skipped
|
||||
.iter()
|
||||
.filter(|id| id.starts_with(&prefix))
|
||||
.cloned(),
|
||||
);
|
||||
source.prices.get(&kind).cloned().unwrap_or_default()
|
||||
}
|
||||
PricingCatalogSource::References(models) => {
|
||||
let mut prices = BTreeMap::new();
|
||||
for (model, reference) in models {
|
||||
match source
|
||||
.prices
|
||||
.get(&reference.provider)
|
||||
.and_then(|models| models.get(&reference.model))
|
||||
{
|
||||
Some(price) => {
|
||||
prices.insert(model, price.clone());
|
||||
}
|
||||
None => result.skipped.push(format!("{kind}/{model}")),
|
||||
for (kind, catalog) in &self.catalogs {
|
||||
let mut prices = BTreeMap::new();
|
||||
let mut insert =
|
||||
|model: String, entry: Option<&ExternalModelPrice>, policy: PricingSourcePolicy| {
|
||||
if let Some(price) = entry.and_then(|entry| policy.price(entry)) {
|
||||
prices.insert(model, price);
|
||||
} else {
|
||||
result.skipped.push(format!("{kind}/{model}"));
|
||||
}
|
||||
};
|
||||
match catalog {
|
||||
PricingCatalogSource::Direct(policy) => {
|
||||
if let Some(models) = source.get(kind) {
|
||||
for (model, entry) in models {
|
||||
insert(model.clone(), entry.as_ref(), *policy);
|
||||
}
|
||||
}
|
||||
prices
|
||||
}
|
||||
};
|
||||
PricingCatalogSource::References(models) => {
|
||||
for (model, reference) in models {
|
||||
let entry = source
|
||||
.get(&reference.provider)
|
||||
.and_then(|models| models.get(&reference.model))
|
||||
.and_then(Option::as_ref);
|
||||
insert(model.clone(), entry, reference.policy);
|
||||
}
|
||||
}
|
||||
}
|
||||
if !prices.is_empty() {
|
||||
result.prices.insert(kind, prices);
|
||||
result.prices.insert(kind.clone(), prices);
|
||||
}
|
||||
}
|
||||
// 整份来源无可用单价时不能把已有同步价当作下架删除
|
||||
// 引用的型号可以全部下架,只要对应来源仍有消费方可以采用的价目
|
||||
if result.prices.is_empty()
|
||||
&& !self.catalogs.values().any(|catalog| {
|
||||
let PricingCatalogSource::References(models) = catalog else {
|
||||
return false;
|
||||
};
|
||||
models.values().any(|reference| {
|
||||
source.get(&reference.provider).is_some_and(|prices| {
|
||||
prices
|
||||
.values()
|
||||
.flatten()
|
||||
.any(|price| reference.policy.accepts(price))
|
||||
})
|
||||
})
|
||||
})
|
||||
{
|
||||
return Err(AdminError::bad_gateway(
|
||||
"无法读取 models.dev 价目,现有价格不变",
|
||||
));
|
||||
}
|
||||
result.skipped.sort();
|
||||
result.skipped.dedup();
|
||||
result
|
||||
Ok(result)
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait PricingSource: Send + Sync {
|
||||
async fn fetch(&self, scope: &PricingSourceScope) -> Result<PricingSyncPreview, AdminError>;
|
||||
async fn fetch(&self, scope: &PricingSourceScope) -> Result<ExternalPrices, AdminError>;
|
||||
}
|
||||
@@ -1,6 +1,9 @@
|
||||
//! 原生 Provider 管理能力与启动时注册表
|
||||
|
||||
use std::{collections::BTreeMap, sync::Arc};
|
||||
use std::{
|
||||
collections::{BTreeMap, BTreeSet},
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
use async_trait::async_trait;
|
||||
use gateway_core::{
|
||||
@@ -145,6 +148,24 @@ struct ProviderAdminDiagnostic {
|
||||
source: Option<gateway_core::error::ErrorSource>,
|
||||
}
|
||||
|
||||
/// 账号事务影响的账号及其中首次创建的账号
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct AccountFactsChange<'a> {
|
||||
pub ids: &'a [ProviderAccountId],
|
||||
pub created_ids: &'a BTreeSet<ProviderAccountId>,
|
||||
}
|
||||
|
||||
impl<'a> AccountFactsChange<'a> {
|
||||
#[must_use]
|
||||
pub const fn updated(ids: &'a [ProviderAccountId]) -> Self {
|
||||
static EMPTY: BTreeSet<ProviderAccountId> = BTreeSet::new();
|
||||
Self {
|
||||
ids,
|
||||
created_ids: &EMPTY,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 一个具体 Provider 对管理控制面提供的解析、验证、上游交互与运行时资源回收能力
|
||||
///
|
||||
/// 数据变更由 Provider 返回 prepared facts;config revision、审计与 PostgreSQL 事务
|
||||
@@ -195,7 +216,7 @@ pub trait ProviderAdmin: Send + Sync {
|
||||
|
||||
/// 外部参考价到本 Provider 上游模型的对应关系,与内置价共用登记
|
||||
fn pricing_source(&self) -> crate::ports::pricing::PricingCatalogSource {
|
||||
crate::ports::pricing::PricingCatalogSource::Direct
|
||||
crate::ports::pricing::PricingCatalogSource::Direct(Default::default())
|
||||
}
|
||||
|
||||
fn evaluate_usage_pricing(
|
||||
@@ -297,7 +318,27 @@ 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<'_>) {}
|
||||
|
||||
/// 选择本批变更后需要观察额度的账号,提交、发布及互联分派由 Admin 负责
|
||||
async fn quota_observation_targets(
|
||||
&self,
|
||||
change: AccountFactsChange<'_>,
|
||||
) -> Vec<ProviderAccountId> {
|
||||
change.ids.to_vec()
|
||||
}
|
||||
|
||||
/// 平台设置由所属 Provider 校验,空对象表示使用平台默认值
|
||||
fn validate_settings(
|
||||
&self,
|
||||
settings: &gateway_core::account::OpaqueProviderData,
|
||||
) -> Result<(), ProviderAdminError> {
|
||||
if settings.expose_to_provider().is_empty() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(ProviderAdminError::new(ProviderAdminErrorKind::Unsupported))
|
||||
}
|
||||
}
|
||||
|
||||
/// 生成一次连接测试所需的 Provider-owned operation;Core 负责实际执行与落账
|
||||
async fn connection_test_operation(
|
||||
|
||||
@@ -36,9 +36,9 @@ use crate::model::{
|
||||
UsageSummaryObservation,
|
||||
},
|
||||
provider_credentials::{
|
||||
AuthorizationCommit, CredentialDetails, CredentialImportCommit, CredentialImportResult,
|
||||
CredentialMutationResult, CredentialRotationCommit, PluginAccountListQuery,
|
||||
PluginAccountPage, ProviderExportCredentialInput,
|
||||
AuthorizationCommit, CredentialDetails, CredentialExportScope, CredentialImportCommit,
|
||||
CredentialImportResult, CredentialMutationResult, CredentialRotationCommit,
|
||||
PluginAccountListQuery, PluginAccountPage, ProviderExportCredentialInput,
|
||||
},
|
||||
quota_forecast::QuotaForecastHistory,
|
||||
settings::{AdminApiKey, AdminApiKeyMutation, ReplaceRuntimeSettings, RuntimeSettings},
|
||||
@@ -216,10 +216,17 @@ pub trait AccountStore:
|
||||
account_id: &gateway_core::account::ProviderAccountId,
|
||||
) -> AdminStoreResult<Option<CredentialDetails>>;
|
||||
|
||||
/// 只读取所选账号的 Provider 和认证方式,缺失的 ID 不在结果中
|
||||
async fn credential_export_scopes(
|
||||
&self,
|
||||
account_ids: &[gateway_core::account::ProviderAccountId],
|
||||
) -> AdminStoreResult<BTreeMap<String, CredentialExportScope>>;
|
||||
|
||||
/// 按请求顺序读取凭据,同时复核每个账号仍属于获准的 Provider 和认证方式
|
||||
async fn load_credentials_for_export(
|
||||
&self,
|
||||
provider_kind: &gateway_core::routing::ProviderKind,
|
||||
account_ids: &[gateway_core::account::ProviderAccountId],
|
||||
accounts: &[(gateway_core::account::ProviderAccountId, String)],
|
||||
) -> AdminStoreResult<Vec<ProviderExportCredentialInput>>;
|
||||
|
||||
/// 插件凭据读取只接收账号 ID,不接受调用方另行声明 Provider
|
||||
@@ -655,6 +662,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 +672,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 +765,11 @@ impl AdminStorePorts {
|
||||
self.accounts.runtime.clone()
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn account_schedules(&self) -> Arc<dyn super::account_schedules::AccountScheduleStore> {
|
||||
self.accounts.schedules.clone()
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn account_groups(&self) -> Arc<dyn AccountGroupStore> {
|
||||
self.accounts.groups.clone()
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
//! 批量排班校验与已提交配置的发布
|
||||
|
||||
use super::{map_store_error, publish_committed};
|
||||
use crate::{
|
||||
model::{
|
||||
AdminError, MutationContext,
|
||||
account_schedules::{
|
||||
ScheduleAccount, ScheduleChange, ScheduleClock, ScheduleItem, ScheduleQuery,
|
||||
ScheduleQueryResult,
|
||||
},
|
||||
provider_credentials::ProviderQuotaRequest,
|
||||
},
|
||||
ports::{account_schedules::AccountScheduleStore, provider::ProviderAdminRegistry},
|
||||
};
|
||||
use futures::{StreamExt, stream};
|
||||
use gateway_core::{account::ProviderAccountId, routing::ProviderKind, runtime::SnapshotControl};
|
||||
use std::sync::Arc;
|
||||
|
||||
pub struct AccountScheduleService {
|
||||
pub(crate) timezone: gateway_core::time::DeploymentTimeZone,
|
||||
pub(crate) providers: ProviderAdminRegistry,
|
||||
pub(crate) store: Arc<dyn AccountScheduleStore>,
|
||||
pub(crate) snapshot: Arc<dyn SnapshotControl>,
|
||||
}
|
||||
|
||||
impl AccountScheduleService {
|
||||
pub async fn query(&self, mut query: ScheduleQuery) -> Result<ScheduleQueryResult, AdminError> {
|
||||
query.validate()?;
|
||||
let clock = query.include_summary.then(|| {
|
||||
let clock = ScheduleClock::at(chrono::Utc::now(), self.timezone);
|
||||
query.summary_minute.get_or_insert(clock.minute);
|
||||
clock
|
||||
});
|
||||
let mut page = self
|
||||
.store
|
||||
.query(&query)
|
||||
.await
|
||||
.map_err(|e| map_store_error(e, "账号排班"))?;
|
||||
stream::iter(page.items.iter_mut().filter_map(|item| match item {
|
||||
ScheduleItem::Account { account, .. } => Some(account),
|
||||
ScheduleItem::Group { .. } => None,
|
||||
}))
|
||||
.for_each_concurrent(8, |account| self.fill_plan(account))
|
||||
.await;
|
||||
Ok(ScheduleQueryResult { page, clock })
|
||||
}
|
||||
|
||||
async fn fill_plan(&self, account: &mut ScheduleAccount) {
|
||||
account.plan_type_display = self
|
||||
.providers
|
||||
.plan_type_display(&account.provider_kind, account.plan_type.as_deref());
|
||||
// 有些套餐名来自上游额度观测,只在目录缺少展示名时读取已保存的快照
|
||||
if account.plan_type_display.is_some()
|
||||
|| !account.has_cached_quota
|
||||
|| account.authentication_kind == "api_key"
|
||||
{
|
||||
return;
|
||||
}
|
||||
let (Ok(kind), Ok(account_id)) = (
|
||||
ProviderKind::new(account.provider_kind.clone()),
|
||||
ProviderAccountId::new(account.id.clone()),
|
||||
) else {
|
||||
return;
|
||||
};
|
||||
let Ok(provider) = self.providers.require(&kind) else {
|
||||
return;
|
||||
};
|
||||
if let Ok(quota) = provider
|
||||
.quota(ProviderQuotaRequest {
|
||||
account_id,
|
||||
refresh: false,
|
||||
rolling_usage: None,
|
||||
})
|
||||
.await
|
||||
{
|
||||
account.plan_type_display = self.providers.resolve_account_plan(
|
||||
&account.provider_kind,
|
||||
&mut account.plan_type,
|
||||
Some("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,16 @@ impl DefaultAccountsService {
|
||||
lookback,
|
||||
);
|
||||
Ok(AccountDirectoryItem {
|
||||
schedule_duty: self
|
||||
.published
|
||||
.snapshot_for_diagnostics()
|
||||
.and_then(|snapshot| {
|
||||
snapshot.account_schedule_duty(
|
||||
account_id,
|
||||
std::time::SystemTime::now(),
|
||||
quota.daily_used_percent,
|
||||
)
|
||||
}),
|
||||
model_cooldowns: stored.model_cooldowns,
|
||||
platform_icon: stored.platform_icon,
|
||||
protection_rules: stored.protection_rules,
|
||||
@@ -625,6 +639,7 @@ impl AccountsService for DefaultAccountsService {
|
||||
self.attach_quota_local_usage(&page.items, &mut quotas)
|
||||
.await?;
|
||||
let mut api_key_usage = self.load_api_key_usage(&page.items, "as).await?;
|
||||
let published = self.published.snapshot_for_diagnostics();
|
||||
let items = page
|
||||
.items
|
||||
.into_iter()
|
||||
@@ -649,6 +664,9 @@ impl AccountsService for DefaultAccountsService {
|
||||
lookback,
|
||||
);
|
||||
Ok(AccountDirectoryItem {
|
||||
schedule_duty: published.as_ref().and_then(|snapshot| {
|
||||
snapshot.account_schedule_duty(&id, now.into(), quota.daily_used_percent)
|
||||
}),
|
||||
model_cooldowns: item.model_cooldowns,
|
||||
platform_icon: item.platform_icon,
|
||||
protection_rules: item.protection_rules,
|
||||
@@ -692,30 +710,40 @@ impl AccountsService for DefaultAccountsService {
|
||||
if account_ids.is_empty() || account_ids.len() > 200 {
|
||||
return Err(AdminError::invalid("账号导出数量必须在 1 到 200 之间"));
|
||||
}
|
||||
let exported_ids = account_ids.clone();
|
||||
if account_ids.iter().collect::<BTreeSet<_>>().len() != account_ids.len() {
|
||||
return Err(AdminError::invalid("账号导出列表包含重复 ID"));
|
||||
}
|
||||
let mut scopes = self
|
||||
.accounts
|
||||
.credential_export_scopes(&account_ids)
|
||||
.await
|
||||
.map_err(|error| map_store_error(error, "provider account export"))?;
|
||||
let mut grouped = BTreeMap::new();
|
||||
// 混选时先检查每个账号的导出能力,再读取任何一组明文凭据
|
||||
for id in account_ids {
|
||||
let (item, provider) = self.provider_for_account(&id).await?;
|
||||
for id in &account_ids {
|
||||
let scope = scopes
|
||||
.remove(id.as_str())
|
||||
.ok_or_else(|| AdminError::not_found("服务商账号不存在"))?;
|
||||
let provider = self
|
||||
.providers
|
||||
.require(&scope.provider_kind)
|
||||
.map_err(|error| map_provider_error(error, "provider account"))?;
|
||||
if !provider
|
||||
.account_capabilities(&id, &item.account.authentication_kind)
|
||||
.account_capabilities(id, &scope.authentication_kind)
|
||||
.credential_export
|
||||
{
|
||||
return Err(AdminError::invalid("所选账号不支持导出"));
|
||||
}
|
||||
let (_, ids) = grouped
|
||||
.entry(item.account.provider_kind)
|
||||
let (_, accounts) = grouped
|
||||
.entry(scope.provider_kind)
|
||||
.or_insert_with(|| (provider, Vec::new()));
|
||||
if ids.contains(&id) {
|
||||
return Err(AdminError::invalid("账号导出列表包含重复 ID"));
|
||||
}
|
||||
ids.push(id);
|
||||
accounts.push((id.clone(), scope.authentication_kind));
|
||||
}
|
||||
let mut documents = Vec::with_capacity(grouped.len());
|
||||
for (provider_kind, (provider, ids)) in grouped {
|
||||
for (provider_kind, (provider, accounts)) in grouped {
|
||||
let credentials = self
|
||||
.accounts
|
||||
.load_credentials_for_export(&provider_kind, &ids)
|
||||
.load_credentials_for_export(&provider_kind, &accounts)
|
||||
.await
|
||||
.map_err(|error| map_store_error(error, "provider account export"))?;
|
||||
documents.push(
|
||||
@@ -726,7 +754,7 @@ impl AccountsService for DefaultAccountsService {
|
||||
);
|
||||
}
|
||||
self.accounts
|
||||
.record_credential_export(&exported_ids, context)
|
||||
.record_credential_export(&account_ids, context)
|
||||
.await
|
||||
.map_err(|error| map_store_error(error, "provider account export audit"))?;
|
||||
Ok(AccountExportBundle {
|
||||
@@ -759,7 +787,7 @@ impl AccountsService for DefaultAccountsService {
|
||||
super::notify_account_facts_changed(
|
||||
self.upstream_info.as_deref(),
|
||||
provider.as_ref(),
|
||||
std::slice::from_ref(&result.account_id),
|
||||
AccountFactsChange::updated(std::slice::from_ref(&result.account_id)),
|
||||
)
|
||||
.await;
|
||||
publish_committed(self.snapshot.as_ref(), result.config_revision).await?;
|
||||
@@ -807,7 +835,7 @@ impl AccountsService for DefaultAccountsService {
|
||||
super::notify_account_facts_changed(
|
||||
self.upstream_info.as_deref(),
|
||||
provider.as_ref(),
|
||||
std::slice::from_ref(&account_id),
|
||||
AccountFactsChange::updated(std::slice::from_ref(&account_id)),
|
||||
)
|
||||
.await;
|
||||
publish_committed(self.snapshot.as_ref(), config_revision).await?;
|
||||
@@ -843,7 +871,7 @@ impl AccountsService for DefaultAccountsService {
|
||||
super::notify_account_facts_changed(
|
||||
self.upstream_info.as_deref(),
|
||||
provider.as_ref(),
|
||||
std::slice::from_ref(&account_id),
|
||||
AccountFactsChange::updated(std::slice::from_ref(&account_id)),
|
||||
)
|
||||
.await;
|
||||
publish_committed(self.snapshot.as_ref(), result.config_revision).await?;
|
||||
@@ -961,7 +989,7 @@ impl AccountsService for DefaultAccountsService {
|
||||
super::notify_account_facts_changed(
|
||||
self.upstream_info.as_deref(),
|
||||
provider.as_ref(),
|
||||
provider_ids,
|
||||
AccountFactsChange::updated(provider_ids),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
@@ -974,7 +1002,7 @@ impl AccountsService for DefaultAccountsService {
|
||||
self.upstream_info.as_ref(),
|
||||
&provider,
|
||||
&self.accounts,
|
||||
&exhausted,
|
||||
AccountFactsChange::updated(&exhausted),
|
||||
context.request_id.as_str(),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -12,7 +12,10 @@ use crate::{
|
||||
ProviderQuotaRequest, StartAuthorization,
|
||||
},
|
||||
},
|
||||
ports::{provider::ProviderAdmin, store::AccountStore},
|
||||
ports::{
|
||||
provider::{AccountFactsChange, ProviderAdmin},
|
||||
store::AccountStore,
|
||||
},
|
||||
};
|
||||
use gateway_core::{account::ProviderAccountId, routing::ProviderKind, runtime::SnapshotControl};
|
||||
|
||||
@@ -24,13 +27,13 @@ pub(super) async fn publish_credentials_and_observe_quota(
|
||||
accounts: &std::sync::Arc<dyn AccountStore>,
|
||||
snapshot: &dyn SnapshotControl,
|
||||
revision: crate::model::Revision,
|
||||
account_ids: &[ProviderAccountId],
|
||||
change: AccountFactsChange<'_>,
|
||||
request_id: &str,
|
||||
) -> Result<(), AdminError> {
|
||||
notify_account_facts_changed(peer.map(AsRef::as_ref), provider.as_ref(), account_ids).await;
|
||||
notify_account_facts_changed(peer.map(AsRef::as_ref), provider.as_ref(), change).await;
|
||||
publish_committed(snapshot, revision).await?;
|
||||
|
||||
observe_account_quotas(peer, provider, accounts, account_ids, request_id);
|
||||
observe_account_quotas(peer, provider, accounts, change, request_id);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -38,49 +41,59 @@ 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 ids = change.ids.to_vec();
|
||||
let created_ids = change.created_ids.clone();
|
||||
let request_id = request_id.to_owned();
|
||||
tokio::spawn(async move {
|
||||
for account_id in account_ids {
|
||||
let change = AccountFactsChange {
|
||||
ids: &ids,
|
||||
created_ids: &created_ids,
|
||||
};
|
||||
let mut seen = std::collections::BTreeSet::new();
|
||||
for account_id in provider.quota_observation_targets(change).await {
|
||||
if !seen.insert(account_id.clone()) {
|
||||
continue;
|
||||
}
|
||||
let account = match accounts.load_account_record(&account_id).await {
|
||||
Ok(Some(account)) if &account.provider_kind == provider.provider_kind() => account,
|
||||
Ok(_) => continue,
|
||||
Err(error) => {
|
||||
tracing::warn!(request_id, account_id = %account_id, error = %error, "quota observation account lookup failed");
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let can_refresh = if peer.is_some()
|
||||
&& provider.supports_peer_connection(&account.authentication_kind)
|
||||
{
|
||||
account.enabled
|
||||
} else {
|
||||
provider
|
||||
.account_capabilities(&account_id, &account.authentication_kind)
|
||||
.quota_refresh
|
||||
};
|
||||
if !can_refresh {
|
||||
continue;
|
||||
}
|
||||
let request = ProviderQuotaRequest {
|
||||
account_id: account_id.clone(),
|
||||
refresh: true,
|
||||
rolling_usage: None,
|
||||
};
|
||||
let result = if let Some(peer) = peer.as_deref() {
|
||||
let account = match accounts.load_account_record(&account_id).await {
|
||||
Ok(Some(account)) => account,
|
||||
Ok(None) => continue,
|
||||
Err(error) => {
|
||||
tracing::warn!(request_id, account_id = %account_id, error = %error, "quota observation account lookup failed");
|
||||
continue;
|
||||
}
|
||||
};
|
||||
if &account.provider_kind != provider.provider_kind()
|
||||
|| (!account.enabled
|
||||
&& provider.supports_peer_connection(&account.authentication_kind))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
// 后台查询与手动刷新共用认证能力分派,互联协议由 Admin 解释
|
||||
super::peer_link::upstream::read_quota(
|
||||
Some(peer),
|
||||
provider.as_ref(),
|
||||
&account,
|
||||
request,
|
||||
)
|
||||
.await
|
||||
} else {
|
||||
provider.quota(request).await
|
||||
};
|
||||
if let Err(error) = result {
|
||||
if let Err(error) = super::peer_link::upstream::read_quota(
|
||||
peer.as_deref(),
|
||||
provider.as_ref(),
|
||||
&account,
|
||||
request,
|
||||
)
|
||||
.await
|
||||
{
|
||||
tracing::warn!(
|
||||
request_id,
|
||||
provider = %provider.provider_kind().as_str(),
|
||||
@@ -292,7 +305,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 +418,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 +428,11 @@ pub(super) async fn delete_credentials(
|
||||
pub(super) async fn notify_account_facts_changed(
|
||||
peer: Option<&dyn crate::ports::peer::PeerUpstreamService>,
|
||||
provider: &dyn ProviderAdmin,
|
||||
ids: &[ProviderAccountId],
|
||||
change: AccountFactsChange<'_>,
|
||||
) {
|
||||
provider.account_facts_changed(ids).await;
|
||||
provider.account_facts_changed(change).await;
|
||||
if let Some(peer) = peer {
|
||||
for id in ids {
|
||||
for id in change.ids {
|
||||
if let Err(error) = peer.account_changed(id).await {
|
||||
tracing::warn!(account_id = %id, error = %error, "upstream information cache invalidation failed");
|
||||
}
|
||||
|
||||
@@ -9,13 +9,16 @@ use crate::{
|
||||
AdminError,
|
||||
provider_credentials::{
|
||||
AuthorizationCommitResult, AuthorizationReceiptKey, AuthorizationStarted,
|
||||
CompleteAuthorization, CredentialDeletion, CredentialDeletionResult,
|
||||
CompleteAuthorization, CredentialChange, CredentialDeletion, CredentialDeletionResult,
|
||||
CredentialImportCommit, CredentialImportResult, CredentialMutationResult,
|
||||
ImportCredentials, PrepareCredentialImport, PrepareCredentialRotation,
|
||||
RotateCredential, StartAuthorization,
|
||||
},
|
||||
},
|
||||
ports::{provider::ProviderAdmin, store::AccountStore},
|
||||
ports::{
|
||||
provider::{AccountFactsChange, ProviderAdmin},
|
||||
store::AccountStore,
|
||||
},
|
||||
};
|
||||
|
||||
use super::super::{
|
||||
@@ -97,7 +100,10 @@ impl ProviderCredentials {
|
||||
&self.accounts,
|
||||
self.snapshot.as_ref(),
|
||||
result.config_revision,
|
||||
&result.credential_ids,
|
||||
AccountFactsChange {
|
||||
ids: &result.credential_ids,
|
||||
created_ids: &result.created_ids,
|
||||
},
|
||||
&context.request_id,
|
||||
)
|
||||
.await?;
|
||||
@@ -175,7 +181,7 @@ impl ProviderCredentials {
|
||||
super::super::notify_account_facts_changed(
|
||||
self.upstream_info.as_deref(),
|
||||
self.provider.as_ref(),
|
||||
std::slice::from_ref(&result.account_id),
|
||||
AccountFactsChange::updated(std::slice::from_ref(&result.account_id)),
|
||||
)
|
||||
.await;
|
||||
publish_committed(self.snapshot.as_ref(), result.config_revision).await?;
|
||||
@@ -248,14 +254,23 @@ impl super::CredentialsService {
|
||||
request_id: &str,
|
||||
) -> Result<CredentialMutationResult, AdminError> {
|
||||
let result = outcome.result;
|
||||
if outcome.newly_committed {
|
||||
if let Some(change) = outcome.change {
|
||||
let ids = std::slice::from_ref(&result.account_id);
|
||||
let created_ids = (change == CredentialChange::Created)
|
||||
.then(|| result.account_id.clone())
|
||||
.into_iter()
|
||||
.collect();
|
||||
let change = AccountFactsChange {
|
||||
ids,
|
||||
created_ids: &created_ids,
|
||||
};
|
||||
publish_credentials_and_observe_quota(
|
||||
self.upstream_info.as_ref(),
|
||||
provider,
|
||||
&self.accounts,
|
||||
self.snapshot.as_ref(),
|
||||
result.config_revision,
|
||||
std::slice::from_ref(&result.account_id),
|
||||
change,
|
||||
request_id,
|
||||
)
|
||||
.await?;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! 管理控制面的用例实现
|
||||
|
||||
pub mod account_groups;
|
||||
pub mod account_schedules;
|
||||
pub mod accounts;
|
||||
pub mod auth;
|
||||
pub mod backup;
|
||||
|
||||
@@ -17,7 +17,7 @@ use crate::{
|
||||
model::{
|
||||
AdminError,
|
||||
peer_link::{PeerLinkExport, PeerLinkLimits},
|
||||
provider_credentials::{ProviderQuotaReadRequest, explicit_plan_type},
|
||||
provider_credentials::ProviderQuotaReadRequest,
|
||||
},
|
||||
ports::{
|
||||
provider::ProviderAdminRegistry,
|
||||
@@ -200,9 +200,15 @@ impl PeerLinkService for DefaultPeerLinkService {
|
||||
let mut window_count = 0usize;
|
||||
let mut by_provider = BTreeMap::new();
|
||||
for account in &accounts {
|
||||
// 仅公开套餐时只补读缺失套餐的本地额度,不回源刷新或扩大公开范围
|
||||
// 部分 Provider 从额度快照读取套餐展示名,仅有账号套餐 ID 仍需补读
|
||||
if !sharing.share_quota
|
||||
&& explicit_plan_type(account.plan_type.as_deref()).is_some()
|
||||
&& self
|
||||
.providers
|
||||
.plan_type_display(
|
||||
account.provider_kind.as_str(),
|
||||
account.plan_type.as_deref(),
|
||||
)
|
||||
.is_some()
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -320,6 +320,13 @@ fn model_observation(
|
||||
reset.min(observed_at + TimeDelta::minutes(30))
|
||||
})
|
||||
.min(now + TimeDelta::minutes(5));
|
||||
let expires_at = if let Some(deadline) = account.quota.exhaustion_deadline()
|
||||
&& account.quota.is_exhausted()
|
||||
{
|
||||
expires_at.min(deadline.into())
|
||||
} else {
|
||||
expires_at
|
||||
};
|
||||
if observed_at > now || expires_at <= now {
|
||||
return None;
|
||||
}
|
||||
|
||||
@@ -214,6 +214,7 @@ impl PeerInfoService {
|
||||
}
|
||||
}
|
||||
ProviderQuota {
|
||||
daily_used_percent: None,
|
||||
paused_windows: Vec::new(),
|
||||
upstream: Some(info),
|
||||
plan_type: None,
|
||||
|
||||
@@ -172,6 +172,7 @@ impl PeerInfoService {
|
||||
.and_then(|peer| quota::observe(&peer, started_at, now))
|
||||
.unwrap_or(QuotaState::unknown());
|
||||
let observation = QuotaObservation {
|
||||
merge_base: None,
|
||||
quota_pause: None,
|
||||
expected_connection: Some(connection.clone()),
|
||||
account_id: id.clone(),
|
||||
|
||||
@@ -19,6 +19,8 @@ use crate::{
|
||||
},
|
||||
};
|
||||
|
||||
use crate::ports::provider::AccountFactsChange;
|
||||
|
||||
use super::{
|
||||
map_provider_error, map_store_error, publish_credentials_and_observe_quota,
|
||||
required_credential, required_plugin_credential, validate_prepared_import,
|
||||
@@ -218,7 +220,10 @@ impl PluginAccountAccess for DefaultPluginAccountAccess {
|
||||
&self.accounts,
|
||||
self.snapshot.as_ref(),
|
||||
result.config_revision,
|
||||
std::slice::from_ref(&account_id),
|
||||
AccountFactsChange {
|
||||
ids: &result.credential_ids,
|
||||
created_ids: &result.created_ids,
|
||||
},
|
||||
&context.request_id,
|
||||
)
|
||||
.await?;
|
||||
@@ -263,7 +268,7 @@ impl PluginAccountAccess for DefaultPluginAccountAccess {
|
||||
&self.accounts,
|
||||
self.snapshot.as_ref(),
|
||||
result.config_revision,
|
||||
std::slice::from_ref(&result.account_id),
|
||||
AccountFactsChange::updated(std::slice::from_ref(&result.account_id)),
|
||||
&context.request_id,
|
||||
)
|
||||
.await?;
|
||||
|
||||
@@ -170,7 +170,7 @@ impl SettingsService for DefaultSettingsService {
|
||||
) -> Result<crate::model::pricing::PricingSyncPreview, AdminError> {
|
||||
let scope = self.providers.pricing_source_scope();
|
||||
let prices = self.pricing_source.fetch(&scope).await?;
|
||||
Ok(scope.project(prices))
|
||||
scope.project(prices)
|
||||
}
|
||||
|
||||
async fn sync_pricing(
|
||||
@@ -412,12 +412,24 @@ impl SettingsService for DefaultSettingsService {
|
||||
))
|
||||
})?;
|
||||
}
|
||||
if !command.request_profile_updates.is_empty() {
|
||||
if !command.request_profile_updates.is_empty()
|
||||
|| !command.values.provider_settings.is_empty()
|
||||
{
|
||||
let current = self
|
||||
.store
|
||||
.load_runtime_settings()
|
||||
.await
|
||||
.map_err(|error| map_store_error(error, "runtime settings"))?;
|
||||
command.values.provider_settings.retain(|kind, settings| {
|
||||
current.values.provider_settings.get(kind) != Some(settings)
|
||||
});
|
||||
for (kind, settings) in &command.values.provider_settings {
|
||||
self.providers
|
||||
.require(kind)
|
||||
.map_err(|error| super::map_provider_error(error, "provider settings"))?
|
||||
.validate_settings(settings)
|
||||
.map_err(|error| super::map_provider_error(error, "provider settings"))?;
|
||||
}
|
||||
for (kind, update) in &command.request_profile_updates {
|
||||
let provider = self
|
||||
.providers
|
||||
|
||||
@@ -106,6 +106,7 @@ fn provider_document_debug_should_not_expose_opaque_material() {
|
||||
#[test]
|
||||
fn representative_quota_should_prefer_short_window_and_highest_usage() {
|
||||
let quota = ProviderQuota {
|
||||
daily_used_percent: None,
|
||||
paused_windows: Vec::new(),
|
||||
upstream: None,
|
||||
credits: None,
|
||||
@@ -131,6 +132,7 @@ fn representative_quota_should_prefer_account_wide_window_over_model_specific_wi
|
||||
let mut model_specific = quota_window("shortTerm", Some(18_000), Some(64.0));
|
||||
model_specific.local_usage_attribution = QuotaLocalUsageAttribution::Unavailable;
|
||||
let quota = ProviderQuota {
|
||||
daily_used_percent: None,
|
||||
paused_windows: Vec::new(),
|
||||
upstream: None,
|
||||
credits: None,
|
||||
@@ -152,6 +154,7 @@ fn representative_quota_should_prefer_account_wide_window_over_model_specific_wi
|
||||
#[test]
|
||||
fn account_exhaustion_preserves_measured_and_unknown_window_usage() {
|
||||
let mut quota = ProviderQuota {
|
||||
daily_used_percent: None,
|
||||
paused_windows: Vec::new(),
|
||||
upstream: None,
|
||||
credits: None,
|
||||
@@ -183,6 +186,7 @@ fn exhausted_quota_should_preserve_the_provider_identified_reached_window() {
|
||||
let mut reached = quota_window("monthly", Some(2_592_000), Some(98.0));
|
||||
reached.limit_reached = true;
|
||||
let mut quota = ProviderQuota {
|
||||
daily_used_percent: None,
|
||||
paused_windows: Vec::new(),
|
||||
upstream: None,
|
||||
credits: None,
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
//! 排班分钟采样在部署时区的跳时和重复时刻重新对齐
|
||||
|
||||
use chrono::{DateTime, TimeDelta, Utc};
|
||||
use gateway_admin::model::account_schedules::ScheduleClock;
|
||||
|
||||
#[test]
|
||||
fn clock_expires_at_both_dst_boundaries() {
|
||||
let zone = "America/New_York".parse().unwrap();
|
||||
for (sample, before, after) in [
|
||||
("2026-03-08T06:59:44.500Z", 119, 180),
|
||||
("2026-11-01T05:59:44.500Z", 119, 60),
|
||||
] {
|
||||
let at: DateTime<Utc> = sample.parse().unwrap();
|
||||
let clock = ScheduleClock::at(at, zone);
|
||||
assert_eq!(clock.minute, before);
|
||||
assert_eq!(clock.valid_for_millis, 15_500);
|
||||
let next = ScheduleClock::at(at + TimeDelta::milliseconds(clock.valid_for_millis), zone);
|
||||
assert_eq!(next.minute, after);
|
||||
assert_eq!(next.valid_for_millis, 86_400_000);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
//! 模型模块测试:镜像 src/model/ 中带逻辑的模块
|
||||
|
||||
mod account_groups;
|
||||
mod account_schedules;
|
||||
mod audit;
|
||||
mod backup;
|
||||
mod client_keys;
|
||||
|
||||
@@ -116,6 +116,7 @@ fn selected_usage_window(quota: &ProviderQuota) -> Option<(&str, AccountUsagePer
|
||||
|
||||
fn usage_quota(windows: Vec<ProviderQuotaWindow>) -> ProviderQuota {
|
||||
ProviderQuota {
|
||||
daily_used_percent: None,
|
||||
paused_windows: Vec::new(),
|
||||
upstream: None,
|
||||
credits: None,
|
||||
@@ -170,6 +171,7 @@ fn usage_window(key: &str, group: &str, seconds: u64) -> ProviderQuotaWindow {
|
||||
#[test]
|
||||
fn dashboard_quota_should_preserve_unknown_and_actual_window_facts() {
|
||||
let mut quota = ProviderQuota {
|
||||
daily_used_percent: None,
|
||||
paused_windows: Vec::new(),
|
||||
upstream: None,
|
||||
credits: None,
|
||||
|
||||
@@ -59,6 +59,7 @@ fn window(key: &str, days: u64) -> ProviderQuotaWindow {
|
||||
|
||||
fn quota(windows: Vec<ProviderQuotaWindow>) -> ProviderQuota {
|
||||
ProviderQuota {
|
||||
daily_used_percent: None,
|
||||
paused_windows: Vec::new(),
|
||||
upstream: None,
|
||||
credits: None,
|
||||
|
||||
@@ -40,17 +40,17 @@ use gateway_admin::{
|
||||
provider_credentials::{
|
||||
AuthorizationCommit, AuthorizationCommitGuard, AuthorizationCredentialCommit,
|
||||
AuthorizationMutationTarget, AuthorizationStarted, CompleteAuthorization,
|
||||
ConsumeProviderResetCredit, CredentialCommitGuard, CredentialDetails,
|
||||
CredentialImportCommit, CredentialImportResult, CredentialMutationResult,
|
||||
CredentialRotationCommit, PendingAuthorizationMutation, PrepareCredentialImport,
|
||||
PrepareCredentialRefresh, PrepareCredentialRotation, PreparedAuthorizationCommit,
|
||||
PreparedAuthorizationCredential, PreparedCredentialCreate, PreparedCredentialImport,
|
||||
PreparedCredentialRotation, PreparedCredentialRotationFacts, PreparedPluginAccountSave,
|
||||
ProviderDocument, ProviderExport, ProviderExportCredentialInput, ProviderModels,
|
||||
ProviderProfileActivityInsights, ProviderProfileStatistics,
|
||||
ProviderProfileStatisticsSummary, ProviderQuota, ProviderQuotaRequest,
|
||||
ProviderQuotaWindow, ProviderResetCreditResult, ProviderSubscription,
|
||||
QuotaLocalUsageAttribution,
|
||||
ConsumeProviderResetCredit, CredentialChange, CredentialCommitGuard, CredentialDetails,
|
||||
CredentialExportScope, CredentialImportCommit, CredentialImportResult,
|
||||
CredentialMutationResult, CredentialRotationCommit, PendingAuthorizationMutation,
|
||||
PrepareCredentialImport, PrepareCredentialRefresh, PrepareCredentialRotation,
|
||||
PreparedAuthorizationCommit, PreparedAuthorizationCredential, PreparedCredentialCreate,
|
||||
PreparedCredentialImport, PreparedCredentialRotation, PreparedCredentialRotationFacts,
|
||||
PreparedPluginAccountSave, ProviderDocument, ProviderExport,
|
||||
ProviderExportCredentialInput, ProviderModels, ProviderProfileActivityInsights,
|
||||
ProviderProfileStatistics, ProviderProfileStatisticsSummary, ProviderQuota,
|
||||
ProviderQuotaRequest, ProviderQuotaWindow, ProviderResetCreditResult,
|
||||
ProviderSubscription, QuotaLocalUsageAttribution,
|
||||
},
|
||||
quota_forecast::{QuotaForecastHistory, QuotaForecastUsage},
|
||||
settings::{
|
||||
@@ -83,7 +83,7 @@ pub(super) struct FakeProviderAdmin {
|
||||
pending: Arc<Mutex<Option<PendingAuthorizationMutation>>>,
|
||||
retry_authorization_after_abort: Mutex<bool>,
|
||||
export_inputs: Mutex<Vec<ProviderExportCredentialInput>>,
|
||||
import_account_ids: Mutex<Vec<String>>,
|
||||
import_accounts: Mutex<Vec<(&'static str, &'static str)>>,
|
||||
quota_requests: Mutex<Vec<ProviderQuotaRequest>>,
|
||||
quota_started: tokio::sync::Notify,
|
||||
quota_gate: Mutex<Option<tokio::sync::oneshot::Receiver<()>>>,
|
||||
@@ -106,7 +106,12 @@ impl FakeProviderAdmin {
|
||||
Arc::new(Self {
|
||||
kind: ProviderKind::new(kind).expect("provider kind"),
|
||||
usage_lookback: Mutex::default(),
|
||||
capabilities: Mutex::default(),
|
||||
capabilities: Mutex::new(
|
||||
gateway_admin::model::accounts::ProviderAccountCapabilities {
|
||||
quota_refresh: true,
|
||||
..Default::default()
|
||||
},
|
||||
),
|
||||
events,
|
||||
failure: Mutex::new(None),
|
||||
import_gate: Mutex::new(None),
|
||||
@@ -114,7 +119,7 @@ impl FakeProviderAdmin {
|
||||
pending: Arc::new(Mutex::new(None)),
|
||||
retry_authorization_after_abort: Mutex::new(false),
|
||||
export_inputs: Mutex::new(Vec::new()),
|
||||
import_account_ids: Mutex::new(vec!["acct_prepared".to_owned()]),
|
||||
import_accounts: Mutex::new(vec![("acct_prepared", "oauth")]),
|
||||
quota_requests: Mutex::new(Vec::new()),
|
||||
quota_started: tokio::sync::Notify::new(),
|
||||
quota_gate: Mutex::new(None),
|
||||
@@ -172,14 +177,11 @@ impl FakeProviderAdmin {
|
||||
*self.quota_failure.lock().expect("provider quota failure") = Some(kind);
|
||||
}
|
||||
|
||||
pub(super) fn set_import_account_ids(&self, account_ids: &[&str]) {
|
||||
pub(super) fn set_import_accounts(&self, accounts: &[(&'static str, &'static str)]) {
|
||||
*self
|
||||
.import_account_ids
|
||||
.import_accounts
|
||||
.lock()
|
||||
.expect("provider import account IDs") = account_ids
|
||||
.iter()
|
||||
.map(|account_id| (*account_id).to_owned())
|
||||
.collect();
|
||||
.expect("provider import accounts") = accounts.to_vec();
|
||||
}
|
||||
|
||||
pub(super) fn quota_requests(&self) -> Vec<ProviderQuotaRequest> {
|
||||
@@ -267,6 +269,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(),
|
||||
@@ -290,15 +293,20 @@ impl ProviderAdmin for FakeProviderAdmin {
|
||||
}
|
||||
|
||||
fn peer_authentication_kinds(&self) -> &[&str] {
|
||||
&["api_key"]
|
||||
match self.kind.as_str() {
|
||||
"openai" => &["api_key"],
|
||||
_ => &[],
|
||||
}
|
||||
}
|
||||
|
||||
fn account_capabilities(
|
||||
&self,
|
||||
_account_id: &ProviderAccountId,
|
||||
_authentication_kind: &str,
|
||||
authentication_kind: &str,
|
||||
) -> gateway_admin::model::accounts::ProviderAccountCapabilities {
|
||||
*self.capabilities.lock().unwrap()
|
||||
let mut capabilities = *self.capabilities.lock().unwrap();
|
||||
capabilities.quota_refresh &= authentication_kind == "oauth";
|
||||
capabilities
|
||||
}
|
||||
fn provider_kind(&self) -> &ProviderKind {
|
||||
&self.kind
|
||||
@@ -346,7 +354,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");
|
||||
}
|
||||
|
||||
@@ -396,17 +407,20 @@ impl ProviderAdmin for FakeProviderAdmin {
|
||||
gate.acquire().await.expect("import permit").forget();
|
||||
}
|
||||
self.require_available()?;
|
||||
let account_ids = self
|
||||
.import_account_ids
|
||||
let accounts = self
|
||||
.import_accounts
|
||||
.lock()
|
||||
.expect("provider import account IDs")
|
||||
.expect("provider import accounts")
|
||||
.clone();
|
||||
Ok(PreparedCredentialImport {
|
||||
provider_kind: self.kind.clone(),
|
||||
credentials: account_ids
|
||||
credentials: accounts
|
||||
.into_iter()
|
||||
.map(|account_id| {
|
||||
prepared_create_with_id(self.kind.clone(), &account_id, "prepared-import")
|
||||
.map(|(account_id, authentication_kind)| {
|
||||
let mut credential =
|
||||
prepared_create_with_id(self.kind.clone(), account_id, "prepared-import");
|
||||
credential.authentication_kind = authentication_kind.into();
|
||||
credential
|
||||
})
|
||||
.collect(),
|
||||
})
|
||||
@@ -639,6 +653,23 @@ pub(super) struct FakeAccountStore {
|
||||
}
|
||||
|
||||
impl FakeAccountStore {
|
||||
fn insert_new_credential(&self, credential: &PreparedCredentialCreate) {
|
||||
let mut accounts = self.accounts.lock().unwrap();
|
||||
if accounts
|
||||
.iter()
|
||||
.any(|a| a.id == credential.account_id.as_str())
|
||||
{
|
||||
return;
|
||||
}
|
||||
let mut account = account_record(credential.provider_kind.as_str());
|
||||
account.id = credential.account_id.to_string();
|
||||
account
|
||||
.authentication_kind
|
||||
.clone_from(&credential.authentication_kind);
|
||||
account.enabled = credential.enabled;
|
||||
accounts.push(account);
|
||||
}
|
||||
|
||||
pub(super) fn new(kind: &str, events: EventLog) -> Arc<Self> {
|
||||
Self::with_account(account_record(kind), events)
|
||||
}
|
||||
@@ -935,32 +966,59 @@ impl AccountStore for FakeAccountStore {
|
||||
}))
|
||||
}
|
||||
|
||||
async fn credential_export_scopes(
|
||||
&self,
|
||||
ids: &[ProviderAccountId],
|
||||
) -> AdminStoreResult<BTreeMap<String, CredentialExportScope>> {
|
||||
self.record("store.credential_export_scopes");
|
||||
Ok(self
|
||||
.accounts
|
||||
.lock()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter(|account| ids.iter().any(|id| id.as_str() == account.id))
|
||||
.map(|account| {
|
||||
(
|
||||
account.id.clone(),
|
||||
CredentialExportScope {
|
||||
provider_kind: account.provider_kind.clone(),
|
||||
authentication_kind: account.authentication_kind.clone(),
|
||||
},
|
||||
)
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
async fn load_credentials_for_export(
|
||||
&self,
|
||||
provider_kind: &ProviderKind,
|
||||
account_ids: &[ProviderAccountId],
|
||||
selected: &[(ProviderAccountId, String)],
|
||||
) -> AdminStoreResult<Vec<ProviderExportCredentialInput>> {
|
||||
self.record("store.load_credentials_for_export");
|
||||
let accounts = self.accounts.lock().expect("accounts").clone();
|
||||
if accounts.iter().any(|account| {
|
||||
&account.provider_kind != provider_kind
|
||||
|| !account_ids
|
||||
let accounts = self.accounts.lock().expect("accounts");
|
||||
selected
|
||||
.iter()
|
||||
.map(|(id, auth)| {
|
||||
let account = accounts
|
||||
.iter()
|
||||
.any(|account_id| account_id.as_str() == account.id)
|
||||
}) {
|
||||
return Err(AdminStoreError::new(
|
||||
AdminStoreErrorKind::NotFound,
|
||||
"test account",
|
||||
"credential not found",
|
||||
));
|
||||
}
|
||||
Ok(accounts
|
||||
.into_iter()
|
||||
.map(|account| ProviderExportCredentialInput {
|
||||
account,
|
||||
provider_material: document(),
|
||||
.find(|account| {
|
||||
account.id == id.as_str()
|
||||
&& &account.provider_kind == provider_kind
|
||||
&& &account.authentication_kind == auth
|
||||
})
|
||||
.ok_or_else(|| {
|
||||
AdminStoreError::new(
|
||||
AdminStoreErrorKind::NotFound,
|
||||
"test account",
|
||||
"credential not found",
|
||||
)
|
||||
})?;
|
||||
Ok(ProviderExportCredentialInput {
|
||||
account: account.clone(),
|
||||
provider_material: document(),
|
||||
})
|
||||
})
|
||||
.collect())
|
||||
.collect()
|
||||
}
|
||||
|
||||
async fn load_credential_for_plugin(
|
||||
@@ -993,7 +1051,16 @@ impl AccountStore for FakeAccountStore {
|
||||
self.record("store.commit_import");
|
||||
self.record_context(context);
|
||||
self.require_commit()?;
|
||||
for credential in &command.prepared.credentials {
|
||||
self.insert_new_credential(credential);
|
||||
}
|
||||
Ok(CredentialImportResult {
|
||||
created_ids: command
|
||||
.prepared
|
||||
.credentials
|
||||
.iter()
|
||||
.map(|c| c.account_id.clone())
|
||||
.collect(),
|
||||
config_revision: revision(2),
|
||||
credential_ids: command
|
||||
.prepared
|
||||
@@ -1018,18 +1085,22 @@ 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) => {
|
||||
self.insert_new_credential(&credential);
|
||||
(credential.account_id, None, CredentialChange::Created)
|
||||
}
|
||||
AuthorizationCredentialCommit::Reauthorize(credential) => (
|
||||
credential.account_id,
|
||||
Some(revision(credential.expected_credential_revision.get() + 1)),
|
||||
CredentialChange::Updated,
|
||||
),
|
||||
};
|
||||
let result = CredentialMutationResult {
|
||||
@@ -1044,7 +1115,7 @@ impl AccountStore for FakeAccountStore {
|
||||
Ok(
|
||||
gateway_admin::model::provider_credentials::AuthorizationCommitResult {
|
||||
result,
|
||||
newly_committed: true,
|
||||
change: Some(change),
|
||||
},
|
||||
)
|
||||
}
|
||||
@@ -1165,7 +1236,7 @@ impl AccountStore for FakeAccountStore {
|
||||
) -> AdminStoreResult<()> {
|
||||
self.record("store.audit_export");
|
||||
self.record_context(context);
|
||||
Ok(())
|
||||
self.require_commit()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1202,6 +1273,7 @@ impl SettingsStore for StaticSettingsStore {
|
||||
rotation_strategy: RotationStrategy::Smart,
|
||||
updated_at: Utc::now(),
|
||||
values: gateway_admin::model::settings::RuntimeSettingsValues {
|
||||
provider_settings: Default::default(),
|
||||
openai_websocket_pool: Default::default(),
|
||||
openai_request_settings: gateway_core::settings::OpenAiRequestSettings {
|
||||
oauth_guardian_review_model: false,
|
||||
@@ -1483,22 +1555,43 @@ async fn connection_test_should_preserve_disabled_account_status() {
|
||||
#[tokio::test]
|
||||
async fn unsupported_account_export_stops_before_loading_credentials() {
|
||||
let calls = events();
|
||||
let provider = FakeProviderAdmin::new("fixture", calls.clone());
|
||||
let store = FakeAccountStore::new("fixture", calls.clone());
|
||||
let id = ProviderAccountId::new(store.accounts.lock().unwrap()[0].id.clone()).unwrap();
|
||||
let services = accounts_service(provider, store).await;
|
||||
let error = services
|
||||
.accounts()
|
||||
.export(&context("export-unsupported"), vec![id])
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(error.kind(), gateway_admin::model::AdminErrorKind::Invalid);
|
||||
assert!(
|
||||
!calls
|
||||
.lock()
|
||||
.unwrap()
|
||||
.contains(&"store.load_credentials_for_export")
|
||||
);
|
||||
let supported = FakeProviderAdmin::new("openai", calls.clone());
|
||||
supported.capabilities.lock().unwrap().credential_export = true;
|
||||
let unsupported = FakeProviderAdmin::new("fixture", calls.clone());
|
||||
let store = FakeAccountStore::new("openai", calls.clone());
|
||||
let mut another = account_record("fixture");
|
||||
another.id = "acct_unsupported".into();
|
||||
store.accounts.lock().unwrap().push(another);
|
||||
let services = super::AdminHarness::new()
|
||||
.accounts(store)
|
||||
.provider(supported)
|
||||
.provider(unsupported)
|
||||
.build()
|
||||
.await;
|
||||
let export = services.accounts();
|
||||
for (second, expected) in [
|
||||
(
|
||||
"acct_unsupported",
|
||||
gateway_admin::model::AdminErrorKind::Invalid,
|
||||
),
|
||||
(
|
||||
"acct_missing",
|
||||
gateway_admin::model::AdminErrorKind::NotFound,
|
||||
),
|
||||
] {
|
||||
calls.lock().unwrap().clear();
|
||||
let result = export
|
||||
.export(
|
||||
&context("export-unsupported"),
|
||||
vec![
|
||||
ProviderAccountId::new("acct_test").unwrap(),
|
||||
ProviderAccountId::new(second).unwrap(),
|
||||
],
|
||||
)
|
||||
.await;
|
||||
assert_eq!(result.unwrap_err().kind(), expected);
|
||||
assert_eq!(*calls.lock().unwrap(), ["store.credential_export_scopes"]);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -1507,17 +1600,28 @@ async fn accounts_export_should_pass_store_loaded_timestamps_and_material_to_pro
|
||||
provider.capabilities.lock().unwrap().credential_export = true;
|
||||
let store = FakeAccountStore::new("openai", events());
|
||||
let expected = store.accounts.lock().expect("accounts")[0].clone();
|
||||
accounts_service(provider.clone(), store)
|
||||
.await
|
||||
let mut second = expected.clone();
|
||||
second.id = "acct_second".into();
|
||||
store.accounts.lock().unwrap().push(second.clone());
|
||||
let services = accounts_service(provider.clone(), store.clone()).await;
|
||||
let ids = vec![
|
||||
ProviderAccountId::new(second.id.clone()).unwrap(),
|
||||
ProviderAccountId::new(expected.id.clone()).unwrap(),
|
||||
];
|
||||
services
|
||||
.accounts()
|
||||
.export(
|
||||
&context("export-complete-input"),
|
||||
vec![ProviderAccountId::new(expected.id.clone()).expect("account ID")],
|
||||
)
|
||||
.export(&context("export-complete-input"), ids.clone())
|
||||
.await
|
||||
.expect("export credentials");
|
||||
|
||||
let inputs = provider.export_inputs();
|
||||
assert_eq!(
|
||||
inputs
|
||||
.iter()
|
||||
.map(|input| &input.account.id)
|
||||
.collect::<Vec<_>>(),
|
||||
[&second.id, &expected.id]
|
||||
);
|
||||
let input = inputs.first().expect("provider export input");
|
||||
assert_eq!(
|
||||
(
|
||||
@@ -1525,7 +1629,18 @@ async fn accounts_export_should_pass_store_loaded_timestamps_and_material_to_pro
|
||||
input.account.updated_at,
|
||||
&input.provider_material,
|
||||
),
|
||||
(expected.created_at, expected.updated_at, &document()),
|
||||
(second.created_at, second.updated_at, &document()),
|
||||
);
|
||||
|
||||
store.fail_next_commit();
|
||||
let error = services
|
||||
.accounts()
|
||||
.export(&context("export-failed-audit"), ids)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(
|
||||
error.kind(),
|
||||
gateway_admin::model::AdminErrorKind::Unavailable
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1603,6 +1718,7 @@ async fn plugin_account_save_publishes_native_credential_change() {
|
||||
"store.commit_rotation",
|
||||
"provider.account_facts_changed",
|
||||
"snapshot.publish_committed",
|
||||
"store.load_account_record",
|
||||
"provider.quota"
|
||||
]
|
||||
);
|
||||
@@ -2149,6 +2265,7 @@ async fn accounts_list_should_degrade_quota_failure_to_empty_window_without_drop
|
||||
let events = events();
|
||||
let openai = FakeProviderAdmin::new("openai", events.clone());
|
||||
openai.set_quota(ProviderQuota {
|
||||
daily_used_percent: None,
|
||||
paused_windows: Vec::new(),
|
||||
upstream: None,
|
||||
credits: None,
|
||||
@@ -2311,6 +2428,7 @@ async fn accounts_list_should_map_unknown_credential_to_error_not_normal() {
|
||||
async fn accounts_list_should_not_derive_rate_limited_from_provider_quota_view() {
|
||||
let provider = FakeProviderAdmin::new("openai", events());
|
||||
provider.set_quota(ProviderQuota {
|
||||
daily_used_percent: None,
|
||||
paused_windows: Vec::new(),
|
||||
upstream: None,
|
||||
credits: None,
|
||||
@@ -2364,6 +2482,7 @@ async fn accounts_list_should_not_derive_rate_limited_from_provider_quota_view()
|
||||
async fn accounts_list_should_not_derive_exhaustion_from_provider_quota_view() {
|
||||
let provider = FakeProviderAdmin::new("openai", events());
|
||||
provider.set_quota(ProviderQuota {
|
||||
daily_used_percent: None,
|
||||
paused_windows: Vec::new(),
|
||||
upstream: None,
|
||||
credits: None,
|
||||
@@ -3130,6 +3249,7 @@ async fn accounts_list_should_attach_local_usage_to_quota_windows() {
|
||||
let provider = FakeProviderAdmin::new("openai", events());
|
||||
let reset_at = Utc::now() + TimeDelta::hours(1);
|
||||
provider.set_quota(ProviderQuota {
|
||||
daily_used_percent: None,
|
||||
paused_windows: Vec::new(),
|
||||
upstream: None,
|
||||
credits: None,
|
||||
@@ -3296,6 +3416,7 @@ async fn account_windows_attach_only_the_usage_allowed_by_the_provider() {
|
||||
let provider = FakeProviderAdmin::new("openai", events());
|
||||
let reset_at = Utc::now() + TimeDelta::days(7);
|
||||
let mut quota = ProviderQuota {
|
||||
daily_used_percent: None,
|
||||
paused_windows: Vec::new(),
|
||||
upstream: None,
|
||||
credits: None,
|
||||
@@ -3619,6 +3740,7 @@ pub(super) fn document() -> ProviderDocument {
|
||||
|
||||
fn empty_quota() -> ProviderQuota {
|
||||
ProviderQuota {
|
||||
daily_used_percent: None,
|
||||
paused_windows: Vec::new(),
|
||||
upstream: None,
|
||||
credits: None,
|
||||
@@ -3707,6 +3829,7 @@ pub(super) fn prepared_create_with_id(
|
||||
) -> PreparedCredentialCreate {
|
||||
let now = Utc::now();
|
||||
PreparedCredentialCreate {
|
||||
preserve_catalog_etag: None,
|
||||
model_access: Default::default(),
|
||||
outbound_proxy: None,
|
||||
account_id: ProviderAccountId::new(account_id).expect("prepared account ID"),
|
||||
@@ -3747,6 +3870,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(),
|
||||
|
||||
@@ -72,6 +72,7 @@ async fn openai_import_should_prepare_before_atomic_store_commit() {
|
||||
"provider.prepare_import",
|
||||
"store.commit_import",
|
||||
"provider.account_facts_changed",
|
||||
"store.load_account_record",
|
||||
"provider.quota",
|
||||
]
|
||||
);
|
||||
@@ -134,7 +135,7 @@ async fn openai_import_should_expose_only_explicit_public_errors_without_committ
|
||||
async fn openai_import_should_refresh_quota_for_every_imported_account() {
|
||||
let events = events();
|
||||
let provider = FakeProviderAdmin::new("openai", events.clone());
|
||||
provider.set_import_account_ids(&["acct_first", "acct_second"]);
|
||||
provider.set_import_accounts(&[("acct_first", "oauth"), ("acct_second", "oauth")]);
|
||||
let store = FakeAccountStore::new("openai", events);
|
||||
let services = service(provider.clone(), store).await;
|
||||
|
||||
@@ -249,6 +250,7 @@ async fn openai_authorization_create_should_observe_initial_quota() {
|
||||
"provider.complete_authorization",
|
||||
"store.commit_authorization",
|
||||
"provider.account_facts_changed",
|
||||
"store.load_account_record",
|
||||
"provider.quota",
|
||||
]
|
||||
);
|
||||
@@ -364,6 +366,7 @@ async fn openai_authorization_store_failure_should_release_claim_for_retry() {
|
||||
"store.commit_authorization",
|
||||
"authorization_guard.commit",
|
||||
"provider.account_facts_changed",
|
||||
"store.load_account_record",
|
||||
"provider.quota",
|
||||
]
|
||||
);
|
||||
@@ -455,6 +458,7 @@ async fn openai_reauthorization_should_commit_after_credential_revision_advances
|
||||
"store.commit_authorization",
|
||||
"guard.finish",
|
||||
"provider.account_facts_changed",
|
||||
"store.load_account_record",
|
||||
"provider.quota",
|
||||
]
|
||||
);
|
||||
|
||||
@@ -26,17 +26,16 @@ use super::super::{
|
||||
async fn imported_peer_accounts_should_start_observation_without_waiting_for_network() {
|
||||
let events = events();
|
||||
let provider = FakeProviderAdmin::new("openai", events.clone());
|
||||
provider.set_import_account_ids(&["acct_disabled", "acct_first", "acct_second"]);
|
||||
let mut first = account_record("openai");
|
||||
first.id = "acct_first".into();
|
||||
first.authentication_kind = "api_key".into();
|
||||
let mut second = first.clone();
|
||||
second.id = "acct_second".into();
|
||||
let store = FakeAccountStore::with_account(first.clone(), events);
|
||||
let mut disabled = first.clone();
|
||||
provider.set_import_accounts(&[
|
||||
("acct_disabled", "api_key"),
|
||||
("acct_first", "api_key"),
|
||||
("acct_second", "api_key"),
|
||||
]);
|
||||
let mut disabled = account_record("openai");
|
||||
disabled.id = "acct_disabled".into();
|
||||
disabled.authentication_kind = "api_key".into();
|
||||
disabled.enabled = false;
|
||||
store.set_accounts(vec![disabled, first, second]);
|
||||
let store = FakeAccountStore::with_account(disabled, events);
|
||||
let peer = Arc::new(PendingPeer::default());
|
||||
let services = AdminHarness::new()
|
||||
.provider(provider.clone())
|
||||
@@ -75,39 +74,61 @@ async fn imported_peer_accounts_should_start_observation_without_waiting_for_net
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn disabled_native_account_should_observe_quota_when_peer_service_is_available() {
|
||||
let events = events();
|
||||
let provider = FakeProviderAdmin::new("openai", events.clone());
|
||||
provider.set_import_account_ids(&["acct_test"]);
|
||||
let mut account = account_record("openai");
|
||||
account.enabled = false;
|
||||
let store = FakeAccountStore::with_account(account, events);
|
||||
let peer = Arc::new(PendingPeer::default());
|
||||
let services = AdminHarness::new()
|
||||
.provider(provider.clone())
|
||||
.accounts(store)
|
||||
.upstream_info(peer.clone())
|
||||
.build()
|
||||
.await;
|
||||
|
||||
services
|
||||
.credentials()
|
||||
.for_provider(&ProviderKind::new("openai").unwrap())
|
||||
.unwrap()
|
||||
.import_document(ImportCredentials {
|
||||
outbound_proxy_id: None,
|
||||
settings: None,
|
||||
context: context("import-native"),
|
||||
document: document(),
|
||||
})
|
||||
.await
|
||||
.expect("native import");
|
||||
provider.wait_for_quota_requests(1).await;
|
||||
assert!(peer.requests.lock().unwrap().is_empty());
|
||||
assert_eq!(
|
||||
provider.quota_requests()[0].account_id.as_str(),
|
||||
"acct_test"
|
||||
);
|
||||
async fn native_import_observes_only_capable_accounts_owned_by_the_provider() {
|
||||
for (kind, has_peer_service) in [
|
||||
("xai", true),
|
||||
("xai", false),
|
||||
("antigravity", true),
|
||||
("antigravity", false),
|
||||
("openai", true),
|
||||
("openai", false),
|
||||
] {
|
||||
let events = events();
|
||||
let provider = FakeProviderAdmin::new(kind, events.clone());
|
||||
provider.set_import_accounts(&[
|
||||
("acct_api_key", "api_key"),
|
||||
("acct_other_provider", "oauth"),
|
||||
("acct_oauth", "oauth"),
|
||||
]);
|
||||
let mut other = account_record("other");
|
||||
other.id = "acct_other_provider".into();
|
||||
let mut oauth = account_record(kind);
|
||||
oauth.id = "acct_oauth".into();
|
||||
oauth.enabled = false;
|
||||
let store = FakeAccountStore::new(kind, events);
|
||||
store.set_accounts(vec![other, oauth]);
|
||||
let peer = Arc::new(PendingPeer::default());
|
||||
peer.gate.add_permits(1);
|
||||
let mut harness = AdminHarness::new()
|
||||
.provider(provider.clone())
|
||||
.accounts(store);
|
||||
if has_peer_service {
|
||||
harness = harness.upstream_info(peer.clone());
|
||||
}
|
||||
let services = harness.build().await;
|
||||
services
|
||||
.credentials()
|
||||
.for_provider(&ProviderKind::new(kind).unwrap())
|
||||
.unwrap()
|
||||
.import_document(ImportCredentials {
|
||||
outbound_proxy_id: None,
|
||||
settings: None,
|
||||
context: context("import-native"),
|
||||
document: document(),
|
||||
})
|
||||
.await
|
||||
.expect("native import");
|
||||
provider.wait_for_quota_requests(1).await;
|
||||
let requests = provider.quota_requests();
|
||||
assert_eq!(requests.len(), 1);
|
||||
assert_eq!(requests[0].account_id.as_str(), "acct_oauth");
|
||||
let peer_requests = peer.requests.lock().unwrap();
|
||||
if kind == "openai" && has_peer_service {
|
||||
assert_eq!(*peer_requests, ["acct_api_key"]);
|
||||
} else {
|
||||
assert!(peer_requests.is_empty());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct PendingPeer {
|
||||
|
||||
@@ -43,6 +43,7 @@ async fn xai_import_should_prepare_before_atomic_store_commit() {
|
||||
"provider.prepare_import",
|
||||
"store.commit_import",
|
||||
"provider.account_facts_changed",
|
||||
"store.load_account_record",
|
||||
"provider.quota"
|
||||
]
|
||||
);
|
||||
@@ -65,7 +66,7 @@ async fn xai_import_should_prepare_before_atomic_store_commit() {
|
||||
async fn xai_import_should_refresh_quota_for_every_imported_account() {
|
||||
let events = events();
|
||||
let provider = FakeProviderAdmin::new("xai", events.clone());
|
||||
provider.set_import_account_ids(&["acct_first", "acct_second"]);
|
||||
provider.set_import_accounts(&[("acct_first", "oauth"), ("acct_second", "oauth")]);
|
||||
let store = FakeAccountStore::new("xai", events);
|
||||
let services = service(provider.clone(), store).await;
|
||||
|
||||
@@ -170,6 +171,7 @@ async fn xai_authorization_should_observe_quota_without_affecting_commit() {
|
||||
"provider.complete_authorization",
|
||||
"store.commit_authorization",
|
||||
"provider.account_facts_changed",
|
||||
"store.load_account_record",
|
||||
"provider.quota",
|
||||
]
|
||||
);
|
||||
|
||||
@@ -33,6 +33,7 @@ fn runtime_settings(enabled: bool, probe_enabled: bool) -> RuntimeSettings {
|
||||
rotation_strategy: gateway_admin::model::settings::RotationStrategy::Smart,
|
||||
updated_at: Utc::now(),
|
||||
values: gateway_admin::model::settings::RuntimeSettingsValues {
|
||||
provider_settings: Default::default(),
|
||||
openai_websocket_pool: Default::default(),
|
||||
openai_request_settings: gateway_core::settings::OpenAiRequestSettings {
|
||||
oauth_guardian_review_model: false,
|
||||
|
||||
@@ -53,11 +53,11 @@ use gateway_admin::{
|
||||
},
|
||||
provider_credentials::{
|
||||
AuthorizationCommit, AuthorizationStarted, CompleteAuthorization, CredentialDetails,
|
||||
CredentialImportCommit, CredentialImportResult, CredentialMutationResult,
|
||||
CredentialRotationCommit, PrepareCredentialImport, PrepareCredentialRefresh,
|
||||
PrepareCredentialRotation, PreparedAuthorizationCommit, PreparedCredentialImport,
|
||||
PreparedCredentialRotation, ProviderExport, ProviderExportCredentialInput,
|
||||
ProviderModels, ProviderQuota,
|
||||
CredentialExportScope, CredentialImportCommit, CredentialImportResult,
|
||||
CredentialMutationResult, CredentialRotationCommit, PrepareCredentialImport,
|
||||
PrepareCredentialRefresh, PrepareCredentialRotation, PreparedAuthorizationCommit,
|
||||
PreparedCredentialImport, PreparedCredentialRotation, ProviderExport,
|
||||
ProviderExportCredentialInput, ProviderModels, ProviderQuota,
|
||||
},
|
||||
settings::{AdminApiKey, AdminApiKeyMutation, ReplaceRuntimeSettings, RuntimeSettings},
|
||||
system::{SystemOperationAccepted, SystemUpdateDetail, SystemUpdateStatus, SystemVersion},
|
||||
@@ -283,6 +283,7 @@ impl AdminHarness {
|
||||
self.accounts,
|
||||
self.account_runtime,
|
||||
self.account_groups,
|
||||
Arc::new(UnavailableStore),
|
||||
self.proxies,
|
||||
),
|
||||
self.auth,
|
||||
@@ -578,10 +579,17 @@ impl AccountStore for UnavailableStore {
|
||||
Err(unavailable("credential"))
|
||||
}
|
||||
|
||||
async fn credential_export_scopes(
|
||||
&self,
|
||||
_: &[ProviderAccountId],
|
||||
) -> AdminStoreResult<BTreeMap<String, CredentialExportScope>> {
|
||||
Err(unavailable("credential export"))
|
||||
}
|
||||
|
||||
async fn load_credentials_for_export(
|
||||
&self,
|
||||
_: &ProviderKind,
|
||||
_: &[ProviderAccountId],
|
||||
_: &[(ProviderAccountId, String)],
|
||||
) -> AdminStoreResult<Vec<ProviderExportCredentialInput>> {
|
||||
Err(unavailable("credential export"))
|
||||
}
|
||||
@@ -1012,6 +1020,7 @@ impl SettingsStore for UnavailableStore {
|
||||
|
||||
struct UnavailableProvider {
|
||||
pricing_bands: &'static [&'static str],
|
||||
pricing_policy: gateway_admin::ports::pricing::PricingSourcePolicy,
|
||||
pricing_references: std::collections::BTreeMap<String, (String, String)>,
|
||||
peer_enabled: bool,
|
||||
kind: ProviderKind,
|
||||
@@ -1025,7 +1034,7 @@ impl gateway_admin::ports::pricing::PricingSource for UnavailablePricingSource {
|
||||
async fn fetch(
|
||||
&self,
|
||||
_: &gateway_admin::ports::pricing::PricingSourceScope,
|
||||
) -> Result<gateway_admin::model::pricing::PricingSyncPreview, gateway_admin::model::AdminError>
|
||||
) -> Result<gateway_admin::ports::pricing::ExternalPrices, gateway_admin::model::AdminError>
|
||||
{
|
||||
Err(gateway_admin::model::AdminError::internal(
|
||||
"pricing source unavailable",
|
||||
@@ -1038,6 +1047,7 @@ impl UnavailableProvider {
|
||||
Self {
|
||||
kind: ProviderKind::new(kind).expect("provider kind"),
|
||||
peer_enabled: false,
|
||||
pricing_policy: Default::default(),
|
||||
pricing_references: Default::default(),
|
||||
pricing_bands: &["standard"],
|
||||
dashboard_profile: None,
|
||||
@@ -1059,7 +1069,7 @@ impl ProviderAdmin for UnavailableProvider {
|
||||
fn pricing_source(&self) -> gateway_admin::ports::pricing::PricingCatalogSource {
|
||||
use gateway_admin::ports::pricing::PricingCatalogSource;
|
||||
if self.pricing_references.is_empty() {
|
||||
return PricingCatalogSource::Direct;
|
||||
return PricingCatalogSource::Direct(self.pricing_policy);
|
||||
}
|
||||
PricingCatalogSource::References(
|
||||
self.pricing_references
|
||||
@@ -1070,6 +1080,7 @@ impl ProviderAdmin for UnavailableProvider {
|
||||
gateway_admin::ports::pricing::PricingSourceModel {
|
||||
provider: provider.clone(),
|
||||
model: source.clone(),
|
||||
policy: self.pricing_policy,
|
||||
},
|
||||
)
|
||||
})
|
||||
@@ -1188,6 +1199,7 @@ impl ProviderAdmin for UnavailableProvider {
|
||||
pub(super) fn dashboard_profile_provider() -> Arc<dyn ProviderAdmin> {
|
||||
Arc::new(UnavailableProvider {
|
||||
pricing_bands: &["standard"],
|
||||
pricing_policy: Default::default(),
|
||||
pricing_references: Default::default(),
|
||||
peer_enabled: false,
|
||||
kind: ProviderKind::new("openai").expect("provider kind"),
|
||||
@@ -1234,6 +1246,7 @@ pub(super) fn calculated_billing_provider() -> Arc<dyn ProviderAdmin> {
|
||||
};
|
||||
Arc::new(UnavailableProvider {
|
||||
pricing_bands: &["standard"],
|
||||
pricing_policy: Default::default(),
|
||||
pricing_references: Default::default(),
|
||||
peer_enabled: false,
|
||||
kind: ProviderKind::new("openai").expect("provider kind"),
|
||||
@@ -1381,3 +1394,20 @@ impl gateway_admin::ports::reset_credit_automation::ResetCreditAutomationStore
|
||||
Err(unavailable("reset-credit automation"))
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl gateway_admin::ports::account_schedules::AccountScheduleStore for UnavailableStore {
|
||||
async fn query(
|
||||
&self,
|
||||
_: &gateway_admin::model::account_schedules::ScheduleQuery,
|
||||
) -> AdminStoreResult<gateway_admin::model::account_schedules::ScheduleList> {
|
||||
unreachable!()
|
||||
}
|
||||
async fn save(
|
||||
&self,
|
||||
_: gateway_admin::model::account_schedules::ScheduleChange,
|
||||
_: &gateway_admin::model::MutationContext,
|
||||
) -> AdminStoreResult<gateway_admin::model::Revision> {
|
||||
unreachable!()
|
||||
}
|
||||
}
|
||||
@@ -337,6 +337,7 @@ impl SettingsStore for FixtureSettingsStore {
|
||||
rotation_strategy: RotationStrategy::Smart,
|
||||
updated_at: Utc::now(),
|
||||
values: gateway_admin::model::settings::RuntimeSettingsValues {
|
||||
provider_settings: Default::default(),
|
||||
openai_websocket_pool: Default::default(),
|
||||
openai_request_settings: gateway_core::settings::OpenAiRequestSettings {
|
||||
oauth_guardian_review_model: false,
|
||||
|
||||
@@ -340,6 +340,7 @@ async fn linked_accounts_share_plan_resolution_and_only_read_cached_quota() {
|
||||
] {
|
||||
let provider = FakeProviderAdmin::new(kind, events());
|
||||
provider.set_quota(ProviderQuota {
|
||||
daily_used_percent: None,
|
||||
paused_windows: Vec::new(),
|
||||
upstream: None,
|
||||
credits: None,
|
||||
|
||||
@@ -387,6 +387,7 @@ fn sdk_settings_contract_matches_host_declarations() {
|
||||
use super::Operation;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{collections::{BTreeMap, BTreeSet}, num::NonZeroU64};
|
||||
pub type ProviderSettings = BTreeMap<String, serde_json::Map<String, serde_json::Value>>;
|
||||
pub type ProviderRequestProfiles = BTreeMap<String, serde_json::Map<String, serde_json::Value>>;
|
||||
pub type ProviderRequestProfileUpdates = BTreeMap<String, Option<serde_json::Map<String, serde_json::Value>>>;
|
||||
pub type ModelMappings = BTreeMap<String, String>;
|
||||
|
||||
@@ -16,6 +16,7 @@ use gateway_admin::{
|
||||
RuntimeSettings,
|
||||
},
|
||||
},
|
||||
ports::pricing::{ExternalModelPrice, ExternalPrices, PricingSourcePolicy},
|
||||
ports::store::{AdminStoreError, AdminStoreErrorKind, AdminStoreResult, SettingsStore},
|
||||
};
|
||||
|
||||
@@ -349,6 +350,7 @@ async fn settings_should_reject_zero_refresh_margin_before_store_call() {
|
||||
model_mappings: Default::default(),
|
||||
rotation_strategy: RotationStrategy::Smart,
|
||||
values: gateway_admin::model::settings::RuntimeSettingsValues {
|
||||
provider_settings: Default::default(),
|
||||
openai_websocket_pool: Default::default(),
|
||||
openai_request_settings: Default::default(),
|
||||
codex_privacy_policy: Default::default(),
|
||||
@@ -402,42 +404,68 @@ fn unused() -> AdminStoreError {
|
||||
)
|
||||
}
|
||||
|
||||
struct ReferencePrices(Mutex<PricingSyncPreview>);
|
||||
struct ReferencePrices(Mutex<ExternalPrices>);
|
||||
#[async_trait]
|
||||
impl gateway_admin::ports::pricing::PricingSource for ReferencePrices {
|
||||
async fn fetch(
|
||||
&self,
|
||||
_: &gateway_admin::ports::pricing::PricingSourceScope,
|
||||
) -> Result<PricingSyncPreview, gateway_admin::model::AdminError> {
|
||||
) -> Result<ExternalPrices, gateway_admin::model::AdminError> {
|
||||
Ok(self.0.lock().unwrap().clone())
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn external_reference_prices_project_to_exact_provider_ids_in_preview_and_sync() {
|
||||
let price: gateway_core::metering::ModelPriceOverride = serde_json::from_value(serde_json::json!({"multiplierBps":10000,"bands":{"standard":{"input":"1","output":"2","cacheRead":"0.1","cacheWrite":"1"}}})).unwrap();
|
||||
let source = Arc::new(ReferencePrices(Mutex::new(PricingSyncPreview {
|
||||
prices: BTreeMap::from([(
|
||||
"google".into(),
|
||||
BTreeMap::from([
|
||||
("base-model".into(), price.clone()),
|
||||
("unmapped".into(), price),
|
||||
]),
|
||||
)]),
|
||||
skipped: vec!["google/missing".into(), "google/unrelated-image".into()],
|
||||
})));
|
||||
let mut provider = super::UnavailableProvider::new("antigravity");
|
||||
let rates = serde_json::from_value(serde_json::json!({
|
||||
"input":"1","output":"2","cacheRead":"0.1","cacheWrite":"1"
|
||||
}))
|
||||
.unwrap();
|
||||
let base = ExternalModelPrice {
|
||||
standard: rates,
|
||||
long_context: None,
|
||||
has_audio_input_price: false,
|
||||
};
|
||||
let tiered = ExternalModelPrice {
|
||||
long_context: Some((200_000, base.standard.clone())),
|
||||
..base.clone()
|
||||
};
|
||||
let audio = ExternalModelPrice {
|
||||
has_audio_input_price: true,
|
||||
..base.clone()
|
||||
};
|
||||
let source = Arc::new(ReferencePrices(Mutex::new(BTreeMap::from([(
|
||||
"source".into(),
|
||||
BTreeMap::from([
|
||||
("base-model".into(), Some(base.clone())),
|
||||
("unmapped".into(), Some(base.clone())),
|
||||
("audio".into(), Some(audio)),
|
||||
("tiered".into(), Some(tiered)),
|
||||
("missing".into(), None),
|
||||
]),
|
||||
)]))));
|
||||
let mut provider = super::UnavailableProvider::new("mapped");
|
||||
provider.pricing_policy = PricingSourcePolicy {
|
||||
long_context_tokens: Some(200_000),
|
||||
text_only_input: true,
|
||||
};
|
||||
provider.pricing_references = BTreeMap::from([
|
||||
("ag-high".into(), ("google".into(), "base-model".into())),
|
||||
("ag-low".into(), ("google".into(), "base-model".into())),
|
||||
("ag-image".into(), ("google".into(), "missing".into())),
|
||||
("ag-high".into(), ("source".into(), "base-model".into())),
|
||||
("ag-low".into(), ("source".into(), "base-model".into())),
|
||||
("ag-image".into(), ("source".into(), "missing".into())),
|
||||
("audio".into(), ("source".into(), "audio".into())),
|
||||
("tiered".into(), ("source".into(), "tiered".into())),
|
||||
]);
|
||||
let mut other = super::UnavailableProvider::new("other");
|
||||
other.pricing_references = provider.pricing_references.clone();
|
||||
other.pricing_policy.long_context_tokens = Some(272_000);
|
||||
let store = Arc::new(PricingSettingsStore::default());
|
||||
let service = gateway_admin::initialize_settings(
|
||||
store.clone(),
|
||||
Arc::new(super::NoopSnapshot),
|
||||
gateway_admin::ports::provider::ProviderAdminRegistry::new(vec![
|
||||
Arc::new(provider) as Arc<dyn gateway_admin::ports::provider::ProviderAdmin>
|
||||
Arc::new(provider) as Arc<dyn gateway_admin::ports::provider::ProviderAdmin>,
|
||||
Arc::new(other),
|
||||
])
|
||||
.unwrap(),
|
||||
source.clone(),
|
||||
@@ -445,23 +473,36 @@ async fn external_reference_prices_project_to_exact_provider_ids_in_preview_and_
|
||||
let preview = service.preview_pricing_sync().await.unwrap();
|
||||
assert_eq!(
|
||||
preview.prices.keys().cloned().collect::<Vec<_>>(),
|
||||
["antigravity"]
|
||||
["mapped", "other"]
|
||||
);
|
||||
assert_eq!(
|
||||
preview.prices["antigravity"]
|
||||
.keys()
|
||||
.cloned()
|
||||
.collect::<Vec<_>>(),
|
||||
preview.prices["mapped"].keys().cloned().collect::<Vec<_>>(),
|
||||
["ag-high", "ag-low", "audio", "tiered"]
|
||||
);
|
||||
assert_eq!(
|
||||
preview.prices["other"].keys().collect::<Vec<_>>(),
|
||||
["ag-high", "ag-low"]
|
||||
);
|
||||
assert_eq!(preview.skipped, ["antigravity/ag-image"]);
|
||||
assert!(
|
||||
preview.prices["mapped"]["tiered"]
|
||||
.bands
|
||||
.contains_key("long_standard")
|
||||
);
|
||||
assert_eq!(
|
||||
preview.skipped,
|
||||
[
|
||||
"mapped/ag-image",
|
||||
"other/ag-image",
|
||||
"other/audio",
|
||||
"other/tiered"
|
||||
]
|
||||
);
|
||||
// 未登记外部型号的变化不会污染同步确认,但实际保存仍重新读取并校验投影价目
|
||||
source
|
||||
.0
|
||||
.lock()
|
||||
.unwrap()
|
||||
.prices
|
||||
.get_mut("google")
|
||||
.get_mut("source")
|
||||
.unwrap()
|
||||
.remove("unmapped");
|
||||
service
|
||||
@@ -472,18 +513,39 @@ async fn external_reference_prices_project_to_exact_provider_ids_in_preview_and_
|
||||
},
|
||||
SyncPricing {
|
||||
preview,
|
||||
models: BTreeMap::from([(
|
||||
"antigravity".into(),
|
||||
BTreeSet::from(["ag-high".into()]),
|
||||
)]),
|
||||
models: BTreeMap::from([("mapped".into(), BTreeSet::from(["ag-high".into()]))]),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
// 已登记型号全部下架时允许预览移除,整份外部价目都无法计费时保留已有同步价
|
||||
let replace_source = |price| {
|
||||
source.0.lock().unwrap().insert(
|
||||
"source".into(),
|
||||
BTreeMap::from([("unmapped".into(), Some(price))]),
|
||||
);
|
||||
};
|
||||
replace_source(base.clone());
|
||||
assert!(
|
||||
service
|
||||
.preview_pricing_sync()
|
||||
.await
|
||||
.unwrap()
|
||||
.prices
|
||||
.is_empty()
|
||||
);
|
||||
replace_source(ExternalModelPrice {
|
||||
long_context: Some((42, base.standard.clone())),
|
||||
..base
|
||||
});
|
||||
assert_eq!(
|
||||
service.preview_pricing_sync().await.unwrap_err().kind(),
|
||||
AdminErrorKind::BadGateway
|
||||
);
|
||||
let saved = store.synced.lock().unwrap();
|
||||
let saved = saved.as_ref().unwrap();
|
||||
assert_eq!(
|
||||
saved["antigravity"].keys().cloned().collect::<Vec<_>>(),
|
||||
saved["mapped"].keys().cloned().collect::<Vec<_>>(),
|
||||
["ag-high"]
|
||||
);
|
||||
}
|
||||
@@ -189,8 +189,7 @@ impl CompleteAccountAuthorizationRequest {
|
||||
if let Some(settings) = &self.settings {
|
||||
settings.validate()?;
|
||||
}
|
||||
let provider = parse_provider(&self.provider)?;
|
||||
validate_authorization_flow(&provider, &self.flow_id)?;
|
||||
parse_provider(&self.provider)?;
|
||||
require_text(&self.callback_url, MAX_CALLBACK_URL_BYTES, "callbackUrl")
|
||||
}
|
||||
|
||||
@@ -215,23 +214,6 @@ impl CompleteAccountAuthorizationRequest {
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_authorization_flow(
|
||||
provider: &ProviderKind,
|
||||
flow_id: &str,
|
||||
) -> Result<(), WireValidationError> {
|
||||
if provider.as_str() == "openai" {
|
||||
if !URL_SAFE_NO_PAD
|
||||
.decode(flow_id)
|
||||
.is_ok_and(|decoded| decoded.len() == 32)
|
||||
{
|
||||
return Err(WireValidationError::new("flowId"));
|
||||
}
|
||||
Ok(())
|
||||
} else {
|
||||
require_wire_id(flow_id, "flowId")
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct UpdateAccountRequest {
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -13,7 +13,6 @@ use axum::{
|
||||
},
|
||||
routing::{get, post},
|
||||
};
|
||||
use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
|
||||
use chrono::{DateTime, Utc};
|
||||
use futures::{Stream, StreamExt as _};
|
||||
use gateway_admin::model::{
|
||||
@@ -68,6 +67,7 @@ mod credentials;
|
||||
mod handlers;
|
||||
mod import_tasks;
|
||||
mod presenter;
|
||||
mod schedules;
|
||||
mod upstream_info;
|
||||
mod wire;
|
||||
|
||||
|
||||
@@ -67,6 +67,7 @@ pub(super) fn account_view(
|
||||
time: crate::time::TimePresenter,
|
||||
) -> AccountView {
|
||||
let AccountDirectoryItem {
|
||||
schedule_duty,
|
||||
model_cooldowns,
|
||||
platform_icon,
|
||||
account,
|
||||
@@ -124,6 +125,7 @@ pub(super) fn account_view(
|
||||
})
|
||||
.collect();
|
||||
AccountView {
|
||||
schedule_duty,
|
||||
platform_icon,
|
||||
quota_settings: account.quota_settings,
|
||||
auto_use_quota_credits: account.auto_use_quota_credits,
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
//! 管理端账号排班的读取与原子保存
|
||||
|
||||
use crate::SessionState;
|
||||
use crate::admin::{
|
||||
AdminAuth, AdminEnvelope, AdminError, AdminJson, AdminResponse, wire::map_admin_service_error,
|
||||
};
|
||||
use axum::{Router, extract::State, http::StatusCode, response::IntoResponse, routing::post};
|
||||
use gateway_admin::model::account_schedules::{ScheduleChange, ScheduleQuery};
|
||||
|
||||
pub fn router<S: SessionState + Clone + Send + Sync + 'static>() -> Router<S> {
|
||||
Router::new()
|
||||
.route("/api/admin/accounts/schedules/query", post(query::<S>))
|
||||
.route("/api/admin/accounts/schedules/update", post(save::<S>))
|
||||
}
|
||||
|
||||
async fn query<S: SessionState + Send + Sync>(
|
||||
_auth: AdminAuth,
|
||||
State(state): State<S>,
|
||||
AdminJson(query): AdminJson<ScheduleQuery>,
|
||||
) -> Result<impl IntoResponse, AdminError> {
|
||||
let page = state
|
||||
.admin_services()
|
||||
.account_schedules()
|
||||
.query(query)
|
||||
.await
|
||||
.map_err(map_admin_service_error)?;
|
||||
Ok(AdminResponse::new(StatusCode::OK, AdminEnvelope::ok(page)))
|
||||
}
|
||||
|
||||
async fn save<S: SessionState + Send + Sync>(
|
||||
auth: AdminAuth,
|
||||
State(state): State<S>,
|
||||
AdminJson(change): AdminJson<ScheduleChange>,
|
||||
) -> Result<impl IntoResponse, AdminError> {
|
||||
let revision = state
|
||||
.admin_services()
|
||||
.account_schedules()
|
||||
.save(change, &auth.context().mutation_context())
|
||||
.await
|
||||
.map_err(map_admin_service_error)?;
|
||||
Ok(AdminResponse::new(
|
||||
StatusCode::OK,
|
||||
AdminEnvelope::ok(revision),
|
||||
))
|
||||
}
|
||||
@@ -247,6 +247,8 @@ pub struct AccountSummaryView {
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AccountView {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub schedule_duty: Option<gateway_core::account::duty::ScheduleDuty>,
|
||||
pub platform_icon: Option<String>,
|
||||
pub quota_settings: gateway_core::account::AccountQuotaSettings,
|
||||
pub auto_use_quota_credits: bool,
|
||||
|
||||
@@ -36,6 +36,8 @@ pub type ProviderRequestProfileUpdates =
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct RuntimeSettingsFields {
|
||||
#[serde(default)]
|
||||
pub provider_settings: gateway_admin::model::settings::ProviderSettings,
|
||||
pub openai_websocket_pool: gateway_core::settings::OpenAiWebSocketPoolSettings,
|
||||
pub openai_request_settings: gateway_core::settings::OpenAiRequestSettings,
|
||||
pub codex_privacy_policy: gateway_core::settings::privacy::CodexPrivacyPolicy,
|
||||
@@ -715,6 +717,7 @@ impl RuntimeSettingsFields {
|
||||
self,
|
||||
) -> Result<gateway_admin::model::settings::RuntimeSettingsValues, WireValidationError> {
|
||||
let values = gateway_admin::model::settings::RuntimeSettingsValues {
|
||||
provider_settings: self.provider_settings,
|
||||
openai_websocket_pool: self.openai_websocket_pool,
|
||||
openai_request_settings: self.openai_request_settings,
|
||||
codex_privacy_policy: self.codex_privacy_policy,
|
||||
@@ -767,6 +770,7 @@ impl RuntimeSettingsFields {
|
||||
impl From<gateway_admin::model::settings::RuntimeSettingsValues> for RuntimeSettingsFields {
|
||||
fn from(settings: gateway_admin::model::settings::RuntimeSettingsValues) -> Self {
|
||||
crate::admin::settings::RuntimeSettingsFields {
|
||||
provider_settings: settings.provider_settings,
|
||||
openai_websocket_pool: settings.openai_websocket_pool,
|
||||
openai_request_settings: settings.openai_request_settings,
|
||||
codex_privacy_policy: settings.codex_privacy_policy,
|
||||
|
||||
@@ -179,7 +179,7 @@ async fn catalog(
|
||||
)
|
||||
}
|
||||
};
|
||||
if generated.binary_search(&model).is_err() || !super::valid_segment(model.as_str()) {
|
||||
if !super::valid_segment(model.as_str()) {
|
||||
continue;
|
||||
}
|
||||
let order = if let Some(menu) = &menu {
|
||||
@@ -190,10 +190,16 @@ async fn catalog(
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let mut methods = vec!["generateContent", "streamGenerateContent"];
|
||||
let mut methods = Vec::new();
|
||||
if generated.binary_search(&model).is_ok() {
|
||||
methods.extend(["generateContent", "streamGenerateContent"]);
|
||||
}
|
||||
if counted.binary_search(&model).is_ok() {
|
||||
methods.push("countTokens");
|
||||
}
|
||||
if methods.is_empty() {
|
||||
continue;
|
||||
}
|
||||
// Cloud Code 模型对象完整保留,只适配 AGY Gateway 发现端点的资源名与调用方法
|
||||
object.insert("name".into(), json!(format!("models/{}", model.as_str())));
|
||||
object.insert("supportedGenerationMethods".into(), json!(methods));
|
||||
|
||||
@@ -381,6 +381,7 @@ async fn account_quota_refresh_time_uses_server_clock_and_deployment_timezone()
|
||||
),
|
||||
] {
|
||||
*fixture.provider_quota.lock().unwrap() = Some(ProviderQuota {
|
||||
daily_used_percent: None,
|
||||
paused_windows: Vec::new(),
|
||||
upstream: None,
|
||||
plan_type: None,
|
||||
|
||||
@@ -865,16 +865,18 @@ mod actions {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oauth_complete_rejects_unknown_fields() {
|
||||
let flow_id = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode([7_u8; 32]);
|
||||
fn oauth_complete_accepts_provider_issued_flow_ids_and_rejects_unknown_fields() {
|
||||
let flow_id = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode([0xff; 32]);
|
||||
let mut payload = json!({
|
||||
"provider": "openai",
|
||||
"flowId": flow_id,
|
||||
"callbackUrl": "http://localhost/callback?code=ok"
|
||||
});
|
||||
let request: CompleteAccountAuthorizationRequest =
|
||||
serde_json::from_value(payload.clone()).expect("decode OAuth completion");
|
||||
assert!(request.validate().is_ok());
|
||||
for provider in ["openai", "xai", "antigravity"] {
|
||||
payload["provider"] = json!(provider);
|
||||
let request: CompleteAccountAuthorizationRequest =
|
||||
serde_json::from_value(payload.clone()).expect("decode OAuth completion");
|
||||
request.validate().expect(provider);
|
||||
}
|
||||
payload["unknownField"] = json!(true);
|
||||
assert!(serde_json::from_value::<CompleteAccountAuthorizationRequest>(payload).is_err());
|
||||
}
|
||||
@@ -914,6 +916,7 @@ mod actions {
|
||||
#[test]
|
||||
fn account_import_response_should_emit_account_ids() {
|
||||
let response = AccountImportData::from_result(CredentialImportResult {
|
||||
created_ids: Default::default(),
|
||||
config_revision: Revision::new(8).expect("revision"),
|
||||
credential_ids: vec![ProviderAccountId::new("acct_imported").expect("account ID")],
|
||||
});
|
||||
|
||||
@@ -46,11 +46,11 @@ use gateway_admin::{
|
||||
},
|
||||
provider_credentials::{
|
||||
AuthorizationCommit, AuthorizationStarted, CompleteAuthorization, CredentialDetails,
|
||||
CredentialImportCommit, CredentialImportResult, CredentialMutationResult,
|
||||
CredentialRotationCommit, PrepareCredentialImport, PrepareCredentialRefresh,
|
||||
PrepareCredentialRotation, PreparedAuthorizationCommit, PreparedCredentialImport,
|
||||
PreparedCredentialRotation, ProviderExport, ProviderExportCredentialInput,
|
||||
ProviderModels, ProviderQuota,
|
||||
CredentialExportScope, CredentialImportCommit, CredentialImportResult,
|
||||
CredentialMutationResult, CredentialRotationCommit, PrepareCredentialImport,
|
||||
PrepareCredentialRefresh, PrepareCredentialRotation, PreparedAuthorizationCommit,
|
||||
PreparedCredentialImport, PreparedCredentialRotation, ProviderExport,
|
||||
ProviderExportCredentialInput, ProviderModels, ProviderQuota,
|
||||
},
|
||||
settings::{
|
||||
AdminApiKey, AdminApiKeyMutation, ModelMappings, ReplaceRuntimeSettings,
|
||||
@@ -184,6 +184,7 @@ impl AdminTestFixture {
|
||||
unused.clone(),
|
||||
unused.clone(),
|
||||
account_groups.clone(),
|
||||
unused.clone(),
|
||||
Arc::new(proxies::MemoryProxies::default()),
|
||||
),
|
||||
auth.clone(),
|
||||
@@ -528,13 +529,20 @@ impl gateway_admin::ports::pricing::PricingSource for StaticPricingSource {
|
||||
async fn fetch(
|
||||
&self,
|
||||
_: &gateway_admin::ports::pricing::PricingSourceScope,
|
||||
) -> Result<gateway_admin::model::pricing::PricingSyncPreview, gateway_admin::model::AdminError>
|
||||
) -> Result<gateway_admin::ports::pricing::ExternalPrices, gateway_admin::model::AdminError>
|
||||
{
|
||||
Ok(gateway_admin::model::pricing::PricingSyncPreview {
|
||||
prices: serde_json::from_value(serde_json::json!({"openai":{"gpt-5.4":{
|
||||
"multiplierBps":10000,"bands":{"standard":{"input":"2.5","output":"15","cacheRead":"0.25","cacheWrite":"0"}}
|
||||
}}})).expect("prices"), skipped: vec![],
|
||||
})
|
||||
let price = gateway_admin::ports::pricing::ExternalModelPrice {
|
||||
standard: serde_json::from_value(serde_json::json!({
|
||||
"input":"2.5","output":"15","cacheRead":"0.25","cacheWrite":"0"
|
||||
}))
|
||||
.expect("rates"),
|
||||
long_context: None,
|
||||
has_audio_input_price: false,
|
||||
};
|
||||
Ok(std::collections::BTreeMap::from([(
|
||||
"openai".into(),
|
||||
std::collections::BTreeMap::from([("gpt-5.4".into(), Some(price))]),
|
||||
)]))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -647,13 +655,17 @@ impl SettingsStore for MemorySettingsStore {
|
||||
request_profiles.remove(&provider);
|
||||
}
|
||||
}
|
||||
let mut values = command.values;
|
||||
let mut provider_settings = std::mem::take(&mut settings.values.provider_settings);
|
||||
provider_settings.append(&mut values.provider_settings);
|
||||
values.provider_settings = provider_settings;
|
||||
let updated = RuntimeSettings {
|
||||
request_profiles,
|
||||
config_revision: next_revision(settings.config_revision),
|
||||
model_mappings: command.model_mappings,
|
||||
rotation_strategy: command.rotation_strategy,
|
||||
updated_at: Utc::now(),
|
||||
values: command.values,
|
||||
values,
|
||||
};
|
||||
*settings = updated.clone();
|
||||
Ok(updated)
|
||||
@@ -1355,10 +1367,17 @@ impl AccountStore for UnusedStore {
|
||||
Err(unavailable("plugin credential"))
|
||||
}
|
||||
|
||||
async fn credential_export_scopes(
|
||||
&self,
|
||||
_: &[ProviderAccountId],
|
||||
) -> AdminStoreResult<BTreeMap<String, CredentialExportScope>> {
|
||||
Err(unavailable("credential export"))
|
||||
}
|
||||
|
||||
async fn load_credentials_for_export(
|
||||
&self,
|
||||
_: &ProviderKind,
|
||||
_: &[ProviderAccountId],
|
||||
_: &[(ProviderAccountId, String)],
|
||||
) -> AdminStoreResult<Vec<ProviderExportCredentialInput>> {
|
||||
Err(unavailable("credential export"))
|
||||
}
|
||||
@@ -1749,6 +1768,23 @@ impl UnusedProvider {
|
||||
|
||||
#[async_trait]
|
||||
impl ProviderAdmin for UnusedProvider {
|
||||
fn plan_type_display(&self, plan_type: &str) -> Option<String> {
|
||||
if self.kind.as_str() == "antigravity" {
|
||||
return None;
|
||||
}
|
||||
Some(
|
||||
match plan_type {
|
||||
"free" => "Free",
|
||||
"plus" => "Plus",
|
||||
"pro" => "Pro",
|
||||
"edu_pro" => "EduPro",
|
||||
"supergrok_plus" => "SupergrokPlus",
|
||||
other => other,
|
||||
}
|
||||
.to_owned(),
|
||||
)
|
||||
}
|
||||
|
||||
fn account_usage_lookback(
|
||||
&self,
|
||||
) -> gateway_admin::model::provider_credentials::AccountUsageLookback {
|
||||
@@ -1996,6 +2032,7 @@ fn test_runtime_settings() -> RuntimeSettings {
|
||||
rotation_strategy: RotationStrategy::Smart,
|
||||
updated_at: Utc::now(),
|
||||
values: gateway_admin::model::settings::RuntimeSettingsValues {
|
||||
provider_settings: Default::default(),
|
||||
openai_websocket_pool: Default::default(),
|
||||
openai_request_settings: Default::default(),
|
||||
codex_privacy_policy: Default::default(),
|
||||
@@ -2112,3 +2149,20 @@ impl gateway_admin::ports::reset_credit_automation::ResetCreditAutomationStore f
|
||||
Err(unavailable("reset-credit automation"))
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl gateway_admin::ports::account_schedules::AccountScheduleStore for UnusedStore {
|
||||
async fn query(
|
||||
&self,
|
||||
_: &gateway_admin::model::account_schedules::ScheduleQuery,
|
||||
) -> AdminStoreResult<gateway_admin::model::account_schedules::ScheduleList> {
|
||||
unreachable!()
|
||||
}
|
||||
async fn save(
|
||||
&self,
|
||||
_: gateway_admin::model::account_schedules::ScheduleChange,
|
||||
_: &gateway_admin::model::MutationContext,
|
||||
) -> AdminStoreResult<gateway_admin::model::Revision> {
|
||||
unreachable!()
|
||||
}
|
||||
}
|
||||
@@ -84,6 +84,7 @@ fn update_body() -> Value {
|
||||
"gpt-5.4": "gpt-5.5",
|
||||
"grok-latest": "grok-4.5"
|
||||
},
|
||||
"providerSettings": {},
|
||||
"refreshMarginSeconds": 1800,
|
||||
"refreshConcurrency": 4,
|
||||
"maxConcurrentPerAccount": 5,
|
||||
@@ -993,22 +994,30 @@ fn decompression_setting_should_reject_invalid_values() {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn settings_update_rejects_unknown_fields_without_writing() {
|
||||
async fn settings_update_rejects_incomplete_and_unknown_fields_without_writing() {
|
||||
let fixture = AdminTestFixture::new().await;
|
||||
fixture.auth.insert_session("valid-session");
|
||||
let app = app(fixture.state());
|
||||
let initial = fixture.settings.settings.lock().unwrap().clone();
|
||||
let mut body = update_body();
|
||||
body["unknownSetting"] = json!(true);
|
||||
let response = app
|
||||
.oneshot(request(
|
||||
Method::POST,
|
||||
"/api/admin/settings/update",
|
||||
Some(body),
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
|
||||
let mut unknown = update_body();
|
||||
unknown["unknownSetting"] = json!(true);
|
||||
let mut incomplete = update_body();
|
||||
incomplete
|
||||
.as_object_mut()
|
||||
.unwrap()
|
||||
.remove("refreshMarginSeconds");
|
||||
for body in [unknown, incomplete] {
|
||||
let response = app
|
||||
.clone()
|
||||
.oneshot(request(
|
||||
Method::POST,
|
||||
"/api/admin/settings/update",
|
||||
Some(body),
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
|
||||
}
|
||||
assert_eq!(*fixture.settings.settings.lock().unwrap(), initial);
|
||||
}
|
||||
|
||||
@@ -1042,7 +1051,36 @@ async fn global_profiles_map_only_updates_submitted_providers() {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn settings_update_rejects_a_new_unknown_profile() {
|
||||
async fn saving_shared_settings_preserves_unchanged_platform_settings() {
|
||||
let fixture = AdminTestFixture::new().await;
|
||||
fixture.auth.insert_session("valid-session");
|
||||
let saved = json!({"plugin.fixture":{"enabled":false}});
|
||||
fixture
|
||||
.settings
|
||||
.settings
|
||||
.lock()
|
||||
.unwrap()
|
||||
.values
|
||||
.provider_settings = serde_json::from_value(saved.clone()).unwrap();
|
||||
let mut update = update_body();
|
||||
update["providerSettings"] = saved.clone();
|
||||
let response = app(fixture.state())
|
||||
.oneshot(request(
|
||||
Method::POST,
|
||||
"/api/admin/settings/update",
|
||||
Some(update),
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
assert_eq!(
|
||||
response_json(response).await["data"]["providerSettings"],
|
||||
saved
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn settings_update_rejects_unregistered_providers_and_unsupported_settings() {
|
||||
let fixture = AdminTestFixture::new().await;
|
||||
fixture.auth.insert_session("valid-session");
|
||||
let mut body = update_body();
|
||||
@@ -1061,6 +1099,23 @@ async fn settings_update_rejects_a_new_unknown_profile() {
|
||||
|
||||
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
|
||||
|
||||
for settings in [
|
||||
json!({"plugin.unknown":{}}),
|
||||
json!({"openai":{"unexpected":true}}),
|
||||
] {
|
||||
let mut update = update_body();
|
||||
update["providerSettings"] = settings;
|
||||
let response = app(fixture.state())
|
||||
.oneshot(request(
|
||||
Method::POST,
|
||||
"/api/admin/settings/update",
|
||||
Some(update),
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
|
||||
}
|
||||
|
||||
body["providerRequestProfiles"] = json!({"plugin.unknown":null});
|
||||
let response = app(fixture.state())
|
||||
.oneshot(request(
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
use super::*;
|
||||
use gateway_core::{
|
||||
account::ProviderAccountId,
|
||||
operation::OperationKind,
|
||||
routing::{
|
||||
ConfigRevision, ModelCapabilities, ProviderKind, ProviderModel, RuntimeSnapshot,
|
||||
@@ -10,18 +11,32 @@ use gateway_core::{
|
||||
};
|
||||
|
||||
fn client() -> AuthenticatedClient {
|
||||
use OperationKind::{CountTokens, Generate};
|
||||
|
||||
let source = authenticated_client(KEY);
|
||||
let caps = ModelCapabilities::new(
|
||||
[OperationKind::Generate, OperationKind::CountTokens].into(),
|
||||
None,
|
||||
)
|
||||
.with_generation_protocol(GENAI_PROTOCOL);
|
||||
let provider = ProviderKind::new("openai").unwrap();
|
||||
let models = ["model-a", "model-b", "model-c", "unreachable/name"].map(|id| {
|
||||
let allowed = ProviderAccountId::new("acct_api_test").unwrap();
|
||||
let other = ProviderAccountId::new("acct_other").unwrap();
|
||||
let models = [
|
||||
("model-a", &allowed, &allowed),
|
||||
("model-b", &allowed, &allowed),
|
||||
("model-c", &allowed, &allowed),
|
||||
("only-count", &other, &allowed),
|
||||
("only-generate", &allowed, &other),
|
||||
("private", &other, &other),
|
||||
("unreachable/name", &allowed, &allowed),
|
||||
]
|
||||
.map(|(id, generate_account, count_account)| {
|
||||
let operations = [
|
||||
(Generate, [generate_account.clone()].into()),
|
||||
(CountTokens, [count_account.clone()].into()),
|
||||
]
|
||||
.into();
|
||||
ProviderModel::new(
|
||||
provider.clone(),
|
||||
UpstreamModelId::new(id).unwrap(),
|
||||
caps.clone(),
|
||||
ModelCapabilities::from_operation_accounts(operations, None)
|
||||
.with_generation_protocol(GENAI_PROTOCOL),
|
||||
)
|
||||
});
|
||||
let snapshot = RuntimeSnapshot::new(
|
||||
@@ -76,9 +91,27 @@ async fn list_pages_and_details_expose_only_supported_native_models() {
|
||||
.await;
|
||||
assert_eq!(
|
||||
second["models"],
|
||||
json!([{"name":"models/model-c","displayName":"model-c","supportedGenerationMethods":["generateContent","streamGenerateContent","countTokens"]}])
|
||||
json!([
|
||||
{"name":"models/model-c","displayName":"model-c","supportedGenerationMethods":["generateContent","streamGenerateContent","countTokens"]},
|
||||
{"name":"models/only-count","displayName":"only-count","supportedGenerationMethods":["countTokens"]}
|
||||
])
|
||||
);
|
||||
assert!(second.get("nextPageToken").is_none());
|
||||
let (_, detail) = query(&router, "/v1beta/models/only-count", true).await;
|
||||
assert_eq!(detail, second["models"][1]);
|
||||
let (_, third) = query(
|
||||
&router,
|
||||
&format!(
|
||||
"/v1beta/models?pageSize=2&pageToken={}",
|
||||
second["nextPageToken"].as_str().unwrap()
|
||||
),
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
third["models"],
|
||||
json!([{"name":"models/only-generate","displayName":"only-generate","supportedGenerationMethods":["generateContent","streamGenerateContent"]}])
|
||||
);
|
||||
assert!(third.get("nextPageToken").is_none());
|
||||
let (status, _) = query(
|
||||
&router,
|
||||
&format!("/v1beta/models?pageSize=1&pageToken={token}"),
|
||||
@@ -146,10 +179,7 @@ async fn google_api_key_reads_the_same_authorized_catalog() {
|
||||
}
|
||||
|
||||
fn agent_menu_client() -> AuthenticatedClient {
|
||||
use gateway_core::{
|
||||
account::ProviderAccountId,
|
||||
routing::{AccountModelMetadata, AgentModelListing},
|
||||
};
|
||||
use gateway_core::routing::{AccountModelMetadata, AgentModelListing};
|
||||
use std::collections::BTreeMap;
|
||||
let source = super::super::authenticated_client_for_provider(KEY, "antigravity");
|
||||
let provider = ProviderKind::new("antigravity").unwrap();
|
||||
|
||||
@@ -134,6 +134,7 @@ async fn fixture(sharing: ClientPeerSharing, plaintext: &str) -> (AdminTestFixtu
|
||||
},
|
||||
});
|
||||
*fixture.provider_quota.lock().unwrap() = Some(ProviderQuota {
|
||||
daily_used_percent: None,
|
||||
paused_windows: Vec::new(),
|
||||
upstream: None,
|
||||
plan_type: Some("pro".into()),
|
||||
@@ -170,7 +171,15 @@ fn router_with_sharing(
|
||||
plaintext: &str,
|
||||
) -> Router {
|
||||
let group = fixture.client_key.lock().unwrap().as_ref().unwrap().groups[0].clone();
|
||||
let provider = ProviderKind::new("openai").unwrap();
|
||||
let provider = fixture
|
||||
.account
|
||||
.lock()
|
||||
.unwrap()
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.account
|
||||
.provider_kind
|
||||
.clone();
|
||||
let id = ClientApiKeyId::new("key-42").unwrap();
|
||||
let directory = Arc::new(RuntimeAccountDirectory::new(BTreeMap::from([(
|
||||
ProviderAccountId::new("acct_private_sentinel").unwrap(),
|
||||
@@ -306,15 +315,12 @@ async fn peer_budget_reports_window_availability_and_actual_duration_without_an_
|
||||
#[tokio::test]
|
||||
async fn pool_plans_use_account_plan_fallback_independently_of_quota_sharing() {
|
||||
for share_quota in [true, false] {
|
||||
let (fixture, app) = fixture(
|
||||
ClientPeerSharing {
|
||||
share_plans: true,
|
||||
share_quota,
|
||||
..sharing()
|
||||
},
|
||||
RAW_KEY,
|
||||
)
|
||||
.await;
|
||||
let sharing = ClientPeerSharing {
|
||||
share_plans: true,
|
||||
share_quota,
|
||||
..sharing()
|
||||
};
|
||||
let (fixture, app) = fixture(sharing, RAW_KEY).await;
|
||||
for (account_plan, quota_plan, expected) in [
|
||||
(None, Some("free"), Some("Free")),
|
||||
(Some("unknown"), Some("free"), Some("Free")),
|
||||
@@ -364,6 +370,27 @@ async fn pool_plans_use_account_plan_fallback_independently_of_quota_sharing() {
|
||||
account_plan,
|
||||
);
|
||||
}
|
||||
{
|
||||
let mut account = fixture.account.lock().unwrap();
|
||||
let account = &mut account.as_mut().unwrap().account;
|
||||
account.provider_kind = ProviderKind::new("antigravity").unwrap();
|
||||
account.plan_type = Some("g1-pro-tier".into());
|
||||
}
|
||||
{
|
||||
let mut quota = fixture.provider_quota.lock().unwrap();
|
||||
let quota = quota.as_mut().unwrap();
|
||||
quota.plan_type = Some("g1-pro-tier".into());
|
||||
quota.plan_type_display = Some("Pro subscription".into());
|
||||
}
|
||||
let app = router_with_sharing(&fixture, sharing, RAW_KEY);
|
||||
let response = query(&app, PATH, Some(RAW_KEY)).await;
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
let body = response_json(response).await;
|
||||
assert_eq!(
|
||||
body["pool"]["plans"],
|
||||
json!([{ "name": "Pro subscription", "count": 1 }])
|
||||
);
|
||||
assert_eq!(body.get("quota").is_some(), share_quota);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
//! 每日重复的账号班次与接单资格,共享请求冻结的配置快照
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{collections::BTreeMap, time::SystemTime};
|
||||
|
||||
use super::{ProviderAccountId, scope::RuntimeAccount};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct DailyShift {
|
||||
pub id: String,
|
||||
pub start: u16,
|
||||
pub end: u16,
|
||||
}
|
||||
|
||||
impl DailyShift {
|
||||
pub fn contains(&self, minute: u16) -> bool {
|
||||
if self.start < self.end {
|
||||
(self.start..self.end).contains(&minute)
|
||||
} else {
|
||||
minute >= self.start || minute < self.end
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum OffShiftSession {
|
||||
Rebind,
|
||||
#[default]
|
||||
Keep,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct SchedulePolicy {
|
||||
pub enabled: bool,
|
||||
pub off_shift_session: OffShiftSession,
|
||||
pub early_finish: bool,
|
||||
pub limit_percent: u8,
|
||||
}
|
||||
|
||||
impl Default for SchedulePolicy {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
enabled: true,
|
||||
off_shift_session: OffShiftSession::default(),
|
||||
early_finish: false,
|
||||
limit_percent: 80,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum ScheduleDuty {
|
||||
OnDuty,
|
||||
OffDuty,
|
||||
QuotaReached,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct AccountSchedules {
|
||||
pub timezone: crate::time::DeploymentTimeZone,
|
||||
pub accounts: BTreeMap<String, Vec<DailyShift>>,
|
||||
pub groups: BTreeMap<String, Vec<DailyShift>>,
|
||||
pub policy: SchedulePolicy,
|
||||
}
|
||||
|
||||
impl AccountSchedules {
|
||||
/// 没有任何班表的账号沿用默认调度;个人和所在组有任一有效时段即可在班
|
||||
pub fn duty(
|
||||
&self,
|
||||
id: &ProviderAccountId,
|
||||
account: &RuntimeAccount,
|
||||
now: SystemTime,
|
||||
daily_used_percent: Option<u8>,
|
||||
) -> Option<ScheduleDuty> {
|
||||
if !self.policy.enabled || (self.accounts.is_empty() && self.groups.is_empty()) {
|
||||
return None;
|
||||
}
|
||||
let mut sources = self
|
||||
.accounts
|
||||
.get(id.as_str())
|
||||
.into_iter()
|
||||
.chain(
|
||||
account
|
||||
.group_ids()
|
||||
.iter()
|
||||
.filter_map(|id| self.groups.get(id.as_str())),
|
||||
)
|
||||
.peekable();
|
||||
sources.peek()?;
|
||||
let minute = self.timezone.minute_of_day(now.into());
|
||||
if !sources.any(|shifts| shifts.iter().any(|shift| shift.contains(minute))) {
|
||||
return Some(ScheduleDuty::OffDuty);
|
||||
}
|
||||
if self.policy.early_finish
|
||||
&& daily_used_percent.is_some_and(|used| used >= self.policy.limit_percent)
|
||||
{
|
||||
return Some(ScheduleDuty::QuotaReached);
|
||||
}
|
||||
Some(ScheduleDuty::OnDuty)
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Provider 账号领域、持久化端口与同一 target 内的账号选择
|
||||
|
||||
pub mod duty;
|
||||
mod error;
|
||||
mod error_protection;
|
||||
pub use error_protection::*;
|
||||
|
||||
@@ -407,6 +407,7 @@ pub struct QuotaState {
|
||||
evidence: Option<QuotaEvidence>,
|
||||
observed_at: Option<SystemTime>,
|
||||
reset_at: Option<SystemTime>,
|
||||
exhaustion_deadline: Option<SystemTime>,
|
||||
limit_window_minutes: Option<u16>,
|
||||
}
|
||||
|
||||
@@ -424,6 +425,7 @@ impl QuotaState {
|
||||
evidence: None,
|
||||
observed_at: None,
|
||||
reset_at: None,
|
||||
exhaustion_deadline: None,
|
||||
limit_window_minutes: None,
|
||||
}
|
||||
}
|
||||
@@ -435,6 +437,7 @@ impl QuotaState {
|
||||
evidence: None,
|
||||
observed_at: Some(observed_at),
|
||||
reset_at: None,
|
||||
exhaustion_deadline: None,
|
||||
limit_window_minutes: None,
|
||||
}
|
||||
}
|
||||
@@ -446,6 +449,7 @@ impl QuotaState {
|
||||
evidence: None,
|
||||
observed_at: Some(observed_at),
|
||||
reset_at: None,
|
||||
exhaustion_deadline: None,
|
||||
limit_window_minutes: None,
|
||||
}
|
||||
}
|
||||
@@ -461,6 +465,7 @@ impl QuotaState {
|
||||
evidence: Some(evidence),
|
||||
observed_at: Some(observed_at),
|
||||
reset_at,
|
||||
exhaustion_deadline: None,
|
||||
limit_window_minutes: None,
|
||||
}
|
||||
}
|
||||
@@ -473,6 +478,7 @@ impl QuotaState {
|
||||
evidence: Some(QuotaEvidence::CreditsAvailable),
|
||||
observed_at: Some(observed_at),
|
||||
reset_at,
|
||||
exhaustion_deadline: None,
|
||||
limit_window_minutes: None,
|
||||
}
|
||||
}
|
||||
@@ -501,6 +507,7 @@ impl QuotaState {
|
||||
evidence,
|
||||
observed_at,
|
||||
reset_at,
|
||||
exhaustion_deadline: None,
|
||||
limit_window_minutes: None,
|
||||
})
|
||||
} else {
|
||||
@@ -528,6 +535,28 @@ impl QuotaState {
|
||||
self.reset_at
|
||||
}
|
||||
|
||||
/// 耗尽观测阻止调度的截止时间;上游重置时间仍独立保留
|
||||
#[must_use]
|
||||
pub const fn exhaustion_deadline(self) -> Option<SystemTime> {
|
||||
self.exhaustion_deadline
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn with_exhaustion_deadline(mut self, deadline: Option<SystemTime>) -> Self {
|
||||
if self.is_exhausted() || self.evidence == Some(QuotaEvidence::CreditsAvailable) {
|
||||
self.exhaustion_deadline = deadline;
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn is_exhausted_at(self, now: SystemTime) -> bool {
|
||||
self.is_exhausted()
|
||||
&& self
|
||||
.exhaustion_deadline
|
||||
.is_none_or(|deadline| now < deadline)
|
||||
}
|
||||
|
||||
/// 本次上游用量拒绝明确指出的窗口时长
|
||||
#[must_use]
|
||||
pub const fn limit_window_minutes(self) -> Option<u16> {
|
||||
@@ -542,9 +571,7 @@ impl QuotaState {
|
||||
self
|
||||
}
|
||||
|
||||
/// 返回当前已确认的额度耗尽结论
|
||||
///
|
||||
/// `reset_at` 只表示何时应重新向 Provider 求证;时间到期本身不是额度恢复证据
|
||||
/// 返回最近观测的耗尽结论,选号使用带时间判断的有效状态
|
||||
#[must_use]
|
||||
pub fn is_exhausted(self) -> bool {
|
||||
self.access == QuotaAccessState::Exhausted
|
||||
@@ -552,13 +579,13 @@ impl QuotaState {
|
||||
|
||||
/// 判断已耗尽额度是否到达 Provider 的下一次复核时间
|
||||
///
|
||||
/// 有明确 `reset_at` 时严格等待该时刻;没有时由 Provider 传入自己的保守复核周期
|
||||
/// 优先使用耗尽截止时间,其次使用上游重置时间,缺省时按观测时间和复核周期计算
|
||||
#[must_use]
|
||||
pub fn exhaustion_refresh_due(self, now: SystemTime, fallback_interval: Duration) -> bool {
|
||||
if !self.is_exhausted() {
|
||||
return false;
|
||||
}
|
||||
let due_at = self.reset_at.or_else(|| {
|
||||
let due_at = self.exhaustion_deadline.or(self.reset_at).or_else(|| {
|
||||
self.observed_at
|
||||
.and_then(|observed_at| observed_at.checked_add(fallback_interval))
|
||||
});
|
||||
@@ -777,7 +804,7 @@ pub fn resolve_account_status(
|
||||
cooldown: None,
|
||||
};
|
||||
}
|
||||
if facts.quota.is_exhausted() {
|
||||
if facts.quota.is_exhausted_at(now) {
|
||||
return status_projection(AccountStatus::QuotaExhausted);
|
||||
}
|
||||
if facts
|
||||
@@ -1316,6 +1343,7 @@ pub struct CredentialCasUpdateParts {
|
||||
pub expected_revision: CredentialRevision,
|
||||
pub profile: ProviderAccountUpdate,
|
||||
pub preserve_profile: bool,
|
||||
pub preserve_catalog_etag: Option<String>,
|
||||
pub preserve_access_token_expiry: bool,
|
||||
pub credential: PlaintextCredential,
|
||||
pub has_refresh_token: bool,
|
||||
@@ -1331,6 +1359,7 @@ pub struct CredentialCasUpdate {
|
||||
expected_revision: CredentialRevision,
|
||||
profile: ProviderAccountUpdate,
|
||||
preserve_profile: bool,
|
||||
preserve_catalog_etag: Option<String>,
|
||||
preserve_access_token_expiry: bool,
|
||||
credential: PlaintextCredential,
|
||||
has_refresh_token: bool,
|
||||
@@ -1386,6 +1415,7 @@ impl CredentialCasUpdate {
|
||||
expected_revision,
|
||||
profile,
|
||||
preserve_profile: false,
|
||||
preserve_catalog_etag: None,
|
||||
preserve_access_token_expiry: false,
|
||||
credential,
|
||||
has_refresh_token,
|
||||
@@ -1402,6 +1432,13 @@ impl CredentialCasUpdate {
|
||||
self
|
||||
}
|
||||
|
||||
/// 同一身份续期只续接旧版本、当前套餐和指定标识均匹配的目录
|
||||
#[must_use]
|
||||
pub fn with_preserved_catalog_etag(mut self, etag: Option<String>) -> Self {
|
||||
self.preserve_catalog_etag = etag;
|
||||
self
|
||||
}
|
||||
|
||||
/// 沿用同一访问令牌时,保留提交时的有效期,避免覆盖在途收到的撤销事实
|
||||
#[must_use]
|
||||
pub const fn preserving_access_token_expiry(mut self) -> Self {
|
||||
@@ -1475,6 +1512,7 @@ impl CredentialCasUpdate {
|
||||
expected_revision: self.expected_revision,
|
||||
profile: self.profile,
|
||||
preserve_profile: self.preserve_profile,
|
||||
preserve_catalog_etag: self.preserve_catalog_etag,
|
||||
preserve_access_token_expiry: self.preserve_access_token_expiry,
|
||||
credential: self.credential,
|
||||
has_refresh_token: self.has_refresh_token,
|
||||
@@ -1503,6 +1541,8 @@ pub struct QuotaObservationVersion {
|
||||
/// Provider quota 的一次完整观察结果
|
||||
#[derive(Clone, PartialEq)]
|
||||
pub struct QuotaObservation {
|
||||
/// 合并旧快照时校验读取的版本,独立观测不需要基准版本
|
||||
pub merge_base: Option<super::QuotaMergeBase>,
|
||||
/// 本地阈值决策与观测一起写入,策略已变时拒绝旧结论
|
||||
pub quota_pause: Option<super::QuotaPauseDecision>,
|
||||
/// 网络查询可额外校验请求出口与启用状态,避免连接变化后的迟到写入
|
||||
|
||||
@@ -94,8 +94,6 @@ pub struct QuotaMergeBase {
|
||||
/// 此次判断依据的策略,以及是否有通用窗口触发暂停
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct QuotaPauseDecision {
|
||||
/// 独立观测无需合并,依赖旧快照的判断必须随写入校验版本
|
||||
pub merge_base: Option<QuotaMergeBase>,
|
||||
pub limits: AccountQuotaSettings,
|
||||
pub paused: bool,
|
||||
}
|
||||
@@ -104,6 +104,7 @@ impl RuntimeAccount {
|
||||
/// 全快照共享的账号、Provider 与分组反向索引
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct RuntimeAccountDirectory {
|
||||
pub schedules: super::duty::AccountSchedules,
|
||||
accounts: BTreeMap<ProviderAccountId, RuntimeAccount>,
|
||||
providers_with_accounts: BTreeSet<ProviderKind>,
|
||||
providers_by_group: BTreeMap<AccountGroupId, BTreeSet<ProviderKind>>,
|
||||
@@ -126,6 +127,7 @@ impl RuntimeAccountDirectory {
|
||||
}
|
||||
}
|
||||
Self {
|
||||
schedules: Default::default(),
|
||||
accounts,
|
||||
providers_with_accounts,
|
||||
providers_by_group,
|
||||
@@ -143,6 +145,12 @@ impl RuntimeAccountDirectory {
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn with_schedules(mut self, schedules: super::duty::AccountSchedules) -> Self {
|
||||
self.schedules = schedules;
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn with_group_fast_modes(mut self, policies: BTreeMap<AccountGroupId, FastMode>) -> Self {
|
||||
self.group_fast_modes = policies;
|
||||
|
||||
@@ -261,6 +261,7 @@ pub struct AccountRuntimeSignals {
|
||||
pub recent_requests: u64,
|
||||
pub last_started_at: Option<SystemTime>,
|
||||
pub quota_reset_at: Option<SystemTime>,
|
||||
pub daily_used_percent: Option<u8>,
|
||||
pub quota_reset_windows: Option<Arc<[AccountQuotaResetWindow]>>,
|
||||
/// Provider 归一化的剩余额度基点:0 耗尽,10_000 全部可用
|
||||
pub quota_remaining_rank: Option<u64>,
|
||||
@@ -549,6 +550,7 @@ impl AccountRuntimeSignals {
|
||||
pub fn with_provider_quota(mut self, quota: Option<AccountQuotaSignals>) -> Self {
|
||||
if let Some(quota) = quota {
|
||||
self.quota_reset_at = quota.reset_at;
|
||||
self.daily_used_percent = quota.daily_used_percent();
|
||||
self.quota_reset_windows = quota.reset_windows;
|
||||
self.quota_remaining_rank = quota.remaining_rank;
|
||||
}
|
||||
@@ -583,6 +585,7 @@ pub struct AccountQuotaResetWindow {
|
||||
/// Provider 从私有 quota JSON 投影出的中立调度事实
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct AccountQuotaSignals {
|
||||
daily_used_percent: Option<u8>,
|
||||
reset_windows: Option<Arc<[AccountQuotaResetWindow]>>,
|
||||
reset_at: Option<SystemTime>,
|
||||
remaining_rank: Option<u64>,
|
||||
@@ -595,10 +598,22 @@ impl AccountQuotaSignals {
|
||||
Self {
|
||||
reset_at,
|
||||
remaining_rank,
|
||||
daily_used_percent: None,
|
||||
reset_windows: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn daily_used_percent(&self) -> Option<u8> {
|
||||
self.daily_used_percent
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn with_daily_used_percent(mut self, percent: Option<u8>) -> Self {
|
||||
self.daily_used_percent = percent;
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn with_reset_windows(mut self, windows: Vec<AccountQuotaResetWindow>) -> Self {
|
||||
self.reset_windows = (!windows.is_empty()).then(|| windows.into());
|
||||
@@ -664,6 +679,8 @@ pub struct AccountSelectionContext {
|
||||
/// 租约争用或队列让位只阻止立即选号,不排除等待资格
|
||||
pub busy_accounts: BTreeSet<ProviderAccountId>,
|
||||
pub preferred_account: Option<ProviderAccountId>,
|
||||
/// 经会话绑定或原生续接验证的账号,缓存偏好不能作为旧会话凭据
|
||||
pub bound_session_account: Option<ProviderAccountId>,
|
||||
/// 优先账号可调度时,是否优先于其它账号的持久权重
|
||||
pub preferred_account_overrides_weight: bool,
|
||||
pub round_robin_cursor: u64,
|
||||
@@ -674,6 +691,50 @@ pub struct AccountSelectionContext {
|
||||
}
|
||||
|
||||
impl AccountSelectionContext {
|
||||
fn off_shift_policy(
|
||||
&self,
|
||||
candidate: &AccountCandidate,
|
||||
) -> Option<super::duty::OffShiftSession> {
|
||||
let directory = self.account_scope.as_ref()?.directory();
|
||||
let id = candidate.account.id();
|
||||
let schedules = &directory.schedules;
|
||||
schedules
|
||||
.duty(
|
||||
id,
|
||||
directory.account(id)?,
|
||||
self.now,
|
||||
candidate.signals.daily_used_percent,
|
||||
)
|
||||
.filter(|duty| *duty != super::duty::ScheduleDuty::OnDuty)
|
||||
.map(|_| schedules.policy.off_shift_session)
|
||||
}
|
||||
|
||||
pub fn allows_shift(&self, candidate: &AccountCandidate) -> bool {
|
||||
match self.off_shift_policy(candidate) {
|
||||
None => true,
|
||||
Some(super::duty::OffShiftSession::Keep) => {
|
||||
self.bound_session_account.as_ref() == Some(candidate.account.id())
|
||||
}
|
||||
Some(super::duty::OffShiftSession::Rebind) => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// 下班后选择沿用原账号时,已有绑定优先于一般亲和与权重,健康和并发仍由共用资格判断约束
|
||||
pub fn prefer_retained_shift_owner(&mut self, candidates: &[AccountCandidate]) {
|
||||
if self.eligibility.bypasses_local_eligibility() {
|
||||
return;
|
||||
}
|
||||
let Some(id) = &self.bound_session_account else {
|
||||
return;
|
||||
};
|
||||
if let Some(candidate) = candidates.iter().find(|c| c.account.id() == id)
|
||||
&& self.off_shift_policy(candidate) == Some(super::duty::OffShiftSession::Keep)
|
||||
{
|
||||
self.preferred_account = Some(id.clone());
|
||||
self.preferred_account_overrides_weight = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// 本请求在该账号上可使用的并发上限;资格判断、租约与策略投影必须共用这一口径
|
||||
#[must_use]
|
||||
pub fn concurrency_limit(&self, candidate: &AccountCandidate) -> AccountConcurrency {
|
||||
@@ -1030,7 +1091,7 @@ impl AccountSelector {
|
||||
.account
|
||||
.status_projection(context.now, candidate.signals.cooldown)
|
||||
.status;
|
||||
if status != AccountStatus::Normal {
|
||||
if status != AccountStatus::Normal || !context.allows_shift(candidate) {
|
||||
return Some(AccountSchedulingBlocker::LocalAvailability);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,6 +13,14 @@ pub trait ProviderRuntimePolicyPort: Send + Sync {
|
||||
Box::pin(async { Ok(None) })
|
||||
}
|
||||
|
||||
/// 读取指定平台的全局运行设置,字段及缺省行为由该 Provider 定义
|
||||
fn load_provider_settings<'a>(
|
||||
&'a self,
|
||||
_provider: &'a ProviderKind,
|
||||
) -> BoxFuture<'a, Result<Option<OpaqueProviderData>, ProviderStoreError>> {
|
||||
Box::pin(async { Ok(None) })
|
||||
}
|
||||
|
||||
/// 后台 OpenAI 操作读取当前全局请求设置
|
||||
fn load_openai_request_settings(
|
||||
&self,
|
||||
|
||||
@@ -36,6 +36,9 @@ impl<'a> ProviderSessionAffinityState<'a> {
|
||||
|
||||
/// 原生续接的固定账号由调用方优先设置,不以软亲和覆盖
|
||||
pub fn apply_preference(&self, context: &mut AccountSelectionContext) {
|
||||
if context.bound_session_account.is_none() {
|
||||
context.bound_session_account = self.bound_account().cloned();
|
||||
}
|
||||
if self.policy.account_affinity() != AccountAffinity::Relaxed
|
||||
&& context.preferred_account.is_none()
|
||||
{
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! 可发布能力集合的中立身份、静态目录与保活合同;不解释包格式、进程或管理配置
|
||||
|
||||
use std::{fmt, sync::Arc};
|
||||
use std::{collections::HashMap, fmt, sync::Arc};
|
||||
|
||||
use futures::future::BoxFuture;
|
||||
|
||||
@@ -51,12 +51,24 @@ pub trait ExtensionSetLease: Send + Sync {
|
||||
pub struct ExtensionSetReference {
|
||||
id: ExtensionSetId,
|
||||
lease: Arc<dyn ExtensionSetLease>,
|
||||
alias_positions: Arc<HashMap<String, usize>>,
|
||||
}
|
||||
|
||||
impl ExtensionSetReference {
|
||||
#[must_use]
|
||||
pub fn new(id: ExtensionSetId, lease: Arc<dyn ExtensionSetLease>) -> Self {
|
||||
Self { id, lease }
|
||||
// 同名别名以发布顺序中的首条为准,目录投影和请求查找共享这一结果
|
||||
let mut alias_positions = HashMap::new();
|
||||
for (position, alias) in lease.model_aliases().iter().enumerate() {
|
||||
alias_positions
|
||||
.entry(alias.id.as_str().to_owned())
|
||||
.or_insert(position);
|
||||
}
|
||||
Self {
|
||||
id,
|
||||
lease,
|
||||
alias_positions: Arc::new(alias_positions),
|
||||
}
|
||||
}
|
||||
#[must_use]
|
||||
pub const fn id(&self) -> &ExtensionSetId {
|
||||
@@ -76,6 +88,19 @@ impl ExtensionSetReference {
|
||||
self.lease.model_aliases()
|
||||
}
|
||||
|
||||
pub(super) fn model_alias(&self, id: &str) -> Option<&ContributedModelAlias> {
|
||||
self.alias_positions
|
||||
.get(id)
|
||||
.map(|&position| &self.model_aliases()[position])
|
||||
}
|
||||
|
||||
pub(super) fn effective_model_aliases(&self) -> impl Iterator<Item = &ContributedModelAlias> {
|
||||
let aliases = self.model_aliases();
|
||||
self.alias_positions
|
||||
.values()
|
||||
.map(|&position| &aliases[position])
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn models(&self) -> &[ContributedModel] {
|
||||
self.lease.models()
|
||||
|
||||
@@ -154,7 +154,7 @@ pub enum SupportLevel {
|
||||
/// Provider 实时模型目录中的能力事实;不落 PostgreSQL
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ModelCapabilities {
|
||||
operations: BTreeSet<OperationKind>,
|
||||
operations: BTreeMap<OperationKind, Option<BTreeSet<crate::account::ProviderAccountId>>>,
|
||||
features: BTreeMap<Feature, SupportLevel>,
|
||||
max_output_tokens: Option<u64>,
|
||||
upstream_validates_features: bool,
|
||||
@@ -431,6 +431,32 @@ impl PublicModelProfile {
|
||||
impl ModelCapabilities {
|
||||
#[must_use]
|
||||
pub fn new(operations: BTreeSet<OperationKind>, max_output_tokens: Option<u64>) -> Self {
|
||||
Self::from_operations(
|
||||
operations.into_iter().map(|kind| (kind, None)).collect(),
|
||||
max_output_tokens,
|
||||
)
|
||||
}
|
||||
|
||||
/// 按账号声明各操作的支持范围,未声明该操作的账号不贡献原生能力
|
||||
#[must_use]
|
||||
pub fn from_operation_accounts(
|
||||
accounts: BTreeMap<OperationKind, BTreeSet<crate::account::ProviderAccountId>>,
|
||||
max_output_tokens: Option<u64>,
|
||||
) -> Self {
|
||||
Self::from_operations(
|
||||
accounts
|
||||
.into_iter()
|
||||
.filter(|(_, accounts)| !accounts.is_empty())
|
||||
.map(|(kind, accounts)| (kind, Some(accounts)))
|
||||
.collect(),
|
||||
max_output_tokens,
|
||||
)
|
||||
}
|
||||
|
||||
fn from_operations(
|
||||
operations: BTreeMap<OperationKind, Option<BTreeSet<crate::account::ProviderAccountId>>>,
|
||||
max_output_tokens: Option<u64>,
|
||||
) -> Self {
|
||||
Self {
|
||||
operations,
|
||||
features: BTreeMap::new(),
|
||||
@@ -530,8 +556,15 @@ impl ModelCapabilities {
|
||||
self
|
||||
}
|
||||
|
||||
fn operation_accounts(
|
||||
&self,
|
||||
kind: OperationKind,
|
||||
) -> Option<&BTreeSet<crate::account::ProviderAccountId>> {
|
||||
self.operations.get(&kind).and_then(Option::as_ref)
|
||||
}
|
||||
|
||||
pub(crate) fn supports_generation_protocol(&self, protocol: &str) -> bool {
|
||||
self.operations.contains(&OperationKind::Generate)
|
||||
self.operations.contains_key(&OperationKind::Generate)
|
||||
&& (self.native_generation_protocols.is_empty()
|
||||
|| self.native_generation_protocols.contains(protocol)
|
||||
|| self.translated_generation_protocols.contains(protocol))
|
||||
@@ -571,7 +604,7 @@ impl ModelCapabilities {
|
||||
&self,
|
||||
requirements: &CapabilityRequirements,
|
||||
) -> Option<BTreeSet<Feature>> {
|
||||
if !self.operations.contains(&requirements.operation())
|
||||
if !self.operations.contains_key(&requirements.operation())
|
||||
|| requirements
|
||||
.requested_output_tokens()
|
||||
.is_some_and(|requested| {
|
||||
|
||||
@@ -194,6 +194,7 @@ impl SnapshotAccountGroupMemberFacts {
|
||||
/// 一次一致性读取产生的全部 RuntimeSnapshot 持久事实
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct SnapshotFacts {
|
||||
schedules: crate::account::duty::AccountSchedules,
|
||||
config_revision: ConfigRevision,
|
||||
observed_current_revision: ConfigRevision,
|
||||
settings: SettingsValues,
|
||||
@@ -217,6 +218,7 @@ impl SnapshotFacts {
|
||||
Self {
|
||||
config_revision,
|
||||
observed_current_revision,
|
||||
schedules: Default::default(),
|
||||
settings,
|
||||
client_policies,
|
||||
account_groups,
|
||||
@@ -230,6 +232,12 @@ impl SnapshotFacts {
|
||||
self.config_revision
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn with_schedules(mut self, schedules: crate::account::duty::AccountSchedules) -> Self {
|
||||
self.schedules = schedules;
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn observed_current_revision(&self) -> ConfigRevision {
|
||||
self.observed_current_revision
|
||||
@@ -584,6 +592,7 @@ async fn compile_runtime_snapshot(
|
||||
.collect();
|
||||
let account_directory = Arc::new(
|
||||
RuntimeAccountDirectory::new(accounts)
|
||||
.with_schedules(facts.schedules)
|
||||
.with_group_model_access(group_model_access)
|
||||
.with_group_fast_modes(
|
||||
groups
|
||||
@@ -735,12 +744,6 @@ impl RuntimeSnapshot {
|
||||
self.extensions.as_ref()
|
||||
}
|
||||
|
||||
fn model_aliases(&self) -> &[super::ContributedModelAlias] {
|
||||
self.extensions
|
||||
.as_ref()
|
||||
.map_or(&[], |set| set.model_aliases())
|
||||
}
|
||||
|
||||
fn contributed_models(&self) -> &[super::ContributedModel] {
|
||||
self.extensions.as_ref().map_or(&[], |set| set.models())
|
||||
}
|
||||
@@ -762,9 +765,7 @@ impl RuntimeSnapshot {
|
||||
}
|
||||
|
||||
fn model_alias(&self, model: &str) -> Option<&super::ContributedModelAlias> {
|
||||
self.model_aliases()
|
||||
.iter()
|
||||
.find(|alias| alias.id.as_str() == model)
|
||||
self.extensions.as_ref()?.model_alias(model)
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
@@ -897,6 +898,21 @@ impl RuntimeSnapshot {
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn account_schedule_duty(
|
||||
&self,
|
||||
id: &ProviderAccountId,
|
||||
now: std::time::SystemTime,
|
||||
daily_used_percent: Option<u8>,
|
||||
) -> Option<crate::account::duty::ScheduleDuty> {
|
||||
self.account_directory.schedules.duty(
|
||||
id,
|
||||
self.account_directory.account(id)?,
|
||||
now,
|
||||
daily_used_percent,
|
||||
)
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn all_account_scope(&self) -> Arc<FrozenAccountScope> {
|
||||
Arc::new(FrozenAccountScope::new(
|
||||
@@ -947,18 +963,21 @@ impl RuntimeSnapshot {
|
||||
.keys()
|
||||
.filter_map(|model| PublicModelId::new(model.clone()).ok()),
|
||||
);
|
||||
models.extend(
|
||||
self.model_aliases()
|
||||
.iter()
|
||||
.filter(|alias| &alias.provider == provider)
|
||||
.map(|alias| alias.id.clone()),
|
||||
);
|
||||
models.extend(
|
||||
self.contributed_models()
|
||||
.iter()
|
||||
.filter(|model| &model.provider == provider)
|
||||
.map(|model| model.id.clone()),
|
||||
);
|
||||
if let Some(extensions) = &self.extensions {
|
||||
for alias in extensions.effective_model_aliases() {
|
||||
if &alias.provider == provider {
|
||||
models.insert(alias.id.clone());
|
||||
} else {
|
||||
models.remove(&alias.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
models.into_iter().collect()
|
||||
}
|
||||
|
||||
@@ -971,37 +990,12 @@ impl RuntimeSnapshot {
|
||||
let Some(presentations) = self.provider_model_presentations.get(provider) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let mut profiles = BTreeMap::new();
|
||||
for (model, presentation) in presentations {
|
||||
if let Ok(public_model) = PublicModelId::new(model.as_str().to_owned()) {
|
||||
profiles.insert(public_model, presentation);
|
||||
}
|
||||
}
|
||||
// 映射覆盖同名模型时,只展示目标画像,包括目标没有画像的情况
|
||||
for alias in self.settings.values.model_mappings.keys() {
|
||||
let Ok(public_model) = PublicModelId::new(alias.clone()) else {
|
||||
continue;
|
||||
};
|
||||
let target = self.mapped_model(alias);
|
||||
if let Some(presentation) = presentations.get(target.as_str()) {
|
||||
profiles.insert(public_model, presentation);
|
||||
} else {
|
||||
profiles.remove(&public_model);
|
||||
}
|
||||
}
|
||||
for alias in self.model_aliases() {
|
||||
if &alias.provider == provider
|
||||
&& let Some(presentation) = presentations.get(&alias.target)
|
||||
{
|
||||
profiles.insert(alias.id.clone(), presentation);
|
||||
} else {
|
||||
profiles.remove(&alias.id);
|
||||
}
|
||||
}
|
||||
profiles
|
||||
self.public_models_for_provider(provider)
|
||||
.into_iter()
|
||||
.map(|(model, presentation)| {
|
||||
super::PublicModelProfile::new(model, presentation.clone())
|
||||
.filter_map(|model| {
|
||||
let target = self.mapped_model(model.as_str());
|
||||
let presentation = presentations.get(target.as_str())?;
|
||||
Some(super::PublicModelProfile::new(model, presentation.clone()))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -1087,45 +1081,47 @@ impl RuntimeSnapshot {
|
||||
scope: &Arc<FrozenAccountScope>,
|
||||
operation: &Operation,
|
||||
) -> Vec<PublicModelId> {
|
||||
let requirements = operation.capability_requirements();
|
||||
self.public_models_for_scope(scope)
|
||||
.into_iter()
|
||||
.filter(|model| {
|
||||
self.plan(
|
||||
model,
|
||||
operation,
|
||||
Arc::clone(scope),
|
||||
&RoutingContext::default(),
|
||||
)
|
||||
.is_ok()
|
||||
|| scope.provider_kinds().iter().any(|provider| {
|
||||
self.contains_public_model_for_provider(model, provider)
|
||||
&& self
|
||||
.model_group(provider, &self.mapped_model(model.as_str()))
|
||||
.is_some_and(|group| {
|
||||
group
|
||||
.match_operation(
|
||||
operation,
|
||||
&operation.capability_requirements(),
|
||||
)
|
||||
.is_some()
|
||||
&& group.reasoning_variants.values().any(|variant| {
|
||||
self.variant_allowed(provider, variant, scope)
|
||||
&& self
|
||||
.provider_models
|
||||
.get(provider)
|
||||
.and_then(|models| models.get(&variant.model))
|
||||
.is_some_and(|target| {
|
||||
target
|
||||
.match_operation(
|
||||
operation,
|
||||
&operation
|
||||
.capability_requirements(),
|
||||
)
|
||||
.is_some()
|
||||
})
|
||||
})
|
||||
})
|
||||
if self
|
||||
.plan(
|
||||
model,
|
||||
operation,
|
||||
Arc::clone(scope),
|
||||
&RoutingContext::default(),
|
||||
)
|
||||
.is_ok()
|
||||
{
|
||||
return true;
|
||||
}
|
||||
// 目录查询没有指定档位,只需一个获准的成员账号支持该操作
|
||||
let target = self.mapped_model(model.as_str());
|
||||
scope.provider_kinds().iter().any(|provider| {
|
||||
let Some(group) = self.model_group(provider, &target) else {
|
||||
return false;
|
||||
};
|
||||
if !self.contains_public_model_for_provider(model, provider)
|
||||
|| group.match_operation(operation, &requirements).is_none()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
group.reasoning_variants.values().any(|variant| {
|
||||
let Some(member) = self
|
||||
.provider_models
|
||||
.get(provider)
|
||||
.and_then(|models| models.get(&variant.model))
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
let accounts = member.operation_accounts(operation.kind());
|
||||
member.match_operation(operation, &requirements).is_some()
|
||||
&& Self::variant_accounts(provider, variant, scope).any(|account| {
|
||||
accounts.is_none_or(|allowed| allowed.contains(account))
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -1212,12 +1208,20 @@ impl RuntimeSnapshot {
|
||||
profiles.retain(|profile| {
|
||||
self.native_catalog_model_allowed_for_scope(provider, profile.model(), scope)
|
||||
&& protocol.is_none_or(|protocol| {
|
||||
let target = self.mapped_model(profile.model().as_str());
|
||||
self.provider_models
|
||||
.get(provider)
|
||||
.and_then(|models| {
|
||||
models.get(self.mapped_model(profile.model().as_str()).as_str())
|
||||
.and_then(|models| models.get(target.as_str()))
|
||||
.is_some_and(|model| {
|
||||
model.supports_generation_protocol(protocol)
|
||||
&& model
|
||||
.operation_accounts(OperationKind::Generate)
|
||||
.is_none_or(|accounts| {
|
||||
accounts
|
||||
.iter()
|
||||
.any(|account| scope.allows_model(account, &target))
|
||||
})
|
||||
})
|
||||
.is_some_and(|model| model.supports_generation_protocol(protocol))
|
||||
})
|
||||
});
|
||||
// Provider 画像按公开 ID 排序,追加的插件画像保留注册顺序,不参与二分查找
|
||||
@@ -1780,6 +1784,25 @@ impl RuntimeSnapshot {
|
||||
&& &model.id == public_model
|
||||
})
|
||||
.collect();
|
||||
if enforce_routing_policy
|
||||
&& let Some(native_accounts) =
|
||||
capabilities.and_then(|model| model.operation_accounts(operation.kind()))
|
||||
{
|
||||
// 适配器独立声明账号与能力,随后与原生候选分别匹配
|
||||
let mut accounts = std::borrow::Cow::Borrowed(native_accounts);
|
||||
if !contributions.is_empty() {
|
||||
accounts.to_mut().extend(
|
||||
contributions
|
||||
.iter()
|
||||
.flat_map(|model| model.accounts.iter().cloned()),
|
||||
);
|
||||
}
|
||||
let narrowed = candidate_scope.restricted_to(&Default::default(), &accounts);
|
||||
if !narrowed.allows_provider_model(provider, upstream_model.as_str()) {
|
||||
continue;
|
||||
}
|
||||
candidate_scope = Arc::new(narrowed);
|
||||
}
|
||||
let emulated_features = if contributions.is_empty() {
|
||||
match capabilities {
|
||||
Some(capabilities) => {
|
||||
@@ -2000,10 +2023,13 @@ impl RuntimeSnapshot {
|
||||
continue;
|
||||
};
|
||||
// 当前范围已有原生型号时仍走普通路由,其他协议的同名模型不能接管 GenAI
|
||||
if models
|
||||
.get(requested_model)
|
||||
.is_some_and(|model| model.native_generation_protocols.contains(protocol))
|
||||
{
|
||||
if models.get(requested_model).is_some_and(|model| {
|
||||
model.native_generation_protocols.contains(protocol)
|
||||
&& model.operations.contains_key(&OperationKind::Generate)
|
||||
&& model
|
||||
.operation_accounts(OperationKind::Generate)
|
||||
.is_none_or(|accounts| accounts.iter().any(|account| scope.allows(account)))
|
||||
}) {
|
||||
return None;
|
||||
}
|
||||
let Some(targets) = models.values().find_map(|model| {
|
||||
@@ -2127,17 +2153,27 @@ impl RuntimeSnapshot {
|
||||
} else {
|
||||
true
|
||||
};
|
||||
let mut candidate_scope = Arc::clone(&account_scope);
|
||||
let model_capable = upstream_model.is_none_or(|model| {
|
||||
match self
|
||||
let Some(capabilities) = self
|
||||
.provider_models
|
||||
.get(provider)
|
||||
.and_then(|models| models.get(model))
|
||||
else {
|
||||
return !self.exhaustive_provider_catalogs.contains(provider);
|
||||
};
|
||||
if capabilities
|
||||
.match_operation(operation, &operation.capability_requirements())
|
||||
.is_none()
|
||||
{
|
||||
Some(capabilities) => capabilities
|
||||
.match_operation(operation, &operation.capability_requirements())
|
||||
.is_some(),
|
||||
None => !self.exhaustive_provider_catalogs.contains(provider),
|
||||
return false;
|
||||
}
|
||||
if let Some(accounts) = capabilities.operation_accounts(operation.kind()) {
|
||||
candidate_scope =
|
||||
Arc::new(account_scope.restricted_to(&Default::default(), accounts));
|
||||
return candidate_scope.allows_provider_model(provider, model.as_str());
|
||||
}
|
||||
true
|
||||
});
|
||||
if !model_binding_valid || !model_capable {
|
||||
return Err(RoutingError::UnsupportedProviderEndpoint {
|
||||
@@ -2151,7 +2187,7 @@ impl RuntimeSnapshot {
|
||||
provider: provider.clone(),
|
||||
upstream_model: upstream_model.cloned(),
|
||||
emulated_features: BTreeSet::new(),
|
||||
account_scope: Arc::clone(&account_scope),
|
||||
account_scope: candidate_scope,
|
||||
};
|
||||
Ok(RoutingPlan {
|
||||
request_body_limit: self.responses_max_decompressed_body_bytes(),
|
||||
|
||||
@@ -2,7 +2,9 @@
|
||||
|
||||
use std::str::FromStr;
|
||||
|
||||
use chrono::{DateTime, Days, NaiveDate, NaiveDateTime, Offset as _, TimeZone as _, Utc};
|
||||
use chrono::{
|
||||
DateTime, Days, NaiveDate, NaiveDateTime, Offset as _, TimeZone as _, Timelike as _, Utc,
|
||||
};
|
||||
use chrono_tz::{GapInfo, Tz};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
@@ -41,6 +43,11 @@ impl DeploymentTimeZone {
|
||||
value.with_timezone(&self.0)
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn minute_of_day(self, value: DateTime<Utc>) -> u16 {
|
||||
(self.local(value).num_seconds_from_midnight() / 60) as u16
|
||||
}
|
||||
|
||||
/// 重复本地时刻只取较早时间点,缺失时刻由调用方决定是否跳过
|
||||
#[must_use]
|
||||
pub fn resolve_local(self, value: NaiveDateTime) -> Option<DateTime<Utc>> {
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
//! 每日排班在内置选号、等待资格和会话绑定上的边界
|
||||
|
||||
use super::*;
|
||||
use gateway_core::account::duty::{
|
||||
AccountSchedules, DailyShift, OffShiftSession, ScheduleDuty, SchedulePolicy,
|
||||
};
|
||||
use gateway_core::routing::AccountGroupId;
|
||||
|
||||
fn shift(start: u16, end: u16) -> DailyShift {
|
||||
DailyShift {
|
||||
id: "shift".into(),
|
||||
start,
|
||||
end,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn daily_schedule_combines_memberships_and_preserves_default_pool() {
|
||||
let group = AccountGroupId::new("grp_11111111111111111111111111111111").unwrap();
|
||||
let provider = ProviderKind::new("openai").unwrap();
|
||||
let managed = candidate("acct_managed", 0, None);
|
||||
let unmanaged = candidate("acct_unmanaged", 0, None);
|
||||
let mut schedules = AccountSchedules::default();
|
||||
schedules
|
||||
.accounts
|
||||
.insert("acct_managed".into(), vec![shift(540, 1020)]);
|
||||
schedules
|
||||
.groups
|
||||
.insert(group.as_str().into(), vec![shift(1290, 405)]);
|
||||
let directory = RuntimeAccountDirectory::new(BTreeMap::from([
|
||||
(
|
||||
managed.account.id().clone(),
|
||||
RuntimeAccount::new(provider.clone(), BTreeSet::from([group])),
|
||||
),
|
||||
(
|
||||
unmanaged.account.id().clone(),
|
||||
RuntimeAccount::new(provider, BTreeSet::new()),
|
||||
),
|
||||
]))
|
||||
.with_schedules(schedules);
|
||||
let mut context = context(RotationStrategy::Smart);
|
||||
context.account_scope = Some(Arc::new(FrozenAccountScope::new(
|
||||
Arc::new(directory),
|
||||
ClientRoutingScope::AllAccounts,
|
||||
)));
|
||||
for (minute, expected) in [
|
||||
(0, true),
|
||||
(404, true),
|
||||
(405, false),
|
||||
(539, false),
|
||||
(540, true),
|
||||
(1019, true),
|
||||
(1020, false),
|
||||
(1290, true),
|
||||
] {
|
||||
context.now =
|
||||
std::time::UNIX_EPOCH + Duration::from_secs(((minute + 1440 - 480) % 1440) * 60);
|
||||
assert_eq!(
|
||||
AccountSelector
|
||||
.select(std::slice::from_ref(&managed), &context)
|
||||
.is_some(),
|
||||
expected
|
||||
);
|
||||
assert!(
|
||||
AccountSelector
|
||||
.select(std::slice::from_ref(&unmanaged), &context)
|
||||
.is_some()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shifts_follow_the_deployment_zone_across_daylight_saving_time() {
|
||||
let managed = candidate("acct_managed", 0, None);
|
||||
let account = RuntimeAccount::new(managed.account.provider().clone(), BTreeSet::new());
|
||||
let id = managed.account.id();
|
||||
let schedules = AccountSchedules {
|
||||
timezone: "America/New_York".parse().unwrap(),
|
||||
accounts: BTreeMap::from([(id.as_str().to_owned(), vec![shift(60, 120)])]),
|
||||
..Default::default()
|
||||
};
|
||||
for (instant, expected) in [
|
||||
("2026-03-08T06:59:00Z", true),
|
||||
("2026-03-08T07:00:00Z", false),
|
||||
("2026-11-01T05:30:00Z", true),
|
||||
("2026-11-01T06:30:00Z", true),
|
||||
("2026-11-01T07:00:00Z", false),
|
||||
] {
|
||||
let now = instant.parse::<chrono::DateTime<chrono::Utc>>().unwrap();
|
||||
assert_eq!(
|
||||
schedules.duty(id, &account, now.into(), None),
|
||||
Some(if expected {
|
||||
ScheduleDuty::OnDuty
|
||||
} else {
|
||||
ScheduleDuty::OffDuty
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disabled_schedule_bypasses_empty_shifts_and_quota_without_removing_them() {
|
||||
let managed = candidate("acct_managed", 0, None);
|
||||
let account = RuntimeAccount::new(managed.account.provider().clone(), BTreeSet::new());
|
||||
let id = managed.account.id();
|
||||
let mut schedules = AccountSchedules {
|
||||
accounts: BTreeMap::from([(id.as_str().to_owned(), vec![])]),
|
||||
policy: SchedulePolicy {
|
||||
enabled: false,
|
||||
early_finish: true,
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
let now = std::time::UNIX_EPOCH;
|
||||
assert_eq!(schedules.duty(id, &account, now, Some(100)), None);
|
||||
schedules.policy.enabled = true;
|
||||
assert_eq!(
|
||||
schedules.duty(id, &account, now, None),
|
||||
Some(ScheduleDuty::OffDuty)
|
||||
);
|
||||
schedules
|
||||
.accounts
|
||||
.get_mut(id.as_str())
|
||||
.unwrap()
|
||||
.push(shift(0, 0));
|
||||
assert_eq!(
|
||||
schedules.duty(id, &account, now, Some(100)),
|
||||
Some(ScheduleDuty::QuotaReached)
|
||||
);
|
||||
schedules.policy.enabled = false;
|
||||
assert_eq!(schedules.duty(id, &account, now, Some(100)), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn daily_quota_and_empty_members_only_restrict_new_work() {
|
||||
let mut managed = candidate("acct_managed", 0, None);
|
||||
let mut context = context(RotationStrategy::Smart);
|
||||
let default_session = SchedulePolicy::default().off_shift_session;
|
||||
for (shifts, percent, bound, session_policy, expected) in [
|
||||
(vec![], None, false, default_session, false),
|
||||
(vec![], None, true, default_session, true),
|
||||
(vec![], None, true, OffShiftSession::Rebind, false),
|
||||
(
|
||||
vec![shift(0, 0)],
|
||||
None,
|
||||
false,
|
||||
OffShiftSession::Rebind,
|
||||
true,
|
||||
),
|
||||
(
|
||||
vec![shift(0, 0)],
|
||||
Some(79),
|
||||
false,
|
||||
OffShiftSession::Rebind,
|
||||
true,
|
||||
),
|
||||
(
|
||||
vec![shift(0, 0)],
|
||||
Some(80),
|
||||
false,
|
||||
OffShiftSession::Keep,
|
||||
false,
|
||||
),
|
||||
(
|
||||
vec![shift(0, 0)],
|
||||
Some(99),
|
||||
true,
|
||||
OffShiftSession::Keep,
|
||||
true,
|
||||
),
|
||||
] {
|
||||
managed.signals.daily_used_percent = percent;
|
||||
context.bound_session_account = bound.then(|| managed.account.id().clone());
|
||||
let retained = bound
|
||||
&& session_policy == OffShiftSession::Keep
|
||||
&& (shifts.is_empty() || percent.is_some_and(|p| p >= 80));
|
||||
let schedules = AccountSchedules {
|
||||
timezone: Default::default(),
|
||||
accounts: BTreeMap::from([("acct_managed".into(), shifts)]),
|
||||
groups: Default::default(),
|
||||
policy: SchedulePolicy {
|
||||
enabled: true,
|
||||
off_shift_session: session_policy,
|
||||
early_finish: true,
|
||||
limit_percent: 80,
|
||||
},
|
||||
};
|
||||
let directory = RuntimeAccountDirectory::new(BTreeMap::from([(
|
||||
managed.account.id().clone(),
|
||||
RuntimeAccount::new(managed.account.provider().clone(), BTreeSet::new()),
|
||||
)]))
|
||||
.with_schedules(schedules);
|
||||
context.account_scope = Some(Arc::new(FrozenAccountScope::new(
|
||||
Arc::new(directory),
|
||||
ClientRoutingScope::AllAccounts,
|
||||
)));
|
||||
let pool = std::slice::from_ref(&managed);
|
||||
context.preferred_account = None;
|
||||
context.preferred_account_overrides_weight = false;
|
||||
context.prefer_retained_shift_owner(pool);
|
||||
assert_eq!(
|
||||
context.preferred_account.as_ref() == Some(managed.account.id()),
|
||||
retained
|
||||
);
|
||||
assert_eq!(context.preferred_account_overrides_weight, retained);
|
||||
assert_eq!(AccountSelector.select(pool, &context).is_some(), expected);
|
||||
context.busy_accounts.insert(managed.account.id().clone());
|
||||
assert_eq!(
|
||||
AccountSelector
|
||||
.wait_candidates(pool, &context)
|
||||
.contains(managed.account.id()),
|
||||
expected
|
||||
);
|
||||
assert!(AccountSelector.select(pool, &context).is_none());
|
||||
context.busy_accounts.clear();
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
//! 账号领域测试入口,以及候选账号与调度输入构造辅助
|
||||
|
||||
mod duty;
|
||||
mod location;
|
||||
mod model_access;
|
||||
mod proxy;
|
||||
@@ -60,6 +61,7 @@ fn candidate(id: &str, in_flight: u32, remaining: Option<u64>) -> AccountCandida
|
||||
recent_requests: 0,
|
||||
last_started_at: None,
|
||||
quota_reset_at: None,
|
||||
daily_used_percent: None,
|
||||
quota_reset_windows: None,
|
||||
quota_remaining_rank: remaining,
|
||||
cooldown: None,
|
||||
@@ -113,6 +115,7 @@ fn context(strategy: RotationStrategy) -> AccountSelectionContext {
|
||||
excluded_accounts: BTreeSet::new(),
|
||||
busy_accounts: Default::default(),
|
||||
preferred_account: None,
|
||||
bound_session_account: None,
|
||||
preferred_account_overrides_weight: false,
|
||||
round_robin_cursor: 0,
|
||||
eligibility: AccountEligibilityPolicy::Enforce,
|
||||
@@ -234,6 +237,7 @@ fn diagnostic_selection_bypasses_all_local_account_eligibility() {
|
||||
recent_requests: 0,
|
||||
last_started_at: None,
|
||||
quota_reset_at: None,
|
||||
daily_used_percent: None,
|
||||
quota_reset_windows: None,
|
||||
quota_remaining_rank: None,
|
||||
cooldown: None,
|
||||
@@ -255,6 +259,7 @@ fn diagnostic_selection_bypasses_all_local_account_eligibility() {
|
||||
recent_requests: 0,
|
||||
last_started_at: None,
|
||||
quota_reset_at: None,
|
||||
daily_used_percent: None,
|
||||
quota_reset_windows: None,
|
||||
quota_remaining_rank: None,
|
||||
cooldown: None,
|
||||
@@ -651,6 +656,7 @@ fn provider_quota_overlay_should_preserve_store_concurrency_facts() {
|
||||
recent_requests: 0,
|
||||
last_started_at: Some(last_started_at),
|
||||
quota_reset_at: None,
|
||||
daily_used_percent: None,
|
||||
quota_reset_windows: None,
|
||||
quota_remaining_rank: None,
|
||||
cooldown: None,
|
||||
@@ -1073,6 +1079,41 @@ fn elapsed_quota_reset_does_not_fabricate_recovery() {
|
||||
assert_eq!(selected.candidate().account.id().as_str(), "acct_healthy");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quota_deadline_releases_status_and_selection_at_the_same_instant() {
|
||||
let mut selection = context(RotationStrategy::Smart);
|
||||
let deadline = selection.now;
|
||||
let state = QuotaState::exhausted(
|
||||
QuotaEvidence::UsageLimitReached,
|
||||
deadline - Duration::from_secs(300),
|
||||
None,
|
||||
)
|
||||
.with_exhaustion_deadline(Some(deadline));
|
||||
let mut account = candidate("acct_window", 0, Some(100));
|
||||
account.account =
|
||||
account
|
||||
.account
|
||||
.with_account_facts(true, CredentialState::Ready, state, None, None);
|
||||
let candidates = [account];
|
||||
for (time, status) in [
|
||||
(
|
||||
deadline - Duration::from_nanos(1),
|
||||
AccountStatus::QuotaExhausted,
|
||||
),
|
||||
(deadline, AccountStatus::Normal),
|
||||
] {
|
||||
selection.now = time;
|
||||
assert_eq!(
|
||||
candidates[0].account.status_projection(time, None).status,
|
||||
status
|
||||
);
|
||||
assert_eq!(
|
||||
AccountSelector.select(&candidates, &selection).is_some(),
|
||||
status == AccountStatus::Normal
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn due_probe_freeze_blocks_scheduling_and_remains_visible_as_rate_limited() {
|
||||
use gateway_core::account::{AccountCooldown, AccountCooldownKind};
|
||||
|
||||
@@ -2473,6 +2473,7 @@ impl Provider for PolicySelectingProvider {
|
||||
recent_requests: 0,
|
||||
last_started_at: None,
|
||||
quota_reset_at: None,
|
||||
daily_used_percent: None,
|
||||
quota_reset_windows: None,
|
||||
quota_remaining_rank: None,
|
||||
cooldown: None,
|
||||
@@ -2486,6 +2487,7 @@ impl Provider for PolicySelectingProvider {
|
||||
excluded_accounts: attempt.excluded_accounts().clone(),
|
||||
busy_accounts: Default::default(),
|
||||
preferred_account: attempt.required_account().cloned(),
|
||||
bound_session_account: None,
|
||||
preferred_account_overrides_weight: true,
|
||||
round_robin_cursor: 0,
|
||||
eligibility: AccountEligibilityPolicy::Enforce,
|
||||
|
||||
@@ -266,7 +266,10 @@ fn capability_declaration_preserves_original_semantics_and_recomputes_upstream_n
|
||||
|
||||
// 后续普通正文修改也不能删掉未承担的原始语义,或藏起实际新增的需求
|
||||
converted.as_object_mut().unwrap().remove("tools");
|
||||
converted["input"] = json!([{"type":"input_image","image_url":"synthetic"}]);
|
||||
converted["input"] = json!([{
|
||||
"role": "user",
|
||||
"content": [{"type": "input_image", "image_url": "https://example.com/image.png"}]
|
||||
}]);
|
||||
let request = request
|
||||
.replace_parts(
|
||||
"openai".into(),
|
||||
|
||||
@@ -78,6 +78,7 @@ fn candidate(id: &str) -> AccountCandidate {
|
||||
recent_requests: 0,
|
||||
last_started_at: None,
|
||||
quota_reset_at: None,
|
||||
daily_used_percent: None,
|
||||
quota_reset_windows: None,
|
||||
quota_remaining_rank: None,
|
||||
cooldown: None,
|
||||
@@ -113,6 +114,7 @@ fn context() -> AccountSelectionContext {
|
||||
excluded_accounts: BTreeSet::new(),
|
||||
busy_accounts: Default::default(),
|
||||
preferred_account: Some(account_id("acct_a")),
|
||||
bound_session_account: None,
|
||||
preferred_account_overrides_weight: true,
|
||||
round_robin_cursor: 0,
|
||||
eligibility: AccountEligibilityPolicy::Enforce,
|
||||
|
||||
@@ -12,6 +12,7 @@ fn scheduling_state_preserves_provider_neutral_signals() {
|
||||
recent_requests: 0,
|
||||
last_started_at: None,
|
||||
quota_reset_at: None,
|
||||
daily_used_percent: None,
|
||||
quota_reset_windows: None,
|
||||
quota_remaining_rank: Some(7),
|
||||
cooldown: None,
|
||||
|
||||
@@ -40,6 +40,7 @@ fn candidate(id: &str, busy: bool) -> AccountCandidate {
|
||||
recent_requests: 0,
|
||||
last_started_at: None,
|
||||
quota_reset_at: None,
|
||||
daily_used_percent: None,
|
||||
quota_reset_windows: None,
|
||||
quota_remaining_rank: None,
|
||||
cooldown: None,
|
||||
@@ -58,6 +59,7 @@ fn context(mode: AccountAffinity) -> AccountSelectionContext {
|
||||
excluded_accounts: Default::default(),
|
||||
busy_accounts: Default::default(),
|
||||
preferred_account: None,
|
||||
bound_session_account: None,
|
||||
preferred_account_overrides_weight: false,
|
||||
round_robin_cursor: 0,
|
||||
eligibility: AccountEligibilityPolicy::Enforce,
|
||||
|
||||
@@ -115,7 +115,15 @@ fn native_search_helper_routes_only_to_each_authorized_accounts_own_target() {
|
||||
ProviderModel::new(
|
||||
provider.clone(),
|
||||
UpstreamModelId::new("search-helper").unwrap(),
|
||||
caps().with_generation_protocol(same_name_protocol),
|
||||
ModelCapabilities::from_operation_accounts(
|
||||
[(
|
||||
OperationKind::Generate,
|
||||
[ProviderAccountId::new("acct_first").unwrap()].into(),
|
||||
)]
|
||||
.into(),
|
||||
None,
|
||||
)
|
||||
.with_generation_protocol(same_name_protocol),
|
||||
),
|
||||
],
|
||||
vec![],
|
||||
@@ -158,6 +166,15 @@ fn native_search_helper_routes_only_to_each_authorized_accounts_own_target() {
|
||||
route("openai", BTreeMap::new(), scope.clone()),
|
||||
Err(RoutingError::WebSearchUnavailable)
|
||||
));
|
||||
let second_only = Arc::new(scope.restricted_to(
|
||||
&Default::default(),
|
||||
&[ProviderAccountId::new("acct_second").unwrap()].into(),
|
||||
));
|
||||
let next = route("genai", targets.clone(), second_only).unwrap();
|
||||
assert_eq!(
|
||||
next.candidates()[0].upstream_model().unwrap().as_str(),
|
||||
"search-b"
|
||||
);
|
||||
assert!(matches!(
|
||||
route("genai", targets, scope),
|
||||
Err(RoutingError::GroupModelDenied)
|
||||
@@ -212,14 +229,16 @@ fn reasoning_groups_resolve_before_account_and_group_model_policies() {
|
||||
)
|
||||
.unwrap(),
|
||||
));
|
||||
let genai = |caps: ModelCapabilities| {
|
||||
caps.with_generation_protocol("genai")
|
||||
.with_translated_generation_protocols(["openai"])
|
||||
.with_upstream_feature_validation()
|
||||
};
|
||||
let caps = || {
|
||||
ModelCapabilities::new(
|
||||
genai(ModelCapabilities::new(
|
||||
BTreeSet::from([OperationKind::Generate, OperationKind::CountTokens]),
|
||||
None,
|
||||
)
|
||||
.with_generation_protocol("genai")
|
||||
.with_translated_generation_protocols(["openai"])
|
||||
.with_upstream_feature_validation()
|
||||
))
|
||||
};
|
||||
let variants = BTreeMap::from_iter(["medium", "high"].map(|level| {
|
||||
(
|
||||
@@ -293,7 +312,17 @@ fn reasoning_groups_resolve_before_account_and_group_model_policies() {
|
||||
ProviderModel::new(
|
||||
provider.clone(),
|
||||
UpstreamModelId::new("family-high").unwrap(),
|
||||
caps().with_account_metadata(BTreeMap::from([
|
||||
genai(ModelCapabilities::from_operation_accounts(
|
||||
BTreeMap::from([
|
||||
(
|
||||
OperationKind::Generate,
|
||||
[declared.clone(), high_only.clone()].into(),
|
||||
),
|
||||
(OperationKind::CountTokens, [declared.clone()].into()),
|
||||
]),
|
||||
None,
|
||||
))
|
||||
.with_account_metadata(BTreeMap::from([
|
||||
(declared.clone(), AccountModelMetadata::default()),
|
||||
(
|
||||
high_only.clone(),
|
||||
@@ -428,12 +457,37 @@ fn reasoning_groups_resolve_before_account_and_group_model_policies() {
|
||||
assert!(target.account_scope().allows(&declared));
|
||||
assert!(!target.account_scope().allows(&other));
|
||||
assert!(!target.account_scope().allows(&high_only));
|
||||
let only_high_scope = all.restricted_to(&BTreeSet::new(), &BTreeSet::from([high_only]));
|
||||
let only_high_scope =
|
||||
Arc::new(all.restricted_to(&BTreeSet::new(), &BTreeSet::from([high_only])));
|
||||
let high_model = UpstreamModelId::new("family-high").unwrap();
|
||||
for (count, supported) in [(false, true), (true, false)] {
|
||||
let request = operation("", count);
|
||||
let listed = snapshot.public_models_for_operation(&only_high_scope, &request);
|
||||
for name in ["family", "family-high", "alias"] {
|
||||
assert_eq!(
|
||||
listed.contains(&PublicModelId::new(name).unwrap()),
|
||||
supported,
|
||||
"{name} {count}"
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
snapshot
|
||||
.plan_provider_endpoint(
|
||||
&provider,
|
||||
Some(&high_model),
|
||||
&request,
|
||||
only_high_scope.clone(),
|
||||
&Default::default()
|
||||
)
|
||||
.is_ok(),
|
||||
supported
|
||||
);
|
||||
}
|
||||
assert!(matches!(
|
||||
snapshot.plan(
|
||||
&base,
|
||||
&native_search,
|
||||
Arc::new(only_high_scope.clone()),
|
||||
only_high_scope.clone(),
|
||||
&RoutingContext::default()
|
||||
),
|
||||
Err(RoutingError::WebSearchUnavailable)
|
||||
@@ -731,7 +785,7 @@ fn same_name_native_and_adapted_sources_keep_account_capabilities_separate() {
|
||||
operation::{Feature, GenerateRequest, Operation, ProtocolPayload},
|
||||
routing::{ContributedModel, SupportLevel},
|
||||
};
|
||||
struct Catalog;
|
||||
struct Catalog(ModelCapabilities);
|
||||
impl ProviderCatalogPort for Catalog {
|
||||
fn catalog_generations(&self) -> BTreeMap<ProviderKind, ProviderCatalogGeneration> {
|
||||
[(
|
||||
@@ -749,7 +803,9 @@ fn same_name_native_and_adapted_sources_keep_account_capabilities_separate() {
|
||||
Ok(vec![
|
||||
ProviderModelCapabilities::new(
|
||||
UpstreamModelId::new("shared-model").unwrap(),
|
||||
super::capabilities().with_feature(Feature::Tools, SupportLevel::Native),
|
||||
self.0
|
||||
.clone()
|
||||
.with_feature(Feature::Tools, SupportLevel::Native),
|
||||
)
|
||||
.with_catalog_accounts([ProviderAccountId::new("acct_a").unwrap()].into())
|
||||
.with_presentation(ModelPresentation::new(Some("Native".into()), None)),
|
||||
@@ -796,14 +852,17 @@ fn same_name_native_and_adapted_sources_keep_account_capabilities_separate() {
|
||||
.collect(),
|
||||
vec![],
|
||||
);
|
||||
let native = block_on(
|
||||
RuntimeSnapshotCompiler::new(
|
||||
Arc::new(TestSnapshotStore::new(Ok(facts))),
|
||||
Arc::new(Catalog),
|
||||
let load_native = |capabilities| {
|
||||
block_on(
|
||||
RuntimeSnapshotCompiler::new(
|
||||
Arc::new(TestSnapshotStore::new(Ok(facts.clone()))),
|
||||
Arc::new(Catalog(capabilities)),
|
||||
)
|
||||
.compile(),
|
||||
)
|
||||
.compile(),
|
||||
)
|
||||
.unwrap();
|
||||
.unwrap()
|
||||
};
|
||||
let native = load_native(super::capabilities());
|
||||
let scope = native.all_account_scope();
|
||||
let b_only = Arc::new(scope.restricted_to(&Default::default(), &[b.clone()].into()));
|
||||
assert!(native.public_models_for_scope(&b_only).is_empty());
|
||||
@@ -824,6 +883,24 @@ fn same_name_native_and_adapted_sources_keep_account_capabilities_separate() {
|
||||
.account_scope()
|
||||
.allows(&b)
|
||||
);
|
||||
let native = load_native(ModelCapabilities::from_operation_accounts(
|
||||
[(
|
||||
OperationKind::Generate,
|
||||
[ProviderAccountId::new("acct_a").unwrap()].into(),
|
||||
)]
|
||||
.into(),
|
||||
None,
|
||||
));
|
||||
assert!(
|
||||
native
|
||||
.plan(
|
||||
&id,
|
||||
&super::operation(),
|
||||
b_only.clone(),
|
||||
&Default::default()
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
let snapshot = native.with_extensions(Some(ExtensionSetReference::new(
|
||||
ExtensionSetId::new("adapted".into()).unwrap(),
|
||||
Arc::new(ModelLease(vec![contribution.clone()])),
|
||||
@@ -1064,7 +1141,10 @@ fn compile_aliases(
|
||||
|
||||
#[test]
|
||||
fn contributed_alias_uses_the_same_target_for_listing_profiles_and_routing() {
|
||||
let snapshot = compile_aliases(vec![alias("plugin-model", "upstream-model")]).unwrap();
|
||||
let mut shadowed = alias("plugin-model", "unrelated-model");
|
||||
shadowed.provider = ProviderKind::new("other").unwrap();
|
||||
let snapshot =
|
||||
compile_aliases(vec![alias("plugin-model", "upstream-model"), shadowed]).unwrap();
|
||||
let model = PublicModelId::new("plugin-model").unwrap();
|
||||
let provider = ProviderKind::new("alpha").unwrap();
|
||||
assert!(
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! 互联请求复用账号出口和证书策略,重定向不会携带密钥跨站点转发
|
||||
|
||||
use std::time::{Duration, SystemTime};
|
||||
use std::time::Duration;
|
||||
|
||||
use futures::StreamExt as _;
|
||||
use gateway_core::account::{ProviderAccount, UpstreamInfoFailure};
|
||||
@@ -59,22 +59,8 @@ impl PeerTransport for HttpPeerTransport {
|
||||
.headers()
|
||||
.get(reqwest::header::RETRY_AFTER)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.and_then(|value| {
|
||||
value
|
||||
.parse::<u64>()
|
||||
.ok()
|
||||
.map(Duration::from_secs)
|
||||
.or_else(|| {
|
||||
chrono::DateTime::parse_from_rfc2822(value)
|
||||
.ok()
|
||||
.and_then(|time| {
|
||||
SystemTime::from(time)
|
||||
.duration_since(SystemTime::now())
|
||||
.ok()
|
||||
})
|
||||
})
|
||||
})
|
||||
.map(|value| value.min(Duration::from_secs(24 * 60 * 60)));
|
||||
.and_then(gateway_protocol::http::parse_retry_after_seconds)
|
||||
.map(|seconds| Duration::from_secs(seconds.min(24 * 60 * 60)));
|
||||
let kind = match response.status().as_u16() {
|
||||
401 => UpstreamInfoFailure::Unauthorized,
|
||||
403 => forbidden_reason(response).await,
|
||||
|
||||
@@ -319,7 +319,7 @@ fn rate_delay(status: u16, headers: &[(String, Vec<u8>)]) -> Option<Duration> {
|
||||
}
|
||||
let retry = header(headers, "retry-after")
|
||||
.and_then(|value| std::str::from_utf8(value).ok())
|
||||
.and_then(|value| value.parse::<u64>().ok());
|
||||
.and_then(gateway_protocol::http::parse_retry_after_seconds);
|
||||
let remaining =
|
||||
header(headers, "x-ratelimit-remaining").and_then(|value| std::str::from_utf8(value).ok());
|
||||
let reset = (remaining == Some("0"))
|
||||
|
||||
@@ -2,10 +2,10 @@
|
||||
|
||||
use async_trait::async_trait;
|
||||
use gateway_admin::{
|
||||
model::{AdminError, pricing::PricingSyncPreview},
|
||||
ports::pricing::{PricingSource, PricingSourceScope},
|
||||
model::AdminError,
|
||||
ports::pricing::{ExternalModelPrice, ExternalPrices, PricingSource, PricingSourceScope},
|
||||
};
|
||||
use gateway_core::metering::{ModelPriceOverride, TokenPrice, TokenPriceOverride};
|
||||
use gateway_core::metering::{TokenPrice, TokenPriceOverride};
|
||||
use serde_json::Value;
|
||||
use std::{collections::BTreeMap, time::Duration};
|
||||
|
||||
@@ -16,7 +16,7 @@ pub struct ModelsDevPricing;
|
||||
|
||||
#[async_trait]
|
||||
impl PricingSource for ModelsDevPricing {
|
||||
async fn fetch(&self, scope: &PricingSourceScope) -> Result<PricingSyncPreview, AdminError> {
|
||||
async fn fetch(&self, scope: &PricingSourceScope) -> Result<ExternalPrices, AdminError> {
|
||||
let client = gateway_egress::http_client(None)
|
||||
.map_err(|_| source_error())?
|
||||
.https_only(true)
|
||||
@@ -51,12 +51,9 @@ fn source_error() -> AdminError {
|
||||
pub fn decode_catalog(
|
||||
body: &[u8],
|
||||
scope: &PricingSourceScope,
|
||||
) -> Result<PricingSyncPreview, AdminError> {
|
||||
) -> Result<ExternalPrices, AdminError> {
|
||||
let catalog: Value = serde_json::from_slice(body).map_err(|_| source_error())?;
|
||||
let mut result = PricingSyncPreview {
|
||||
prices: BTreeMap::new(),
|
||||
skipped: Vec::new(),
|
||||
};
|
||||
let mut result = ExternalPrices::new();
|
||||
for provider in scope.vendors() {
|
||||
let Some(models) = catalog
|
||||
.get(provider)
|
||||
@@ -76,66 +73,61 @@ pub fn decode_catalog(
|
||||
{
|
||||
continue;
|
||||
}
|
||||
match model_price(provider, value) {
|
||||
Some(price) => {
|
||||
prices.insert(model.clone(), price);
|
||||
}
|
||||
None => result.skipped.push(format!("{provider}/{model}")),
|
||||
}
|
||||
prices.insert(model.clone(), model_price(value));
|
||||
}
|
||||
if !prices.is_empty() {
|
||||
result.prices.insert(provider.to_owned(), prices);
|
||||
result.insert(provider.to_owned(), prices);
|
||||
}
|
||||
}
|
||||
if result.prices.is_empty() {
|
||||
if !result
|
||||
.values()
|
||||
.any(|models| models.values().any(Option::is_some))
|
||||
{
|
||||
return Err(source_error());
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
fn model_price(provider: &str, model: &Value) -> Option<ModelPriceOverride> {
|
||||
fn model_price(model: &Value) -> Option<ExternalModelPrice> {
|
||||
let output = model.pointer("/modalities/output")?.as_array()?;
|
||||
if output.len() != 1 || output[0].as_str()? != "text" {
|
||||
return None;
|
||||
}
|
||||
let cost = model.get("cost")?;
|
||||
// Google 参考价只含文本单价,消费方须跳过无法据此拆分计费的音频请求
|
||||
if ["reasoning", "input_audio", "output_audio"]
|
||||
.iter()
|
||||
.any(|key| cost.get(key).is_some() && !(provider == "google" && *key == "input_audio"))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let long_context_threshold = if provider == "openai" {
|
||||
272_000
|
||||
} else {
|
||||
200_000
|
||||
};
|
||||
let mut bands = BTreeMap::from([("standard".to_owned(), rates(cost)?)]);
|
||||
if let Some(tiers) = cost.get("tiers") {
|
||||
let tiers = tiers.as_array()?;
|
||||
if tiers.len() > 1 {
|
||||
return None;
|
||||
}
|
||||
if let Some(tier) = tiers.first() {
|
||||
if tier.pointer("/tier/size")?.as_u64()? != long_context_threshold {
|
||||
return None;
|
||||
let long = if let Some(tiers) = cost.get("tiers") {
|
||||
match tiers.as_array()?.as_slice() {
|
||||
[] => None,
|
||||
[tier] => {
|
||||
let band = tier.get("tier")?;
|
||||
// models.dev 把省略的类型定义为 context
|
||||
if band.get("type").is_some_and(|kind| kind != "context") {
|
||||
return None;
|
||||
}
|
||||
Some((band.get("size")?.as_u64()?, tier))
|
||||
}
|
||||
bands.insert("long_standard".to_owned(), rates(tier)?);
|
||||
_ => return None,
|
||||
}
|
||||
} else if let Some(long) = cost.get("context_over_200k") {
|
||||
if long_context_threshold != 200_000 {
|
||||
return None;
|
||||
}
|
||||
bands.insert("long_standard".to_owned(), rates(long)?);
|
||||
}
|
||||
Some(ModelPriceOverride {
|
||||
multiplier_bps: 10_000,
|
||||
bands,
|
||||
} else {
|
||||
cost.get("context_over_200k").map(|tier| (200_000, tier))
|
||||
};
|
||||
let mut has_audio_input_price = cost.get("input_audio").is_some();
|
||||
let long_context = if let Some((threshold, tier)) = long {
|
||||
has_audio_input_price |= tier.get("input_audio").is_some();
|
||||
Some((threshold, rates(tier)?))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Some(ExternalModelPrice {
|
||||
standard: rates(cost)?,
|
||||
long_context,
|
||||
has_audio_input_price,
|
||||
})
|
||||
}
|
||||
|
||||
fn rates(cost: &Value) -> Option<TokenPriceOverride> {
|
||||
if cost.get("reasoning").is_some() || cost.get("output_audio").is_some() {
|
||||
return None;
|
||||
}
|
||||
let price = |key: &str| -> Option<TokenPrice> {
|
||||
cost.get(key)?.as_number()?.to_string().try_into().ok()
|
||||
};
|
||||
|
||||
@@ -160,7 +160,8 @@ impl Metadata {
|
||||
if !status.is_success() {
|
||||
let headers = response.headers();
|
||||
let header = |name: &str| headers.get(name).and_then(|h| h.to_str().ok());
|
||||
let retry = header("retry-after").and_then(|s| s.parse::<u64>().ok());
|
||||
let retry =
|
||||
header("retry-after").and_then(gateway_protocol::http::parse_retry_after_seconds);
|
||||
let exhausted = header("x-ratelimit-remaining") == Some("0");
|
||||
if status == StatusCode::TOO_MANY_REQUESTS || status == StatusCode::FORBIDDEN {
|
||||
let now = SystemTime::now()
|
||||
|
||||
@@ -6,6 +6,7 @@ mod config;
|
||||
mod logging;
|
||||
mod official_plugins;
|
||||
mod outbound;
|
||||
mod peer;
|
||||
mod plugin_distribution;
|
||||
mod pricing;
|
||||
mod process;
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
//! 验证互联上游的限流等待提示
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use gateway_admin::ports::peer::{PeerConnection, PeerTransport};
|
||||
use gateway_core::{
|
||||
account::{CredentialRevision, ProviderAccount, ProviderAccountId, UpstreamInfoFailure},
|
||||
routing::ProviderKind,
|
||||
};
|
||||
use gateway_host::peer::HttpPeerTransport;
|
||||
use wiremock::{Mock, MockServer, ResponseTemplate, matchers::path};
|
||||
|
||||
#[tokio::test]
|
||||
async fn peer_rate_limit_preserves_elapsed_dates_and_bounds_long_delays() {
|
||||
let account = ProviderAccount::new(
|
||||
ProviderAccountId::new("acct_peer").unwrap(),
|
||||
ProviderKind::new("test").unwrap(),
|
||||
"peer".into(),
|
||||
None,
|
||||
"api_key".into(),
|
||||
CredentialRevision::new(1).unwrap(),
|
||||
None,
|
||||
);
|
||||
let transport = HttpPeerTransport::with_client_builder(|builder| builder.no_proxy().build());
|
||||
for (header, seconds) in [("Sun Nov 6 08:49:37 1994", 0), ("100000", 86400)] {
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(path("/cpr/link"))
|
||||
.respond_with(ResponseTemplate::new(429).insert_header("retry-after", header))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let failure = transport
|
||||
.fetch(
|
||||
&account,
|
||||
&PeerConnection {
|
||||
base_url: server.uri(),
|
||||
bearer_token: "test".into(),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(failure.kind, UpstreamInfoFailure::RateLimited);
|
||||
assert_eq!(failure.retry_after, Some(Duration::from_secs(seconds)));
|
||||
}
|
||||
}
|
||||
@@ -197,7 +197,9 @@ async fn cancelling_all_active_queries_releases_the_bounded_download_capacity()
|
||||
async fn rate_limit_expiry_releases_the_identity_without_reusing_a_failure_cache_entry() {
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(path("/repos/limited/plugin/releases/latest"))
|
||||
.respond_with(ResponseTemplate::new(429).insert_header("retry-after", "1"))
|
||||
.respond_with(
|
||||
ResponseTemplate::new(429).insert_header("retry-after", "Sun Nov 6 08:49:37 1994"),
|
||||
)
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
//! 验证外部价格源的 Provider 选择、免费价格与无效文档拒绝
|
||||
|
||||
use gateway_admin::ports::pricing::{PricingCatalogSource, PricingSourceModel, PricingSourceScope};
|
||||
use gateway_admin::ports::pricing::{
|
||||
ExternalPrices, PricingCatalogSource, PricingSourceModel, PricingSourceScope,
|
||||
};
|
||||
use gateway_host::pricing;
|
||||
use serde_json::json;
|
||||
|
||||
fn decode_catalog(
|
||||
body: &[u8],
|
||||
) -> Result<gateway_admin::model::pricing::PricingSyncPreview, gateway_admin::model::AdminError> {
|
||||
fn decode_catalog(body: &[u8]) -> Result<ExternalPrices, gateway_admin::model::AdminError> {
|
||||
pricing::decode_catalog(
|
||||
body,
|
||||
&scope(
|
||||
@@ -19,7 +19,12 @@ fn decode_catalog(
|
||||
fn scope(direct: &[&str], references: &[&str]) -> PricingSourceScope {
|
||||
let mut sources: std::collections::BTreeMap<_, _> = direct
|
||||
.iter()
|
||||
.map(|vendor| (vendor.to_string(), PricingCatalogSource::Direct))
|
||||
.map(|vendor| {
|
||||
(
|
||||
vendor.to_string(),
|
||||
PricingCatalogSource::Direct(Default::default()),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
sources.insert(
|
||||
"mapped-provider".into(),
|
||||
@@ -32,6 +37,7 @@ fn scope(direct: &[&str], references: &[&str]) -> PricingSourceScope {
|
||||
PricingSourceModel {
|
||||
provider: vendor.to_string(),
|
||||
model: "example".into(),
|
||||
policy: Default::default(),
|
||||
},
|
||||
)
|
||||
})
|
||||
@@ -49,23 +55,37 @@ fn source_selects_supported_providers_and_preserves_free_prices() {
|
||||
"normal":{"modalities":{"output":["text"]},"cost":{"input":2.5,"output":10,"cache_read":0.25}},
|
||||
"image":{"modalities":{"output":["image"]},"cost":{"input":1,"output":2}},
|
||||
"invalid":{"modalities":{"output":["text"]},"cost":{"input":-1,"output":2}},
|
||||
"wrong-tier":{"modalities":{"output":["text"]},"cost":{"input":1,"output":2,"tiers":[{"tier":{"size":200000},"input":2,"output":4}]}}
|
||||
"default-tier":{"modalities":{"output":["text"]},"cost":{"input":1,"output":2,"tiers":[{"tier":{"size":272000},"input":2,"output":4}]}},
|
||||
"wrong-tier":{"modalities":{"output":["text"]},"cost":{"input":1,"output":2,"tiers":[{"tier":{"type":"request","size":272000},"input":2,"output":4}]}}
|
||||
}},
|
||||
"xai":{"models":{}},
|
||||
"unrelated":{"models":{"secret":{}}}
|
||||
});
|
||||
let result = decode_catalog(&serde_json::to_vec(&catalog).unwrap()).unwrap();
|
||||
let models = &result.prices["openai"];
|
||||
assert_eq!(models.len(), 2);
|
||||
assert_eq!(models["free"].bands["standard"].input.ticks_per_token(), 0);
|
||||
let models = &result["openai"];
|
||||
assert_eq!(models.values().flatten().count(), 3);
|
||||
assert_eq!(
|
||||
models["normal"].bands["standard"]
|
||||
models["free"]
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.standard
|
||||
.input
|
||||
.ticks_per_token(),
|
||||
0
|
||||
);
|
||||
assert_eq!(
|
||||
models["normal"]
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.standard
|
||||
.cache_read
|
||||
.ticks_per_token(),
|
||||
2500
|
||||
);
|
||||
assert_eq!(result.skipped.len(), 3);
|
||||
assert!(!result.prices.contains_key("unrelated"));
|
||||
for skipped in ["image", "invalid", "wrong-tier"] {
|
||||
assert!(models[skipped].is_none(), "{skipped}");
|
||||
}
|
||||
assert!(!result.contains_key("unrelated"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -93,31 +113,20 @@ fn source_exposes_google_anthropic_and_vertex_reference_prices_with_supported_co
|
||||
"google-vertex":{"models":{"openai/gpt-oss-120b-maas":{"modalities":{"output":["text"]},"cost":{"input":0.09,"output":0.36}}}}
|
||||
});
|
||||
let result = decode_catalog(&serde_json::to_vec(&source).unwrap()).unwrap();
|
||||
assert_eq!(
|
||||
result.prices["google"]["flash"].bands["standard"]
|
||||
.input
|
||||
.ticks_per_token(),
|
||||
3000
|
||||
);
|
||||
assert_eq!(
|
||||
result.prices["google"]["pro"].bands["long_standard"]
|
||||
.output
|
||||
.ticks_per_token(),
|
||||
150000
|
||||
);
|
||||
assert_eq!(
|
||||
result.prices["anthropic"]["sonnet"].bands["standard"]
|
||||
.cache_write
|
||||
.ticks_per_token(),
|
||||
25000
|
||||
);
|
||||
assert_eq!(
|
||||
result.prices["google-vertex"]["openai/gpt-oss-120b-maas"].bands["standard"]
|
||||
.output
|
||||
.ticks_per_token(),
|
||||
3600
|
||||
);
|
||||
assert_eq!(result.skipped, ["google/image"]);
|
||||
let flash = result["google"]["flash"].as_ref().unwrap();
|
||||
assert_eq!(flash.standard.input.ticks_per_token(), 3000);
|
||||
assert!(flash.has_audio_input_price);
|
||||
let pro = result["google"]["pro"].as_ref().unwrap();
|
||||
let (threshold, rates) = pro.long_context.as_ref().unwrap();
|
||||
assert_eq!(*threshold, 200_000);
|
||||
assert_eq!(rates.output.ticks_per_token(), 150000);
|
||||
let sonnet = result["anthropic"]["sonnet"].as_ref().unwrap();
|
||||
assert_eq!(sonnet.standard.cache_write.ticks_per_token(), 25000);
|
||||
let oss = result["google-vertex"]["openai/gpt-oss-120b-maas"]
|
||||
.as_ref()
|
||||
.unwrap();
|
||||
assert_eq!(oss.standard.output.ticks_per_token(), 3600);
|
||||
assert!(result["google"]["image"].is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -129,5 +138,5 @@ fn source_reads_the_registered_scope_without_a_host_allowlist() {
|
||||
.unwrap();
|
||||
let scope = scope(&["custom-vendor"], &["missing-reference"]);
|
||||
let preview = pricing::decode_catalog(&source, &scope).unwrap();
|
||||
assert_eq!(preview.prices.keys().collect::<Vec<_>>(), ["custom-vendor"]);
|
||||
assert_eq!(preview.keys().collect::<Vec<_>>(), ["custom-vendor"]);
|
||||
}
|
||||
@@ -178,7 +178,11 @@ async fn api_cooldown_is_shared_and_summary_does_not_advertise_an_unverified_rel
|
||||
)
|
||||
.await;
|
||||
let limit = if status == 429 {
|
||||
ResponseTemplate::new(status).insert_header("retry-after", "300")
|
||||
let retry_at = chrono::Utc::now() + Duration::from_secs(300);
|
||||
ResponseTemplate::new(status).insert_header(
|
||||
"retry-after",
|
||||
retry_at.format("%a, %d %b %Y %T GMT").to_string(),
|
||||
)
|
||||
} else {
|
||||
let reset = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
|
||||
@@ -17,7 +17,7 @@ use gateway_plugin_sdk::{
|
||||
MiddlewareTransport as WireMiddlewareTransport,
|
||||
},
|
||||
};
|
||||
use gateway_protocol::openai::sse::parse_sse_events;
|
||||
use gateway_protocol::openai::sse::{parse_sse_events, sse_frame_end};
|
||||
|
||||
use crate::{
|
||||
RpcError, RpcStream,
|
||||
@@ -564,7 +564,7 @@ fn valid_plugin_frame(framing: MiddlewareFraming, bytes: &[u8]) -> bool {
|
||||
serde_json::from_slice::<serde::de::IgnoredAny>(bytes).is_ok()
|
||||
}
|
||||
MiddlewareFraming::SseEvent => {
|
||||
(bytes.ends_with(b"\n\n") || bytes.ends_with(b"\r\n\r\n"))
|
||||
sse_frame_end(bytes) == Some(bytes.len())
|
||||
&& std::str::from_utf8(bytes).is_ok_and(|event| parse_sse_events(event).is_ok())
|
||||
}
|
||||
MiddlewareFraming::RawBytes => true,
|
||||
|
||||
@@ -225,6 +225,7 @@ fn prepare_create(
|
||||
) -> Result<PreparedCredentialCreate, PluginFault> {
|
||||
validate_facts(&facts)?;
|
||||
Ok(PreparedCredentialCreate {
|
||||
preserve_catalog_etag: None,
|
||||
model_access: None,
|
||||
outbound_proxy: None,
|
||||
account_id: ProviderAccountId::new(format!("acct_{}", uuid::Uuid::now_v7().simple()))
|
||||
@@ -266,6 +267,7 @@ fn prepare_replace(
|
||||
email: facts.email,
|
||||
plan_type: facts.plan_type,
|
||||
preserve_profile: false,
|
||||
preserve_catalog_etag: None,
|
||||
preserve_credential_state: false,
|
||||
preserve_access_token_expiry: false,
|
||||
provider_material: ProviderDocument::new(OpaqueProviderData::new(facts.material)),
|
||||
|
||||
@@ -158,6 +158,7 @@ impl PluginAccountAccess for Facts {
|
||||
self.reads.fetch_add(1, Ordering::SeqCst);
|
||||
assert_eq!(account.as_str(), "acct_facts");
|
||||
Ok(ProviderQuota {
|
||||
daily_used_percent: None,
|
||||
paused_windows: Vec::new(),
|
||||
upstream: None,
|
||||
credits: Some(ProviderQuotaCredits {
|
||||
|
||||
Loaded 100 of 301 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user