mirror of
https://github.com/zyycn/codex-proxy-rs.git
synced 2026-12-06 08:01:57 +00:00
Compare commits
7
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6f6b8dd3a0 | ||
|
|
8fc756ffec | ||
|
|
efd5357fac | ||
|
|
2bb7679b1b | ||
|
|
f2c1de1568 | ||
|
|
a77d38dd77 | ||
|
|
9a14263f1a |
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、产物、正文和预发行状态。
|
||||
|
||||
|
||||
+7
-7
@@ -127,7 +127,7 @@ 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,7 +225,7 @@ 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、工具链、依赖或构建配置变化时执行完整源码镜像构建,定期安全检查也覆盖源码构建。两条路径均验证容器运行、安全扫描与关闭行为
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
## 快速预览
|
||||
|
||||
|
||||
@@ -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],
|
||||
|
||||
@@ -102,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,
|
||||
@@ -741,12 +743,6 @@ impl PreparedCredentialRotation {
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn preserving_catalog(mut self, etag: String) -> Self {
|
||||
self.facts.preserve_catalog_etag = Some(etag);
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn facts(&self) -> &PreparedCredentialRotationFacts {
|
||||
&self.facts
|
||||
@@ -1318,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 {
|
||||
|
||||
@@ -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,7 +48,9 @@ pub use gateway_core::account::RotationStrategy;
|
||||
/// 运行设置的共同值;版本、Provider 画像更新和数据库秘密由外层类型拥有
|
||||
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct RuntimeSettingsValues {
|
||||
pub antigravity_background_refresh: bool,
|
||||
/// 平台运行设置按 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,
|
||||
|
||||
@@ -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>;
|
||||
}
|
||||
@@ -148,7 +148,7 @@ struct ProviderAdminDiagnostic {
|
||||
source: Option<gateway_core::error::ErrorSource>,
|
||||
}
|
||||
|
||||
/// 区分新账号首查与既有账号变更后的后台观察
|
||||
/// 账号事务影响的账号及其中首次创建的账号
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct AccountFactsChange<'a> {
|
||||
pub ids: &'a [ProviderAccountId],
|
||||
@@ -216,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(
|
||||
@@ -320,9 +320,24 @@ pub trait ProviderAdmin: Send + Sync {
|
||||
/// 没有账号派生状态的 Provider 可使用默认空实现
|
||||
async fn account_facts_changed(&self, _change: AccountFactsChange<'_>) {}
|
||||
|
||||
/// 既有账号变更后是否主动查额,手动刷新与新账号首查独立执行
|
||||
async fn background_quota_refresh_enabled(&self) -> Result<bool, ProviderAdminError> {
|
||||
Ok(true)
|
||||
/// 选择本批变更后需要观察额度的账号,提交、发布及互联分派由 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 负责实际执行与落账
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -710,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(
|
||||
@@ -744,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 {
|
||||
|
||||
@@ -48,58 +48,52 @@ pub(super) fn observe_account_quotas(
|
||||
let provider = provider.clone();
|
||||
let peer = peer.cloned();
|
||||
let accounts = accounts.clone();
|
||||
let mut seen = std::collections::BTreeSet::new();
|
||||
let (initial, updated): (Vec<_>, Vec<_>) = change
|
||||
.ids
|
||||
.iter()
|
||||
.filter(|id| seen.insert(*id))
|
||||
.cloned()
|
||||
.partition(|id| change.created_ids.contains(id));
|
||||
let ids = change.ids.to_vec();
|
||||
let created_ids = change.created_ids.clone();
|
||||
let request_id = request_id.to_owned();
|
||||
tokio::spawn(async move {
|
||||
let mut account_ids = initial;
|
||||
if !updated.is_empty() {
|
||||
match provider.background_quota_refresh_enabled().await {
|
||||
Ok(true) => account_ids.extend(updated),
|
||||
Ok(false) => {}
|
||||
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, error = %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;
|
||||
}
|
||||
}
|
||||
for account_id in account_ids {
|
||||
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(),
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -41,16 +41,16 @@ use gateway_admin::{
|
||||
AuthorizationCommit, AuthorizationCommitGuard, AuthorizationCredentialCommit,
|
||||
AuthorizationMutationTarget, AuthorizationStarted, CompleteAuthorization,
|
||||
ConsumeProviderResetCredit, CredentialChange, 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,
|
||||
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> {
|
||||
@@ -291,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
|
||||
@@ -400,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(),
|
||||
})
|
||||
@@ -643,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)
|
||||
}
|
||||
@@ -939,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(
|
||||
@@ -997,6 +1051,9 @@ 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
|
||||
@@ -1037,6 +1094,7 @@ impl AccountStore for FakeAccountStore {
|
||||
self.require_commit()?;
|
||||
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) => (
|
||||
@@ -1178,7 +1236,7 @@ impl AccountStore for FakeAccountStore {
|
||||
) -> AdminStoreResult<()> {
|
||||
self.record("store.audit_export");
|
||||
self.record_context(context);
|
||||
Ok(())
|
||||
self.require_commit()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1215,7 +1273,7 @@ impl SettingsStore for StaticSettingsStore {
|
||||
rotation_strategy: RotationStrategy::Smart,
|
||||
updated_at: Utc::now(),
|
||||
values: gateway_admin::model::settings::RuntimeSettingsValues {
|
||||
antigravity_background_refresh: true,
|
||||
provider_settings: Default::default(),
|
||||
openai_websocket_pool: Default::default(),
|
||||
openai_request_settings: gateway_core::settings::OpenAiRequestSettings {
|
||||
oauth_guardian_review_model: false,
|
||||
@@ -1497,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]
|
||||
@@ -1521,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!(
|
||||
(
|
||||
@@ -1539,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
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1617,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"
|
||||
]
|
||||
);
|
||||
@@ -3727,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"),
|
||||
|
||||
@@ -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,7 +33,7 @@ fn runtime_settings(enabled: bool, probe_enabled: bool) -> RuntimeSettings {
|
||||
rotation_strategy: gateway_admin::model::settings::RotationStrategy::Smart,
|
||||
updated_at: Utc::now(),
|
||||
values: gateway_admin::model::settings::RuntimeSettingsValues {
|
||||
antigravity_background_refresh: true,
|
||||
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},
|
||||
@@ -579,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"))
|
||||
}
|
||||
@@ -1013,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,
|
||||
@@ -1026,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",
|
||||
@@ -1039,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,
|
||||
@@ -1060,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
|
||||
@@ -1071,6 +1080,7 @@ impl ProviderAdmin for UnavailableProvider {
|
||||
gateway_admin::ports::pricing::PricingSourceModel {
|
||||
provider: provider.clone(),
|
||||
model: source.clone(),
|
||||
policy: self.pricing_policy,
|
||||
},
|
||||
)
|
||||
})
|
||||
@@ -1189,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"),
|
||||
@@ -1235,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"),
|
||||
|
||||
@@ -337,7 +337,7 @@ impl SettingsStore for FixtureSettingsStore {
|
||||
rotation_strategy: RotationStrategy::Smart,
|
||||
updated_at: Utc::now(),
|
||||
values: gateway_admin::model::settings::RuntimeSettingsValues {
|
||||
antigravity_background_refresh: true,
|
||||
provider_settings: Default::default(),
|
||||
openai_websocket_pool: Default::default(),
|
||||
openai_request_settings: gateway_core::settings::OpenAiRequestSettings {
|
||||
oauth_guardian_review_model: false,
|
||||
|
||||
@@ -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,7 +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 {
|
||||
antigravity_background_refresh: true,
|
||||
provider_settings: Default::default(),
|
||||
openai_websocket_pool: Default::default(),
|
||||
openai_request_settings: Default::default(),
|
||||
codex_privacy_policy: Default::default(),
|
||||
@@ -403,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(),
|
||||
@@ -446,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
|
||||
@@ -473,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 {
|
||||
|
||||
@@ -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::{
|
||||
|
||||
@@ -36,7 +36,8 @@ pub type ProviderRequestProfileUpdates =
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct RuntimeSettingsFields {
|
||||
pub antigravity_background_refresh: bool,
|
||||
#[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,
|
||||
@@ -716,7 +717,7 @@ impl RuntimeSettingsFields {
|
||||
self,
|
||||
) -> Result<gateway_admin::model::settings::RuntimeSettingsValues, WireValidationError> {
|
||||
let values = gateway_admin::model::settings::RuntimeSettingsValues {
|
||||
antigravity_background_refresh: self.antigravity_background_refresh,
|
||||
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,
|
||||
@@ -769,7 +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 {
|
||||
antigravity_background_refresh: settings.antigravity_background_refresh,
|
||||
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));
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
@@ -529,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))]),
|
||||
)]))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -648,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)
|
||||
@@ -1356,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"))
|
||||
}
|
||||
@@ -1750,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 {
|
||||
@@ -1997,7 +2032,7 @@ fn test_runtime_settings() -> RuntimeSettings {
|
||||
rotation_strategy: RotationStrategy::Smart,
|
||||
updated_at: Utc::now(),
|
||||
values: gateway_admin::model::settings::RuntimeSettingsValues {
|
||||
antigravity_background_refresh: true,
|
||||
provider_settings: Default::default(),
|
||||
openai_websocket_pool: Default::default(),
|
||||
openai_request_settings: Default::default(),
|
||||
codex_privacy_policy: Default::default(),
|
||||
|
||||
@@ -84,7 +84,7 @@ fn update_body() -> Value {
|
||||
"gpt-5.4": "gpt-5.5",
|
||||
"grok-latest": "grok-4.5"
|
||||
},
|
||||
"antigravityBackgroundRefresh": false,
|
||||
"providerSettings": {},
|
||||
"refreshMarginSeconds": 1800,
|
||||
"refreshConcurrency": 4,
|
||||
"maxConcurrentPerAccount": 5,
|
||||
@@ -638,7 +638,6 @@ fn settings_service_contract_flattens_values_and_rejects_unknown_fields() {
|
||||
command
|
||||
);
|
||||
for field in [
|
||||
"antigravity_background_refresh",
|
||||
"openai_request_settings",
|
||||
"reset_credit_on_low_weekly_quota",
|
||||
] {
|
||||
@@ -1006,7 +1005,7 @@ async fn settings_update_rejects_incomplete_and_unknown_fields_without_writing()
|
||||
incomplete
|
||||
.as_object_mut()
|
||||
.unwrap()
|
||||
.remove("antigravityBackgroundRefresh");
|
||||
.remove("refreshMarginSeconds");
|
||||
for body in [unknown, incomplete] {
|
||||
let response = app
|
||||
.clone()
|
||||
@@ -1052,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();
|
||||
@@ -1071,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();
|
||||
|
||||
@@ -171,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(),
|
||||
@@ -307,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")),
|
||||
@@ -365,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);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -13,9 +13,12 @@ pub trait ProviderRuntimePolicyPort: Send + Sync {
|
||||
Box::pin(async { Ok(None) })
|
||||
}
|
||||
|
||||
/// 是否允许定时或缓存缺失时自动查询 Antigravity OAuth 账号
|
||||
fn antigravity_background_refresh(&self) -> BoxFuture<'_, Result<bool, ProviderStoreError>> {
|
||||
Box::pin(async { Ok(true) })
|
||||
/// 读取指定平台的全局运行设置,字段及缺省行为由该 Provider 定义
|
||||
fn load_provider_settings<'a>(
|
||||
&'a self,
|
||||
_provider: &'a ProviderKind,
|
||||
) -> BoxFuture<'a, Result<Option<OpaqueProviderData>, ProviderStoreError>> {
|
||||
Box::pin(async { Ok(None) })
|
||||
}
|
||||
|
||||
/// 后台 OpenAI 操作读取当前全局请求设置
|
||||
|
||||
@@ -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| {
|
||||
|
||||
@@ -744,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())
|
||||
}
|
||||
@@ -771,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]
|
||||
@@ -971,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()
|
||||
}
|
||||
|
||||
@@ -995,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()
|
||||
}
|
||||
@@ -1111,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()
|
||||
}
|
||||
@@ -1236,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 排序,追加的插件画像保留注册顺序,不参与二分查找
|
||||
@@ -1804,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) => {
|
||||
@@ -2024,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| {
|
||||
@@ -2151,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 {
|
||||
@@ -2175,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(),
|
||||
|
||||
@@ -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(),
|
||||
|
||||
@@ -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()))
|
||||
|
||||
@@ -75,6 +75,7 @@ async fn import_account(
|
||||
let result = access
|
||||
.save(
|
||||
PreparedPluginAccountSave::Create(PreparedCredentialCreate {
|
||||
preserve_catalog_etag: None,
|
||||
account_id: gateway_core::account::ProviderAccountId::new(format!(
|
||||
"acct_{}",
|
||||
uuid::Uuid::new_v4().simple()
|
||||
|
||||
@@ -1064,6 +1064,66 @@ async fn middleware_next_and_lazy_body_mapping_use_one_real_rpc_call() {
|
||||
super::wait_until_empty(cache.path()).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn middleware_accepts_one_complete_sse_frame_per_mapped_output() {
|
||||
for (replacement, single_frame) in [
|
||||
("data: first\r\ndata: second\r\n\r\n", true),
|
||||
("data: first\n\ndata: second\r\n\r\n", false),
|
||||
] {
|
||||
let (cache, runtime) = setup(vec![InstanceFixture {
|
||||
id: "sse-map",
|
||||
configuration: serde_json::json!({
|
||||
"middleware_map_body": true,
|
||||
"middleware_mapped_body": replacement,
|
||||
}),
|
||||
bindings: vec![binding(
|
||||
MIDDLEWARE_CONTRIBUTION,
|
||||
"request",
|
||||
0,
|
||||
PluginFailurePolicy::Reject,
|
||||
)],
|
||||
}])
|
||||
.await;
|
||||
let generation = prepare(&runtime).await;
|
||||
let plan = runtime
|
||||
.execution_registry()
|
||||
.middleware(&generation)
|
||||
.unwrap();
|
||||
let request = MiddlewareRequest::new("openai", middleware_headers(), Bytes::new());
|
||||
let next = TransparencyNext {
|
||||
status: 200,
|
||||
expected: request.clone(),
|
||||
headers: vec![],
|
||||
frames: VecDeque::from([MiddlewareFrame::new(
|
||||
Bytes::from_static(b"data: original\n\n"),
|
||||
MiddlewareFraming::SseEvent,
|
||||
true,
|
||||
)]),
|
||||
};
|
||||
let response = plan
|
||||
.handle(
|
||||
middleware_context(ClientTransport::HttpSse),
|
||||
request,
|
||||
next.into_next(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let mut body = response.into_parts().3;
|
||||
let frame = body.next_frame().await;
|
||||
if single_frame {
|
||||
let frame = frame.unwrap().unwrap();
|
||||
assert!(frame.transformed() && frame.terminal());
|
||||
assert_eq!(frame.bytes().as_ref(), replacement.as_bytes());
|
||||
} else {
|
||||
assert!(matches!(frame, Err(MiddlewareError::InvalidState)));
|
||||
}
|
||||
body.close().await;
|
||||
drop(plan);
|
||||
drop(generation);
|
||||
super::wait_until_empty(cache.path()).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn middleware_classifies_real_rpc_output_after_a_terminal_frame() {
|
||||
for (id, extra_chunk, terminal_error) in [
|
||||
|
||||
@@ -61,7 +61,7 @@ async fn explicit_service_dispatch_composes_once_and_preserves_native_transactio
|
||||
.unwrap();
|
||||
let typed: gateway_plugin_sdk::call::services::settings::RuntimeSettings =
|
||||
serde_json::from_value(through_registry).unwrap();
|
||||
assert!(typed.antigravity_background_refresh);
|
||||
assert!(typed.provider_settings.is_empty());
|
||||
assert_eq!(typed.refresh_margin_seconds, 4321);
|
||||
// 返回层改写不是持久化写入;原 owner 保留真实配置事实
|
||||
assert_eq!(
|
||||
@@ -78,7 +78,6 @@ async fn explicit_service_dispatch_composes_once_and_preserves_native_transactio
|
||||
);
|
||||
|
||||
let mut command = ReplaceRuntimeSettings::from(original);
|
||||
command.values.antigravity_background_refresh = false;
|
||||
command.values.refresh_margin_seconds = 999;
|
||||
command
|
||||
.values
|
||||
@@ -111,7 +110,6 @@ async fn explicit_service_dispatch_composes_once_and_preserves_native_transactio
|
||||
.unwrap();
|
||||
let saved: gateway_plugin_sdk::call::services::settings::RuntimeSettings =
|
||||
serde_json::from_value(saved).unwrap();
|
||||
assert!(!saved.antigravity_background_refresh);
|
||||
assert_eq!(saved.refresh_margin_seconds, 1234);
|
||||
assert!(saved.config_revision.get() > command.expected_revision.get());
|
||||
let current = environment
|
||||
@@ -121,7 +119,6 @@ async fn explicit_service_dispatch_composes_once_and_preserves_native_transactio
|
||||
.load_runtime_settings()
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(!current.values.antigravity_background_refresh);
|
||||
assert_eq!(current.values.refresh_margin_seconds, 1234);
|
||||
assert!(
|
||||
!current
|
||||
@@ -303,10 +300,8 @@ async fn cli_service_callback_uses_the_same_public_settings_and_plugin_chain() {
|
||||
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>
|
||||
{
|
||||
unreachable!("reading settings does not fetch external pricing")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,7 +19,6 @@ use gateway_admin::{
|
||||
PluginInstance,
|
||||
},
|
||||
},
|
||||
pricing::PricingSyncPreview,
|
||||
proxies::ProxyTestResult,
|
||||
system::{SystemOperationAccepted, SystemUpdateDetail, SystemUpdateStatus, SystemVersion},
|
||||
},
|
||||
@@ -944,7 +943,7 @@ impl PricingSource for UnusedAdminRuntime {
|
||||
async fn fetch(
|
||||
&self,
|
||||
_: &gateway_admin::ports::pricing::PricingSourceScope,
|
||||
) -> Result<PricingSyncPreview, AdminError> {
|
||||
) -> Result<gateway_admin::ports::pricing::ExternalPrices, AdminError> {
|
||||
Err(AdminError::unavailable("unused pricing source"))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1125,7 +1125,11 @@ impl Peer {
|
||||
.unwrap();
|
||||
let read: MiddlewareBodyReadResult = serde_json::from_value(result).unwrap();
|
||||
assert!(!read.eof && read.source_id != 0);
|
||||
source.push(b' ');
|
||||
if let Some(body) = self.configuration["middleware_mapped_body"].as_str() {
|
||||
source = body.as_bytes().to_vec();
|
||||
} else {
|
||||
source.push(b' ');
|
||||
}
|
||||
let response = MiddlewareResponseHead {
|
||||
response: Some(downstream.response),
|
||||
protocol: None,
|
||||
|
||||
@@ -16,15 +16,13 @@ Rust 插件只需依赖 `gateway-plugin-sdk`。SDK `0.1.0` 处于实验阶段,
|
||||
| `call::services` | 公开服务的类型化操作、输入输出及错误合同,`usage` 提供[用量查询、维护与计价](docs/usage-data.md) |
|
||||
| `call::upstream_adapter` | 内置 OpenAI / xAI 的[受管上游适配器](docs/upstream-adapters.md)注册、执行、出站与续接合同 |
|
||||
| `call::policy` | 模型路由、账号调度与重试决策合同 |
|
||||
| `call::catalog` | 固定 Provider 的直接别名与适配模型注册合同,见[模型目录](docs/capabilities.md#模型目录) |
|
||||
| `call::catalog` | 直接指向上游模型的别名,以及由同实例适配器提供的模型,见[模型目录](docs/capabilities.md#模型目录) |
|
||||
| `call::data` | 账号事实、当前额度与历史额度观测 |
|
||||
| `call::observation` | 请求完成、用量、费用与实际上游 WebSocket 响应事件的统一观察合同 |
|
||||
| `call::host` | 账号、私有状态、受管 HTTP、模型、亲和、日志及调用内流的宿主回调合同 |
|
||||
| `call::management` | 管理 API、页面与资源声明、公开回调,以及 CLI 命令与待保存账号 |
|
||||
| `client` | 通过 `io` feature 开启的 `PluginBuilder`、会话、中间件与异步帧收发 |
|
||||
|
||||
`message.rs` 定义消息与帧。改写现有请求、响应或推理参数使用 `call::middleware`,其中 `websocket` 处理下游消息,`outbound` 处理上游发送前的请求。响应观察只读。需要自行选择业务上游并解析响应时使用 `call::upstream_adapter`
|
||||
|
||||
```rust
|
||||
use gateway_plugin_sdk::{Frame, Message, PluginFault};
|
||||
use gateway_plugin_sdk::call::{host::ModelEventBatch, model::ExecutionEvent};
|
||||
@@ -32,23 +30,15 @@ use gateway_plugin_sdk::call::{host::ModelEventBatch, model::ExecutionEvent};
|
||||
use gateway_plugin_sdk::client::{read_frame, write_frame};
|
||||
```
|
||||
|
||||
默认 feature 不引入异步运行时。`io` 提供帧编解码、`PluginBuilder`、`PluginSession::accept/run` 和 `PluginHandler`。
|
||||
[类型化构建器](docs/capabilities.md#类型化作者入口)按清单注册处理器。会话管理握手、并发、父调用关联、回调、流信用、取消、排空与关闭,容量与计时见[并发与期限](#并发与期限)
|
||||
默认 feature 不引入异步运行时。启用 `io` 后,用 `PluginBuilder` 按清单组合处理器,再交给 `PluginSession::run` 管理握手、父调用关联、回调、流控、取消和关闭。仅实现中间件时也可使用 `MiddlewarePlugin`。参见[类型化作者入口](docs/capabilities.md#类型化作者入口)和[洋葱中间件](docs/capabilities.md#洋葱中间件)。
|
||||
|
||||
`HostClient::scan_usage_records` 与 `query_usage_statistics` 提供用量明细扫描和完整分组统计,按批读取与关闭见[用量查询](docs/usage-data.md#完整扫描与分组统计)
|
||||
|
||||
`ResponseStream::channel` 提供有界流生产入口,`ResponseStream::pull` 按消费进度驱动生产者;`PluginCall` 的宿主客户端只代表当前父调用,
|
||||
不能把一个调用的资源误用到另一个调用。插件程序自行选择运行时和启动入口,不会启动网关。
|
||||
`ResponseStream::channel` 提供有界流生产入口,`ResponseStream::pull` 按消费进度驱动生产者。`PluginCall` 的宿主客户端和资源仅在当前父调用内有效。插件程序自行选择运行时和启动入口。
|
||||
`SessionConfig.maximum_stream_chunk_bytes` 默认 1 MiB,只约束单个业务流分块;
|
||||
流式响应还需满足宿主实际授予的信用窗口。普通调用与回调的正文不受此预算限制。
|
||||
模型请求中间件默认接收完整正文,内存占用随正文增长。`request` 和 `attempt` 可按阶段省略正文,WebSocket 可只订阅指定下行错误,见[清单](docs/manifest.md#扩展项简写)。HTTP 与下游 WebSocket 中间件使用惰性正文句柄,透传不复制正文
|
||||
|
||||
## 通信边界
|
||||
|
||||
启用 `io` 时优先用 [`PluginBuilder`](docs/capabilities.md#类型化作者入口) 组合业务处理器,再交给
|
||||
`PluginSession::run`。仅实现中间件时也可直接使用
|
||||
[`MiddlewarePlugin`](docs/capabilities.md#洋葱中间件)
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant H as 宿主 Runtime
|
||||
|
||||
@@ -47,7 +47,7 @@ session.run(plugin).await?;
|
||||
|
||||
## 能力与方法
|
||||
|
||||
Provider 固定为宿主内置的 OpenAI 与 xAI。宿主开放以下 11 类扩展能力,版本与声明规则见[扩展项简写](manifest.md#扩展项简写):
|
||||
插件使用宿主已有的 Provider。各能力支持的版本和声明方式见[扩展项简写](manifest.md#扩展项简写)。
|
||||
|
||||
| 能力 | 类型化方法 |
|
||||
| --- | --- |
|
||||
@@ -67,10 +67,7 @@ Provider 固定为宿主内置的 OpenAI 与 xAI。宿主开放以下 11 类扩
|
||||
|
||||
所有回调都通过当前 `TypedCall.host` 发起,关联父调用及其取消信号。普通调用使用父调用剩余期限;已经建立的资源流按[会话生命周期](../README.md#帧与会话)回收,网络操作单独计时
|
||||
|
||||
用量扫描和完整分组统计使用 `HostClient::scan_usage_records`、`query_usage_statistics`,
|
||||
对应 `host.usage.records.scan`、`host.usage.statistics.query`。返回的读取资源通过
|
||||
`host.usage.read.next` 和 `host.usage.read.close` 拉取与关闭,SDK 提供 `UsageReader` 封装。
|
||||
这些回调使用空控制参数和二进制 JSON 载荷,查询语义、快照与预算见[用量查询](usage-data.md#完整扫描与分组统计)
|
||||
用量明细、统计、维护与费用试算的入口见[用量查询、维护与计价](usage-data.md)。
|
||||
|
||||
### 基础事实
|
||||
|
||||
@@ -200,7 +197,7 @@ Key 明文仍通过宿主管理面查看,插件模型调用使用返回的 Key
|
||||
| `get_key_budget_window` / `host.keys.get_budget_window` | `{client_key_id, period}`;`period` 为 `daily` 或 `weekly`;返回 `{revision, explicit, starts_at_us, ends_at_us, used_usd}` |
|
||||
| `set_key_budget_window` / `host.keys.set_budget_window` | `{client_key_id, period, expected_revision, window}`;返回 `{revision}` |
|
||||
|
||||
`list_keys` / `host.keys.list` 仍可查询非秘密目录,仅返回 `{id,name,enabled}` 和游标,沿用目录的控制参数编码。
|
||||
`list_keys` / `host.keys.list` 使用目录的控制参数编码,仅返回 `{id,name,enabled}` 和游标。
|
||||
上述操作均接受 Key ID,不接受 Key 明文,也不要求先查询目录
|
||||
|
||||
金额为非负十进制字符串,沿用原生金额精度;上限 `"0"` 表示不限。`KeyBudget` 的字段为
|
||||
@@ -246,7 +243,7 @@ SDK 不自动重试。超时或断连不能证明写入未提交;重试上限
|
||||
### Key、模型与模型调用
|
||||
|
||||
- `host.keys.list`:分页返回 `{id, name, enabled}`
|
||||
- `host.models.list`:以显式 `client_key_id` 查询该 Key 当前可见的模型目录
|
||||
- `host.models.list`:以显式 `client_key_id`、`protocol` 和 `client_version` 查询模型 ID。协议值 `codex` 查询 Responses 执行协议(`openai`)下该 Key 可见的目录
|
||||
- `host.model.execute[_stream]`:交给 Core 的路由、准入、租约、重试、账本和计费链路执行
|
||||
- `host.model.stream_read/close`:读取或关闭当前父调用创建的有界流
|
||||
|
||||
@@ -254,8 +251,7 @@ SDK 不自动重试。超时或断连不能证明写入未提交;重试上限
|
||||
`responses_max_decompressed_body_bytes` 取得原始正文预算 `L`,通过
|
||||
`call::model::request_payload_limit(L)` 为内部请求预留 JSON 字符串转义和元数据空间
|
||||
(`2 × L + 64 KiB`,受请求编码的 32 位分段长度约束)。超限返回带 HTTP 413 的
|
||||
`invalid_input`,不启动模型执行。上游适配器的请求 `GPAQ` 也使用请求预算,响应事件仍受
|
||||
原有 8 MiB 编码上限、Runtime 缓冲预算及流控窗口限制
|
||||
`invalid_input`,不启动模型执行。上游适配器的请求 `GPAQ` 也使用请求预算。响应事件受 8 MiB 编码上限、Runtime 缓冲预算及流控窗口限制。
|
||||
|
||||
HTTP 和 request 中间件使用有效请求设置。attempt、outbound、路由、调度、重试及上游适配器沿用冻结的模型请求预算。
|
||||
显式 Key 的预检与执行共用父调用内的身份快照,后续发布的配置在新的父调用解析身份时生效
|
||||
@@ -326,8 +322,7 @@ attempt、outbound、路由、调度、重试和上游适配器使用执行冻
|
||||
`next.run(input)` 消费自身,最多执行一次;结果按相反顺序经过外层。重试或独立子请求通过宿主执行服务发起
|
||||
|
||||
调用上下文的 `timeout_ms` 限制插件自身处理时间,入站与返回处理合计使用同一预算。
|
||||
父处理任务真正挂起时释放执行名额,恢复取得授权后继续同一次调用。仅等待 `next` 时暂停处理预算;并行包含普通回调时继续计时,具体规则见[并发与期限](../README.md#并发与期限)。
|
||||
排队、在途容量与过载行为见 [SDK 并发与期限](../README.md#并发与期限)。
|
||||
父处理任务挂起时释放执行名额,取得恢复授权后继续同一次调用。仅等待 `next` 时暂停处理预算,并行等待普通回调时继续计时。排队、容量与过载规则见[并发与期限](../README.md#并发与期限)。
|
||||
请求总期限、下游操作超时和取消信号独立生效,客户端取消或插件退出会结束等待并回收资源
|
||||
|
||||
HTTP 总入口统一包裹原生路由,`dispatch_http` 复用同一路由与组合能力;无需为每个 HTTP 接口登记新的挂载点。
|
||||
@@ -341,16 +336,17 @@ HTTP 总入口统一包裹原生路由,`dispatch_http` 复用同一路由与
|
||||
返回 `ServiceResponse::from_result::<O>(result)` 可以改写结果、短路或恢复业务错误;
|
||||
不感兴趣的操作调用 `forward()`。公开值完整传递,类型校验不承担字段权限控制
|
||||
|
||||
`settings` 提供 `Load`、`PreviewPrivacyPolicy`、`Replace`、`ApiKeyExists`、`RegenerateApiKey`、`DeleteApiKey`、
|
||||
`settings` 提供 `Load`、`PreviewPromptRewrite`、`PreviewPrivacyPolicy`、`Replace`、`ApiKeyExists`、`RegenerateApiKey`、`DeleteApiKey`、
|
||||
`Pricing`、`PreviewPricingSync`、`Sync`、`Update`、`ClientProfileOptions`、`PreviewClientProfile`。
|
||||
插件回调和 CLI 经注册表主动调用时统一进入一次 `service` 组合;网关原生设置接口由 HTTP 总入口包裹。
|
||||
各入口共用同一业务实现,业务方法内部调用不重复进入 `service` 组合。
|
||||
其他管理接口复用既有 HTTP 路由,不要求按内部方法另建服务目录;既有账号、Key 等资源回调不自动进入 `service` 组合
|
||||
|
||||
`Load` 返回完整运行设置与 `config_revision`。`ReplaceRuntimeSettings::from(settings)` 保留该版本并构造更新命令;
|
||||
`Replace` 接收 `(MutationContext, ReplaceRuntimeSettings)`,通过已有校验、事务、审计和快照发布保存设置。
|
||||
每次写入都必须提供 `openai_request_settings`、`openai_websocket_pool`、`reset_credit_on_low_weekly_quota` 和 `prompt_rewrite_rules`。清空提示词改写规则时提交空数组,范围与顺序见[提示词改写](../../../../../docs/api.md#提示词改写)。
|
||||
版本过期返回 `ServiceError { kind: "conflict", message }`。读取结果的普通改写不会持久化,也不会回滚已经提交的事务
|
||||
`Load`(`settings.load`)读取持久化的运行设置和 `config_revision`。`request_profiles` 只含已保存的画像,读取不会初始化缺失项。查询某个 Provider 的有效全局画像,使用 `ClientProfileOptions` 返回的 `globalConfiguration`。当前请求经中间件、Client Key 改写后的值见[模型请求与 attempt](#模型请求与-attempt)。
|
||||
|
||||
写入时,用 `ReplaceRuntimeSettings::from(settings)` 从读取结果构造完整命令,再调用 `Replace`,参数为 `(MutationContext, ReplaceRuntimeSettings)`。构造器将 `config_revision` 带入 `expected_revision`,写入时版本过期返回 `conflict`。`provider_settings` 只替换提交的 Provider 对象,由所属 Provider 校验。画像更新在 `request_profile_updates` 中按 Provider 指定,省略保留,显式 `null` 删除已保存值。
|
||||
|
||||
命令中的必填设置须完整保留,包括 `openai_request_settings`、`openai_websocket_pool`、`reset_credit_on_low_weekly_quota` 和 `prompt_rewrite_rules`。要清空提示词改写规则,提交空数组。`Replace` 提交设置及审计后发布配置。中间件改写服务返回值只影响调用方看到的结果,不会持久化该改写或回滚已提交的事务。规则范围与顺序见[提示词改写](../../../../../docs/api.md#提示词改写)。
|
||||
|
||||
`accounts::GetResetCreditAutomation` 接收账号 ID,返回 `ResetCreditAutomationStatus`:开关、全局提前分钟数、
|
||||
生效的周额度触发值(临期模式为 `None`)、下次发现与使用时间、最近结果;时间为 RFC 3339 字符串,无计划时为 `None`。
|
||||
@@ -376,8 +372,7 @@ let status = host.service::<SetResetCreditAutomation>((account_id, true)).await?
|
||||
插件改写后的设置用于认证、版本检查、正文解压及执行。`timeout_ms` 默认取宿主 HTTP 超时,
|
||||
插件可改写或用 `None` 清除;终端按有效值执行,不恢复宿主默认值。宿主快照不可用时 `settings` 为 `null`
|
||||
|
||||
`POST /v1/chat/completions` 在 HTTP 挂载中保留 Chat 请求与 Chat JSON/SSE 响应视图,
|
||||
转换为 Responses 发生在内层模型入口。自行按 URI 筛选、改写或分派模型请求的 HTTP 插件,
|
||||
`POST /v1/chat/completions` 在 HTTP 挂载中保留 Chat 请求与 Chat JSON/SSE 响应视图,目标协议转换由选中的 Provider 处理。自行按 URI 筛选、改写或分派模型请求的 HTTP 插件,
|
||||
需要将该路径包含在自身匹配范围内;只匹配 `/v1/responses` 不会覆盖 Chat
|
||||
|
||||
`HttpCall.settings_sources` 返回 `config_revision`、宿主 `host` 基线、运行设置的 `overrides`、Key 作用域的 `execution` 与 `http_timeout`。
|
||||
@@ -519,7 +514,7 @@ Provider 选定账号后直接转换到实际目标,`outbound` 看到目标协
|
||||
同一挂载边界仍遵守原始字节保留规则;字段范围见 [Chat 合同](../../../../../docs/api.md#chat-completions-请求)
|
||||
|
||||
Messages 入站的 `protocol` 为 `anthropic`,端点为 `/v1/messages`;计数使用 `/v1/messages/count_tokens` 与 `count_tokens` 操作。
|
||||
原生请求只选择同协议账号,不调用内置 Chat 转换。插件自行承担转换与回译;宿主不保留旧 Chat 视图,不修复插件输出或补偿插件状态
|
||||
原生请求只选择同协议账号。插件若需转换协议,自行处理请求转换与响应回译。宿主不修复插件输出或补偿插件状态。
|
||||
|
||||
中间件可读取和改写完整请求、响应 headers、正文与响应帧,也不按字段名称过滤认证、Cookie、会话或连接头。
|
||||
该能力遵循[完整信任](manifest.md#完整信任)边界;类型、HTTP 格式、大小及资源生命周期仍需符合合同
|
||||
@@ -529,6 +524,8 @@ Messages 入站的 `protocol` 为 `anthropic`,端点为 `/v1/messages`;计
|
||||
默认使用 `MiddlewareRequestBody::Preserve` 将宿主保存的当前正文交给下一层。`replace_body(Vec::new())` 明确清空,包括本层省略正文的情况。
|
||||
Header 修改采用增量 remove/append,保留合法多值。`MiddlewareBody::map_frames` 复用会话的流控和唯一终态
|
||||
|
||||
改写后的 `SseEvent` 必须恰好包含一个完整 UTF-8 SSE 帧,直到结束空行。一个事件可以有多行 `data:`。单次返回多个事件、缺少帧边界或带有下一帧的部分字节,都会在交付前被拒绝。
|
||||
|
||||
`response.metadata` 提供 Provider、实际模型、账号、上游请求 ID 和账号选择观测。
|
||||
`response.body.with_facts()?.inspect_frames(...)` 或 `.map_frames(...)` 通过 `frame.facts` 读取完整事件快照;纯事实帧可没有正文。
|
||||
快照按需读取,未开启读取或未消费正文时不复制事件载荷;来源帧完成后对应句柄失效。
|
||||
@@ -566,8 +563,6 @@ restore_and_validate_response(response).await
|
||||
仅实现中间件时也可使用轻量的 `MiddlewarePlugin`;需要与管理或其他方法组合时使用
|
||||
`PluginBuilder`,两者复用相同的类型化调用与结果合同
|
||||
|
||||
用量查询、明细与聚合维护、费用试算使用 `call::services::usage`,输入输出和批量语义见 [用量查询、维护与计价](usage-data.md)
|
||||
|
||||
### 扩展的组合边界
|
||||
|
||||
请求处理沿 `request middleware → 原生选路与选号 → attempt middleware → 原生上游或 upstream_adapter` 推进,
|
||||
@@ -589,7 +584,7 @@ restore_and_validate_response(response).await
|
||||
`model_catalog` 仅支持 v2,在 registration 阶段通过 `model_catalog.register` 一次提交
|
||||
`ModelCatalogRegistrationV2 { aliases, models }`,不接受请求级 binding。
|
||||
返回值必须同时包含 `aliases` 和 `models`,没有对应条目时使用空数组。
|
||||
`aliases` 的每条 `ModelAlias { id, provider, model }` 定义公开 ID、Provider 及直接上游目标,条目正确性由插件负责。
|
||||
`aliases` 的每条 `ModelAlias { id, provider, model }` 定义公开 ID、Provider 标识及直接上游目标。此处接受合法的 Provider 标识,目标能否执行取决于宿主注册的 Provider、模型及账号资格。
|
||||
别名条目重复、目标不存在或 Provider 未注册不阻止宿主快照发布。
|
||||
请求按发布顺序取首个匹配条目,插件别名优先于静态映射,目标直接用于上游选路,不递归展开别名或目标上的静态映射
|
||||
|
||||
@@ -614,7 +609,7 @@ let plugin = PluginBuilder::from_json(include_bytes!("../plugin.json"))?
|
||||
|
||||
- `adapter_id` 必须指向同实例已绑定的 `upstream_adapter`,Provider、生成协议与非空账号集合取自该适配器声明
|
||||
- 适配器及 binding 的模型范围必须覆盖 `id`;带 Key/账号组条件的适配器不能贡献静态目录,不能丢弃这些条件扩大可见范围
|
||||
- `features` 使用 `RequestFeature`,仅为生成操作声明工具、图片输入、推理或 JSON Schema 支持;没有声明的能力不能借用同名原生模型的支持事实
|
||||
- `features` 使用 `RequestFeature`,为生成操作声明工具、图片输入、推理或 JSON Schema 支持。与原生模型同名时,宿主按本次操作和账号分别判断能力。例如,适配器声明生成能力不会让该账号获得同名模型的 Token 计数能力
|
||||
- `presentation` 是独立通用画像,字段见 `call::catalog::ModelPresentation`;省略的布尔能力为 false,未声明推理档位不补猜
|
||||
- `presentation.reasoning_summary` 独立声明 `reasoning.summary` 参数支持,默认 false;推理档位不代表摘要能力,只有能够处理该参数的适配器才声明 true,客户端目录相应使用 `auto` 或 `none` 作为摘要默认值
|
||||
- 同名条目可关联不同账号,但 Provider、能力及画像须一致,账号集合不能重叠,也不能与插件直接别名同名,以免展示与实际选择产生歧义
|
||||
|
||||
@@ -16,7 +16,17 @@
|
||||
| `package` | 作者清单须省略。CLI 填入协议版本、目标平台与文件摘要 |
|
||||
|
||||
直接反序列化 `Manifest` 只应用可选字段默认值。需要推导 ID 和固定阶段时使用作者清单入口。
|
||||
打包后,`package.files` 须包含 `main` 与所有资源
|
||||
|
||||
## 包内路径
|
||||
|
||||
`main` 的值和 `resources` 的键均为相对于包根目录的路径。打包后,`package.files` 须包含可执行文件及所有声明资源的摘要。
|
||||
|
||||
- 路径至多 240 个 ASCII 字节,以 `/` 分段。每段只可含字母、数字、`-`、`_`、`.`。空段、`.`、`..`、末尾带点的段和 Windows 保留设备名(如 `CON.txt`、`LPT1`)均无效
|
||||
- 根目录的 `plugin.json` 为清单保留。所有包内文件按 ASCII 大小写无关判重,文件与父目录也不得冲突。例如,`Web/logo.png` 与 `web/LOGO.PNG` 不能同时使用,`plugin.json/icon.svg` 也不能作为资源
|
||||
|
||||
本地构建目录与包内资源路径的映射见[打包命令](../../../../apps/plugin-cli/README.md#打包)。
|
||||
|
||||
## 版本与兼容
|
||||
|
||||
宿主实际开放的合同由 [plugin-host-compatibility.json](../../runtime/plugin-host-compatibility.json)
|
||||
声明,SDK 的 `Capability::contract_versions()` 只表示 SDK 能描述的行为版本,不能代替宿主支持检查
|
||||
@@ -50,8 +60,7 @@ CLI 按 SDK 合同校验声明。安装包清单拒绝未知字段,并校验
|
||||
| `middleware` | `6` |
|
||||
| `scheduler` | `4` |
|
||||
| `upstream_adapter` | `5` |
|
||||
| `frontend_authentication`、`model_router`、`retry_policy`、`observer`、`management` | `2` |
|
||||
| `model_catalog` | `2` |
|
||||
| `frontend_authentication`、`model_router`、`model_catalog`、`retry_policy`、`observer`、`management` | `2` |
|
||||
| `command_line`、`maintenance` | `1` |
|
||||
|
||||
例如,仅声明管理页面、命令行和模型请求中间件:
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
使用 `PluginBuilder::on` 注册
|
||||
`methods::UPSTREAM_ADAPTER_REGISTER` 与 `methods::UPSTREAM_ADAPTER_EXECUTE`
|
||||
|
||||
注册返回 `UpstreamAdapterRegistration`,最多包含 16 个适配器:
|
||||
注册返回 `UpstreamAdapterRegistration`,每实例最多声明 16 个适配器,注册结果的 JSON 载荷最多 64 KiB。
|
||||
|
||||
| 字段 | 含义 |
|
||||
| --- | --- |
|
||||
@@ -21,21 +21,20 @@
|
||||
| `paths` | 请求路径与 `inference` 或 `auxiliary` 用途的对应关系 |
|
||||
| `authentication_kinds` | 可使用的现有认证类型,宿主复核已选账号 |
|
||||
| `transport` | `http_json`、`http_sse` 或 `websocket` |
|
||||
| `protocol` | 请求和客户端 wire 使用的协议 |
|
||||
| `protocol` | 入站生成请求与适配完成后的客户端 wire 必须使用此协议。插件自行编解码实际业务上游的协议 |
|
||||
| `models` | 公开请求模型的精确匹配,空集合沿用绑定范围 |
|
||||
| `account_ids` | 上游账号 ID 范围,必填;空数组匹配所有账号 |
|
||||
|
||||
实例只允许一个 `upstream` 绑定,故障策略为 `reject`。Key、账号组、Provider 和模型限定请求范围,插件注册的 `account_ids` 只能进一步收窄账号范围
|
||||
|
||||
发布适配器提供的新模型时,另用同实例的 `model_catalog` 关联 `adapter_id`。此用途要求非空的静态账号范围,目录条目从适配器继承 Provider 和生成协议。完整条件见[模型目录](capabilities.md#模型目录)。
|
||||
|
||||
同一模型可按账号使用不同适配器。每个账号按发布顺序取首个匹配声明,后续声明的故障不影响已匹配的适配器。未匹配时使用原生上游,命中但不可用时拒绝执行
|
||||
|
||||
取得租约前,宿主排除适配器不可用或认证不兼容的账号。xAI 原生编码不支持请求时,仅排除原生账号,匹配的适配器账号仍可使用。宿主按亲和与调度策略取得租约后,从同一发布代次解析适配器
|
||||
|
||||
停用或卸载实例会移除绑定。维护前先停用依赖该适配器的账号并排空请求
|
||||
|
||||
能力、清单、进程 RPC 和宿主兼容声明分别校验各自版本,见[清单](manifest.md)。
|
||||
Provider、业务协议和传输名称不能写入宿主兼容清单的 capability / RPC 版本位置
|
||||
|
||||
## 执行与受管出站
|
||||
|
||||
`TypedCall<UpstreamAdapterRequest>` 包含只读的 Key、账号、凭据版本、模型、协议、Header 和宿主续接投影;
|
||||
@@ -77,16 +76,18 @@ let (message, ()) = tokio::try_join!(
|
||||
)?;
|
||||
```
|
||||
|
||||
宿主先注入已选账号认证,插件显式提供的同名头覆盖默认值。路径支持相对基址或完整 HTTP(S) URL;
|
||||
声明路径用于标记发送用途,不是访问白名单。出站复用账号代理,未绑定可用代理时使用部署默认出口,代理失败不能回退直连,重定向不自动跟随。
|
||||
`auxiliary` 路径的出站计入请求副作用水位,防止附件上传等操作在失败后被透明重复执行
|
||||
宿主先注入已选账号认证,插件显式提供的同名头覆盖默认值。请求路径可相对 `base_url`,也可使用完整 HTTP(S) URL。宿主按调用传入的路径字符串精确匹配 `paths`,未声明的路径按 `inference` 处理。例如上传附件时应将调用使用的路径声明为 `auxiliary`,辅助出站计入请求副作用,影响失败后的重放资格。
|
||||
|
||||
出站使用账号绑定的代理,无显式绑定时走部署默认出口。代理失败时请求失败,重定向不自动跟随。
|
||||
WebSocket 握手只接受 `inference` 用途的路径。
|
||||
|
||||
## 事件、结算和续接
|
||||
|
||||
执行返回 `TypedReply<Empty>` 的有界 `ResponseStream`。每个 chunk 使用 `UpstreamAdapterEvent::encode()`,
|
||||
包含标准事实与可选原始 wire;事件需符合开始、内容、工具、用量和唯一结束的顺序。
|
||||
原始 JSON / SSE / WebSocket 字节与标准事实分开传递,错误使用 `UpstreamFailure`;宿主网络观测决定发送状态,插件不能将其降为未发送
|
||||
`status`、`code`、可选 `error_type` 和 `message` 保留实际上游错误字段,缺失类型保持空值;流内失败不能使用成功握手状态或从业务码推导状态
|
||||
执行返回 `TypedReply<Empty>` 的有界 `ResponseStream`。每个 chunk 由 `UpstreamAdapterEvent::encode()` 编码,按开始、内容、工具、用量和唯一结束的顺序提供标准事实。原始 JSON、SSE 或 WebSocket 字节作为可选的 wire 单独传递。
|
||||
|
||||
`WirePayload::RawSse` 的 `frame` 和 `WirePayload::Json` 的 `raw_sse` 均只接受一个完整 UTF-8 SSE 帧,不能夹带下一帧字节。若随 JSON 一并提供原始 SSE,其事件名、ID、重试值和解码后的 JSON 数据必须与所报字段一致。
|
||||
|
||||
错误使用 `UpstreamFailure`。`status`、`code`、可选 `error_type` 和 `message` 保留实际上游错误字段,缺失类型保持空值。流内失败不能使用成功握手状态或从业务码推导状态。发送状态以宿主网络观测为准,插件不能将其降为未发送。
|
||||
|
||||
宿主只对一次受管 `inference` HTTP 调用明确返回的 429 提供有限重放证明:插件必须报告
|
||||
`rate_limited` 和 `status: 429`,且此前及失败事件中均无业务事实、wire 或续接材料。
|
||||
|
||||
@@ -20,7 +20,7 @@
|
||||
## 完整扫描与分组统计
|
||||
|
||||
启用 `io` feature 后,`HostClient::scan_usage_records(ScanUsageRecords)` 与
|
||||
`HostClient::query_usage_statistics(QueryUsageStatistics)` 返回 `UsageReader`,通过 `next_batch()` 逐批处理结果
|
||||
`HostClient::query_usage_statistics(QueryUsageStatistics)` 返回 `UsageReader`,通过 `next_batch()` 逐批处理结果。对应回调为 `host.usage.records.scan` 和 `host.usage.statistics.query`。SDK 使用 `host.usage.read.next` 和 `host.usage.read.close` 拉取、关闭读取资源。四个回调均使用空控制参数和二进制 JSON 载荷。
|
||||
|
||||
```rust,no_run
|
||||
use gateway_plugin_sdk::{PluginFault, client::HostClient};
|
||||
@@ -105,9 +105,12 @@ async fn read_statistics(
|
||||
|
||||
## 费用试算与写回
|
||||
|
||||
`EvaluatePricing` 按 OpenAI 或 xAI 的单请求公式,用当前价目或指定价格试算 Token 费用。须提供输入、输出、缓存读取、缓存写入和图像 Token,纯文本的图像 Token 填零。Provider 不支持、用量不全或价格未知时返回 `not_estimable`
|
||||
`EvaluatePricing` 将上游模型、Token 用量、服务档位及当前或指定价格交给对应 Provider 的单请求公式。每项独立返回 `estimated` 或 `not_estimable`,试算不会写入请求记录。
|
||||
|
||||
试算不含图像、工具等附加费用,也不写入请求记录
|
||||
- OpenAI、xAI 的文本试算要求明确提供输入、输出、缓存读取和缓存写入 Token。图像输入、图像输出都必须是已知的 `"0"`,缺失或非零时无法按文本公式试算
|
||||
- Antigravity 按模型价带计算,要求已知输入和输出 Token。有图像价带时还需提供图像输出 Token。图文输入单价不同时,须提供图像输入 Token,缓存用量也须能按模态唯一拆分
|
||||
|
||||
缺少对应 Provider、所需用量或可用价格时返回 `not_estimable`。结果仅覆盖能从所给 Token 计算的费用。
|
||||
|
||||
调用方可查询明细、选择目标、逐条试算,再通过 `WriteRecords::Update` 写回费用。补全缺失时只处理 `unavailable`;全部覆盖时自行选择整个范围。日汇总若缺少逐请求分布,长上下文档位和逐请求舍入可能无法复现,计算方法由调用方决定
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ 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>>>;
|
||||
@@ -189,7 +190,9 @@ pub struct PrivacyPreviewResult {
|
||||
#[derive(Clone, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct RuntimeSettings {
|
||||
pub antigravity_background_refresh: bool,
|
||||
/// 平台运行设置按 Provider 更新,省略的平台保留已提交值
|
||||
#[serde(default)]
|
||||
pub provider_settings: ProviderSettings,
|
||||
pub openai_websocket_pool: OpenAiWebSocketPoolSettings,
|
||||
pub openai_request_settings: OpenAiRequestSettings,
|
||||
pub codex_privacy_policy: CodexPrivacyPolicy,
|
||||
@@ -233,7 +236,9 @@ pub struct RuntimeSettings {
|
||||
#[derive(Clone, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct ReplaceRuntimeSettings {
|
||||
pub antigravity_background_refresh: bool,
|
||||
/// 平台运行设置按 Provider 更新,省略的平台保留已提交值
|
||||
#[serde(default)]
|
||||
pub provider_settings: ProviderSettings,
|
||||
pub openai_websocket_pool: OpenAiWebSocketPoolSettings,
|
||||
pub openai_request_settings: OpenAiRequestSettings,
|
||||
pub codex_privacy_policy: CodexPrivacyPolicy,
|
||||
@@ -455,7 +460,7 @@ impl Operation for PreviewClientProfile {
|
||||
impl From<RuntimeSettings> for ReplaceRuntimeSettings {
|
||||
fn from(settings: RuntimeSettings) -> Self {
|
||||
Self {
|
||||
antigravity_background_refresh: settings.antigravity_background_refresh,
|
||||
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,
|
||||
|
||||
@@ -224,8 +224,6 @@ impl Manifest {
|
||||
.iter()
|
||||
.any(|text| !valid_text(text))
|
||||
|| self.author.as_ref().is_some_and(|text| !valid_text(text))
|
||||
|| !valid_package_path(&self.main)
|
||||
|| self.main == "plugin.json"
|
||||
|| self.contributes.len() > 64
|
||||
|| self.resources.len() > 128
|
||||
|| self.secret_fields.len() > 64
|
||||
@@ -233,6 +231,7 @@ impl Manifest {
|
||||
{
|
||||
return Err(ManifestError::Invalid);
|
||||
}
|
||||
validate_file_paths(std::iter::once(&self.main).chain(self.resources.keys()))?;
|
||||
self.validate_contributions(&plugin_id)?;
|
||||
self.validate_resources()?;
|
||||
self.validate_icon()?;
|
||||
@@ -333,10 +332,8 @@ impl Manifest {
|
||||
}
|
||||
|
||||
fn validate_resources(&self) -> Result<(), ManifestError> {
|
||||
for (path, content_type) in &self.resources {
|
||||
if !valid_package_path(path)
|
||||
|| path == "plugin.json"
|
||||
|| content_type.is_empty()
|
||||
for content_type in self.resources.values() {
|
||||
if content_type.is_empty()
|
||||
|| content_type.len() > 128
|
||||
|| !content_type.is_ascii()
|
||||
|| content_type.chars().any(char::is_control)
|
||||
@@ -429,30 +426,15 @@ impl Manifest {
|
||||
{
|
||||
return Err(ManifestError::Invalid);
|
||||
}
|
||||
for (path, digest) in &package.files {
|
||||
if !valid_package_path(path)
|
||||
|| path == "plugin.json"
|
||||
|| digest.len() != 64
|
||||
validate_file_paths(package.files.keys())?;
|
||||
for digest in package.files.values() {
|
||||
if digest.len() != 64
|
||||
|| !digest
|
||||
.bytes()
|
||||
.all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
|
||||
{
|
||||
return Err(ManifestError::Invalid);
|
||||
}
|
||||
// 文件不能同时充当父目录,避免跨平台路径覆盖与解压顺序歧义
|
||||
if path
|
||||
.split('/')
|
||||
.scan(String::new(), |parent, part| {
|
||||
if !parent.is_empty() {
|
||||
parent.push('/');
|
||||
}
|
||||
parent.push_str(part);
|
||||
Some(parent.clone())
|
||||
})
|
||||
.any(|parent| parent != *path && package.files.contains_key(&parent))
|
||||
{
|
||||
return Err(ManifestError::Invalid);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -584,6 +566,25 @@ fn platform_component(value: &str) -> bool {
|
||||
.all(|byte| byte.is_ascii_alphanumeric() || b"-_.".contains(&byte))
|
||||
}
|
||||
|
||||
// 归档在大小写不敏感的文件系统上也须能展开,每条路径及其父目录均不能占用另一个文件
|
||||
fn validate_file_paths<'a>(paths: impl Iterator<Item = &'a String>) -> Result<(), ManifestError> {
|
||||
let mut files = BTreeSet::from(["plugin.json".to_owned()]);
|
||||
for path in paths {
|
||||
if !valid_package_path(path) || !files.insert(path.to_ascii_lowercase()) {
|
||||
return Err(ManifestError::Invalid);
|
||||
}
|
||||
}
|
||||
for path in &files {
|
||||
if path
|
||||
.match_indices('/')
|
||||
.any(|(end, _)| files.contains(&path[..end]))
|
||||
{
|
||||
return Err(ManifestError::Invalid);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 逐个检查原始路径段,不能让操作系统先规范化掉 `.`、空段或反斜线
|
||||
#[must_use]
|
||||
pub fn valid_package_path(path: &str) -> bool {
|
||||
|
||||
@@ -71,6 +71,37 @@ fn package_paths_reject_platform_escapes_and_ambiguous_names() {
|
||||
assert!(valid_package_path("bin/example-worker.exe"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn declared_files_share_one_portable_namespace_with_the_manifest() {
|
||||
for path in [
|
||||
"Plugin.JSON",
|
||||
"Plugin.JSON/logo",
|
||||
"BIN",
|
||||
"BIN/Worker",
|
||||
"Bin/Worker/icon",
|
||||
] {
|
||||
let mut author = source_manifest();
|
||||
author
|
||||
.resources
|
||||
.insert(path.to_owned(), "text/plain".into());
|
||||
assert_eq!(author.validate(), Err(ManifestError::Invalid), "{path}");
|
||||
|
||||
let mut built = packaged_manifest();
|
||||
built
|
||||
.package
|
||||
.as_mut()
|
||||
.unwrap()
|
||||
.files
|
||||
.insert(path.to_owned(), "b".repeat(64));
|
||||
assert_eq!(built.validate(), Err(ManifestError::Invalid), "{path}");
|
||||
}
|
||||
let mut author = source_manifest();
|
||||
author
|
||||
.resources
|
||||
.insert("bin/worker-help".to_owned(), "text/plain".into());
|
||||
assert!(author.validate().is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn source_manifest_allows_missing_package_and_wildcard_engine() {
|
||||
let manifest = source_manifest();
|
||||
|
||||
@@ -81,20 +81,17 @@ pub fn request_observation(
|
||||
/// 按协议提取能力事实,未知协议保留空事实供其 owner 补齐
|
||||
#[must_use]
|
||||
pub fn request_facts(protocol: &str, body: &Map<String, Value>) -> RequestFacts {
|
||||
let mut facts = RequestFacts {
|
||||
tools: body
|
||||
.get("tools")
|
||||
.and_then(Value::as_array)
|
||||
.is_some_and(|v| !v.is_empty()),
|
||||
..RequestFacts::default()
|
||||
};
|
||||
let mut facts = RequestFacts::default();
|
||||
match protocol {
|
||||
OPENAI_PROTOCOL => {
|
||||
facts.max_output_tokens = body
|
||||
.get("max_output_tokens")
|
||||
.and_then(Value::as_u64)
|
||||
.filter(|n| *n > 0);
|
||||
facts.vision = contains_type(body.get("input"), "input_image");
|
||||
facts.vision = body
|
||||
.get("input")
|
||||
.and_then(Value::as_array)
|
||||
.is_some_and(|items| items.iter().any(responses_item_has_image));
|
||||
facts.image_generation = requests_image_generation(body);
|
||||
facts.reasoning = body.get("reasoning").is_some_and(Value::is_object);
|
||||
facts.json_schema = body
|
||||
@@ -110,7 +107,14 @@ pub fn request_facts(protocol: &str, body: &Map<String, Value>) -> RequestFacts
|
||||
}
|
||||
ANTHROPIC_PROTOCOL => {
|
||||
facts.max_output_tokens = body.get("max_tokens").and_then(Value::as_u64);
|
||||
facts.vision = contains_type(body.get("messages"), "image");
|
||||
facts.vision = body
|
||||
.get("messages")
|
||||
.and_then(Value::as_array)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|message| message.get("content")?.as_array())
|
||||
.flatten()
|
||||
.any(messages_block_has_image);
|
||||
facts.reasoning = body
|
||||
.get("thinking")
|
||||
.and_then(|v| v.get("type"))
|
||||
@@ -124,9 +128,13 @@ pub fn request_facts(protocol: &str, body: &Map<String, Value>) -> RequestFacts
|
||||
== Some("json_schema");
|
||||
}
|
||||
GENAI_PROTOCOL => genai::request_facts(body, &mut facts),
|
||||
CHAT_PROTOCOL => facts = chat_completions::request_facts(body),
|
||||
_ => {}
|
||||
CHAT_PROTOCOL => return chat_completions::request_facts(body),
|
||||
_ => return facts,
|
||||
}
|
||||
facts.tools = body
|
||||
.get("tools")
|
||||
.and_then(Value::as_array)
|
||||
.is_some_and(|tools| !tools.is_empty());
|
||||
facts
|
||||
}
|
||||
|
||||
@@ -159,13 +167,40 @@ fn is_image_tool(value: &Value) -> bool {
|
||||
value.get("type").and_then(Value::as_str) == Some("image_generation")
|
||||
}
|
||||
|
||||
fn contains_type(value: Option<&Value>, expected: &str) -> bool {
|
||||
match value {
|
||||
Some(Value::Array(values)) => values.iter().any(|v| contains_type(Some(v), expected)),
|
||||
Some(Value::Object(object)) => {
|
||||
object.get("type").and_then(Value::as_str) == Some(expected)
|
||||
|| object.values().any(|v| contains_type(Some(v), expected))
|
||||
fn responses_item_has_image(item: &Value) -> bool {
|
||||
let content = match item.get("type").and_then(Value::as_str) {
|
||||
Some("message") => item.get("content"),
|
||||
None if item.get("role").is_some_and(Value::is_string) => item.get("content"),
|
||||
Some("function_call_output" | "custom_tool_call_output") => item.get("output"),
|
||||
Some("computer_call_output") => return item["output"]["type"] == "computer_screenshot",
|
||||
_ => return false,
|
||||
};
|
||||
content
|
||||
.and_then(Value::as_array)
|
||||
.is_some_and(|parts| parts.iter().any(|part| part["type"] == "input_image"))
|
||||
}
|
||||
|
||||
fn messages_block_has_image(block: &Value) -> bool {
|
||||
match block["type"].as_str() {
|
||||
Some("tool_result") => block["content"]
|
||||
.as_array()
|
||||
.is_some_and(|parts| parts.iter().any(messages_media_has_image)),
|
||||
Some("web_fetch_tool_result") => {
|
||||
let result = &block["content"];
|
||||
result["type"] == "web_fetch_result" && document_has_image(&result["content"])
|
||||
}
|
||||
_ => false,
|
||||
_ => messages_media_has_image(block),
|
||||
}
|
||||
}
|
||||
|
||||
fn messages_media_has_image(block: &Value) -> bool {
|
||||
block["type"] == "image" || document_has_image(block)
|
||||
}
|
||||
|
||||
fn document_has_image(block: &Value) -> bool {
|
||||
block["type"] == "document"
|
||||
&& block["source"]["type"] == "content"
|
||||
&& block["source"]["content"]
|
||||
.as_array()
|
||||
.is_some_and(|parts| parts.iter().any(|part| part["type"] == "image"))
|
||||
}
|
||||
@@ -54,6 +54,71 @@ fn responses_facts_keep_native_continuation_separate_from_history() {
|
||||
assert!(!facts.tools && !facts.vision && !facts.reasoning && !facts.json_schema);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_protocol_leaves_capability_fields_to_its_owner() {
|
||||
let body = json!({"tools":["editor"],"max_tokens":512,"input":[{"role":"user",
|
||||
"content":[{"type":"input_image","image_url":"https://example.invalid/image.png"}]}]});
|
||||
assert_eq!(
|
||||
request_facts("private", body.as_object().unwrap()),
|
||||
Default::default()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn responses_vision_uses_message_content_and_tool_outputs() {
|
||||
let part = json!({"type":"input_image","image_url":"https://example.invalid/image.png"});
|
||||
for item in [
|
||||
json!({"role":"user","content":[part]}),
|
||||
json!({"type":"message","role":"user","content":[part]}),
|
||||
json!({"type":"function_call_output","call_id":"f","output":[part]}),
|
||||
json!({"type":"custom_tool_call_output","call_id":"c","output":[part]}),
|
||||
json!({"type":"computer_call_output","call_id":"s","output":{
|
||||
"type":"computer_screenshot","image_url":"https://example.invalid/screen.png"
|
||||
}}),
|
||||
] {
|
||||
let body = json!({"input":[item]});
|
||||
assert!(
|
||||
request_facts("openai", body.as_object().unwrap()).vision,
|
||||
"{body}"
|
||||
);
|
||||
}
|
||||
let body = json!({"input":[
|
||||
{"type":"additional_tools","tools":[{"type":"function","name":"lookup",
|
||||
"parameters":{"type":"object","examples":[part]}}]},
|
||||
{"role":"user","content":[{"type":"input_text","text":"hello","metadata":part}]},
|
||||
{"type":"tool_search_call","arguments":{"content":[part]}},
|
||||
{"type":"future_item","content":[part]}
|
||||
]});
|
||||
assert!(!request_facts("openai", body.as_object().unwrap()).vision);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn messages_vision_uses_content_blocks_and_document_sources() {
|
||||
let image =
|
||||
json!({"type":"image","source":{"type":"url","url":"https://example.invalid/image.png"}});
|
||||
let document = json!({"type":"document","source":{"type":"content","content":[image]}});
|
||||
for block in [
|
||||
image.clone(),
|
||||
document.clone(),
|
||||
json!({"type":"tool_result","tool_use_id":"t","content":[document]}),
|
||||
json!({"type":"web_fetch_tool_result","tool_use_id":"t","content":{
|
||||
"type":"web_fetch_result","url":"https://example.invalid","content":document
|
||||
}}),
|
||||
] {
|
||||
let body = json!({"messages":[{"role":"user","content":[block]}]});
|
||||
assert!(
|
||||
request_facts("anthropic", body.as_object().unwrap()).vision,
|
||||
"{body}"
|
||||
);
|
||||
}
|
||||
let body = json!({"messages":[{"role":"assistant","content":[
|
||||
{"type":"tool_use","id":"t","name":"lookup","input":{"content":[image]}},
|
||||
{"type":"future_block","content":[image]},
|
||||
{"type":"text","text":"hello","metadata":image}
|
||||
]}]});
|
||||
assert!(!request_facts("anthropic", body.as_object().unwrap()).vision);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn image_generation_detection_distinguishes_tools_from_image_inputs_and_passive_namespaces() {
|
||||
for body in [
|
||||
|
||||
@@ -93,7 +93,7 @@ impl SettingsStore for AdminSettingsStoreAdapter {
|
||||
MutationAuditOperation::RuntimeSettingsReplace,
|
||||
"1",
|
||||
vec![
|
||||
"antigravity_background_refresh".to_owned(),
|
||||
"provider_settings_json".to_owned(),
|
||||
"provider_request_profiles_json".to_owned(),
|
||||
"request_location_enabled".to_owned(),
|
||||
"request_location_json".to_owned(),
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
use async_trait::async_trait;
|
||||
use chrono::{DateTime, Utc};
|
||||
use gateway_admin::model::MutationContext;
|
||||
use sqlx::{PgPool, Postgres, Transaction};
|
||||
use sqlx::{Executor, PgPool, Postgres, QueryBuilder, Transaction};
|
||||
|
||||
use crate::{Revision, StoreError, StoreResult, postgres_unavailable, require_nonempty};
|
||||
|
||||
@@ -91,6 +91,12 @@ pub(crate) fn mutation_audit(
|
||||
entity_ref,
|
||||
}
|
||||
.event(context, changed_fields);
|
||||
unversioned_audit_event(event)
|
||||
}
|
||||
|
||||
pub(super) fn unversioned_audit_event(
|
||||
event: gateway_admin::model::auth::AdminAuditEvent,
|
||||
) -> AdminAuditEvent {
|
||||
AdminAuditEvent {
|
||||
id: event.id,
|
||||
actor_kind: event.actor_kind.into(),
|
||||
@@ -208,28 +214,7 @@ impl AdminSecurityAuditRepository for PgAdminSecurityAuditRepository {
|
||||
}
|
||||
|
||||
async fn append_admin_audit_event(&self, event: AdminAuditEvent) -> StoreResult<()> {
|
||||
event.validate()?;
|
||||
sqlx::query(
|
||||
"insert into admin_audit_events (
|
||||
id, actor_kind, actor_admin_user_id, actor_ref, admin_request_id,
|
||||
action, entity_kind, entity_ref, config_revision, changed_fields, created_at
|
||||
) values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)",
|
||||
)
|
||||
.bind(event.id)
|
||||
.bind(event.actor_kind.as_str())
|
||||
.bind(event.actor_admin_user_id)
|
||||
.bind(event.actor_ref)
|
||||
.bind(event.admin_request_id)
|
||||
.bind(event.action)
|
||||
.bind(event.entity_kind)
|
||||
.bind(event.entity_ref)
|
||||
.bind(event.config_revision)
|
||||
.bind(event.changed_fields)
|
||||
.bind(event.created_at)
|
||||
.execute(&self.pool)
|
||||
.await
|
||||
.map_err(|source| postgres_unavailable("append admin audit event", source))?;
|
||||
Ok(())
|
||||
insert_admin_audit_events(&self.pool, &[event]).await
|
||||
}
|
||||
}
|
||||
|
||||
@@ -246,27 +231,43 @@ pub(crate) async fn append_admin_audit_event_in_transaction(
|
||||
})
|
||||
})
|
||||
.transpose()?;
|
||||
event.validate()?;
|
||||
sqlx::query(
|
||||
insert_admin_audit_events(&mut **transaction, &[event]).await
|
||||
}
|
||||
|
||||
pub(super) async fn insert_admin_audit_events<'e>(
|
||||
executor: impl Executor<'e, Database = Postgres>,
|
||||
events: &[AdminAuditEvent],
|
||||
) -> StoreResult<()> {
|
||||
if events.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
for event in events {
|
||||
event.validate()?;
|
||||
}
|
||||
let mut sql = QueryBuilder::<Postgres>::new(
|
||||
"insert into admin_audit_events (
|
||||
id, actor_kind, actor_admin_user_id, actor_ref, admin_request_id,
|
||||
action, entity_kind, entity_ref, config_revision, changed_fields, created_at
|
||||
) values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)",
|
||||
)
|
||||
.bind(event.id)
|
||||
.bind(event.actor_kind.as_str())
|
||||
.bind(event.actor_admin_user_id)
|
||||
.bind(event.actor_ref)
|
||||
.bind(event.admin_request_id)
|
||||
.bind(event.action)
|
||||
.bind(event.entity_kind)
|
||||
.bind(event.entity_ref)
|
||||
.bind(event.config_revision)
|
||||
.bind(event.changed_fields)
|
||||
.bind(event.created_at)
|
||||
.execute(&mut **transaction)
|
||||
.await
|
||||
.map_err(|source| postgres_unavailable("append admin audit event in transaction", source))?;
|
||||
id, actor_kind, actor_admin_user_id, actor_ref, admin_request_id,
|
||||
action, entity_kind, entity_ref, config_revision, changed_fields, created_at
|
||||
) ",
|
||||
);
|
||||
sql.push_values(events, |mut row, event| {
|
||||
row.push_bind(&event.id)
|
||||
.push_bind(event.actor_kind.as_str())
|
||||
.push_bind(&event.actor_admin_user_id)
|
||||
.push_bind(&event.actor_ref)
|
||||
.push_bind(&event.admin_request_id)
|
||||
.push_bind(&event.action)
|
||||
.push_bind(&event.entity_kind)
|
||||
.push_bind(&event.entity_ref)
|
||||
.push_bind(event.config_revision)
|
||||
.push_bind(&event.changed_fields)
|
||||
.push_bind(event.created_at);
|
||||
});
|
||||
sql.build()
|
||||
.persistent(events.len() == 1)
|
||||
.execute(executor)
|
||||
.await
|
||||
.map_err(|source| postgres_unavailable("append admin audit event", source))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -1841,29 +1841,31 @@ async fn load_client_key_memberships(
|
||||
"with requested_keys(key_id) as (
|
||||
select unnest($1::text[])
|
||||
),
|
||||
global_providers as (
|
||||
select coalesce(array_agg(distinct provider_kind order by provider_kind), '{}')
|
||||
as provider_kinds
|
||||
from provider_accounts
|
||||
bindings as (
|
||||
select b.client_api_key_id, b.account_group_id
|
||||
from client_api_key_groups b
|
||||
where b.client_api_key_id = any($1::text[])
|
||||
),
|
||||
group_providers as (
|
||||
select m.account_group_id,
|
||||
array_agg(distinct a.provider_kind order by a.provider_kind) as provider_kinds
|
||||
from (select distinct account_group_id from bindings) b
|
||||
join account_groups g on g.id = b.account_group_id and g.enabled
|
||||
join account_group_accounts m on m.account_group_id = g.id
|
||||
join provider_accounts a on a.id = m.provider_account_id
|
||||
group by m.account_group_id
|
||||
)
|
||||
select requested_keys.key_id,
|
||||
groups.id as group_id, groups.name as group_name, groups.color as group_color,
|
||||
groups.enabled as group_enabled,
|
||||
global_providers.provider_kinds as global_provider_kinds,
|
||||
coalesce(array_agg(distinct accounts.provider_kind order by accounts.provider_kind)
|
||||
filter (where accounts.provider_kind is not null), '{}')
|
||||
as group_provider_kinds
|
||||
case when groups.id is null then
|
||||
(select coalesce(array_agg(distinct provider_kind order by provider_kind), '{}')
|
||||
from provider_accounts)
|
||||
else coalesce(group_providers.provider_kinds, '{}') end as provider_kinds
|
||||
from requested_keys
|
||||
cross join global_providers
|
||||
left join client_api_key_groups bindings
|
||||
on bindings.client_api_key_id = requested_keys.key_id
|
||||
left join bindings on bindings.client_api_key_id = requested_keys.key_id
|
||||
left join account_groups groups on groups.id = bindings.account_group_id
|
||||
left join account_group_accounts memberships
|
||||
on memberships.account_group_id = groups.id and groups.enabled
|
||||
left join provider_accounts accounts
|
||||
on accounts.id = memberships.provider_account_id
|
||||
group by requested_keys.key_id, global_providers.provider_kinds,
|
||||
groups.id, groups.name, groups.color, groups.enabled
|
||||
left join group_providers on group_providers.account_group_id = groups.id
|
||||
order by requested_keys.key_id, groups.id",
|
||||
)
|
||||
.bind(ids)
|
||||
@@ -1896,20 +1898,13 @@ async fn load_client_key_memberships(
|
||||
invalid("invalid client API key group state").with_source(source)
|
||||
})?,
|
||||
});
|
||||
providers.entry(key_id).or_default().extend(
|
||||
row.try_get::<Vec<String>, _>("group_provider_kinds")
|
||||
.map_err(|source| {
|
||||
invalid("invalid client API key provider kinds").with_source(source)
|
||||
})?,
|
||||
);
|
||||
} else {
|
||||
providers.entry(key_id).or_default().extend(
|
||||
row.try_get::<Vec<String>, _>("global_provider_kinds")
|
||||
.map_err(|source| {
|
||||
invalid("invalid global provider kinds").with_source(source)
|
||||
})?,
|
||||
);
|
||||
}
|
||||
providers.entry(key_id).or_default().extend(
|
||||
row.try_get::<Vec<String>, _>("provider_kinds")
|
||||
.map_err(|source| {
|
||||
invalid("invalid client API key provider kinds").with_source(source)
|
||||
})?,
|
||||
);
|
||||
}
|
||||
for record in records {
|
||||
record.groups = groups.remove(&record.id).unwrap_or_default();
|
||||
|
||||
@@ -678,8 +678,7 @@ impl ModelRequestRepository for PgExecutionStore {
|
||||
and prior.outcome in ('failed', 'incomplete')
|
||||
and prior.error_kind = 'continuation_recovery_required'
|
||||
and prior.recovered_at is null
|
||||
and current.started_at >= prior.completed_at
|
||||
and current.started_at <= prior.completed_at + interval '30 seconds'
|
||||
and prior.completed_at between current.started_at - interval '30 seconds' and current.started_at
|
||||
order by prior.completed_at desc, prior.id desc
|
||||
limit 1
|
||||
), recovery_update as (
|
||||
@@ -720,8 +719,7 @@ impl ModelRequestRepository for PgExecutionStore {
|
||||
and prior.upstream_send_state = 'ambiguous'
|
||||
and prior.downstream_committed_at is null
|
||||
and prior.recovered_at is null
|
||||
and current.started_at >= prior.completed_at
|
||||
and current.started_at <= prior.completed_at + interval '30 seconds'
|
||||
and prior.completed_at between current.started_at - interval '30 seconds' and current.started_at
|
||||
), session_transport_recovery_update as (
|
||||
update model_requests prior
|
||||
set recovery_attempt_count = prior.recovery_attempt_count + 1,
|
||||
|
||||
@@ -692,19 +692,19 @@ async fn retained_account_usage_range(
|
||||
pub(crate) async fn account_usage_sort_values(
|
||||
snapshot: &mut AnalyticsSnapshot<'_>,
|
||||
now: DateTime<Utc>,
|
||||
) -> StoreResult<(Vec<String>, Vec<i64>, Vec<Option<DateTime<Utc>>>)> {
|
||||
ids: &[String],
|
||||
) -> StoreResult<(Vec<i64>, Vec<Option<DateTime<Utc>>>)> {
|
||||
if ids.is_empty() {
|
||||
return Ok((Vec::new(), Vec::new()));
|
||||
}
|
||||
let range = retained_account_usage_range(snapshot, now).await?;
|
||||
let ids: Vec<String> = sqlx::query_scalar("select id from provider_accounts")
|
||||
.fetch_all(&mut *snapshot.tx)
|
||||
.await
|
||||
.map_err(|error| postgres_unavailable("read account usage sort identities", error))?;
|
||||
let mut totals = BTreeMap::<String, MetricState>::new();
|
||||
for ((account, _), state) in snapshot.account_states(range, &ids, false).await? {
|
||||
for ((account, _), state) in snapshot.account_states(range, ids, false).await? {
|
||||
totals.entry(account).or_default().merge(&state)?;
|
||||
}
|
||||
let mut tokens = Vec::with_capacity(ids.len());
|
||||
let mut latest = Vec::with_capacity(ids.len());
|
||||
for id in &ids {
|
||||
for id in ids {
|
||||
let state = totals.remove(id).unwrap_or_default();
|
||||
tokens.push(
|
||||
i64::try_from(state.count("window_total_tokens"))
|
||||
@@ -712,7 +712,7 @@ pub(crate) async fn account_usage_sort_values(
|
||||
);
|
||||
latest.push(state.last_used_at());
|
||||
}
|
||||
Ok((ids, tokens, latest))
|
||||
Ok((tokens, latest))
|
||||
}
|
||||
|
||||
pub(crate) async fn account_group_usage(
|
||||
|
||||
@@ -127,8 +127,8 @@ pub(super) async fn rebuild_bucket_batch(
|
||||
if phase == 1 {
|
||||
// 增量前缀判断使用 Rust 字节序,SQL 游标必须使用同一排序规则
|
||||
let statement = format!(
|
||||
"{} where mr.started_at >= $1 and mr.started_at < $1+interval '15 minutes' and (mr.started_at,mr.id collate \"C\")>($2,$3) order by mr.started_at,mr.id collate \"C\" limit $4",
|
||||
fact_select()
|
||||
"select {} from request_analytics_facts mr where mr.started_at >= $1 and mr.started_at < $1+interval '15 minutes' and (mr.started_at,mr.id collate \"C\")>($2,$3) order by mr.started_at,mr.id collate \"C\" limit $4",
|
||||
fact_columns()
|
||||
);
|
||||
let rows = sqlx::query(sqlx::AssertSqlSafe(statement))
|
||||
.bind(bucket)
|
||||
|
||||
@@ -56,9 +56,9 @@ pub(crate) async fn begin_snapshot(
|
||||
Ok(transaction)
|
||||
}
|
||||
|
||||
fn fact_select() -> String {
|
||||
fn fact_columns() -> String {
|
||||
format!(
|
||||
"select mr.*, mr.cost_amount::text as cost_amount_text, mr.standard_cost_amount::text as standard_cost_amount_text, mr.no_cache_cost_amount::text as no_cache_cost_amount_text, coalesce(({}),false) as is_completed_usage from request_analytics_facts mr",
|
||||
"mr.*, mr.cost_amount::text as cost_amount_text, mr.standard_cost_amount::text as standard_cost_amount_text, mr.no_cache_cost_amount::text as no_cache_cost_amount_text, coalesce(({}),false) as is_completed_usage",
|
||||
completed_usage_fact_predicate("mr")
|
||||
)
|
||||
}
|
||||
|
||||
@@ -54,7 +54,14 @@ pub(crate) async fn declare_usage_statistics(
|
||||
continue;
|
||||
}
|
||||
let (key, model, provider, account) = summary_columns(collection);
|
||||
let group = group_expression(request.group_by, key, model, "null::text", false);
|
||||
// 汇总以空串保存缺失维度,仅分组输出还原 NULL,筛选直接使用维度索引
|
||||
let group = group_expression(
|
||||
request.group_by,
|
||||
&format!("nullif({key},'')"),
|
||||
&format!("nullif({model},'')"),
|
||||
"null::text",
|
||||
false,
|
||||
);
|
||||
query.push(format!(" union all select names.name,a.counts,a.costs from {table} a cross join lateral (values ({group}),('null')) names(name) where a.collection="))
|
||||
.push_bind(collection).push(" and a.schema_version=").push_bind(SCHEMA_VERSION)
|
||||
.push(" and a.histogram_version=").push_bind(HISTOGRAM_VERSION);
|
||||
@@ -67,8 +74,9 @@ pub(crate) async fn declare_usage_statistics(
|
||||
] {
|
||||
if let Some(value) = value {
|
||||
query
|
||||
.push(format!(" and {column}="))
|
||||
.push_bind(value.clone());
|
||||
.push(format!(" and {column}=nullif("))
|
||||
.push_bind(value.clone())
|
||||
.push(",'')");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -208,28 +216,23 @@ fn collection(query: &QueryUsageStatistics) -> Option<&'static str> {
|
||||
|
||||
fn summary_columns(collection: &str) -> (&'static str, &'static str, &'static str, &'static str) {
|
||||
match collection {
|
||||
"key" => (
|
||||
"nullif(a.dimensions[1],'')",
|
||||
"null::text",
|
||||
"null::text",
|
||||
"null::text",
|
||||
),
|
||||
"key" => ("a.dimensions[1]", "null::text", "null::text", "null::text"),
|
||||
"key_model" => (
|
||||
"nullif(a.dimensions[1],'')",
|
||||
"nullif(a.dimensions[4],'')",
|
||||
"nullif(a.dimensions[2],'')",
|
||||
"a.dimensions[1]",
|
||||
"a.dimensions[4]",
|
||||
"a.dimensions[2]",
|
||||
"null::text",
|
||||
),
|
||||
"account_model" => (
|
||||
"null::text",
|
||||
"nullif(a.dimensions[4],'')",
|
||||
"nullif(a.dimensions[2],'')",
|
||||
"nullif(a.dimensions[1],'')",
|
||||
"a.dimensions[4]",
|
||||
"a.dimensions[2]",
|
||||
"a.dimensions[1]",
|
||||
),
|
||||
_ => (
|
||||
"null::text",
|
||||
"nullif(a.dimensions[3],'')",
|
||||
"nullif(a.dimensions[1],'')",
|
||||
"a.dimensions[3]",
|
||||
"a.dimensions[1]",
|
||||
"null::text",
|
||||
),
|
||||
}
|
||||
|
||||
@@ -120,15 +120,17 @@ impl PgRequestAnalyticsRepository {
|
||||
publish_generation(&mut transaction, true).await?;
|
||||
}
|
||||
transaction.commit().await.map_err(|error| postgres_unavailable("publish analytics maintenance", error))?;
|
||||
// 快照后提交的源版本会让 RR 下的行锁直接序列化失败,持续写入时整批投影会反复回滚
|
||||
// ACK 在投影提交后使用 READ COMMITTED,行锁按最新提交版本重新比较,已改写的版本不再匹配
|
||||
let mut transaction = connection.begin().await.map_err(|error| postgres_unavailable("begin analytics acknowledgement", error))?;
|
||||
sqlx::query("set local statement_timeout = '10s'").execute(&mut *transaction).await.map_err(|error| postgres_unavailable("set analytics query deadline", error))?;
|
||||
// ACK 跳过源事务持有的队列行,避免等待并发更新或删除
|
||||
// 被跳过的版本保留在持久队列中重放,只有精确匹配且已取得行锁的版本才确认
|
||||
sqlx::query("with acknowledged as materialized (select pending.request_id,pending.change_version from request_analytics_pending_requests pending join unnest($1::text[],$2::bigint[]) job(id,version) on pending.request_id=job.id and pending.change_version=job.version for update of pending skip locked) delete from request_analytics_pending_requests pending using acknowledged where pending.request_id=acknowledged.request_id and pending.change_version=acknowledged.change_version")
|
||||
.bind(ids).bind(versions).execute(&mut *transaction).await.map_err(|error| postgres_unavailable("confirm analytics request versions", error))?;
|
||||
transaction.commit().await.map_err(|error| postgres_unavailable("complete analytics acknowledgement", error))?;
|
||||
if !ids.is_empty() {
|
||||
// 快照后提交的源版本会让 RR 下的行锁直接序列化失败,持续写入时整批投影会反复回滚
|
||||
// ACK 在投影提交后使用 READ COMMITTED,行锁按最新提交版本重新比较,已改写的版本不再匹配
|
||||
let mut transaction = connection.begin().await.map_err(|error| postgres_unavailable("begin analytics acknowledgement", error))?;
|
||||
sqlx::query("set local statement_timeout = '10s'").execute(&mut *transaction).await.map_err(|error| postgres_unavailable("set analytics query deadline", error))?;
|
||||
// ACK 跳过源事务持有的队列行,避免等待并发更新或删除
|
||||
// 被跳过的版本保留在持久队列中重放,只有精确匹配且已取得行锁的版本才确认
|
||||
sqlx::query("with acknowledged as materialized (select pending.request_id,pending.change_version from request_analytics_pending_requests pending join unnest($1::text[],$2::bigint[]) job(id,version) on pending.request_id=job.id and pending.change_version=job.version for update of pending skip locked) delete from request_analytics_pending_requests pending using acknowledged where pending.request_id=acknowledged.request_id and pending.change_version=acknowledged.change_version")
|
||||
.bind(ids).bind(versions).execute(&mut *transaction).await.map_err(|error| postgres_unavailable("confirm analytics request versions", error))?;
|
||||
transaction.commit().await.map_err(|error| postgres_unavailable("complete analytics acknowledgement", error))?;
|
||||
}
|
||||
// 每个阶段使用独立短事务,聚合只锁自己的队列,不把读放大传递到请求终结
|
||||
let mut transaction = begin_snapshot(&mut connection).await?;
|
||||
let acquired: bool = sqlx::query_scalar("select pg_try_advisory_xact_lock(hashtextextended(current_schema()::text,382032))")
|
||||
@@ -158,19 +160,14 @@ impl PgRequestAnalyticsRepository {
|
||||
if ids.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let columns = fact_columns();
|
||||
let previous = sqlx::query(sqlx::AssertSqlSafe(format!(
|
||||
"{} where mr.id=any($1::text[])",
|
||||
fact_select()
|
||||
"delete from request_analytics_facts mr where mr.id=any($1::text[]) returning {columns}"
|
||||
)))
|
||||
.bind(ids)
|
||||
.fetch_all(&mut **tx)
|
||||
.await
|
||||
.map_err(|error| postgres_unavailable("read previous analytics contributions", error))?;
|
||||
sqlx::query("delete from request_analytics_facts where id=any($1::text[])")
|
||||
.bind(ids)
|
||||
.execute(&mut **tx)
|
||||
.await
|
||||
.map_err(|error| postgres_unavailable("replace analytics facts", error))?;
|
||||
.map_err(|error| postgres_unavailable("replace analytics facts", error))?;
|
||||
sqlx::query(PROJECT_REQUEST)
|
||||
.bind(ids)
|
||||
.execute(&mut **tx)
|
||||
@@ -178,8 +175,7 @@ impl PgRequestAnalyticsRepository {
|
||||
.map_err(|error| postgres_unavailable("project analytics facts", error))?;
|
||||
self.project_billing_batch(tx, ids).await?;
|
||||
let current = sqlx::query(sqlx::AssertSqlSafe(format!(
|
||||
"{} where mr.id=any($1::text[])",
|
||||
fact_select()
|
||||
"select {columns} from request_analytics_facts mr where mr.id=any($1::text[])"
|
||||
)))
|
||||
.bind(ids)
|
||||
.fetch_all(&mut **tx)
|
||||
|
||||
@@ -28,7 +28,7 @@ use gateway_admin::{
|
||||
store::{AdminStoreError, AdminStoreErrorKind, AdminStoreResult},
|
||||
},
|
||||
};
|
||||
use sqlx::{PgConnection, Postgres, Row as _, Transaction};
|
||||
use sqlx::{PgConnection, Postgres, QueryBuilder, Row as _, Transaction};
|
||||
use tokio::sync::OwnedSemaphorePermit;
|
||||
|
||||
use super::artifacts::PgPluginStore;
|
||||
@@ -872,21 +872,14 @@ impl PluginStateStore for PgPluginStore {
|
||||
let mut next_version = generation.next_record_version;
|
||||
let mut record_count = generation.record_count;
|
||||
let mut total_bytes = generation.total_bytes;
|
||||
for ((change, source), expected_key) in command
|
||||
.changes
|
||||
.iter()
|
||||
.zip(source_rows.iter())
|
||||
.zip(&command.expected_keys)
|
||||
{
|
||||
let value = match &change.action {
|
||||
let mut records = Vec::with_capacity(command.changes.len());
|
||||
for (change, source) in command.changes.into_iter().zip(source_rows) {
|
||||
let value = match change.action {
|
||||
PluginStateMigrationAction::Keep => {
|
||||
Some(source.try_get("value_json").map_err(|_| unavailable())?)
|
||||
source.try_get("value_json").map_err(|_| unavailable())?
|
||||
}
|
||||
PluginStateMigrationAction::Replace(value) => Some(value.clone()),
|
||||
PluginStateMigrationAction::Delete => None,
|
||||
};
|
||||
let Some(value) = value else {
|
||||
continue;
|
||||
PluginStateMigrationAction::Replace(value) => value,
|
||||
PluginStateMigrationAction::Delete => continue,
|
||||
};
|
||||
let bytes = u64::try_from(serde_json::to_vec(&value).map_err(|_| invalid())?.len())
|
||||
.map_err(|_| quota())?;
|
||||
@@ -900,28 +893,39 @@ impl PluginStateStore for PgPluginStore {
|
||||
}
|
||||
let version = next_version;
|
||||
next_version = next_version.checked_add(1).ok_or_else(quota)?;
|
||||
sqlx::query(
|
||||
"insert into plugin_state_records( \
|
||||
generation_id,state_key,value_json,value_bytes,record_version \
|
||||
) values ($1,$2,$3,$4,$5)",
|
||||
)
|
||||
.bind(generation.id)
|
||||
.bind(expected_key)
|
||||
.bind(value)
|
||||
.bind(i64::try_from(bytes).map_err(|_| quota())?)
|
||||
.bind(i64::try_from(version).map_err(|_| quota())?)
|
||||
.execute(&mut *transaction)
|
||||
.await
|
||||
.map_err(|error| {
|
||||
if error
|
||||
.as_database_error()
|
||||
.is_some_and(|database| database.is_unique_violation())
|
||||
{
|
||||
conflict()
|
||||
} else {
|
||||
unavailable()
|
||||
}
|
||||
})?;
|
||||
records.push((
|
||||
change.key,
|
||||
value,
|
||||
i64::try_from(bytes).map_err(|_| quota())?,
|
||||
i64::try_from(version).map_err(|_| quota())?,
|
||||
));
|
||||
}
|
||||
if !records.is_empty() {
|
||||
let mut insert = QueryBuilder::<Postgres>::new(
|
||||
"insert into plugin_state_records(generation_id,state_key,value_json,value_bytes,record_version) ",
|
||||
);
|
||||
insert.push_values(records, |mut row, (key, value, bytes, version)| {
|
||||
row.push_bind(generation.id)
|
||||
.push_bind(key)
|
||||
.push_bind(value)
|
||||
.push_bind(bytes)
|
||||
.push_bind(version);
|
||||
});
|
||||
insert
|
||||
.build()
|
||||
.persistent(false)
|
||||
.execute(&mut *transaction)
|
||||
.await
|
||||
.map_err(|error| {
|
||||
if error
|
||||
.as_database_error()
|
||||
.is_some_and(|database| database.is_unique_violation())
|
||||
{
|
||||
conflict()
|
||||
} else {
|
||||
unavailable()
|
||||
}
|
||||
})?;
|
||||
}
|
||||
let complete = command.expected_keys.is_empty();
|
||||
let next_cursor = command.expected_keys.last().or(command.cursor.as_ref());
|
||||
|
||||
@@ -9,6 +9,17 @@ use gateway_core::provider_ports::ProviderCooldownPort;
|
||||
use super::*;
|
||||
use crate::postgres::ObservabilityQueryBudget;
|
||||
|
||||
fn credential_export_input(
|
||||
record: ProviderAccountRecord,
|
||||
) -> AdminStoreResult<ProviderExportCredentialInput> {
|
||||
Ok(ProviderExportCredentialInput {
|
||||
account: admin_account_record(record.summary)?,
|
||||
provider_material: ProviderDocument::new(OpaqueProviderData::new(
|
||||
record.provider_credentials_json.into_fields(),
|
||||
)),
|
||||
})
|
||||
}
|
||||
|
||||
fn account_capacity(
|
||||
account: &AccountRecord,
|
||||
default_concurrency: u64,
|
||||
@@ -541,45 +552,69 @@ impl AccountStore for PgAdminAccountStore {
|
||||
.transpose()
|
||||
}
|
||||
|
||||
async fn credential_export_scopes(
|
||||
&self,
|
||||
account_ids: &[CoreProviderAccountId],
|
||||
) -> AdminStoreResult<BTreeMap<String, CredentialExportScope>> {
|
||||
let ids = account_ids
|
||||
.iter()
|
||||
.map(CoreProviderAccountId::as_str)
|
||||
.collect::<Vec<_>>();
|
||||
let rows: Vec<(String, String, String)> = sqlx::query_as(
|
||||
"select id, provider_kind, authentication_kind from provider_accounts where id = any($1::text[])",
|
||||
)
|
||||
.bind(&ids)
|
||||
.fetch_all(&self.pool)
|
||||
.await
|
||||
.map_err(|source| {
|
||||
admin_store_error(ENTITY, postgres_unavailable("read credential export scopes", source))
|
||||
})?;
|
||||
rows.into_iter()
|
||||
.map(|(id, kind, authentication_kind)| {
|
||||
let provider_kind = ProviderKind::new(kind).map_err(|source| {
|
||||
admin_store_error(
|
||||
ENTITY,
|
||||
invalid("persisted Provider kind is invalid").with_source(source),
|
||||
)
|
||||
})?;
|
||||
Ok((
|
||||
id,
|
||||
CredentialExportScope {
|
||||
provider_kind,
|
||||
authentication_kind,
|
||||
},
|
||||
))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
async fn load_credentials_for_export(
|
||||
&self,
|
||||
provider_kind: &ProviderKind,
|
||||
account_ids: &[CoreProviderAccountId],
|
||||
accounts: &[(CoreProviderAccountId, String)],
|
||||
) -> AdminStoreResult<Vec<ProviderExportCredentialInput>> {
|
||||
let ids = account_ids
|
||||
let ids = accounts
|
||||
.iter()
|
||||
.map(|id| id.as_str().to_owned())
|
||||
.map(|(id, _)| id.as_str().to_owned())
|
||||
.collect::<Vec<_>>();
|
||||
validate_admin_account_ids(&ids).map_err(|error| admin_store_error(ENTITY, error))?;
|
||||
let mut credentials = Vec::with_capacity(account_ids.len());
|
||||
for account_id in account_ids {
|
||||
let record = self
|
||||
.accounts
|
||||
.load_provider_account(account_id.as_str())
|
||||
.await
|
||||
.map_err(|error| admin_store_error(ENTITY, error))?
|
||||
.ok_or_else(|| {
|
||||
AdminStoreError::new(
|
||||
AdminStoreErrorKind::NotFound,
|
||||
ENTITY,
|
||||
"one or more exported credentials do not exist",
|
||||
)
|
||||
})?;
|
||||
if record.summary.provider_kind != provider_kind.as_str() {
|
||||
return Err(AdminStoreError::new(
|
||||
AdminStoreErrorKind::NotFound,
|
||||
ENTITY,
|
||||
"one or more exported credentials belong to another Provider",
|
||||
));
|
||||
}
|
||||
credentials.push(ProviderExportCredentialInput {
|
||||
account: admin_account_record(record.summary)?,
|
||||
provider_material: ProviderDocument::new(OpaqueProviderData::new(
|
||||
record.provider_credentials_json.fields().clone(),
|
||||
)),
|
||||
});
|
||||
let kinds = accounts
|
||||
.iter()
|
||||
.map(|(_, kind)| kind.as_str())
|
||||
.collect::<Vec<_>>();
|
||||
let records = self
|
||||
.accounts
|
||||
.load_export_records(provider_kind.as_str(), &ids, Some(&kinds))
|
||||
.await
|
||||
.map_err(|error| admin_store_error(ENTITY, error))?;
|
||||
if records.len() != ids.len() {
|
||||
return Err(AdminStoreError::new(
|
||||
AdminStoreErrorKind::NotFound,
|
||||
ENTITY,
|
||||
"one or more credentials are missing or outside the verified export scope",
|
||||
));
|
||||
}
|
||||
Ok(credentials)
|
||||
records.into_iter().map(credential_export_input).collect()
|
||||
}
|
||||
|
||||
async fn load_credential_for_plugin(
|
||||
@@ -590,14 +625,7 @@ impl AccountStore for PgAdminAccountStore {
|
||||
.load_provider_account(account_id.as_str())
|
||||
.await
|
||||
.map_err(|error| admin_store_error(ENTITY, error))?
|
||||
.map(|record| {
|
||||
Ok(ProviderExportCredentialInput {
|
||||
account: admin_account_record(record.summary)?,
|
||||
provider_material: ProviderDocument::new(OpaqueProviderData::new(
|
||||
record.provider_credentials_json.fields().clone(),
|
||||
)),
|
||||
})
|
||||
})
|
||||
.map(credential_export_input)
|
||||
.transpose()
|
||||
}
|
||||
|
||||
@@ -890,27 +918,6 @@ impl AccountStore for PgAdminAccountStore {
|
||||
.map(|id| id.as_str().to_owned())
|
||||
.collect::<Vec<_>>();
|
||||
validate_admin_account_ids(&ids).map_err(|error| admin_store_error(ENTITY, error))?;
|
||||
for account_id in &ids {
|
||||
if self
|
||||
.accounts
|
||||
.load_provider_account(account_id)
|
||||
.await
|
||||
.map_err(|error| admin_store_error(ENTITY, error))?
|
||||
.is_none()
|
||||
{
|
||||
return Err(AdminStoreError::new(
|
||||
AdminStoreErrorKind::NotFound,
|
||||
ENTITY,
|
||||
"one or more exported credentials do not exist",
|
||||
));
|
||||
}
|
||||
}
|
||||
let control_plane = self
|
||||
.control_plane
|
||||
.load_control_plane()
|
||||
.await
|
||||
.map_err(|error| admin_store_error(ENTITY, error))?;
|
||||
let revision = control_plane.settings.config_revision;
|
||||
let mut transaction = self.accounts.pool.begin().await.map_err(|source| {
|
||||
admin_store_error(
|
||||
ENTITY,
|
||||
@@ -918,20 +925,38 @@ impl AccountStore for PgAdminAccountStore {
|
||||
)
|
||||
})?;
|
||||
let result = async {
|
||||
for account_id in &ids {
|
||||
append_admin_audit_event_in_transaction(
|
||||
&mut transaction,
|
||||
mutation_audit(
|
||||
// 凭据序列化后重新确认账号存在,并阻止删除越过本次审计提交
|
||||
let (revision, locked_ids): (i64, Vec<String>) = sqlx::query_as(
|
||||
"select config_revision, array(
|
||||
select id from provider_accounts where id = any($1::text[]) order by id for key share
|
||||
) from runtime_settings where id = 1",
|
||||
)
|
||||
.bind(&ids)
|
||||
.fetch_one(&mut *transaction)
|
||||
.await
|
||||
.map_err(|source| postgres_unavailable("lock audited credential export accounts", source))?;
|
||||
let found = locked_ids.into_iter().collect::<BTreeSet<_>>();
|
||||
if let Some(id) = ids.iter().find(|id| !found.contains(*id)) {
|
||||
return Err(StoreError::NotFound {
|
||||
entity: ENTITY,
|
||||
id: id.clone(),
|
||||
source: None,
|
||||
});
|
||||
}
|
||||
let events = ids
|
||||
.iter()
|
||||
.map(|id| {
|
||||
let mut event = mutation_audit(
|
||||
context,
|
||||
MutationAuditOperation::ProviderAccountExportCredentials,
|
||||
account_id,
|
||||
id,
|
||||
Vec::new(),
|
||||
),
|
||||
revision,
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
Ok(())
|
||||
);
|
||||
event.config_revision = Some(revision);
|
||||
event
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
crate::postgres::insert_admin_audit_events(&mut *transaction, &events).await
|
||||
}
|
||||
.await;
|
||||
finish_admin_transaction(transaction, result, "credential export audit")
|
||||
|
||||
@@ -10,6 +10,47 @@ pub(crate) struct AdminAccountPageRows {
|
||||
pub(crate) summary: AccountSummary,
|
||||
}
|
||||
|
||||
// 目录筛选同时用于普通分页和用量排序的候选账号,分页前按相同条件确定集合
|
||||
const DIRECTORY_CTES: &str = "
|
||||
with account_statuses as (
|
||||
select a.id, a.provider_kind, a.name, a.email, a.upstream_account_id, a.plan_type, a.access_token_expires_at,
|
||||
case
|
||||
when not a.enabled then 'disabled'
|
||||
when a.credential_state <> 'ready'
|
||||
or a.access_token_expires_at <= $2 then 'error'
|
||||
when a.quota_access_state = 'exhausted'
|
||||
and (a.quota_exhaustion_deadline is null or a.quota_exhaustion_deadline > $2) then 'quota_exhausted'
|
||||
when a.id = any($1::text[]) or exists (
|
||||
select 1 from unnest($8::text[], $9::bigint[]) as limits(account_id, revision)
|
||||
where limits.account_id = a.id and limits.revision = a.credential_revision
|
||||
) then 'rate_limited'
|
||||
when a.quota_paused then 'quota_paused'
|
||||
else 'normal'
|
||||
end as admin_status
|
||||
from provider_accounts a
|
||||
),
|
||||
filtered as (
|
||||
select a.*
|
||||
from account_statuses a
|
||||
where ($3::text is null or a.provider_kind = $3)
|
||||
and ($4::text is null or
|
||||
lower(a.name) like $4 escape '\\' or
|
||||
lower(coalesce(a.email, '')) like $4 escape '\\')
|
||||
and ($5::text is null or a.admin_status = $5)
|
||||
and ($6::smallint = 0 or
|
||||
($6 = 1 and exists (
|
||||
select 1
|
||||
from account_group_accounts membership
|
||||
where membership.provider_account_id = a.id
|
||||
and membership.account_group_id = $7
|
||||
)) or
|
||||
($6 = 2 and not exists (
|
||||
select 1
|
||||
from account_group_accounts membership
|
||||
where membership.provider_account_id = a.id
|
||||
)))
|
||||
)";
|
||||
|
||||
pub(crate) async fn load_admin_account_page(
|
||||
pool: &PgPool,
|
||||
budget: &crate::postgres::ObservabilityQueryBudget,
|
||||
@@ -45,29 +86,14 @@ pub(crate) async fn load_admin_account_page(
|
||||
AdminAccountSortField::Usage | AdminAccountSortField::LastUsedAt
|
||||
)
|
||||
});
|
||||
let usage_join = if needs_usage {
|
||||
"left join usage_values usage on usage.provider_account_ref = a.id"
|
||||
let candidates = if needs_usage {
|
||||
"usage_values"
|
||||
} else {
|
||||
""
|
||||
"filtered"
|
||||
};
|
||||
|
||||
let statement = format!(
|
||||
"with usage_values as (select * from unnest($10::text[],$11::bigint[],$12::timestamptz[]) as usage(provider_account_ref,total_tokens,last_used_at)), account_statuses as (
|
||||
select a.id, a.provider_kind,
|
||||
case
|
||||
when not a.enabled then 'disabled'
|
||||
when a.credential_state <> 'ready'
|
||||
or a.access_token_expires_at <= $2 then 'error'
|
||||
when a.quota_access_state = 'exhausted'
|
||||
and (a.quota_exhaustion_deadline is null or a.quota_exhaustion_deadline > $2) then 'quota_exhausted'
|
||||
when a.id = any($1::text[]) or exists (
|
||||
select 1 from unnest($13::text[], $14::bigint[]) as limits(account_id, revision)
|
||||
where limits.account_id = a.id and limits.revision = a.credential_revision
|
||||
) then 'rate_limited'
|
||||
when a.quota_paused then 'quota_paused'
|
||||
else 'normal'
|
||||
end as admin_status
|
||||
from provider_accounts a
|
||||
let page_sql = format!(
|
||||
", usage_values as (
|
||||
select * from unnest($12::text[],$13::bigint[],$14::timestamptz[]) as usage(id,total_tokens,last_used_at)
|
||||
),
|
||||
global_summary as (
|
||||
select count(*)::bigint as summary_total,
|
||||
@@ -82,30 +108,8 @@ pub(crate) async fn load_admin_account_page(
|
||||
count(*) filter (where admin_status = 'error')::bigint as summary_error
|
||||
from account_statuses
|
||||
),
|
||||
filtered as materialized (
|
||||
select status.id, status.admin_status
|
||||
from account_statuses status
|
||||
join provider_accounts a on a.id = status.id
|
||||
where ($3::text is null or a.provider_kind = $3)
|
||||
and ($4::text is null or
|
||||
lower(a.name) like $4 escape '\\' or
|
||||
lower(coalesce(a.email, '')) like $4 escape '\\')
|
||||
and ($5::text is null or status.admin_status = $5)
|
||||
and ($6::smallint = 0 or
|
||||
($6 = 1 and exists (
|
||||
select 1
|
||||
from account_group_accounts membership
|
||||
where membership.provider_account_id = a.id
|
||||
and membership.account_group_id = $7
|
||||
)) or
|
||||
($6 = 2 and not exists (
|
||||
select 1
|
||||
from account_group_accounts membership
|
||||
where membership.provider_account_id = a.id
|
||||
)))
|
||||
),
|
||||
filtered_total as (
|
||||
select count(*)::bigint as filtered_total from filtered
|
||||
select count(*)::bigint as filtered_total from {candidates}
|
||||
),
|
||||
settings as (
|
||||
select config_revision, usage_retention_days, max_concurrent_per_account
|
||||
@@ -130,12 +134,10 @@ pub(crate) async fn load_admin_account_page(
|
||||
left join lateral (
|
||||
select ordered.*, row_number() over ()::bigint as page_position
|
||||
from (
|
||||
select filtered.id, filtered.admin_status
|
||||
from filtered
|
||||
join provider_accounts a on a.id = filtered.id
|
||||
{usage_join}
|
||||
select a.id
|
||||
from {candidates} a
|
||||
order by {order_by}
|
||||
limit $8 offset $9
|
||||
limit $10 offset $11
|
||||
) ordered
|
||||
) page on true
|
||||
left join provider_accounts a on a.id = page.id
|
||||
@@ -153,27 +155,43 @@ pub(crate) async fn load_admin_account_page(
|
||||
&mut connection,
|
||||
)
|
||||
.await?;
|
||||
let directory = |suffix: &str| {
|
||||
sqlx::query(sqlx::AssertSqlSafe(format!("{DIRECTORY_CTES}{suffix}")))
|
||||
.bind(&active_rate_limited_ids)
|
||||
.bind(now)
|
||||
.bind(&provider_kind)
|
||||
.bind(&search_pattern)
|
||||
.bind(&status)
|
||||
.bind(group_mode)
|
||||
.bind(&group_id)
|
||||
.bind(&model_account_ids)
|
||||
.bind(&model_revisions)
|
||||
};
|
||||
let (usage_ids, usage_tokens, usage_latest) = if needs_usage {
|
||||
crate::postgres::observability::account_usage_sort_values(&mut snapshot, now)
|
||||
.await?
|
||||
let ids: Vec<String> = directory(" select id from filtered")
|
||||
.try_map(|row| row.try_get("id"))
|
||||
.fetch_all(&mut *snapshot.tx)
|
||||
.await
|
||||
.map_err(|error| {
|
||||
postgres_unavailable("read account usage sort candidates", error)
|
||||
})?;
|
||||
let (tokens, latest) =
|
||||
crate::postgres::observability::account_usage_sort_values(
|
||||
&mut snapshot,
|
||||
now,
|
||||
&ids,
|
||||
)
|
||||
.await?;
|
||||
(ids, tokens, latest)
|
||||
} else {
|
||||
(Vec::new(), Vec::new(), Vec::new())
|
||||
};
|
||||
let rows = sqlx::query(sqlx::AssertSqlSafe(statement))
|
||||
.bind(active_rate_limited_ids)
|
||||
.bind(now)
|
||||
.bind(provider_kind)
|
||||
.bind(search_pattern)
|
||||
.bind(status)
|
||||
.bind(group_mode)
|
||||
.bind(group_id)
|
||||
let rows = directory(&page_sql)
|
||||
.bind(page_size)
|
||||
.bind(offset)
|
||||
.bind(usage_ids)
|
||||
.bind(usage_tokens)
|
||||
.bind(usage_latest)
|
||||
.bind(model_account_ids)
|
||||
.bind(model_revisions)
|
||||
.fetch_all(&mut *snapshot.tx)
|
||||
.await
|
||||
.map_err(|source| postgres_unavailable("load admin account page", source))?;
|
||||
@@ -266,11 +284,11 @@ fn admin_account_order(sort: Option<AdminAccountSort>) -> String {
|
||||
"lower(coalesce(nullif(btrim(a.name), ''), nullif(btrim(a.email), ''), a.upstream_account_id, a.id))"
|
||||
}
|
||||
AdminAccountSortField::Status => {
|
||||
"case filtered.admin_status when 'normal' then 0 when 'rate_limited' then 1 when 'quota_exhausted' then 2 when 'quota_paused' then 3 when 'error' then 4 else 5 end"
|
||||
"case a.admin_status when 'normal' then 0 when 'rate_limited' then 1 when 'quota_exhausted' then 2 when 'quota_paused' then 3 when 'error' then 4 else 5 end"
|
||||
}
|
||||
AdminAccountSortField::PlanType => "a.plan_type",
|
||||
AdminAccountSortField::Usage => "usage.total_tokens",
|
||||
AdminAccountSortField::LastUsedAt => "usage.last_used_at",
|
||||
AdminAccountSortField::Usage => "a.total_tokens",
|
||||
AdminAccountSortField::LastUsedAt => "a.last_used_at",
|
||||
AdminAccountSortField::ExpiresAt => "a.access_token_expires_at",
|
||||
};
|
||||
match sort.direction {
|
||||
|
||||
@@ -58,6 +58,7 @@ impl ProviderAccountStore for PgProviderAccountRepository {
|
||||
)
|
||||
.map_err(core_store_error)?;
|
||||
self.insert_provider_account(NewProviderAccount {
|
||||
preserve_catalog_etag: None,
|
||||
outbound_proxy: account.account.outbound_proxy().cloned(),
|
||||
id: account.account.id().as_str().to_owned(),
|
||||
provider_kind: account.account.provider().as_str().to_owned(),
|
||||
|
||||
@@ -54,6 +54,7 @@ pub(crate) fn prepared_account(
|
||||
credential: PreparedCredentialCreate,
|
||||
) -> StoreResult<NewProviderAccount> {
|
||||
Ok(NewProviderAccount {
|
||||
preserve_catalog_etag: credential.preserve_catalog_etag,
|
||||
outbound_proxy: credential.outbound_proxy,
|
||||
id: credential.account_id.as_str().to_owned(),
|
||||
provider_kind: credential.provider_kind.as_str().to_owned(),
|
||||
|
||||
@@ -19,10 +19,10 @@ use gateway_admin::{
|
||||
observability::TimeRange,
|
||||
provider_credentials::{
|
||||
AuthorizationCommit, AuthorizationCredentialCommit, CredentialDetails,
|
||||
CredentialImportCommit, CredentialImportResult, CredentialMutationResult,
|
||||
CredentialRotationCommit, PluginAccountListQuery, PluginAccountPage,
|
||||
PreparedCredentialCreate, PreparedCredentialImport, PreparedCredentialRotationFacts,
|
||||
ProviderDocument, ProviderExportCredentialInput,
|
||||
CredentialExportScope, CredentialImportCommit, CredentialImportResult,
|
||||
CredentialMutationResult, CredentialRotationCommit, PluginAccountListQuery,
|
||||
PluginAccountPage, PreparedCredentialCreate, PreparedCredentialImport,
|
||||
PreparedCredentialRotationFacts, ProviderDocument, ProviderExportCredentialInput,
|
||||
},
|
||||
},
|
||||
ports::store::{AccountStore, AdminStoreError, AdminStoreErrorKind, AdminStoreResult},
|
||||
|
||||
@@ -13,9 +13,9 @@ impl PgProviderAccountRepository {
|
||||
previous_revision: i64,
|
||||
revision: i64,
|
||||
etag: &str,
|
||||
) -> Result<(), sqlx::Error> {
|
||||
) -> Result<bool, sqlx::Error> {
|
||||
// 取得账号 CAS 行锁后用新语句读目录,覆盖刚刚在锁前提交的首次观测
|
||||
sqlx::query(
|
||||
let result = sqlx::query(
|
||||
"update provider_account_model_catalogs c set credential_revision = a.credential_revision
|
||||
from provider_accounts a where a.id = $1 and c.account_id = a.id
|
||||
and c.credential_revision = $2 and a.credential_revision = $3
|
||||
@@ -27,7 +27,7 @@ impl PgProviderAccountRepository {
|
||||
.bind(etag)
|
||||
.execute(&mut **transaction)
|
||||
.await?;
|
||||
Ok(())
|
||||
Ok(result.rows_affected() == 1)
|
||||
}
|
||||
|
||||
pub(super) async fn load_model_catalogs(
|
||||
|
||||
@@ -99,6 +99,22 @@ impl PgProviderAccountRepository {
|
||||
self
|
||||
}
|
||||
|
||||
pub(super) async fn load_export_records(
|
||||
&self,
|
||||
provider_kind: &str,
|
||||
ids: &[String],
|
||||
authentication_kinds: Option<&[&str]>,
|
||||
) -> StoreResult<Vec<ProviderAccountRecord>> {
|
||||
let rows = sqlx::query(ACCOUNT_SELECT_BY_IDS)
|
||||
.bind(ids)
|
||||
.bind(provider_kind)
|
||||
.bind(authentication_kinds)
|
||||
.fetch_all(&self.pool)
|
||||
.await
|
||||
.map_err(|source| postgres_unavailable("export provider accounts", source))?;
|
||||
rows.into_iter().map(account_record_from_row).collect()
|
||||
}
|
||||
|
||||
pub(super) async fn list_provider_account_summaries(
|
||||
&self,
|
||||
provider_kind: Option<&str>,
|
||||
@@ -453,33 +469,15 @@ impl ProviderAccountAdminRepository for PgProviderAccountRepository {
|
||||
) -> StoreResult<Vec<ProviderAccountRecord>> {
|
||||
scope.validate()?;
|
||||
validate_admin_account_ids(&account_ids)?;
|
||||
let rows = sqlx::query(ACCOUNT_SELECT_BY_IDS)
|
||||
.bind(&account_ids)
|
||||
.bind(&scope.provider_kind)
|
||||
.fetch_all(&self.pool)
|
||||
.await
|
||||
.map_err(|source| postgres_unavailable("export provider accounts", source))?;
|
||||
let records = rows
|
||||
.into_iter()
|
||||
.map(account_record_from_row)
|
||||
.collect::<StoreResult<Vec<_>>>()?;
|
||||
let records = self
|
||||
.load_export_records(&scope.provider_kind, &account_ids, None)
|
||||
.await?;
|
||||
if records.len() != account_ids.len() {
|
||||
return Err(invalid(
|
||||
"one or more exported accounts are missing or outside the Provider scope",
|
||||
));
|
||||
}
|
||||
let by_id = records
|
||||
.into_iter()
|
||||
.map(|record| (record.summary.id.clone(), record))
|
||||
.collect::<std::collections::HashMap<_, _>>();
|
||||
account_ids
|
||||
.into_iter()
|
||||
.map(|id| {
|
||||
by_id.get(&id).cloned().ok_or_else(|| {
|
||||
invalid("one or more exported accounts are missing after loading")
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
Ok(records)
|
||||
}
|
||||
|
||||
async fn import_provider_accounts(
|
||||
@@ -797,7 +795,8 @@ pub(crate) async fn upsert_provider_account_in_transaction(
|
||||
model_access_json = coalesce($20, provider_accounts.model_access_json),
|
||||
name = excluded.name,
|
||||
email = excluded.email,
|
||||
plan_type = excluded.plan_type,
|
||||
plan_type = case when $21 and provider_accounts.authentication_kind = excluded.authentication_kind
|
||||
then coalesce(excluded.plan_type, provider_accounts.plan_type) else excluded.plan_type end,
|
||||
authentication_kind = excluded.authentication_kind,
|
||||
provider_credentials_json = excluded.provider_credentials_json,
|
||||
outbound_proxy_url = coalesce(excluded.outbound_proxy_url, provider_accounts.outbound_proxy_url),
|
||||
@@ -808,15 +807,13 @@ pub(crate) async fn upsert_provider_account_in_transaction(
|
||||
next_refresh_at = excluded.next_refresh_at,
|
||||
enabled = excluded.enabled,
|
||||
credential_state = excluded.credential_state,
|
||||
provider_quota_json = null, quota_paused = false, quota_warmup_state = '{}'::jsonb, quota_warmup_revision = provider_accounts.quota_warmup_revision + 1,
|
||||
quota_access_state = 'unknown',
|
||||
quota_evidence = null,
|
||||
quota_access_observed_at = null,
|
||||
quota_reset_at = null,
|
||||
quota_exhaustion_deadline = null,
|
||||
quota_limit_window_minutes = null,
|
||||
(provider_quota_json, quota_observed_at) = (
|
||||
select provider_accounts.provider_quota_json, provider_accounts.quota_observed_at
|
||||
where provider_accounts.quota_paused or excluded.outbound_proxy_url is null
|
||||
or provider_accounts.outbound_proxy_url is not distinct from excluded.outbound_proxy_url
|
||||
),
|
||||
quota_warmup_revision = provider_accounts.quota_warmup_revision + 1,
|
||||
credential_observed_at = excluded.credential_observed_at,
|
||||
quota_observed_at = null,
|
||||
last_error_reason = null,
|
||||
last_error_message = null,
|
||||
updated_at = greatest(now(), provider_accounts.updated_at, excluded.credential_observed_at)
|
||||
@@ -842,6 +839,7 @@ pub(crate) async fn upsert_provider_account_in_transaction(
|
||||
.bind(account.outbound_proxy.as_ref().map(|proxy| proxy.expose_url()))
|
||||
.bind(proxy_id)
|
||||
.bind(account.model_access.as_ref().map(sqlx::types::Json))
|
||||
.bind(account.preserve_catalog_etag.is_some())
|
||||
.fetch_optional(&mut **transaction)
|
||||
.await
|
||||
.map_err(|error| {
|
||||
@@ -865,7 +863,36 @@ pub(crate) async fn upsert_provider_account_in_transaction(
|
||||
id: account.id.clone(),
|
||||
kind: ConflictKind::InvalidTransition,
|
||||
})?;
|
||||
Ok((imported.0, Revision::new(to_u64(imported.1)?)?))
|
||||
let (id, revision) = imported;
|
||||
if revision > 1 {
|
||||
let carried = match &account.preserve_catalog_etag {
|
||||
Some(etag) => PgProviderAccountRepository::carry_model_catalog(
|
||||
transaction,
|
||||
&id,
|
||||
revision - 1,
|
||||
revision,
|
||||
etag,
|
||||
)
|
||||
.await
|
||||
.map_err(|error| postgres_unavailable("carry imported account catalog", error))?,
|
||||
None => false,
|
||||
};
|
||||
// 目录无法续接时,一并清除依赖旧模型和套餐的额度观测
|
||||
if !carried {
|
||||
sqlx::query("update provider_accounts set
|
||||
plan_type = $2,
|
||||
provider_quota_json = null, quota_paused = false, quota_warmup_state = '{}'::jsonb,
|
||||
quota_access_state = 'unknown', quota_evidence = null, quota_access_observed_at = null,
|
||||
quota_reset_at = null, quota_exhaustion_deadline = null, quota_limit_window_minutes = null,
|
||||
quota_observed_at = null where id = $1")
|
||||
.bind(&id)
|
||||
.bind(&account.plan_type)
|
||||
.execute(&mut **transaction)
|
||||
.await
|
||||
.map_err(|error| postgres_unavailable("reset imported account quota", error))?;
|
||||
}
|
||||
}
|
||||
Ok((id, Revision::new(to_u64(revision)?)?))
|
||||
}
|
||||
|
||||
pub(crate) async fn rotate_provider_account_in_transaction(
|
||||
@@ -966,7 +993,6 @@ pub(crate) async fn rotate_provider_account_in_transaction(
|
||||
})?;
|
||||
if let Some(etag) = update.preserve_catalog_etag.as_deref()
|
||||
&& !replace_identity
|
||||
&& !reauthorization
|
||||
{
|
||||
PgProviderAccountRepository::carry_model_catalog(
|
||||
transaction,
|
||||
|
||||
@@ -102,6 +102,8 @@ impl fmt::Debug for ProviderAccountRecord {
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct NewProviderAccount {
|
||||
/// 同身份重复导入时,允许沿用与此标识匹配的本地目录
|
||||
pub preserve_catalog_etag: Option<String>,
|
||||
pub outbound_proxy: Option<gateway_core::account::OutboundProxy>,
|
||||
pub id: String,
|
||||
pub provider_kind: String,
|
||||
@@ -351,8 +353,10 @@ pub(crate) const ACCOUNT_SELECT_BY_IDS: &str = "select coalesce(proxy_enabled, t
|
||||
from provider_accounts
|
||||
left join (select id as location_proxy_id, enabled as proxy_enabled, max_websocket_connections, auto_location, detected_location_json, location_country, location_region, location_city, location_timezone from outbound_proxies) proxy_location
|
||||
on outbound_proxy_id = location_proxy_id
|
||||
where id = any($1::text[]) and provider_kind = $2
|
||||
order by id";
|
||||
join unnest($1::text[], $3::text[]) with ordinality as selected(account_id, expected_auth, position)
|
||||
on id = selected.account_id and ($3::text[] is null or authentication_kind = selected.expected_auth)
|
||||
where provider_kind = $2
|
||||
order by selected.position";
|
||||
|
||||
pub(crate) const REFRESH_CANDIDATES_SELECT: &str = "select coalesce(proxy_enabled, true) as outbound_proxy_enabled, coalesce(max_websocket_connections, 0) as outbound_proxy_max_websocket_connections, auto_location, detected_location_json, location_country, location_region, location_city, location_timezone, outbound_proxy_id, outbound_proxy_url, id, provider_kind, name, notes, email, upstream_user_id,
|
||||
upstream_account_id, plan_type, authentication_kind, provider_credentials_json, credential_revision,
|
||||
|
||||
@@ -152,7 +152,7 @@ impl RuntimeSettingsRepository for PgRuntimeSettingsRepository {
|
||||
|
||||
pub(crate) async fn load_runtime_settings_from_pool(pool: &PgPool) -> StoreResult<RuntimeSettings> {
|
||||
let row = sqlx::query_as::<_, RuntimeSettingsRow>(
|
||||
"select antigravity_background_refresh, provider_request_profiles_json, config_revision, admin_api_key, refresh_margin_seconds, request_location_json, request_location_enabled, codex_privacy_policy_json,
|
||||
"select provider_settings_json, provider_request_profiles_json, config_revision, admin_api_key, refresh_margin_seconds, request_location_json, request_location_enabled, codex_privacy_policy_json,
|
||||
refresh_concurrency, max_concurrent_per_account,
|
||||
rotation_strategy, smart_scheduling_json, quota_reset_window_weights_json, model_mappings_json, usage_retention_days, ops_event_retention_days,
|
||||
audit_retention_days, min_codex_desktop_version,
|
||||
@@ -173,18 +173,25 @@ pub(crate) async fn load_runtime_settings_from_pool(pool: &PgPool) -> StoreResul
|
||||
}
|
||||
|
||||
impl ProviderRuntimePolicyPort for PgRuntimeSettingsRepository {
|
||||
fn antigravity_background_refresh(
|
||||
&self,
|
||||
) -> futures::future::BoxFuture<'_, Result<bool, ProviderStoreError>> {
|
||||
fn load_provider_settings<'a>(
|
||||
&'a self,
|
||||
provider: &'a gateway_core::routing::ProviderKind,
|
||||
) -> futures::future::BoxFuture<
|
||||
'a,
|
||||
Result<Option<gateway_core::account::OpaqueProviderData>, ProviderStoreError>,
|
||||
> {
|
||||
Box::pin(async move {
|
||||
sqlx::query_scalar(
|
||||
"select antigravity_background_refresh from runtime_settings where id = 1",
|
||||
let settings = sqlx::query_scalar::<
|
||||
_,
|
||||
Option<sqlx::types::Json<gateway_core::account::OpaqueProviderData>>,
|
||||
>(
|
||||
"select provider_settings_json -> $1::text from runtime_settings where id = 1",
|
||||
)
|
||||
.bind(provider.as_str())
|
||||
.fetch_one(&self.pool)
|
||||
.await
|
||||
.map_err(|source| {
|
||||
crate::provider_unavailable("load Antigravity background refresh", source)
|
||||
})
|
||||
.map_err(|source| crate::provider_unavailable("load provider settings", source))?;
|
||||
Ok(settings.map(|value| value.0))
|
||||
})
|
||||
}
|
||||
|
||||
@@ -370,7 +377,7 @@ pub(crate) async fn load_runtime_settings_in_transaction(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
) -> StoreResult<RuntimeSettings> {
|
||||
let row = sqlx::query_as::<_, RuntimeSettingsRow>(
|
||||
"select antigravity_background_refresh, provider_request_profiles_json, config_revision, admin_api_key, refresh_margin_seconds, request_location_json, request_location_enabled, codex_privacy_policy_json,
|
||||
"select provider_settings_json, provider_request_profiles_json, config_revision, admin_api_key, refresh_margin_seconds, request_location_json, request_location_enabled, codex_privacy_policy_json,
|
||||
refresh_concurrency, max_concurrent_per_account,
|
||||
rotation_strategy, smart_scheduling_json, quota_reset_window_weights_json, model_mappings_json, usage_retention_days, ops_event_retention_days,
|
||||
audit_retention_days, min_codex_desktop_version,
|
||||
@@ -462,7 +469,7 @@ pub(crate) async fn update_runtime_settings_in_transaction(
|
||||
openai_request_settings_json = $36,
|
||||
openai_websocket_pool_json = $37,
|
||||
prompt_rewrite_rules_json = $38,
|
||||
antigravity_background_refresh = $39,
|
||||
provider_settings_json = provider_settings_json || $39::jsonb,
|
||||
updated_at = now()
|
||||
where id = 1
|
||||
returning config_revision",
|
||||
@@ -513,7 +520,7 @@ pub(crate) async fn update_runtime_settings_in_transaction(
|
||||
.bind(sqlx::types::Json(&update.values.openai_request_settings))
|
||||
.bind(sqlx::types::Json(&update.values.openai_websocket_pool))
|
||||
.bind(sqlx::types::Json(&update.values.prompt_rewrite_rules))
|
||||
.bind(update.values.antigravity_background_refresh)
|
||||
.bind(sqlx::types::Json(&update.values.provider_settings))
|
||||
.fetch_optional(&mut **transaction)
|
||||
.await
|
||||
.map_err(|source| postgres_unavailable("update runtime settings in transaction", source))?
|
||||
@@ -578,7 +585,7 @@ pub(crate) async fn update_admin_api_key_in_transaction(
|
||||
|
||||
#[derive(sqlx::FromRow)]
|
||||
struct RuntimeSettingsRow {
|
||||
antigravity_background_refresh: bool,
|
||||
provider_settings_json: sqlx::types::Json<gateway_admin::model::settings::ProviderSettings>,
|
||||
provider_request_profiles_json: sqlx::types::Json<
|
||||
std::collections::BTreeMap<String, serde_json::Map<String, serde_json::Value>>,
|
||||
>,
|
||||
@@ -652,7 +659,7 @@ fn runtime_settings_from_row(row: RuntimeSettingsRow) -> StoreResult<RuntimeSett
|
||||
model_mappings: row.model_mappings_json.0,
|
||||
updated_at: row.updated_at,
|
||||
values: gateway_admin::model::settings::RuntimeSettingsValues {
|
||||
antigravity_background_refresh: row.antigravity_background_refresh,
|
||||
provider_settings: row.provider_settings_json.0,
|
||||
openai_websocket_pool: row.openai_websocket_pool_json.0,
|
||||
openai_request_settings: row.openai_request_settings_json.0,
|
||||
refresh_margin_seconds: to_u64(row.refresh_margin_seconds)?,
|
||||
|
||||
@@ -58,12 +58,14 @@ impl UsageDataStore for PgUsageDataStore {
|
||||
|mut connection| async move {
|
||||
let mut tx = begin(&mut connection).await?;
|
||||
let mut changed_ids = Vec::with_capacity(command.changes.len());
|
||||
let mut events = Vec::with_capacity(command.changes.len());
|
||||
for (change, event) in command.changes {
|
||||
if records::write(&mut tx, &change).await? {
|
||||
changed_ids.push(change.id().to_owned());
|
||||
}
|
||||
audit(&mut tx, event).await?;
|
||||
events.push(super::unversioned_audit_event(event));
|
||||
}
|
||||
audit(&mut tx, &events).await?;
|
||||
tx.commit().await.map_err(db_error)?;
|
||||
Ok(UsageWriteResult { changed_ids })
|
||||
},
|
||||
@@ -91,18 +93,24 @@ impl UsageDataStore for PgUsageDataStore {
|
||||
&self,
|
||||
command: StoredAggregateWrite,
|
||||
) -> UsageDataResult<UsageAggregateWriteResult> {
|
||||
self.budget.run(&self.pool, "write usage aggregates", |mut connection| async move {
|
||||
let mut tx = begin(&mut connection).await?;
|
||||
let mut changed=Vec::with_capacity(command.changes.len());
|
||||
for (change,event) in command.changes {
|
||||
changed.push(aggregates::write(&mut tx,change).await?);
|
||||
audit(&mut tx,event).await?;
|
||||
}
|
||||
// 沿用现有统计发布代次,让读缓存能观察到直接维护的聚合值
|
||||
sqlx::query("update request_analytics_build_state set generation=generation+1,updated_at=clock_timestamp() where singleton").execute(&mut *tx).await.map_err(db_error)?;
|
||||
tx.commit().await.map_err(db_error)?;
|
||||
Ok(UsageAggregateWriteResult { changed })
|
||||
}).await.map_err(public_error)
|
||||
self.budget
|
||||
.run(&self.pool, "write usage aggregates", |mut connection| async move {
|
||||
let mut tx = begin(&mut connection).await?;
|
||||
let mut changed = Vec::with_capacity(command.changes.len());
|
||||
let mut events = Vec::with_capacity(command.changes.len());
|
||||
for (change, event) in command.changes {
|
||||
changed.push(aggregates::write(&mut tx, change).await?);
|
||||
events.push(super::unversioned_audit_event(event));
|
||||
}
|
||||
audit(&mut tx, &events).await?;
|
||||
// 沿用现有统计发布代次,让读缓存能观察到直接维护的聚合值
|
||||
sqlx::query("update request_analytics_build_state set generation=generation+1,updated_at=clock_timestamp() where singleton")
|
||||
.execute(&mut *tx).await.map_err(db_error)?;
|
||||
tx.commit().await.map_err(db_error)?;
|
||||
Ok(UsageAggregateWriteResult { changed })
|
||||
})
|
||||
.await
|
||||
.map_err(public_error)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -158,24 +166,10 @@ fn public_error(error: StoreError) -> UsageDataError {
|
||||
}
|
||||
async fn audit(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
event: gateway_admin::model::auth::AdminAuditEvent,
|
||||
events: &[super::AdminAuditEvent],
|
||||
) -> StoreResult<()> {
|
||||
super::append_admin_audit_event_in_transaction(
|
||||
tx,
|
||||
super::AdminAuditEvent {
|
||||
id: event.id,
|
||||
actor_kind: event.actor_kind.into(),
|
||||
actor_admin_user_id: event.actor_admin_user_id,
|
||||
actor_ref: event.actor_ref,
|
||||
admin_request_id: event.request_id,
|
||||
action: event.action,
|
||||
entity_kind: event.entity_kind,
|
||||
entity_ref: event.entity_ref,
|
||||
config_revision: None,
|
||||
changed_fields: event.changed_fields,
|
||||
created_at: event.occurred_at,
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
for batch in events.chunks(USAGE_DATA_MAX_TARGETS) {
|
||||
super::insert_admin_audit_events(&mut **tx, batch).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -73,8 +73,8 @@ pub(crate) fn push_usage_read_filter(query: &mut QueryBuilder<Postgres>, filter:
|
||||
}
|
||||
if let Some(group) = &filter.routing_group_ref {
|
||||
query
|
||||
.push(" and ")
|
||||
.push(" and mr.routing_group_refs @> array[")
|
||||
.push_bind(group.clone())
|
||||
.push("=any(mr.routing_group_refs)");
|
||||
.push("]::text[]");
|
||||
}
|
||||
}
|
||||
@@ -90,6 +90,10 @@ impl JsonObject {
|
||||
pub fn fields(&self) -> &Map<String, Value> {
|
||||
&self.0
|
||||
}
|
||||
|
||||
pub(crate) fn into_fields(self) -> Map<String, Value> {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for JsonObject {
|
||||
|
||||
@@ -1059,7 +1059,7 @@ async fn successful_replay_recovers_only_the_incomplete_request_that_required_it
|
||||
let affinity_hash = "a".repeat(64);
|
||||
let replay_at = Utc::now() - Duration::seconds(1);
|
||||
for (id, seconds_before_replay, reason) in [
|
||||
("req_rotated", 11, Some("account_rotated")),
|
||||
("req_rotated", 30, Some("account_rotated")),
|
||||
("req_overloaded", 4, None),
|
||||
] {
|
||||
let completed_at = replay_at - Duration::seconds(seconds_before_replay);
|
||||
@@ -1117,8 +1117,9 @@ async fn successful_http_downgrade_should_mark_pending_websocket_failures_recove
|
||||
return;
|
||||
};
|
||||
let affinity_hash = "d".repeat(64);
|
||||
let first_failure_at = Utc::now() - Duration::seconds(8);
|
||||
let second_failure_at = first_failure_at + Duration::seconds(1);
|
||||
let recovery_started_at = Utc::now() - Duration::seconds(4);
|
||||
let first_failure_at = recovery_started_at - Duration::seconds(30);
|
||||
let second_failure_at = recovery_started_at;
|
||||
seed_websocket_transport_failure(
|
||||
&database.pool,
|
||||
"req_websocket_failed_first",
|
||||
@@ -1149,7 +1150,6 @@ async fn successful_http_downgrade_should_mark_pending_websocket_failures_recove
|
||||
.await
|
||||
.expect("mark control failure delivered downstream");
|
||||
|
||||
let recovery_started_at = first_failure_at + Duration::seconds(4);
|
||||
seed_transport_recovery_request(
|
||||
&database.pool,
|
||||
"req_http_fallback_succeeded",
|
||||
@@ -1188,7 +1188,7 @@ async fn successful_http_downgrade_should_mark_pending_websocket_failures_recove
|
||||
let delivered = &recovered[0];
|
||||
assert_eq!(delivered.0, "req_websocket_failed_after_delivery");
|
||||
assert_eq!((&delivered.1, delivered.2, delivered.3), (&None, None, 0));
|
||||
for (row, expected_delay_ms) in recovered[1..].iter().zip([4_000, 3_000]) {
|
||||
for (row, expected_delay_ms) in recovered[1..].iter().zip([30_000, 0]) {
|
||||
assert_eq!(row.1.as_deref(), Some("req_http_fallback_succeeded"));
|
||||
assert!(row.2.is_some());
|
||||
assert_eq!(row.3, 1);
|
||||
@@ -1265,7 +1265,7 @@ async fn websocket_success_or_late_http_success_should_not_hide_transport_failur
|
||||
&database.pool,
|
||||
"req_http_late_success",
|
||||
&late_affinity,
|
||||
failure_at + Duration::seconds(31),
|
||||
failure_at + Duration::seconds(30) + Duration::microseconds(1),
|
||||
)
|
||||
.await;
|
||||
let mut late_recovery = successful_core_finalization("req_http_late_success");
|
||||
@@ -1342,7 +1342,7 @@ async fn failed_or_late_new_chain_should_leave_continuation_failure_unresolved()
|
||||
&database.pool,
|
||||
"req_continuation_retry_late",
|
||||
&affinity_hash,
|
||||
failure_completed_at + Duration::seconds(31),
|
||||
failure_completed_at + Duration::seconds(30) + Duration::microseconds(1),
|
||||
false,
|
||||
)
|
||||
.await;
|
||||
|
||||
@@ -919,6 +919,8 @@ async fn state_cas_quota_and_fence_are_independent_from_global_revision() {
|
||||
|
||||
#[tokio::test]
|
||||
async fn migration_promotes_atomically_and_incomplete_staging_cannot_replace_active_state() {
|
||||
use PluginStateMigrationAction::{Delete, Keep, Replace};
|
||||
|
||||
let Some(database) = TestDatabase::create("plugin_state_migration").await else {
|
||||
return;
|
||||
};
|
||||
@@ -945,7 +947,7 @@ async fn migration_promotes_atomically_and_incomplete_staging_cannot_replace_act
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
for (key, value) in [("a", 1), ("b", 2)] {
|
||||
for (key, value) in [("a", 1), ("b", 2), ("c", 3), ("d", 4)] {
|
||||
store
|
||||
.put(
|
||||
&first_owner,
|
||||
@@ -960,7 +962,7 @@ async fn migration_promotes_atomically_and_incomplete_staging_cannot_replace_act
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
let second_state = configuration(schema(2, vec![1], 4));
|
||||
let second_state = configuration(schema(2, vec![1], 2));
|
||||
assert!(
|
||||
store
|
||||
.transition_required(&saved.instance.id, &second_state)
|
||||
@@ -977,7 +979,7 @@ async fn migration_promotes_atomically_and_incomplete_staging_cannot_replace_act
|
||||
.await
|
||||
.unwrap();
|
||||
let batch = store
|
||||
.migration_batch(&transition.id, "cache", 64)
|
||||
.migration_batch(&transition.id, "cache", 3)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
@@ -986,25 +988,57 @@ async fn migration_promotes_atomically_and_incomplete_staging_cannot_replace_act
|
||||
.iter()
|
||||
.map(|record| record.key.as_str())
|
||||
.collect::<Vec<_>>(),
|
||||
["a", "b"]
|
||||
["a", "b", "c"]
|
||||
);
|
||||
store
|
||||
.apply_migration_batch(ApplyPluginStateMigration {
|
||||
let migration = |cursor: Option<String>, actions: Vec<(&str, PluginStateMigrationAction)>| {
|
||||
ApplyPluginStateMigration {
|
||||
transition_id: transition.id.clone(),
|
||||
namespace: "cache".into(),
|
||||
cursor: batch.cursor,
|
||||
expected_keys: vec!["a".into(), "b".into()],
|
||||
changes: vec![
|
||||
PluginStateMigrationChange {
|
||||
key: "a".into(),
|
||||
action: PluginStateMigrationAction::Keep,
|
||||
},
|
||||
PluginStateMigrationChange {
|
||||
key: "b".into(),
|
||||
action: PluginStateMigrationAction::Replace(json!({"value": 20})),
|
||||
},
|
||||
cursor,
|
||||
expected_keys: actions.iter().map(|(key, _)| (*key).to_owned()).collect(),
|
||||
changes: actions
|
||||
.into_iter()
|
||||
.map(|(key, action)| PluginStateMigrationChange {
|
||||
key: key.to_owned(),
|
||||
action,
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
};
|
||||
for (actions, expected_error) in [
|
||||
(
|
||||
vec![("a", Keep), ("a", Keep)],
|
||||
PluginStateStoreErrorKind::Invalid,
|
||||
),
|
||||
(
|
||||
vec![("a", Keep), ("b", Keep), ("c", Keep)],
|
||||
PluginStateStoreErrorKind::Quota,
|
||||
),
|
||||
] {
|
||||
let error = store
|
||||
.apply_migration_batch(migration(batch.cursor.clone(), actions))
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(error.kind(), expected_error);
|
||||
}
|
||||
store
|
||||
.apply_migration_batch(migration(
|
||||
batch.cursor,
|
||||
vec![
|
||||
("a", Keep),
|
||||
("b", Delete),
|
||||
("c", Replace(json!({"value": 20}))),
|
||||
],
|
||||
})
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
let remaining = store
|
||||
.migration_batch(&transition.id, "cache", 64)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(remaining.cursor.as_deref(), Some("c"));
|
||||
store
|
||||
.apply_migration_batch(migration(remaining.cursor, vec![("d", Delete)]))
|
||||
.await
|
||||
.unwrap();
|
||||
let terminal = store
|
||||
@@ -1012,14 +1046,9 @@ async fn migration_promotes_atomically_and_incomplete_staging_cannot_replace_act
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(terminal.records.is_empty());
|
||||
assert_eq!(terminal.cursor.as_deref(), Some("d"));
|
||||
store
|
||||
.apply_migration_batch(ApplyPluginStateMigration {
|
||||
transition_id: transition.id.clone(),
|
||||
namespace: "cache".into(),
|
||||
cursor: terminal.cursor,
|
||||
expected_keys: vec![],
|
||||
changes: vec![],
|
||||
})
|
||||
.apply_migration_batch(migration(terminal.cursor, vec![]))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
@@ -1049,11 +1078,27 @@ async fn migration_promotes_atomically_and_incomplete_staging_cannot_replace_act
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let migrated = store
|
||||
.get(&second_owner, "cache", "b")
|
||||
let kept = store
|
||||
.get(&second_owner, "cache", "a")
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!((kept.version, kept.value), (1, json!({"value": 1})));
|
||||
for key in ["b", "d"] {
|
||||
assert!(
|
||||
store
|
||||
.get(&second_owner, "cache", key)
|
||||
.await
|
||||
.unwrap()
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
let migrated = store
|
||||
.get(&second_owner, "cache", "c")
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(migrated.version, 2);
|
||||
assert_eq!(migrated.schema_version, 2);
|
||||
assert_eq!(migrated.value, json!({"value": 20}));
|
||||
drop(transition);
|
||||
@@ -1091,7 +1136,7 @@ async fn migration_promotes_atomically_and_incomplete_staging_cannot_replace_act
|
||||
store.abort_transition(&incomplete.id).await.unwrap();
|
||||
assert_eq!(
|
||||
store
|
||||
.get(&second_owner, "cache", "b")
|
||||
.get(&second_owner, "cache", "c")
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
|
||||
@@ -2,6 +2,94 @@
|
||||
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn credential_export_checks_selected_scopes_and_audits_every_existing_account() {
|
||||
use gateway_admin::ports::store::AdminStoreErrorKind;
|
||||
|
||||
let Some(db) = TestDatabase::create("account_export").await else {
|
||||
return;
|
||||
};
|
||||
let repository = PgProviderAccountRepository::new(db.pool.clone());
|
||||
let store = admin_account_store(&db.pool);
|
||||
let provider = ProviderKind::new("openai").unwrap();
|
||||
let ids = ["acct_b", "acct_a"].map(|id| ProviderAccountId::new(id).unwrap());
|
||||
for id in &ids {
|
||||
repository
|
||||
.insert_provider_account(account(id.as_str(), id.as_str()))
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
let scopes = store.credential_export_scopes(&ids).await.unwrap();
|
||||
let selected = ids.clone().map(|id| {
|
||||
let scope = &scopes[id.as_str()];
|
||||
assert_eq!(scope.provider_kind, provider);
|
||||
(id, scope.authentication_kind.clone())
|
||||
});
|
||||
let inputs = store
|
||||
.load_credentials_for_export(&provider, &selected)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
inputs
|
||||
.iter()
|
||||
.map(|input| input.account.id.as_str())
|
||||
.collect::<Vec<_>>(),
|
||||
["acct_b", "acct_a"]
|
||||
);
|
||||
|
||||
let mut stale = selected.clone();
|
||||
stale[0].1 = "api_key".to_string();
|
||||
assert_eq!(
|
||||
store
|
||||
.load_credentials_for_export(&provider, &stale)
|
||||
.await
|
||||
.unwrap_err()
|
||||
.kind(),
|
||||
AdminStoreErrorKind::NotFound
|
||||
);
|
||||
assert_eq!(
|
||||
store
|
||||
.load_credentials_for_export(&ProviderKind::new("other").unwrap(), &selected)
|
||||
.await
|
||||
.unwrap_err()
|
||||
.kind(),
|
||||
AdminStoreErrorKind::NotFound
|
||||
);
|
||||
|
||||
let context = MutationContext {
|
||||
actor: MutationActor::System,
|
||||
request_id: "audit_batch_export".into(),
|
||||
};
|
||||
store
|
||||
.record_credential_export(&ids, &context)
|
||||
.await
|
||||
.unwrap();
|
||||
let rows: Vec<(String,i64)> = sqlx::query_as("select entity_ref, config_revision from admin_audit_events where admin_request_id=$1 and action='export_credentials' order by entity_ref")
|
||||
.bind(&context.request_id).fetch_all(&db.pool).await.unwrap();
|
||||
assert_eq!(rows, [("acct_a".into(), 1), ("acct_b".into(), 1)]);
|
||||
|
||||
// Provider 准备好导出文档后账号被删,整批审计失败
|
||||
sqlx::query("delete from provider_accounts where id=$1")
|
||||
.bind(ids[0].as_str())
|
||||
.execute(&db.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let context = MutationContext {
|
||||
request_id: "audit_deleted_export".into(),
|
||||
..context
|
||||
};
|
||||
assert_eq!(
|
||||
store
|
||||
.record_credential_export(&ids, &context)
|
||||
.await
|
||||
.unwrap_err()
|
||||
.kind(),
|
||||
AdminStoreErrorKind::NotFound
|
||||
);
|
||||
assert_eq!(audit_count(&db.pool, &context.request_id).await, 0);
|
||||
db.close().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn quota_deadline_agrees_across_account_filters_summary_and_detail() {
|
||||
let Some(database) = TestDatabase::create("quota_deadline").await else {
|
||||
@@ -615,6 +703,7 @@ async fn plugin_account_provider_filter_is_optional_and_applied_before_cursor_pa
|
||||
|
||||
pub(super) fn credential(id: &str, user: &str) -> PreparedCredentialCreate {
|
||||
PreparedCredentialCreate {
|
||||
preserve_catalog_etag: None,
|
||||
account_id: ProviderAccountId::new(id).unwrap(),
|
||||
provider_kind: ProviderKind::new("openai").unwrap(),
|
||||
name: "login account".into(),
|
||||
|
||||
@@ -414,6 +414,53 @@ async fn reauthorization_keeps_disabled_account_quota_only_for_the_same_identity
|
||||
database.close().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reauthorization_carries_a_verified_catalog_to_the_new_revision() {
|
||||
let Some(database) = TestDatabase::create("reauthorize_catalog").await else {
|
||||
return;
|
||||
};
|
||||
let store = admin_account_store(&database.pool);
|
||||
let repo = PgProviderAccountRepository::new(database.pool.clone());
|
||||
let (seed, context) = command(credential("acct_reauthorize", "verified-user"));
|
||||
let id = store
|
||||
.commit_authorization(seed, &context)
|
||||
.await
|
||||
.unwrap()
|
||||
.result
|
||||
.account_id;
|
||||
let original = repo.get_account(&id).await.unwrap().unwrap();
|
||||
let catalog = gateway_core::account::AccountCatalogObservation {
|
||||
account_id: id.clone(),
|
||||
revision: original.revision(),
|
||||
plan: original.plan_type().map(str::to_owned),
|
||||
etag: Some("registration".into()),
|
||||
observed_at: SystemTime::UNIX_EPOCH,
|
||||
};
|
||||
assert!(
|
||||
repo.save_account_catalog(&catalog, b"models")
|
||||
.await
|
||||
.unwrap()
|
||||
);
|
||||
let mut authorization = reauthorization(&id, &context, "verified-flow", None);
|
||||
let AuthorizationCredentialCommit::Reauthorize(facts) = &mut authorization.credential else {
|
||||
unreachable!()
|
||||
};
|
||||
facts.preserve_catalog_etag = catalog.etag.clone();
|
||||
facts.preserve_profile = true;
|
||||
store
|
||||
.commit_authorization(authorization, &context)
|
||||
.await
|
||||
.unwrap();
|
||||
let catalogs = repo
|
||||
.load_account_catalogs(original.provider())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(catalogs[0].accounts[0].revision.get(), 2);
|
||||
assert_eq!(catalogs[0].accounts[0].observed_at, catalog.observed_at);
|
||||
assert_eq!(catalogs[0].document.as_ref(), b"models");
|
||||
database.close().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reauthorization_replay_keeps_the_committed_revision_and_later_profile_edits() {
|
||||
let Some(database) = TestDatabase::create("reauthorization_receipt").await else {
|
||||
|
||||
@@ -685,6 +685,82 @@ async fn profile_changes_survive_inflight_background_and_manual_token_refresh()
|
||||
database.close().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reimport_reuses_only_observations_matching_the_verified_catalog() {
|
||||
let Some(database) = TestDatabase::create("reimport_catalog").await else {
|
||||
return;
|
||||
};
|
||||
let repo = PgProviderAccountRepository::new(database.pool.clone());
|
||||
let provider = ProviderKind::new("antigravity").unwrap();
|
||||
let id = ProviderAccountId::new("acct_import_catalog").unwrap();
|
||||
let seed = || {
|
||||
let mut row = account(id.as_str(), "verified-subject");
|
||||
row.provider_kind = provider.to_string();
|
||||
row
|
||||
};
|
||||
repo.insert_provider_account(seed()).await.unwrap();
|
||||
let observed_at = SystemTime::UNIX_EPOCH + Duration::from_secs(1234);
|
||||
let catalog = gateway_core::account::AccountCatalogObservation {
|
||||
account_id: id.clone(),
|
||||
revision: CredentialRevision::new(1).unwrap(),
|
||||
plan: Some("pro".into()),
|
||||
etag: Some("verified-registration".into()),
|
||||
observed_at,
|
||||
};
|
||||
assert!(
|
||||
repo.save_account_catalog(&catalog, b"models")
|
||||
.await
|
||||
.unwrap()
|
||||
);
|
||||
let quota = QuotaObservation {
|
||||
account_id: id.clone(),
|
||||
expected_revision: catalog.revision,
|
||||
quota: OpaqueProviderData::new(json!({"remaining":0}).as_object().unwrap().clone()),
|
||||
observed_at,
|
||||
state: QuotaState::allowed(observed_at),
|
||||
expected_connection: None,
|
||||
merge_base: None,
|
||||
quota_pause: None,
|
||||
plan_type: None,
|
||||
};
|
||||
repo.compare_and_swap_quota(quota.clone()).await.unwrap();
|
||||
for (etag, expected_revision) in [("verified-registration", 2), ("different-registration", 3)] {
|
||||
let mut reimport = seed();
|
||||
reimport.id = "acct_import_candidate".into();
|
||||
reimport.plan_type = None;
|
||||
reimport.preserve_catalog_etag = Some(etag.into());
|
||||
let result = repo
|
||||
.import_provider_accounts(ImportProviderAccounts {
|
||||
settings: None,
|
||||
outbound_proxy: None,
|
||||
scope: ProviderAccountAdminScope {
|
||||
provider_kind: provider.to_string(),
|
||||
},
|
||||
accounts: vec![reimport],
|
||||
audit: audit(etag, "import", id.as_str()),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(result.created_ids.is_empty());
|
||||
let current = repo.get_account(&id).await.unwrap().unwrap();
|
||||
assert_eq!(current.revision().get(), expected_revision);
|
||||
let catalogs = repo.load_account_catalogs(&provider).await.unwrap();
|
||||
let snapshots = repo.get_quotas(std::slice::from_ref(&id)).await.unwrap();
|
||||
if etag == "verified-registration" {
|
||||
assert_eq!(current.plan_type(), Some("pro"));
|
||||
assert_eq!(catalogs[0].document.as_ref(), b"models");
|
||||
assert_eq!(catalogs[0].accounts[0].revision, current.revision());
|
||||
assert_eq!(catalogs[0].accounts[0].observed_at, observed_at);
|
||||
assert_eq!(snapshots[0].quota, quota.quota);
|
||||
assert_eq!(snapshots[0].expected_revision, current.revision());
|
||||
} else {
|
||||
assert!(catalogs.is_empty() && snapshots.is_empty());
|
||||
assert_eq!(current.plan_type(), None);
|
||||
}
|
||||
}
|
||||
database.close().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn catalog_carry_rejects_a_different_revision_plan_registration_or_identity() {
|
||||
let Some(database) = TestDatabase::create("catalog_carry_fences").await else {
|
||||
@@ -1096,24 +1172,53 @@ async fn terminal_admin_list_filters_and_sorts_before_pagination_with_retained_u
|
||||
assert_eq!(email_domain_page.items.len(), 2);
|
||||
assert_eq!(email_domain_page.summary, usage_page.summary);
|
||||
|
||||
let error_filter = AccountListQuery {
|
||||
page: 1,
|
||||
page_size: PageSize::new(10).expect("page size"),
|
||||
provider_kind: None,
|
||||
group_filter: None,
|
||||
search: None,
|
||||
status: Some(AccountStatus::Error),
|
||||
sort: None,
|
||||
};
|
||||
let error_accounts = store
|
||||
.list_accounts(
|
||||
AccountListQuery {
|
||||
page: 1,
|
||||
page_size: PageSize::new(10).expect("page size"),
|
||||
provider_kind: None,
|
||||
group_filter: None,
|
||||
search: None,
|
||||
status: Some(AccountStatus::Error),
|
||||
sort: None,
|
||||
},
|
||||
Default::default(),
|
||||
)
|
||||
.list_accounts(error_filter.clone(), Default::default())
|
||||
.await
|
||||
.expect("filter error accounts");
|
||||
assert_eq!(error_accounts.items.len(), 2);
|
||||
assert_eq!(error_accounts.items[0].account.id, "acct_beta");
|
||||
assert_eq!(error_accounts.items[1].account.id, "acct_invalid");
|
||||
|
||||
// 候选账号的导入贡献参与排序,筛选范围外的超额负修正不能干扰本页
|
||||
sqlx::query(
|
||||
"insert into request_analytics_1h
|
||||
(bucket_start,collection,dimensions,outcome,schema_version,histogram_version,counts,costs,distributions)
|
||||
select date_trunc('hour',$1::timestamptz),'usage_contribution',
|
||||
array['openai','',id,'','','','import'],'',0,0,jsonb_build_object('total_tokens',tokens),'{}','{}'
|
||||
from (values ('acct_invalid',80),('acct_disabled',-1)) imported(id,tokens)",
|
||||
)
|
||||
.bind(now - TimeDelta::hours(1))
|
||||
.execute(&database.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let ranked_errors = store
|
||||
.list_accounts(
|
||||
AccountListQuery {
|
||||
page_size: PageSize::new(1).expect("page size"),
|
||||
sort: Some(AccountSort {
|
||||
field: AccountSortField::Usage,
|
||||
direction: SortDirection::Desc,
|
||||
}),
|
||||
..error_filter
|
||||
},
|
||||
Default::default(),
|
||||
)
|
||||
.await
|
||||
.expect("rank filtered accounts with aggregate contributions");
|
||||
assert_eq!(ranked_errors.total, 2);
|
||||
assert_eq!(ranked_errors.summary, usage_page.summary);
|
||||
assert_eq!(ranked_errors.items.len(), 1);
|
||||
assert_eq!(ranked_errors.items[0].account.id, "acct_invalid");
|
||||
// 上游耗尽优先展示,不重复计入本地额度暂停
|
||||
sqlx::query("update provider_accounts set quota_paused = true where id in ('acct_alpha', 'acct_charlie')")
|
||||
.execute(&database.pool).await.unwrap();
|
||||
@@ -2395,6 +2500,7 @@ async fn authorization_create_returns_existing_account_id_when_identity_is_upser
|
||||
),
|
||||
credential: AuthorizationCredentialCommit::Create(Box::new(
|
||||
PreparedCredentialCreate {
|
||||
preserve_catalog_etag: None,
|
||||
model_access: Default::default(),
|
||||
outbound_proxy: None,
|
||||
account_id: ProviderAccountId::new("acct_authorization_candidate")
|
||||
@@ -2572,6 +2678,7 @@ async fn core_refresh_cas_updates_profile_and_credential_under_one_revision() {
|
||||
let repository = PgProviderAccountRepository::new(database.pool.clone());
|
||||
repository
|
||||
.insert_provider_account(NewProviderAccount {
|
||||
preserve_catalog_etag: None,
|
||||
model_access: Default::default(),
|
||||
outbound_proxy: None,
|
||||
id: "acct_core_refresh".to_owned(),
|
||||
@@ -3568,6 +3675,7 @@ async fn disabled_account_updates_credentials_without_enabling_scheduling() {
|
||||
|
||||
pub(super) fn account(id: &str, upstream_user_id: &str) -> NewProviderAccount {
|
||||
NewProviderAccount {
|
||||
preserve_catalog_etag: None,
|
||||
model_access: Default::default(),
|
||||
outbound_proxy: None,
|
||||
id: id.to_owned(),
|
||||
|
||||
@@ -22,7 +22,7 @@ pub(super) fn settings_with_margin(refresh_margin_seconds: u64) -> RuntimeSettin
|
||||
("grok-latest".to_owned(), "grok-4.5".to_owned()),
|
||||
]),
|
||||
values: gateway_admin::model::settings::RuntimeSettingsValues {
|
||||
antigravity_background_refresh: true,
|
||||
provider_settings: Default::default(),
|
||||
openai_websocket_pool: Default::default(),
|
||||
openai_request_settings: Default::default(),
|
||||
codex_privacy_policy: Default::default(),
|
||||
@@ -220,33 +220,44 @@ fn runtime_settings_require_model_when_warmup_is_enabled() {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn antigravity_refresh_defaults_to_scheduled_and_round_trips() {
|
||||
let Some(database) = TestDatabase::create("antigravity_refresh").await else {
|
||||
async fn provider_settings_replace_only_submitted_providers() {
|
||||
use gateway_core::provider_ports::ProviderRuntimePolicyPort;
|
||||
let Some(database) = TestDatabase::create("provider_settings").await else {
|
||||
return;
|
||||
};
|
||||
let repository = PgRuntimeSettingsRepository::new(database.pool.clone());
|
||||
let provider = gateway_core::routing::ProviderKind::new("antigravity").unwrap();
|
||||
assert!(
|
||||
repository
|
||||
.load_runtime_settings()
|
||||
.load_provider_settings(&provider)
|
||||
.await
|
||||
.unwrap()
|
||||
.values
|
||||
.antigravity_background_refresh
|
||||
.is_none()
|
||||
);
|
||||
let settings = serde_json::from_value(serde_json::json!({"backgroundRefresh": false})).unwrap();
|
||||
let mut update = settings_with_margin(3600);
|
||||
update
|
||||
.values
|
||||
.provider_settings
|
||||
.insert(provider.clone(), settings);
|
||||
repository.update_runtime_settings(update).await.unwrap();
|
||||
repository
|
||||
.update_runtime_settings(settings_with_margin(7200))
|
||||
.await
|
||||
.unwrap();
|
||||
let saved = repository.load_runtime_settings().await.unwrap();
|
||||
assert_eq!(
|
||||
saved.values.provider_settings[&provider].expose_to_provider()["backgroundRefresh"],
|
||||
false
|
||||
);
|
||||
assert_eq!(
|
||||
repository
|
||||
.load_provider_settings(&provider)
|
||||
.await
|
||||
.unwrap()
|
||||
.as_ref(),
|
||||
saved.values.provider_settings.get(&provider)
|
||||
);
|
||||
for value in [false, true] {
|
||||
let mut update = settings_with_margin(3600);
|
||||
update.values.antigravity_background_refresh = value;
|
||||
repository.update_runtime_settings(update).await.unwrap();
|
||||
assert_eq!(
|
||||
repository
|
||||
.load_runtime_settings()
|
||||
.await
|
||||
.unwrap()
|
||||
.values
|
||||
.antigravity_background_refresh,
|
||||
value
|
||||
);
|
||||
}
|
||||
database.close().await;
|
||||
}
|
||||
|
||||
|
||||
@@ -124,6 +124,29 @@ async fn detail_crud_is_retry_safe_atomic_and_updates_native_statistics() {
|
||||
.write_records(records(vec![put("a", 10)]))
|
||||
.await
|
||||
.unwrap();
|
||||
// 两次业务写入都成功后,审计主键冲突仍须回滚整批,包括已修改的明细
|
||||
let mut conflict = records(vec![put("a", 99), put("audit-conflict", 35)]);
|
||||
let repeated_id = conflict.changes[0].1.id.clone();
|
||||
conflict.changes[1].1.id.clone_from(&repeated_id);
|
||||
assert!(store.write_records(conflict).await.is_err());
|
||||
assert_eq!(
|
||||
sqlx::query_scalar::<_, i64>("select count(*) from admin_audit_events where id=$1")
|
||||
.bind(repeated_id)
|
||||
.fetch_one(&db.pool)
|
||||
.await
|
||||
.unwrap(),
|
||||
0
|
||||
);
|
||||
assert_eq!(
|
||||
store
|
||||
.get_record(GetUsageRecord {
|
||||
id: "audit-conflict".into()
|
||||
})
|
||||
.await
|
||||
.unwrap_err()
|
||||
.kind,
|
||||
UsageErrorKind::NotFound
|
||||
);
|
||||
let first = store
|
||||
.list_records(ListUsageRecords {
|
||||
filter: filter(),
|
||||
|
||||
@@ -46,7 +46,7 @@ impl ProviderAdmin for AntigravityAdmin {
|
||||
}
|
||||
|
||||
fn is_direct_account(&self, authentication_kind: &str) -> bool {
|
||||
authentication_kind == "oauth"
|
||||
crate::credential::Authentication::is_direct_account_kind(authentication_kind)
|
||||
}
|
||||
async fn peer_model_facts(
|
||||
&self,
|
||||
@@ -110,8 +110,28 @@ impl ProviderAdmin for AntigravityAdmin {
|
||||
async fn account_unavailable(&self, _: &ProviderAccountId) {
|
||||
self.catalog.invalidate();
|
||||
}
|
||||
async fn background_quota_refresh_enabled(&self) -> Result<bool, ProviderAdminError> {
|
||||
self.credentials.background_refresh_enabled().await
|
||||
fn validate_settings(&self, settings: &OpaqueProviderData) -> Result<(), ProviderAdminError> {
|
||||
CredentialService::parse_background_refresh(settings).map(|_| ())
|
||||
}
|
||||
|
||||
async fn quota_observation_targets(
|
||||
&self,
|
||||
change: AccountFactsChange<'_>,
|
||||
) -> Vec<ProviderAccountId> {
|
||||
if change.ids.iter().all(|id| change.created_ids.contains(id)) {
|
||||
return change.ids.to_vec();
|
||||
}
|
||||
match self.credentials.background_refresh_enabled().await {
|
||||
Ok(true) => return change.ids.to_vec(),
|
||||
Ok(false) => {}
|
||||
Err(error) => tracing::warn!(%error, "读取 Antigravity 账号查询设置失败"),
|
||||
}
|
||||
change
|
||||
.ids
|
||||
.iter()
|
||||
.filter(|id| change.created_ids.contains(*id))
|
||||
.cloned()
|
||||
.collect()
|
||||
}
|
||||
async fn account_facts_changed(&self, change: AccountFactsChange<'_>) {
|
||||
self.catalog.invalidate();
|
||||
|
||||
@@ -20,7 +20,7 @@ pub(crate) fn calculate(
|
||||
};
|
||||
let input = usage.input_tokens?;
|
||||
let output = usage.output_tokens?;
|
||||
let long = input > 200_000 && band("long_standard").is_some();
|
||||
let long = input > super::LONG_CONTEXT_THRESHOLD && band("long_standard").is_some();
|
||||
let rates = band(if long { "long_standard" } else { "standard" })?;
|
||||
let image_rates = band("image");
|
||||
// 图片模型必须报告输出模态数量,避免把图片误按文本单价计费
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
|
||||
pub(crate) const SUPPORTED_PRICING_BANDS: &[&str] = &["standard", "long_standard", "image"];
|
||||
|
||||
use gateway_admin::ports::pricing::PricingSourceModel;
|
||||
use gateway_admin::ports::pricing::{PricingSourceModel, PricingSourcePolicy};
|
||||
use gateway_core::metering::{ModelPriceOverride, TokenPriceOverride};
|
||||
use std::{collections::BTreeMap, sync::LazyLock};
|
||||
|
||||
@@ -207,6 +207,10 @@ pub(crate) fn source_models() -> BTreeMap<String, PricingSourceModel> {
|
||||
PricingSourceModel {
|
||||
provider: family.provider.to_owned(),
|
||||
model: family.source.to_owned(),
|
||||
policy: PricingSourcePolicy {
|
||||
long_context_tokens: Some(super::LONG_CONTEXT_THRESHOLD),
|
||||
text_only_input: family.provider == "google",
|
||||
},
|
||||
},
|
||||
)
|
||||
})
|
||||
|
||||
Loaded 100 of 136 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user