mirror of
https://github.com/zyycn/codex-proxy-rs.git
synced 2026-11-29 16:00:51 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f4254104c9 | ||
|
|
36136728c6 | ||
|
|
0d731c5059 | ||
|
|
3fe4248fd6 | ||
|
|
3cc9c71ab5 | ||
|
|
2dc3ba8d56 | ||
|
|
7c16190936 | ||
|
|
c89152ce08 | ||
|
|
4b8825a28f | ||
|
|
95a89e9010 | ||
|
|
4fc8f836be | ||
|
|
ddd33da737 | ||
|
|
1d875def09 | ||
|
|
e6def7b634 | ||
|
|
f5d3c55d75 | ||
|
|
30487dfbf1 | ||
|
|
71cfdcb33e | ||
|
|
98954aefb6 | ||
|
|
c74c570228 | ||
|
|
fbf1aa1d9b | ||
|
|
91d3b8cad8 | ||
|
|
591dead0ec | ||
|
|
44cc0757a3 | ||
|
|
0cfaca2a2b | ||
|
|
3ec00a152c | ||
|
|
7633a62368 | ||
|
|
9684b9d00f | ||
|
|
4c49ddb479 | ||
|
|
be58d38aef | ||
|
|
40cab881d0 | ||
|
|
2ec300ecf4 | ||
|
|
2b6536236f | ||
|
|
01cebb810d | ||
|
|
909b514074 | ||
|
|
533a415a99 | ||
|
|
7b04e08d81 | ||
|
|
8acf376091 | ||
|
|
62e9cd03c5 | ||
|
|
81dacf603f | ||
|
|
5173314136 | ||
|
|
a51395bbc5 | ||
|
|
eece08a4a2 | ||
|
|
4bdb15ccd9 | ||
|
|
aad6304a33 | ||
|
|
db22550e61 | ||
|
|
6950c02ee4 | ||
|
|
5265cc8424 | ||
|
|
984b3e8e08 | ||
|
|
a5c23374e7 | ||
|
|
83bf9fafb3 | ||
|
|
409e36bf95 | ||
|
|
77ff65f400 | ||
|
|
75d0d0e0f8 | ||
|
|
1d92d638ba | ||
|
|
4e96567b6d | ||
|
|
42fdaecd7a |
@@ -1,6 +1,6 @@
|
||||
---
|
||||
name: cpr-dev-guide
|
||||
description: Codex Proxy RS 的需求评估、排障、开发、代码审查与文档维护入口
|
||||
description: Codex Proxy RS 的需求评估、排障、开发、代码审查与文档维护,包括对代码和文档改动的验收
|
||||
---
|
||||
|
||||
# 开发指南
|
||||
@@ -22,9 +22,9 @@ 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) |
|
||||
@@ -41,11 +41,13 @@ description: Codex Proxy RS 的需求评估、排障、开发、代码审查与
|
||||
|
||||
## 执行与收尾
|
||||
|
||||
长任务按 [任务延续与收尾](../../../AGENTS.md#任务延续与收尾)恢复已匹配的领域、具体约束与验证进度。单独收到验收请求时,先确认待验收版本和范围,发现偏差按当前授权处理
|
||||
|
||||
1. 遵守已提供的 [AGENTS.md](../../../AGENTS.md),按其 CodeGraph 约定定位代码;确认工作区、任务范围与已有改动,找到事实归属、同类实现和调用链,补齐上表命中规范及[项目约定](../../../CONTRIBUTING.md#项目约定)对应条目后再修改
|
||||
2. 以最终差异重新匹配上表,补齐新增领域的规范并检查实际实现,再处理本次引入的职责越界、重复规则、冗余状态与无依据分支;删除或替换功能时一并清理失效的配置、类型、调用、测试与文档,已部署数据和公开合同仍遵守所属迁移及兼容规则;仅审查时报告,不自行修复
|
||||
2. 按最终差异与受影响行为重新匹配上表,逐项对照适用条款检查实际实现。处理本次引入的职责越界、重复规则、冗余状态与无依据分支;删除或替换功能时一并清理失效的配置、类型、调用、测试与文档,已部署数据和公开合同仍遵守所属迁移及兼容规则;仅审查时报告,不自行修复
|
||||
3. 模块移动或重命名时,同步核对源码、测试、公开导出及配置、脚本中的名称和路径引用;在本任务内更新受影响的文档、示例和引用
|
||||
4. 按变更范围执行[验证](../../../CONTRIBUTING.md#验证)及其停止条件,后端命令见[验证命令](../../../docs/architecture.md#验证命令);复用仍适用的验证证据与用户已确定的验收分工,区分通过、失败、跳过与未执行
|
||||
5. 交付前按[首要写作要求](#首要写作要求言简意赅)通读本次新增或修改的文字。交代实际结果与验证缺口;前端按[前端流程](references/frontend.md)核对运行证据,后端按上表检查生命周期,不把构建通过当作行为验收
|
||||
5. 交付前按[首要写作要求](#首要写作要求言简意赅)通读本次新增或修改的文字。验收结论同时依据规范核对结果与行为验证证据;有规范偏差或缺少必要证据时,指出具体位置或未验证场景。前端按[前端流程](references/frontend.md)核对运行证据,后端按上表检查生命周期
|
||||
6. 按授权完成提交与交付;提交前按[提交约定](../../../CONTRIBUTING.md#项目约定)准备提交信息与实际共同作者署名,提交后核对实际提交消息,PR 的 AI 披露不能替代提交署名
|
||||
|
||||
## 测试维护
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
interface:
|
||||
display_name: "cpr-dev-guide"
|
||||
short_description: "开发、排障与审查入口,按行为影响匹配领域边界并验证实现"
|
||||
default_prompt: "使用 $cpr-dev-guide 按请求、行为影响和实际文件匹配领域必读规范,读完职责边界再确定方案,完成已授权的开发或审查、自审与验证。"
|
||||
short_description: "开发、排障、审查与验收入口,按受影响行为匹配并执行领域规范"
|
||||
default_prompt: "使用 $cpr-dev-guide 按受影响行为和实际文件匹配领域规范,开发时据此确定方案,验收时对照最终实现和验证证据。"
|
||||
policy:
|
||||
allow_implicit_invocation: true
|
||||
|
||||
@@ -4,13 +4,13 @@
|
||||
|
||||
| 任务意图与常见说法 | 必用技能 |
|
||||
| --- | --- |
|
||||
| 需求评估、排障、开发、修复、代码审查、改文档,包括“看下这个 Issue”“改弹窗/样式/文案”“修接口/调度/数据库” | [cpr-dev-guide](.agents/skills/cpr-dev-guide/SKILL.md),按实际操作和文件匹配规范,跨前后端同时执行 |
|
||||
| 需求评估、排障、开发、修复、代码审查、改文档、验收实现,包括“看下这个 Issue”“改弹窗/样式/文案”“修接口/调度/数据库”“验收一下这次改动” | [cpr-dev-guide](.agents/skills/cpr-dev-guide/SKILL.md),按实际操作和文件匹配规范,跨前后端同时执行 |
|
||||
| 提交/提个 PR、准备或更新 PR、看下 PR、回复 PR 讨论、处理 PR 审查意见 | [cpr-github-pr](.agents/skills/cpr-github-pr/SKILL.md);实现自审、审查或修改同时执行 cpr-dev-guide |
|
||||
| 提 Issue、反馈到仓库、把问题或建议整理成 Issue、补充或回复 Issue | [cpr-github-issue](.agents/skills/cpr-github-issue/SKILL.md) |
|
||||
| 写、修或审查独立网关插件,排查插件接入、打包插件 | [cpr-plugin-dev](.agents/skills/cpr-plugin-dev/SKILL.md),同时执行 cpr-dev-guide;仅改宿主能力时由 cpr-dev-guide 加载插件边界 |
|
||||
| 发版、准备版本、发布 beta/实验版、整理发布说明、打发行 tag | [cpr-release](.agents/skills/cpr-release/SKILL.md) |
|
||||
|
||||
结合上下文识别“提交吧”“看看这个问题”等省略说法:普通 Git 提交不自动变成 PR,代码排查不自动变成 Issue;审查与发版准备不代表获准远程写入
|
||||
结合当前任务判断“继续”“验收一下”等省略说法。验收代码或文档改动时执行开发指南;核对发布产物时走发版技能。普通 Git 提交不自动变成 PR,代码排查不自动变成 Issue;审查与发版准备不代表获准远程写入
|
||||
|
||||
首次命中技能时完整读取其 `SKILL.md`,再读取领域必读规范,之后按当前步骤补充实现、命令和示例。技能名称、描述或入口摘要不能代替首次读取的正文与必读引用;引用中明确要求“先读”“必须读取”或“执行”的规范也要落实,其他资料按需读取
|
||||
|
||||
@@ -26,7 +26,7 @@ Issue 和 PR 回复统一按 [GitHub 回复口吻](CONTRIBUTING.md#github-回复
|
||||
### 任务延续与收尾
|
||||
|
||||
- 在任务上下文和压缩摘要中保留目标、授权、当前阶段、已读规范的路径与关键约束、验证命令与结果及对应代码状态、剩余事项
|
||||
- 同一任务可复用实际完成的读取与验证记录;仅在规范变更、进入未覆盖领域或具体决策缺少条款时补读对应内容。输出截断只补缺失部分,上下文压缩与阶段切换本身不触发重读或重验
|
||||
- 续接任务时,从记录中恢复当前步骤适用的规范与待查项,核对已有证据对应的实现。规范变更、进入新领域或缺少具体约束时补读对应条款,输出截断只补缺失部分。已有证据仍适用的检查直接复用
|
||||
- 远端更新或合并冲突后,按实际变更及其依赖影响补充自审和验证,复用未受影响的证据
|
||||
- 实现、自审与必要验证完成后,按[验证停止条件](CONTRIBUTING.md#验证)停止扩围;完成已获授权的剩余交付步骤并确认结果后结束
|
||||
|
||||
|
||||
+3
-3
@@ -55,7 +55,7 @@ AI 开发和审查入口是根目录的 [AGENTS.md](AGENTS.md)。在仓库上下
|
||||
### 项目技能
|
||||
|
||||
仓库技能位于 `.agents/skills/`,随代码共享。技能提供执行流程,协作与审查标准仍以本文和 `AGENTS.md` 为准。
|
||||
AI 开发、排查、代码审查和文档修改必须执行 `cpr-dev-guide`;准备、创建、更新及审查 PR 必须执行 `cpr-github-pr`,不以用户是否显式点名技能为条件。PR 内修复仍须经过开发流程,不能用填写 PR 正文代替实现自审与验证
|
||||
AI 开发、排查、代码审查、文档修改及对这些改动的验收必须执行 `cpr-dev-guide`;准备、创建、更新及审查 PR 必须执行 `cpr-github-pr`,不以用户是否显式点名技能为条件。PR 内修复仍须经过开发流程,不能用填写 PR 正文代替实现自审与验证
|
||||
|
||||
| 技能 | 用途 | 调用示例 |
|
||||
| --- | --- | --- |
|
||||
@@ -144,8 +144,8 @@ PR 不接受以下协作规则文件的新增、修改、删除或重命名:
|
||||
| [插件使用](docs/plugins.md) | 如何安装、授权、配置和使用插件 | 管理员操作与影响,不展开 SDK 调用或宿主事务实现 |
|
||||
| [插件 SDK](backend/crates/gateway-plugin/sdk/README.md) / [CLI](backend/apps/plugin-cli/README.md) | 如何编写和打包插件 | 作者合同、权限边界、示例与打包验证 |
|
||||
| [数据库迁移](backend/migrations/README.md) | 如何维护 schema 和准备测试库 | 冻结规则、升级约束和测试环境,不罗列迁移历史 |
|
||||
| [共用组件](modules/ui/README.md)及其组件参考 | 如何安装、使用和开发独立 UI 库 | 组件公开 API、主题能力与库内开发;宿主页面约定归管理端主题,跨仓库联调归开发文档 |
|
||||
| [官方插件示例](modules/plugins/README.md)及其示例说明 | 如何构建、使用和维护示例插件 | 示例自身的功能、配置与验证;通用协议归 SDK,宿主安装操作归插件使用文档 |
|
||||
| [共用组件](https://github.com/zyycn/codex-proxy-ui/blob/main/README.md)及其组件参考 | 如何安装、使用和开发独立 UI 库 | 组件公开 API、主题能力与库内开发;宿主页面约定归管理端主题,跨仓库联调归开发文档 |
|
||||
| [官方插件示例](https://github.com/zyycn/codex-proxy-plugins/blob/main/README.md)及其示例说明 | 如何构建、使用和维护示例插件 | 示例自身的功能、配置与验证;通用协议归 SDK,宿主安装操作归插件使用文档 |
|
||||
| [AGENTS.md](AGENTS.md) 与[项目技能](.agents/skills/cpr-dev-guide/SKILL.md) | AI 如何选择并执行任务流程 | 任务匹配、执行步骤和规范入口,不另建模块合同、版本表或协作标准 |
|
||||
| 本文 | 如何协作、审查和交付 | 流程、判断标准与验证要求,任务入口由 [开发技能](.agents/skills/cpr-dev-guide/SKILL.md) 串联 |
|
||||
|
||||
|
||||
@@ -5,10 +5,10 @@
|
||||
|
||||
# Codex Proxy RS
|
||||
|
||||
面向 Codex 的自托管多账号 AI 网关
|
||||
多平台自托管多账号 AI 网关
|
||||
|
||||
[](https://github.com/zyycn/codex-proxy-rs/actions/workflows/ci.yml)
|
||||
[](https://github.com/zyycn/codex-proxy-rs/releases)
|
||||
[](https://github.com/zyycn/codex-proxy-rs/releases)
|
||||
[](https://github.com/zyycn/codex-proxy-rs/pkgs/container/codex-proxy-rs)
|
||||
[](LICENSE)
|
||||
|
||||
|
||||
Generated
+2
@@ -1762,6 +1762,7 @@ dependencies = [
|
||||
"thiserror",
|
||||
"tokio",
|
||||
"tracing",
|
||||
"url",
|
||||
"uuid",
|
||||
]
|
||||
|
||||
@@ -1819,6 +1820,7 @@ dependencies = [
|
||||
"gateway-protocol",
|
||||
"http",
|
||||
"http-body-util",
|
||||
"regex-automata",
|
||||
"semver",
|
||||
"serde",
|
||||
"serde_json",
|
||||
|
||||
@@ -131,6 +131,7 @@ fn config_loader_should_ignore_unknown_fields_in_configuration_sections() {
|
||||
let mut document = valid_config_document();
|
||||
document["host"]["system_update"] = serde_json::json!({});
|
||||
document["store"]["pool"] = serde_json::json!({});
|
||||
document["openai"] = serde_json::json!({});
|
||||
for path in [
|
||||
"",
|
||||
"/host",
|
||||
@@ -369,31 +370,6 @@ fn config_loader_should_reject_zero_server_port() {
|
||||
assert_rejected(valid_config().replace("port: 8080", "port: 0"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn config_loader_should_accept_optional_openai_routing_strings() {
|
||||
for value in [
|
||||
serde_json::Value::Null,
|
||||
serde_json::json!("us"),
|
||||
serde_json::json!("custom-value"),
|
||||
serde_json::json!(""),
|
||||
] {
|
||||
let mut document = valid_config_document();
|
||||
document["openai"]["residency"] = value.clone();
|
||||
document["openai"]["account_routing_override"] = value;
|
||||
parse_config(&document.to_string()).expect("optional routing strings");
|
||||
}
|
||||
let mut document = valid_config_document();
|
||||
document["openai"]
|
||||
.as_object_mut()
|
||||
.unwrap()
|
||||
.remove("residency");
|
||||
document["openai"]
|
||||
.as_object_mut()
|
||||
.unwrap()
|
||||
.remove("account_routing_override");
|
||||
parse_config(&document.to_string()).expect("omitted routing strings");
|
||||
}
|
||||
|
||||
fn assert_rejected(config: String) {
|
||||
assert!(parse_config(&config).is_err());
|
||||
}
|
||||
|
||||
@@ -32,6 +32,7 @@ sha2 = "0.11"
|
||||
subtle = "2.6.1"
|
||||
thiserror = "2.0.18"
|
||||
tracing = "0.1.44"
|
||||
url = "2.5.8"
|
||||
uuid = { version = "1.23.3", features = ["v4", "v7"] }
|
||||
cron = "0.17"
|
||||
chrono-tz = "0.10"
|
||||
|
||||
@@ -42,6 +42,7 @@ pub struct ProviderAccountCapabilities {
|
||||
/// 导入时应用的账号设置;名称只覆盖单账号导入,其余设置统一应用
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct AccountImportSettings {
|
||||
pub platform_icon: Option<String>,
|
||||
pub name: Option<String>,
|
||||
pub notes: Option<String>,
|
||||
pub enabled: bool,
|
||||
@@ -222,6 +223,7 @@ pub struct AccountPage {
|
||||
/// 同一状态快照下的账号事实与唯一状态投影
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct AccountPageItem {
|
||||
pub platform_icon: Option<String>,
|
||||
pub protection_rules: Vec<gateway_core::account::AccountProtectionMatch>,
|
||||
pub account: AccountRecord,
|
||||
pub projection: AccountStatusProjection,
|
||||
@@ -240,6 +242,7 @@ pub struct AccountCapacity {
|
||||
/// 账号可编辑事实的一次性替换命令
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct UpdateAccount {
|
||||
pub platform_icon: Option<String>,
|
||||
pub account_id: String,
|
||||
/// 缺省保留名称,空字符串清除名称并使用邮箱展示
|
||||
pub name: Option<String>,
|
||||
|
||||
@@ -47,6 +47,7 @@ pub enum MutationAuditOperation {
|
||||
OutboundProxyUpdate,
|
||||
OutboundProxyDelete,
|
||||
OutboundProxyTest,
|
||||
ProxyTestTargetsUpdate,
|
||||
AccountGroupPluginReconcile,
|
||||
ClientApiKeyPluginReconcile,
|
||||
ProviderAccountImportDocument,
|
||||
@@ -110,6 +111,7 @@ impl MutationAuditOperation {
|
||||
Self::OutboundProxyCreate => ("create", "outbound_proxy"),
|
||||
Self::OutboundProxyUpdate => ("update", "outbound_proxy"),
|
||||
Self::OutboundProxyDelete => ("delete", "outbound_proxy"),
|
||||
Self::ProxyTestTargetsUpdate => ("update", "proxy_test_targets"),
|
||||
Self::OutboundProxyTest => ("test", "outbound_proxy"),
|
||||
Self::AccountGroupPluginReconcile => ("plugin_reconcile", "account_group"),
|
||||
Self::ClientApiKeyPluginReconcile => ("plugin_reconcile", "client_api_key"),
|
||||
|
||||
@@ -108,6 +108,7 @@ pub struct ClientKeyListQuery {
|
||||
/// 不含完整明文 Key 的管理投影
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ClientKeyRecord {
|
||||
pub validity: gateway_core::policy::ClientKeyValidity,
|
||||
pub peer_sharing: gateway_core::policy::ClientPeerSharing,
|
||||
pub request_profile_overrides: ProviderRequestProfileOverrides,
|
||||
pub id: ClientApiKeyId,
|
||||
@@ -124,6 +125,13 @@ pub struct ClientKeyRecord {
|
||||
pub updated_at: DateTime<Utc>,
|
||||
}
|
||||
|
||||
impl ClientKeyRecord {
|
||||
#[must_use]
|
||||
pub fn is_active(&self) -> bool {
|
||||
self.enabled && self.validity.is_active()
|
||||
}
|
||||
}
|
||||
|
||||
/// Client Key 列表页
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ClientKeyPage {
|
||||
@@ -168,6 +176,7 @@ impl fmt::Debug for ClientKeySecret {
|
||||
/// API 提交的 Client Key 创建命令
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct CreateClientKey {
|
||||
pub validity: gateway_core::policy::ClientKeyValidity,
|
||||
pub peer_sharing: gateway_core::policy::ClientPeerSharing,
|
||||
pub request_profile_overrides: ProviderRequestProfileOverrides,
|
||||
pub custom_key: Option<PlaintextClientApiKey>,
|
||||
@@ -181,6 +190,7 @@ pub struct CreateClientKey {
|
||||
/// 管理用例生成 ID 与明文后的持久化命令
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
pub struct NewClientKey {
|
||||
pub validity: gateway_core::policy::ClientKeyValidity,
|
||||
pub peer_sharing: gateway_core::policy::ClientPeerSharing,
|
||||
pub request_profile_overrides: ProviderRequestProfileOverrides,
|
||||
pub id: ClientApiKeyId,
|
||||
@@ -207,6 +217,7 @@ impl fmt::Debug for NewClientKey {
|
||||
/// 修改 Client Key 的公开策略字段
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct UpdateClientKey {
|
||||
pub validity: Option<gateway_core::policy::ClientKeyValidity>,
|
||||
pub peer_sharing: Option<gateway_core::policy::ClientPeerSharing>,
|
||||
pub request_profile_override_updates: ProviderRequestProfileOverrideUpdates,
|
||||
pub id: ClientApiKeyId,
|
||||
@@ -293,13 +304,33 @@ pub enum ClientKeyBudgetPeriod {
|
||||
All,
|
||||
}
|
||||
|
||||
/// 清零所选窗口并恢复日历规则,保留限额与历史费用
|
||||
/// 清零所选窗口,保留限额与历史费用
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ResetClientKeyBudget {
|
||||
pub id: ClientApiKeyId,
|
||||
pub period: ClientKeyBudgetPeriod,
|
||||
}
|
||||
|
||||
impl ResetClientKeyBudget {
|
||||
/// 返回所选日、周窗口的终点;插件重置以起止相同表示等待下次使用
|
||||
#[must_use]
|
||||
pub fn window_ends(
|
||||
&self,
|
||||
origin: &ClientKeyBudgetMutationOrigin,
|
||||
start: DateTime<Utc>,
|
||||
) -> (Option<DateTime<Utc>>, Option<DateTime<Utc>>) {
|
||||
let end = |days| match origin {
|
||||
ClientKeyBudgetMutationOrigin::Admin => start + chrono::Duration::days(days),
|
||||
ClientKeyBudgetMutationOrigin::Plugin(_) => start,
|
||||
};
|
||||
match self.period {
|
||||
ClientKeyBudgetPeriod::Daily => (Some(end(1)), None),
|
||||
ClientKeyBudgetPeriod::Weekly => (None, Some(end(7))),
|
||||
ClientKeyBudgetPeriod::All => (Some(end(1)), Some(end(7))),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 显式窗口复用已有日/周金额上限,外部周期的选择归调用方
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ClientKeyBudgetWindowPeriod {
|
||||
@@ -319,7 +350,9 @@ impl ClientKeyBudgetWindowPeriod {
|
||||
|
||||
/// 手动对齐只需要账号身份,列表不读取凭据、额度或用量
|
||||
#[derive(serde::Serialize, Debug)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct BudgetReferenceAccount {
|
||||
pub platform_icon: Option<String>,
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub email: Option<String>,
|
||||
|
||||
@@ -783,6 +783,7 @@ pub struct AccountRequestBucket {
|
||||
/// Dashboard 中一个账号的完整用量事实
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct DashboardAccountUsage {
|
||||
pub platform_icon: Option<String>,
|
||||
pub upstream: Option<super::upstream_info::ProviderUpstreamInfo>,
|
||||
pub account_id: String,
|
||||
pub provider_kind: String,
|
||||
@@ -890,6 +891,7 @@ impl UsageErrorOrigin {
|
||||
/// 使用记录表格的窄读模型
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct UsageListRecord {
|
||||
pub platform_icon: Option<String>,
|
||||
pub outcome: RequestOutcome,
|
||||
/// 已保存的上游错误对象含非空字符串 code、type 或 message
|
||||
pub has_upstream_error: bool,
|
||||
@@ -1167,9 +1169,11 @@ pub struct DiagnosticsObservation {
|
||||
pub struct DiagnosticObservation {
|
||||
pub key: String,
|
||||
pub name: String,
|
||||
pub account_provider_kind: Option<String>,
|
||||
pub providers: Vec<String>,
|
||||
pub platform_icon: Option<String>,
|
||||
pub account_authentication_kind: Option<String>,
|
||||
pub account_plan_type: Option<String>,
|
||||
pub account_plan_type_display: Option<String>,
|
||||
pub request_count: u64,
|
||||
pub success_count: u64,
|
||||
pub failure_count: u64,
|
||||
@@ -1639,6 +1643,8 @@ pub struct UsageInsight {
|
||||
/// 已完成分母计算的诊断项
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct DiagnosticsItem {
|
||||
pub providers: Vec<String>,
|
||||
pub platform_icon: Option<String>,
|
||||
pub key: String,
|
||||
pub name: String,
|
||||
pub account_authentication_kind: Option<String>,
|
||||
|
||||
@@ -1052,14 +1052,23 @@ pub struct ProviderResetCreditResult {
|
||||
pub credit: Option<ProviderResetCredit>,
|
||||
}
|
||||
|
||||
impl ProviderQuota {
|
||||
/// 保留账号已有的套餐子类型,仅在缺失时使用上游额度快照补全
|
||||
pub(crate) fn fill_missing_plan_type(&self, account_plan_type: &mut Option<String>) {
|
||||
if explicit_plan_type(account_plan_type.as_deref()).is_none() {
|
||||
*account_plan_type = explicit_plan_type(self.plan_type.as_deref()).map(str::to_owned);
|
||||
}
|
||||
/// 用额度观测补齐缺失的套餐 ID,只采用与账号套餐相符的描述
|
||||
pub fn resolve_observed_plan<'a>(
|
||||
account_plan_type: &mut Option<String>,
|
||||
observed_type: Option<&str>,
|
||||
observed_display: Option<&'a str>,
|
||||
) -> Option<&'a str> {
|
||||
let observed_type = explicit_plan_type(observed_type);
|
||||
if explicit_plan_type(account_plan_type.as_deref()).is_none() {
|
||||
*account_plan_type = observed_type.map(str::to_owned);
|
||||
}
|
||||
observed_display.filter(|_| {
|
||||
observed_type
|
||||
.is_none_or(|id| Some(id.trim()) == account_plan_type.as_deref().map(str::trim))
|
||||
})
|
||||
}
|
||||
|
||||
impl ProviderQuota {
|
||||
/// 选择账号用量统计窗口,同时返回展示所需的周期事实
|
||||
///
|
||||
/// 周/月额度使用边界完整、可归属到整个账号的窗口
|
||||
@@ -1310,6 +1319,7 @@ impl fmt::Debug for ProviderExport {
|
||||
/// 统一账号目录的一行完整结果
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct AccountDirectoryItem {
|
||||
pub platform_icon: Option<String>,
|
||||
pub protection_rules: Vec<gateway_core::account::AccountProtectionMatch>,
|
||||
pub account: AccountRecord,
|
||||
pub capacity: super::accounts::AccountCapacity,
|
||||
|
||||
@@ -27,6 +27,7 @@ pub struct ProxyListQuery {
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ProxyAccountRef {
|
||||
pub platform_icon: Option<String>,
|
||||
pub upstream: Option<super::upstream_info::ProviderUpstreamInfo>,
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
@@ -56,6 +57,41 @@ pub struct ProxyAccountPage {
|
||||
pub page_size: u16,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct ProxyTestTarget {
|
||||
pub name: String,
|
||||
pub url: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct ProxyTestTargets {
|
||||
pub revision: Revision,
|
||||
pub targets: Vec<ProxyTestTarget>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct TargetProbeResult {
|
||||
pub latency_ms: u64,
|
||||
#[serde(flatten)]
|
||||
pub outcome: TargetProbeOutcome,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(tag = "kind", rename_all = "camelCase")]
|
||||
pub enum TargetProbeOutcome {
|
||||
Http {
|
||||
status: u16,
|
||||
#[serde(rename = "exitIp")]
|
||||
exit_ip: Option<std::net::IpAddr>,
|
||||
},
|
||||
Failed {
|
||||
message: String,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ProxyTestResult {
|
||||
pub location: ProxyLocationDetection,
|
||||
|
||||
@@ -45,8 +45,8 @@ pub use gateway_core::account::RotationStrategy;
|
||||
/// 运行设置的共同值;版本、Provider 画像更新和数据库秘密由外层类型拥有
|
||||
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct RuntimeSettingsValues {
|
||||
pub openai_oauth_guardian_review_model: bool,
|
||||
pub openai_request_country: gateway_core::account::OpenAiRequestCountry,
|
||||
pub openai_websocket_pool: gateway_core::settings::OpenAiWebSocketPoolSettings,
|
||||
pub openai_request_settings: gateway_core::settings::OpenAiRequestSettings,
|
||||
pub codex_privacy_policy: gateway_core::settings::privacy::CodexPrivacyPolicy,
|
||||
pub request_location_enabled: bool,
|
||||
pub request_location: gateway_core::account::RequestLocation,
|
||||
@@ -71,6 +71,7 @@ pub struct RuntimeSettingsValues {
|
||||
pub usage_retention_days: u32,
|
||||
pub ops_event_retention_days: u32,
|
||||
pub audit_retention_days: u32,
|
||||
pub prompt_rewrite_rules: Vec<gateway_core::settings::prompt_rewrite::PromptRewriteRule>,
|
||||
pub account_error_protection: gateway_core::account::AccountErrorProtection,
|
||||
pub account_warmup_enabled: bool,
|
||||
pub account_warmup_cron: String,
|
||||
@@ -192,6 +193,9 @@ impl From<RuntimeSettings> for ReplaceRuntimeSettings {
|
||||
impl RuntimeSettingsValues {
|
||||
/// 校验共同事实,返回字段名供边界转换错误;SQL 类型转换仍由 Store 处理
|
||||
pub fn validate(&self) -> Result<(), &'static str> {
|
||||
for rule in &self.prompt_rewrite_rules {
|
||||
rule.validate().map_err(|_| "prompt_rewrite_rules")?;
|
||||
}
|
||||
if !(1..=1440).contains(&self.reset_credit_lead_minutes) {
|
||||
return Err("reset_credit_lead_minutes");
|
||||
}
|
||||
@@ -201,9 +205,8 @@ impl RuntimeSettingsValues {
|
||||
{
|
||||
return Err("reset_credit_max_weekly_remaining_percent");
|
||||
}
|
||||
self.openai_request_country
|
||||
.validate()
|
||||
.map_err(|_| "openai_request_country")?;
|
||||
self.openai_websocket_pool.validate()?;
|
||||
self.openai_request_settings.validate()?;
|
||||
self.request_location
|
||||
.validate()
|
||||
.map_err(|_| "request_location")?;
|
||||
|
||||
@@ -20,7 +20,7 @@ use crate::model::provider_credentials::{
|
||||
ProviderExport, ProviderExportCredentialInput, ProviderModelCatalogDocument, ProviderModels,
|
||||
ProviderProfileAvatar, ProviderProfileStatistics, ProviderQuota, ProviderQuotaReadRequest,
|
||||
ProviderQuotaRequest, ProviderResetCreditResult, ProviderResetCredits, ProviderSubscription,
|
||||
explicit_plan_type,
|
||||
explicit_plan_type, resolve_observed_plan,
|
||||
};
|
||||
use crate::model::{
|
||||
provider_credentials::{ProviderDocument, ProviderQuotaWindow},
|
||||
@@ -558,15 +558,14 @@ impl ProviderAdminRegistry {
|
||||
plan_type: &mut Option<String>,
|
||||
quota: Option<&ProviderQuota>,
|
||||
) -> Option<String> {
|
||||
if let Some(quota) = quota {
|
||||
quota.fill_missing_plan_type(plan_type);
|
||||
// 保留账号已知的套餐,不能给它配上另一档快照的描述
|
||||
let quota_id = explicit_plan_type(quota.plan_type.as_deref()).map(str::trim);
|
||||
if let Some(display) = "a.plan_type_display
|
||||
&& quota_id.is_none_or(|id| Some(id) == plan_type.as_deref().map(str::trim))
|
||||
{
|
||||
return Some(display.clone());
|
||||
}
|
||||
if let Some(quota) = quota
|
||||
&& let Some(display) = resolve_observed_plan(
|
||||
plan_type,
|
||||
quota.plan_type.as_deref(),
|
||||
quota.plan_type_display.as_deref(),
|
||||
)
|
||||
{
|
||||
return Some(display.to_owned());
|
||||
}
|
||||
self.plan_type_display(provider_kind, plan_type.as_deref())
|
||||
}
|
||||
|
||||
@@ -8,7 +8,8 @@ use crate::model::{
|
||||
AdminError, MutationContext, Revision,
|
||||
proxies::{
|
||||
ImportProxyBinding, NewProxy, ProxyAccountListQuery, ProxyAccountPage, ProxyListQuery,
|
||||
ProxyMutation, ProxyPage, ProxyRecord, ProxyTestResult, UpdateProxy,
|
||||
ProxyMutation, ProxyPage, ProxyRecord, ProxyTestResult, ProxyTestTargets,
|
||||
TargetProbeResult, UpdateProxy,
|
||||
},
|
||||
};
|
||||
|
||||
@@ -21,6 +22,12 @@ pub trait PluginProxyAccess: Send + Sync {
|
||||
|
||||
#[async_trait]
|
||||
pub trait ProxyStore: Send + Sync {
|
||||
async fn test_targets(&self) -> AdminStoreResult<ProxyTestTargets>;
|
||||
async fn replace_test_targets(
|
||||
&self,
|
||||
settings: &ProxyTestTargets,
|
||||
context: &MutationContext,
|
||||
) -> AdminStoreResult<Revision>;
|
||||
/// 在凭据交换到提交期间保护选定代理的连接配置和测试结果
|
||||
async fn reserve_import(&self, id: &str) -> AdminStoreResult<ProxyImportReservation>;
|
||||
async fn list(&self, query: ProxyListQuery) -> AdminStoreResult<ProxyPage>;
|
||||
@@ -78,5 +85,6 @@ pub enum ProbeRoute<'a> {
|
||||
|
||||
#[async_trait]
|
||||
pub trait ProxyProbe: Send + Sync {
|
||||
async fn test_target(&self, proxy: &OutboundProxy, endpoint: &str) -> TargetProbeResult;
|
||||
async fn test(&self, proxy: ProbeRoute<'_>, detect_location: bool) -> ProxyTestResult;
|
||||
}
|
||||
|
||||
@@ -25,6 +25,13 @@ pub(super) fn register(
|
||||
}};
|
||||
}
|
||||
register!(Load, load, (), ());
|
||||
register!(
|
||||
PreviewPromptRewrite,
|
||||
preview_prompt_rewrite,
|
||||
gateway_core::settings::prompt_rewrite::PromptRewritePreviewRequest,
|
||||
request,
|
||||
request
|
||||
);
|
||||
register!(
|
||||
PreviewPrivacyPolicy,
|
||||
preview_privacy_policy,
|
||||
|
||||
@@ -513,6 +513,7 @@ impl DefaultAccountsService {
|
||||
lookback,
|
||||
);
|
||||
Ok(AccountDirectoryItem {
|
||||
platform_icon: stored.platform_icon,
|
||||
protection_rules: stored.protection_rules,
|
||||
capacity: super::peer_link::upstream::account_capacity(
|
||||
&stored.account,
|
||||
@@ -647,6 +648,7 @@ impl AccountsService for DefaultAccountsService {
|
||||
lookback,
|
||||
);
|
||||
Ok(AccountDirectoryItem {
|
||||
platform_icon: item.platform_icon,
|
||||
protection_rules: item.protection_rules,
|
||||
capacity: crate::model::accounts::AccountCapacity {
|
||||
used_slots: in_flight
|
||||
|
||||
@@ -337,6 +337,11 @@ impl ClientKeyService for DefaultClientKeyService {
|
||||
context: &MutationContext,
|
||||
command: CreateClientKey,
|
||||
) -> Result<CreatedClientKey, AdminError> {
|
||||
if !command.validity.is_valid() {
|
||||
return Err(AdminError::invalid(
|
||||
"请填写完整有效期,到期时间须晚于生效时间",
|
||||
));
|
||||
}
|
||||
crate::model::client_keys::validate_group_ids(&command.group_ids)
|
||||
.map_err(|_| AdminError::invalid("API Key 分组不合法"))?;
|
||||
for (provider, profile) in &command.request_profile_overrides {
|
||||
@@ -354,6 +359,7 @@ impl ClientKeyService for DefaultClientKeyService {
|
||||
.store
|
||||
.create_client_key(
|
||||
NewClientKey {
|
||||
validity: command.validity,
|
||||
peer_sharing: command.peer_sharing,
|
||||
request_profile_overrides: command.request_profile_overrides,
|
||||
id,
|
||||
@@ -382,6 +388,11 @@ impl ClientKeyService for DefaultClientKeyService {
|
||||
) -> Result<ClientKeyMutation, AdminError> {
|
||||
crate::model::client_keys::validate_group_ids(&command.group_ids)
|
||||
.map_err(|_| AdminError::invalid("API Key 分组不合法"))?;
|
||||
if command.validity.is_some_and(|range| !range.is_valid()) {
|
||||
return Err(AdminError::invalid(
|
||||
"请填写完整有效期,到期时间须晚于生效时间",
|
||||
));
|
||||
}
|
||||
for (provider, profile) in &command.request_profile_override_updates {
|
||||
self.validate_profile(provider, profile.as_ref())?;
|
||||
}
|
||||
|
||||
@@ -137,7 +137,7 @@ impl KeyUsageService for DefaultKeyUsageService {
|
||||
self.keys
|
||||
.get_client_key(id)
|
||||
.await
|
||||
.map(|key| key.filter(|key| key.enabled).map(|key| key.budget))
|
||||
.map(|key| key.filter(|key| key.is_active()).map(|key| key.budget))
|
||||
.map_err(|error| map_store_error(error, "key usage budget"))
|
||||
}
|
||||
|
||||
@@ -159,7 +159,7 @@ impl KeyUsageService for DefaultKeyUsageService {
|
||||
self.keys
|
||||
.reveal_client_key(&id)
|
||||
.await
|
||||
.map(|secret| secret.filter(|secret| secret.record.enabled))
|
||||
.map(|secret| secret.filter(|secret| secret.record.is_active()))
|
||||
.map_err(|error| map_store_error(error, "key usage config"))
|
||||
}
|
||||
|
||||
@@ -176,7 +176,7 @@ impl KeyUsageService for DefaultKeyUsageService {
|
||||
.get_client_key(&id)
|
||||
.await
|
||||
.map_err(|error| map_store_error(error, "key usage profile"))?
|
||||
.filter(|key| key.enabled)
|
||||
.filter(|key| key.is_active())
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
@@ -109,6 +109,9 @@ impl UsageErrorOrigin {
|
||||
"no_available_provider",
|
||||
"no_eligible_account",
|
||||
"account_capacity_unavailable",
|
||||
"account_pool_quota_exhausted",
|
||||
"key_rate_limited",
|
||||
"key_concurrency_limited",
|
||||
"middleware_capacity_unavailable",
|
||||
"concurrency_queue_full",
|
||||
"concurrency_queue_timeout",
|
||||
|
||||
@@ -380,12 +380,13 @@ impl ObservabilityService for DefaultObservabilityService {
|
||||
key: item.key,
|
||||
name: item.name,
|
||||
account_authentication_kind: item.account_authentication_kind,
|
||||
account_plan_type_display: item.account_provider_kind.as_deref().and_then(
|
||||
|provider| {
|
||||
self.providers
|
||||
.plan_type_display(provider, item.account_plan_type.as_deref())
|
||||
},
|
||||
account_plan_type_display: self.historical_plan_display(
|
||||
item.account_plan_type_display,
|
||||
item.providers.first().map(String::as_str),
|
||||
item.account_plan_type.as_deref(),
|
||||
),
|
||||
providers: item.providers,
|
||||
platform_icon: item.platform_icon,
|
||||
account_plan_type: item.account_plan_type,
|
||||
request_count: item.request_count,
|
||||
success_count: item.success_count,
|
||||
@@ -422,17 +423,26 @@ impl ObservabilityService for DefaultObservabilityService {
|
||||
.await
|
||||
.map_err(|error| map_store_error(error, "operations errors"))?;
|
||||
for error in &mut page.items {
|
||||
error.provider_account_plan_type_display =
|
||||
error.provider_kind.as_deref().and_then(|provider| {
|
||||
self.providers
|
||||
.plan_type_display(provider, error.provider_account_plan_type.as_deref())
|
||||
});
|
||||
error.provider_account_plan_type_display = self.historical_plan_display(
|
||||
error.provider_account_plan_type_display.take(),
|
||||
error.provider_kind.as_deref(),
|
||||
error.provider_account_plan_type.as_deref(),
|
||||
);
|
||||
}
|
||||
Ok(page)
|
||||
}
|
||||
}
|
||||
|
||||
impl DefaultObservabilityService {
|
||||
fn historical_plan_display(
|
||||
&self,
|
||||
display: Option<String>,
|
||||
provider: Option<&str>,
|
||||
plan_type: Option<&str>,
|
||||
) -> Option<String> {
|
||||
display.or_else(|| self.providers.plan_type_display(provider?, plan_type))
|
||||
}
|
||||
|
||||
async fn current_upstream_peers<'a>(
|
||||
&self,
|
||||
ids: impl Iterator<Item = &'a str>,
|
||||
@@ -540,11 +550,11 @@ impl DefaultObservabilityService {
|
||||
.provider_account_ref
|
||||
.as_ref()
|
||||
.and_then(|id| peers.get(id).copied());
|
||||
record.provider_account_plan_type_display =
|
||||
record.provider_kind.as_deref().and_then(|provider| {
|
||||
self.providers
|
||||
.plan_type_display(provider, record.provider_account_plan_type.as_deref())
|
||||
});
|
||||
record.provider_account_plan_type_display = self.historical_plan_display(
|
||||
record.provider_account_plan_type_display.take(),
|
||||
record.provider_kind.as_deref(),
|
||||
record.provider_account_plan_type.as_deref(),
|
||||
);
|
||||
let Some(UsageBilling::Total { source, total }) = record.billing.as_ref() else {
|
||||
continue;
|
||||
};
|
||||
|
||||
@@ -104,7 +104,7 @@ impl PeerLinkService for DefaultPeerLinkService {
|
||||
.get_client_key(client.policy().key_id())
|
||||
.await
|
||||
.map_err(|error| map_store_error(error, "client API key"))?
|
||||
.filter(|key| key.enabled)
|
||||
.filter(|key| key.is_active())
|
||||
.ok_or(PeerLinkError::Unauthorized)?;
|
||||
let budget_observed_at = Utc::now();
|
||||
let sharing = intersect_sharing(frozen_sharing, key.peer_sharing);
|
||||
|
||||
@@ -11,10 +11,10 @@ use gateway_core::{
|
||||
use std::{collections::BTreeMap, sync::Arc, time::SystemTime};
|
||||
|
||||
impl PeerInfoService {
|
||||
pub(crate) async fn read_summaries(
|
||||
pub(super) async fn hydrate(
|
||||
&self,
|
||||
connections: &[UpstreamConnection],
|
||||
) -> Result<Vec<(UpstreamConnection, ProviderQuota)>, StoreError> {
|
||||
) -> Result<(), StoreError> {
|
||||
let _refresh = self.cache_refresh.lock().await;
|
||||
let ids = connections
|
||||
.iter()
|
||||
@@ -78,6 +78,15 @@ impl PeerInfoService {
|
||||
self.cache(connection, observation);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) async fn read_summaries(
|
||||
&self,
|
||||
connections: &[UpstreamConnection],
|
||||
) -> Result<Vec<(UpstreamConnection, ProviderQuota)>, StoreError> {
|
||||
self.hydrate(connections).await?;
|
||||
let now = SystemTime::now();
|
||||
let summaries = {
|
||||
let observations = self
|
||||
.observations
|
||||
|
||||
@@ -42,13 +42,15 @@ impl PeerInfoService {
|
||||
.clone()
|
||||
}
|
||||
|
||||
pub(super) fn refresh_due(&self, connection: &UpstreamConnection) -> bool {
|
||||
if self.unsupported(connection) {
|
||||
return false;
|
||||
}
|
||||
let state = self.refresh_state(connection);
|
||||
state.try_lock().is_ok_and(|state| {
|
||||
state.connection != *connection || Instant::now() >= state.next_attempt
|
||||
pub(super) fn retry_ready(&self, connection: &UpstreamConnection) -> bool {
|
||||
let attempts = self
|
||||
.attempts
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
attempts.get(&connection.account_id).is_none_or(|slot| {
|
||||
slot.try_lock().is_ok_and(|state| {
|
||||
state.connection != *connection || Instant::now() >= state.next_attempt
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
@@ -128,8 +130,9 @@ impl PeerInfoService {
|
||||
};
|
||||
let now = SystemTime::now();
|
||||
let failure = result.as_ref().err().copied();
|
||||
let min_delay = Duration::from_secs(15);
|
||||
let delay = match failure {
|
||||
None => Duration::from_secs(240 + stable_jitter(id.as_str())),
|
||||
None => min_delay,
|
||||
Some(UpstreamInfoFailure::Unauthorized | UpstreamInfoFailure::SharingDisabled) => {
|
||||
Duration::from_secs(1800)
|
||||
}
|
||||
@@ -138,8 +141,7 @@ impl PeerInfoService {
|
||||
.max(retry_after.unwrap_or_default());
|
||||
state.next_attempt = Instant::now() + delay;
|
||||
// 管理员修复授权后可主动复核,不继承自动重试的长退避,仍遵守上游限流
|
||||
state.manual_after =
|
||||
Instant::now() + Duration::from_secs(15).max(retry_after.unwrap_or_default());
|
||||
state.manual_after = Instant::now() + min_delay.max(retry_after.unwrap_or_default());
|
||||
state.last_error = failure;
|
||||
let document = match result {
|
||||
Ok(document) => Some(document),
|
||||
@@ -214,12 +216,6 @@ impl PeerInfoService {
|
||||
}
|
||||
}
|
||||
|
||||
fn stable_jitter(id: &str) -> u64 {
|
||||
id.bytes().fold(0_u64, |hash, byte| {
|
||||
hash.wrapping_mul(31).wrapping_add(u64::from(byte))
|
||||
}) % 60
|
||||
}
|
||||
|
||||
fn refresh_error(error: UpstreamInfoFailure) -> Option<ProviderAdminError> {
|
||||
let message = match error {
|
||||
UpstreamInfoFailure::Unauthorized => "上游未授权读取互联信息",
|
||||
|
||||
@@ -12,7 +12,8 @@ use futures::{StreamExt as _, stream};
|
||||
use gateway_core::{
|
||||
account::{
|
||||
LoadedCredential, ProviderAccount, ProviderAccountId, ProviderAccountStore,
|
||||
UpstreamConnection, UpstreamInfoFailure, UpstreamInfoSource, UpstreamSchedulingSignal,
|
||||
QuotaObservationVersion, UpstreamConnection, UpstreamInfoFailure, UpstreamInfoSource,
|
||||
UpstreamSchedulingSignal,
|
||||
},
|
||||
error::{StoreError, StoreErrorKind},
|
||||
routing::ProviderKind,
|
||||
@@ -22,11 +23,12 @@ use gateway_protocol::peer::PeerLink;
|
||||
use std::{
|
||||
collections::{BTreeMap, HashMap},
|
||||
sync::{Arc, Mutex, RwLock},
|
||||
time::SystemTime,
|
||||
time::{Duration, SystemTime},
|
||||
};
|
||||
use tokio::sync::Semaphore;
|
||||
|
||||
const REFRESH_CONCURRENCY: usize = 4;
|
||||
const REFRESH_INTERVAL: Duration = Duration::from_secs(5 * 60);
|
||||
|
||||
pub(super) struct CachedObservation {
|
||||
pub connection: UpstreamConnection,
|
||||
@@ -209,56 +211,35 @@ impl PeerInfoService {
|
||||
if context.cancellation().is_cancelled() {
|
||||
break;
|
||||
}
|
||||
let accounts = match self.accounts.list_for_provider(provider, false).await {
|
||||
let mut accounts = match self.accounts.list_for_provider(provider, false).await {
|
||||
Ok(accounts) => accounts,
|
||||
Err(error) => {
|
||||
failure.get_or_insert(error);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let connections = accounts
|
||||
.iter()
|
||||
.filter(|account| self.supported(account))
|
||||
.map(UpstreamConnection::for_account)
|
||||
.collect::<Vec<_>>();
|
||||
active.extend(
|
||||
connections
|
||||
.iter()
|
||||
.map(|connection| connection.account_id.clone()),
|
||||
);
|
||||
let connections = {
|
||||
accounts.retain(|account| self.supported(account));
|
||||
active.extend(accounts.iter().map(|account| account.id().clone()));
|
||||
if accounts.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let batch = {
|
||||
let mut cursors = self
|
||||
.cursors
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let offset = cursors.entry(provider.clone()).or_default();
|
||||
if *offset >= connections.len() {
|
||||
if *offset >= accounts.len() {
|
||||
*offset = 0;
|
||||
}
|
||||
let batch = connections
|
||||
.iter()
|
||||
.skip(*offset)
|
||||
.take(100)
|
||||
.cloned()
|
||||
.collect::<Vec<_>>();
|
||||
*offset += batch.len();
|
||||
let end = (*offset + 100).min(accounts.len());
|
||||
let batch = &accounts[*offset..end];
|
||||
*offset = end;
|
||||
batch
|
||||
};
|
||||
if let Err(error) = self.read_summaries(&connections).await {
|
||||
if let Err(error) = self.refresh_batch(batch).await {
|
||||
failure.get_or_insert(error);
|
||||
continue;
|
||||
}
|
||||
// 每轮有界并发,运行期到期记录在请求开始时预留,取消后可按普通重试恢复
|
||||
let pending = connections
|
||||
.into_iter()
|
||||
.filter(|connection| self.refresh_due(connection))
|
||||
.take(100)
|
||||
.collect::<Vec<_>>();
|
||||
stream::iter(pending).map(|connection| async move {
|
||||
if let Err(error) = self.refresh(&connection.account_id, false).await {
|
||||
tracing::warn!(account_id = %connection.account_id, error = %error, "Upstream quota refresh failed");
|
||||
}
|
||||
}).buffer_unordered(REFRESH_CONCURRENCY).collect::<Vec<_>>().await;
|
||||
}
|
||||
// 查询失败时保留该轮无法核对的账号,避免错误风暴清空所有节流记录
|
||||
if failure.is_none() && !context.cancellation().is_cancelled() {
|
||||
@@ -279,6 +260,74 @@ impl PeerInfoService {
|
||||
drop(removed);
|
||||
failure.map_or(Ok(()), Err)
|
||||
}
|
||||
|
||||
async fn refresh_batch(&self, accounts: &[ProviderAccount]) -> Result<(), StoreError> {
|
||||
let connections: Vec<_> = accounts
|
||||
.iter()
|
||||
.map(UpstreamConnection::for_account)
|
||||
.collect();
|
||||
self.hydrate(&connections).await?;
|
||||
let now = SystemTime::now();
|
||||
let mut due = Vec::new();
|
||||
let mut stale = Vec::new();
|
||||
{
|
||||
let observations = self
|
||||
.observations
|
||||
.read()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
for (account, connection) in accounts.iter().zip(connections) {
|
||||
let cached = observations
|
||||
.get(account.id())
|
||||
.filter(|c| c.connection == connection);
|
||||
if cached
|
||||
.is_some_and(|c| c.stored_failure == Some(UpstreamInfoFailure::Unsupported))
|
||||
|| !self.retry_ready(&connection)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
// 只有成功识别的快照参与惰性刷新,授权失败等识别记录仍按退避复查
|
||||
let Some(observed_at) = cached
|
||||
.filter(|c| c.summary.is_some())
|
||||
.and_then(|c| c.observed_at)
|
||||
else {
|
||||
due.push(connection.account_id);
|
||||
continue;
|
||||
};
|
||||
let aged = now.duration_since(observed_at).unwrap_or_default() >= REFRESH_INTERVAL;
|
||||
let quota = account.quota();
|
||||
if quota.is_exhausted() {
|
||||
// 已在重置后查过但未获恢复证据时,等下一个复查周期
|
||||
if quota.exhaustion_refresh_due(now, REFRESH_INTERVAL)
|
||||
&& (aged || quota.reset_at().is_some_and(|reset| observed_at < reset))
|
||||
{
|
||||
due.push(connection.account_id);
|
||||
}
|
||||
} else if aged {
|
||||
stale.push(QuotaObservationVersion {
|
||||
account_id: connection.account_id,
|
||||
credential_revision: connection.credential_revision,
|
||||
observed_at,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
// 用量查询失败只影响正常账号,首查与耗尽复查仍可执行
|
||||
let mut outcome = Ok(());
|
||||
if !stale.is_empty() {
|
||||
match self.accounts.accounts_used_since_quota(&stale).await {
|
||||
Ok(active) => due.extend(active),
|
||||
Err(error) => outcome = Err(error),
|
||||
}
|
||||
}
|
||||
stream::iter(due)
|
||||
.for_each_concurrent(REFRESH_CONCURRENCY, |id| async move {
|
||||
if let Err(error) = self.refresh(&id, false).await {
|
||||
tracing::warn!(account_id = %id, error = %error, "Upstream quota refresh failed");
|
||||
}
|
||||
})
|
||||
.await;
|
||||
outcome
|
||||
}
|
||||
}
|
||||
|
||||
impl UpstreamInfoSource for PeerInfoService {
|
||||
|
||||
@@ -85,6 +85,7 @@ impl PluginResourceAccess for DefaultPluginResourceAccess {
|
||||
resource_key,
|
||||
groups,
|
||||
NewClientKey {
|
||||
validity: Default::default(),
|
||||
peer_sharing: Default::default(),
|
||||
id,
|
||||
name: command.name,
|
||||
|
||||
@@ -69,6 +69,18 @@ async fn list_proxies(
|
||||
|
||||
#[async_trait]
|
||||
pub trait ProxiesService: Send + Sync {
|
||||
async fn test_targets(&self) -> Result<ProxyTestTargets, AdminError>;
|
||||
async fn replace_test_targets(
|
||||
&self,
|
||||
settings: ProxyTestTargets,
|
||||
context: &MutationContext,
|
||||
) -> Result<ProxyTestTargets, AdminError>;
|
||||
async fn test_target(
|
||||
&self,
|
||||
proxy_id: &str,
|
||||
name: &str,
|
||||
revision: Revision,
|
||||
) -> Result<(String, TargetProbeResult), AdminError>;
|
||||
async fn create_batch(
|
||||
&self,
|
||||
commands: Vec<Result<NewProxy, AdminError>>,
|
||||
@@ -131,6 +143,12 @@ pub(crate) struct DefaultProxiesService {
|
||||
}
|
||||
|
||||
impl DefaultProxiesService {
|
||||
fn test_slot(&self) -> Result<tokio::sync::SemaphorePermit<'_>, AdminError> {
|
||||
self.test_slots
|
||||
.try_acquire()
|
||||
.map_err(|_| AdminError::new(AdminErrorKind::RateLimited, "代理测试已达并发上限"))
|
||||
}
|
||||
|
||||
pub(crate) fn new(
|
||||
store: Arc<dyn ProxyStore>,
|
||||
probe: Arc<dyn ProxyProbe>,
|
||||
@@ -151,6 +169,84 @@ impl DefaultProxiesService {
|
||||
|
||||
#[async_trait]
|
||||
impl ProxiesService for DefaultProxiesService {
|
||||
async fn test_targets(&self) -> Result<ProxyTestTargets, AdminError> {
|
||||
self.store
|
||||
.test_targets()
|
||||
.await
|
||||
.map_err(|error| map_store_error(error, "proxy test targets"))
|
||||
}
|
||||
|
||||
async fn replace_test_targets(
|
||||
&self,
|
||||
mut settings: ProxyTestTargets,
|
||||
context: &MutationContext,
|
||||
) -> Result<ProxyTestTargets, AdminError> {
|
||||
if settings.targets.len() > 32 {
|
||||
return Err(AdminError::invalid("最多可配置 32 个测试目标"));
|
||||
}
|
||||
let mut names = std::collections::HashSet::new();
|
||||
for target in &mut settings.targets {
|
||||
target.name = target.name.trim().to_owned();
|
||||
if target.name.is_empty()
|
||||
|| target.name.chars().count() > 100
|
||||
|| target.name.chars().any(char::is_control)
|
||||
{
|
||||
return Err(AdminError::invalid("目标名称需要 1 至 100 个字符"));
|
||||
}
|
||||
if !names.insert(target.name.as_str()) {
|
||||
return Err(AdminError::invalid("测试目标名称重复"));
|
||||
}
|
||||
let raw = target.url.trim();
|
||||
let url = url::Url::parse(raw)
|
||||
.ok()
|
||||
.filter(|url| {
|
||||
!raw.chars().any(char::is_control)
|
||||
&& url.scheme() == "https"
|
||||
&& url.has_host()
|
||||
&& url.username().is_empty()
|
||||
&& url.password().is_none()
|
||||
&& url.fragment().is_none()
|
||||
})
|
||||
.ok_or_else(|| AdminError::invalid("请输入不含凭据和片段的 HTTPS 目标地址"))?;
|
||||
if raw.len() > 2048 || url.as_str().len() > 2048 {
|
||||
return Err(AdminError::invalid("目标地址不能超过 2048 字节"));
|
||||
}
|
||||
target.url = url.into();
|
||||
}
|
||||
settings.revision = self
|
||||
.store
|
||||
.replace_test_targets(&settings, context)
|
||||
.await
|
||||
.map_err(|error| map_store_error(error, "proxy test targets"))?;
|
||||
publish_committed(self.snapshot.as_ref(), settings.revision).await?;
|
||||
Ok(settings)
|
||||
}
|
||||
|
||||
async fn test_target(
|
||||
&self,
|
||||
proxy_id: &str,
|
||||
name: &str,
|
||||
revision: Revision,
|
||||
) -> Result<(String, TargetProbeResult), AdminError> {
|
||||
let _permit = self.test_slot()?;
|
||||
let settings = self.test_targets().await?;
|
||||
if settings.revision != revision {
|
||||
return Err(AdminError::conflict("测试目标已更新,请重新选择"));
|
||||
}
|
||||
let target = settings
|
||||
.targets
|
||||
.iter()
|
||||
.find(|target| target.name == name)
|
||||
.ok_or_else(|| AdminError::not_found("测试目标不存在"))?;
|
||||
let record = self
|
||||
.store
|
||||
.get(proxy_id)
|
||||
.await
|
||||
.map_err(|error| map_store_error(error, "proxy"))?;
|
||||
let result = self.probe.test_target(&record.proxy, &target.url).await;
|
||||
Ok((record.name, result))
|
||||
}
|
||||
|
||||
async fn create_batch(
|
||||
&self,
|
||||
commands: Vec<Result<NewProxy, AdminError>>,
|
||||
@@ -394,10 +490,7 @@ impl ProxiesService for DefaultProxiesService {
|
||||
proxy: ProbeRoute<'_>,
|
||||
detect_location: bool,
|
||||
) -> Result<ProxyTestResult, AdminError> {
|
||||
let _permit = self
|
||||
.test_slots
|
||||
.try_acquire()
|
||||
.map_err(|_| AdminError::new(AdminErrorKind::RateLimited, "代理测试已达并发上限"))?;
|
||||
let _permit = self.test_slot()?;
|
||||
Ok(self.probe.test(proxy, detect_location).await)
|
||||
}
|
||||
|
||||
@@ -408,10 +501,7 @@ impl ProxiesService for DefaultProxiesService {
|
||||
detect_location: bool,
|
||||
context: &MutationContext,
|
||||
) -> Result<ProxyRecord, AdminError> {
|
||||
let _permit = self
|
||||
.test_slots
|
||||
.try_acquire()
|
||||
.map_err(|_| AdminError::new(AdminErrorKind::RateLimited, "代理测试已达并发上限"))?;
|
||||
let _permit = self.test_slot()?;
|
||||
let record = self
|
||||
.store
|
||||
.get(id)
|
||||
|
||||
@@ -22,6 +22,17 @@ use super::{map_store_error, publish_committed};
|
||||
/// API 消费的 Runtime settings 管理服务
|
||||
#[async_trait]
|
||||
pub trait SettingsService: Send + Sync {
|
||||
async fn preview_prompt_rewrite(
|
||||
&self,
|
||||
request: gateway_core::settings::prompt_rewrite::PromptRewritePreviewRequest,
|
||||
) -> Result<gateway_core::settings::prompt_rewrite::PromptRewritePreviewResult, AdminError>
|
||||
{
|
||||
request
|
||||
.rule
|
||||
.preview(&request.text)
|
||||
.map_err(|_| AdminError::invalid("正则表达式无效或超出编译大小限制"))
|
||||
}
|
||||
|
||||
async fn preview_privacy_policy(
|
||||
&self,
|
||||
_request: gateway_core::settings::privacy::PrivacyPreviewRequest,
|
||||
@@ -117,7 +128,22 @@ fn validate_settings(command: &ReplaceRuntimeSettings) -> Result<(), AdminError>
|
||||
)
|
||||
.map_err(|_| AdminError::invalid("运行时设置不满足约束"))?;
|
||||
command.values.validate().map_err(|field| match field {
|
||||
"openai_request_country" => AdminError::invalid("请求国家必须是两位大写 ASCII 字母"),
|
||||
"prompt_rewrite_rules" => AdminError::invalid("正则表达式无效或超出编译大小限制"),
|
||||
"openai_websocket_pool.fast_path_budget_ms" => {
|
||||
AdminError::invalid("WS 建连等待时间须为 1–15000 毫秒")
|
||||
}
|
||||
"openai_websocket_pool.max_age_ms"
|
||||
| "openai_websocket_pool.idle_timeout_ms"
|
||||
| "openai_websocket_pool.max_connecting" => {
|
||||
AdminError::invalid("WS 连接寿命、空闲回收时间和最大并发建连数必须大于零")
|
||||
}
|
||||
"openai_request_settings.residency"
|
||||
| "openai_request_settings.account_routing_override" => {
|
||||
AdminError::invalid("数据驻留和账号路由必须是有效的单行请求头值")
|
||||
}
|
||||
"openai_request_settings.request_country" => {
|
||||
AdminError::invalid("请求国家必须是两位大写 ASCII 字母")
|
||||
}
|
||||
_ => AdminError::invalid("运行时设置不满足约束"),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -740,6 +740,7 @@ impl FakeAccountStore {
|
||||
last_error_message: account.last_error_message.clone(),
|
||||
};
|
||||
AccountPageItem {
|
||||
platform_icon: None,
|
||||
protection_rules: Vec::new(),
|
||||
capacity: gateway_admin::model::accounts::AccountCapacity {
|
||||
used_slots: None,
|
||||
@@ -1200,8 +1201,11 @@ impl SettingsStore for StaticSettingsStore {
|
||||
rotation_strategy: RotationStrategy::Smart,
|
||||
updated_at: Utc::now(),
|
||||
values: gateway_admin::model::settings::RuntimeSettingsValues {
|
||||
openai_oauth_guardian_review_model: false,
|
||||
openai_request_country: Default::default(),
|
||||
openai_websocket_pool: Default::default(),
|
||||
openai_request_settings: gateway_core::settings::OpenAiRequestSettings {
|
||||
oauth_guardian_review_model: false,
|
||||
..Default::default()
|
||||
},
|
||||
codex_privacy_policy: Default::default(),
|
||||
request_location_enabled: false,
|
||||
request_location: Default::default(),
|
||||
@@ -1226,6 +1230,7 @@ impl SettingsStore for StaticSettingsStore {
|
||||
usage_retention_days: 30,
|
||||
ops_event_retention_days: 30,
|
||||
audit_retention_days: 30,
|
||||
prompt_rewrite_rules: Vec::new(),
|
||||
account_error_protection: gateway_core::account::AccountErrorProtection::default(),
|
||||
account_warmup_enabled: false,
|
||||
account_warmup_cron: "0 8 * * *".to_owned(),
|
||||
@@ -1891,6 +1896,7 @@ async fn accounts_update_should_commit_then_release_disabled_account_and_publish
|
||||
.update(
|
||||
&context("update-request"),
|
||||
UpdateAccount {
|
||||
platform_icon: None,
|
||||
name: None,
|
||||
notes: None,
|
||||
model_access: Default::default(),
|
||||
@@ -1931,6 +1937,7 @@ async fn accounts_update_should_not_notify_provider_when_store_commit_fails() {
|
||||
.update(
|
||||
&context("update-failure"),
|
||||
UpdateAccount {
|
||||
platform_icon: None,
|
||||
name: None,
|
||||
notes: None,
|
||||
model_access: Default::default(),
|
||||
@@ -4013,6 +4020,7 @@ fn unsupported() -> ProviderAdminError {
|
||||
|
||||
pub(super) fn import_settings() -> gateway_admin::model::accounts::AccountImportSettings {
|
||||
gateway_admin::model::accounts::AccountImportSettings {
|
||||
platform_icon: None,
|
||||
name: None,
|
||||
notes: Some("团队备用".to_owned()),
|
||||
model_access: Default::default(),
|
||||
|
||||
@@ -151,6 +151,7 @@ impl ClientKeyStore for TestClientKeyStore {
|
||||
}
|
||||
self.plaintexts.lock().unwrap().push(key.plaintext);
|
||||
let record = ClientKeyRecord {
|
||||
validity: Default::default(),
|
||||
peer_sharing: key.peer_sharing,
|
||||
request_profile_overrides: Default::default(),
|
||||
id: key.id,
|
||||
@@ -318,6 +319,7 @@ async fn plugin_client_key_list_projects_only_public_identity_and_uses_stable_na
|
||||
list_response: Mutex::new(Some(ClientKeyPage {
|
||||
config_revision: Revision::new(7).expect("revision"),
|
||||
items: vec![ClientKeyRecord {
|
||||
validity: Default::default(),
|
||||
peer_sharing: Default::default(),
|
||||
request_profile_overrides: Default::default(),
|
||||
id: key_id.clone(),
|
||||
@@ -455,6 +457,7 @@ async fn duplicate_names_report_the_same_actionable_conflict_on_create_and_updat
|
||||
.update(
|
||||
&mutation_context(),
|
||||
UpdateClientKey {
|
||||
validity: Default::default(),
|
||||
peer_sharing: None,
|
||||
request_profile_override_updates: Default::default(),
|
||||
id: ClientApiKeyId::new("key_existing").unwrap(),
|
||||
@@ -476,6 +479,7 @@ async fn duplicate_names_report_the_same_actionable_conflict_on_create_and_updat
|
||||
|
||||
fn create_command(key: Option<&str>) -> CreateClientKey {
|
||||
CreateClientKey {
|
||||
validity: Default::default(),
|
||||
peer_sharing: Default::default(),
|
||||
request_profile_overrides: Default::default(),
|
||||
custom_key: key.map(|value| PlaintextClientApiKey::new(value).unwrap()),
|
||||
@@ -570,6 +574,7 @@ async fn duplicate_group_ids_are_rejected_before_key_creation_or_update() {
|
||||
.update(
|
||||
&mutation_context(),
|
||||
UpdateClientKey {
|
||||
validity: Default::default(),
|
||||
peer_sharing: None,
|
||||
request_profile_override_updates: Default::default(),
|
||||
id: ClientApiKeyId::new("key_existing").unwrap(),
|
||||
@@ -592,6 +597,7 @@ async fn duplicate_group_ids_are_rejected_before_key_creation_or_update() {
|
||||
async fn clearing_an_unregistered_provider_profile_is_rejected_before_writing() {
|
||||
let services = super::AdminHarness::new().build().await;
|
||||
let command = UpdateClientKey {
|
||||
validity: None,
|
||||
id: ClientApiKeyId::new("key_existing").unwrap(),
|
||||
name: "test".to_owned(),
|
||||
label: None,
|
||||
|
||||
@@ -33,8 +33,11 @@ fn runtime_settings(enabled: bool, probe_enabled: bool) -> RuntimeSettings {
|
||||
rotation_strategy: gateway_admin::model::settings::RotationStrategy::Smart,
|
||||
updated_at: Utc::now(),
|
||||
values: gateway_admin::model::settings::RuntimeSettingsValues {
|
||||
openai_oauth_guardian_review_model: false,
|
||||
openai_request_country: Default::default(),
|
||||
openai_websocket_pool: Default::default(),
|
||||
openai_request_settings: gateway_core::settings::OpenAiRequestSettings {
|
||||
oauth_guardian_review_model: false,
|
||||
..Default::default()
|
||||
},
|
||||
codex_privacy_policy: Default::default(),
|
||||
request_location_enabled: false,
|
||||
request_location: Default::default(),
|
||||
@@ -59,6 +62,7 @@ fn runtime_settings(enabled: bool, probe_enabled: bool) -> RuntimeSettings {
|
||||
usage_retention_days: 31,
|
||||
ops_event_retention_days: 30,
|
||||
audit_retention_days: 90,
|
||||
prompt_rewrite_rules: Vec::new(),
|
||||
account_error_protection: gateway_core::account::AccountErrorProtection {
|
||||
enabled,
|
||||
probe_enabled,
|
||||
|
||||
@@ -516,6 +516,7 @@ async fn dashboard_should_preserve_provider_plan_names() {
|
||||
*store.account_usage.lock().unwrap() = plans
|
||||
.iter()
|
||||
.map(|(plan, _)| DashboardAccountUsage {
|
||||
platform_icon: None,
|
||||
upstream: None,
|
||||
account_id: format!("account-{plan}"),
|
||||
provider_kind: "openai".to_owned(),
|
||||
|
||||
@@ -43,6 +43,9 @@ fn usage_error_origin_recognizes_unambiguous_failure_kinds() {
|
||||
("no_available_provider", Proxy),
|
||||
("no_eligible_account", Proxy),
|
||||
("account_capacity_unavailable", Proxy),
|
||||
("account_pool_quota_exhausted", Proxy),
|
||||
("key_rate_limited", Proxy),
|
||||
("key_concurrency_limited", Proxy),
|
||||
("middleware_capacity_unavailable", Proxy),
|
||||
("concurrency_queue_full", Proxy),
|
||||
("concurrency_queue_timeout", Proxy),
|
||||
|
||||
@@ -337,8 +337,11 @@ impl SettingsStore for FixtureSettingsStore {
|
||||
rotation_strategy: RotationStrategy::Smart,
|
||||
updated_at: Utc::now(),
|
||||
values: gateway_admin::model::settings::RuntimeSettingsValues {
|
||||
openai_oauth_guardian_review_model: false,
|
||||
openai_request_country: Default::default(),
|
||||
openai_websocket_pool: Default::default(),
|
||||
openai_request_settings: gateway_core::settings::OpenAiRequestSettings {
|
||||
oauth_guardian_review_model: false,
|
||||
..Default::default()
|
||||
},
|
||||
codex_privacy_policy: Default::default(),
|
||||
request_location_enabled: false,
|
||||
request_location: Default::default(),
|
||||
@@ -363,6 +366,7 @@ impl SettingsStore for FixtureSettingsStore {
|
||||
usage_retention_days: 31,
|
||||
ops_event_retention_days: 30,
|
||||
audit_retention_days: 30,
|
||||
prompt_rewrite_rules: Vec::new(),
|
||||
account_error_protection: gateway_core::account::AccountErrorProtection::default(),
|
||||
account_warmup_enabled: false,
|
||||
account_warmup_cron: "0 8 * * *".to_owned(),
|
||||
@@ -447,6 +451,7 @@ fn total_record(
|
||||
now: DateTime<Utc>,
|
||||
) -> UsageListRecord {
|
||||
UsageListRecord {
|
||||
platform_icon: None,
|
||||
provider_account_upstream_peer: None,
|
||||
has_upstream_error: false,
|
||||
error_code: None,
|
||||
@@ -538,9 +543,11 @@ fn diagnostic(name: &str, request_count: u64) -> DiagnosticObservation {
|
||||
caller_error_count: 0,
|
||||
retry_count: 0,
|
||||
retried_request_count: 0,
|
||||
account_provider_kind: None,
|
||||
providers: vec![],
|
||||
platform_icon: None,
|
||||
account_authentication_kind: None,
|
||||
account_plan_type: None,
|
||||
account_plan_type_display: None,
|
||||
key: name.to_owned(),
|
||||
name: name.to_owned(),
|
||||
request_count,
|
||||
|
||||
@@ -49,6 +49,7 @@ async fn manual_and_periodic_refreshes_share_capacity_and_release_it_after_failu
|
||||
let accounts = Arc::new(TestAccounts {
|
||||
accounts: Mutex::new(records.clone()),
|
||||
records: Mutex::default(),
|
||||
last_generation: Mutex::default(),
|
||||
failed_provider: None,
|
||||
});
|
||||
let transport = Arc::new(GatedTransport::new());
|
||||
@@ -113,6 +114,7 @@ async fn queued_refresh_reads_current_account_after_capacity_becomes_available()
|
||||
let accounts = Arc::new(TestAccounts {
|
||||
accounts: Mutex::new(records.clone()),
|
||||
records: Mutex::default(),
|
||||
last_generation: Mutex::default(),
|
||||
failed_provider: None,
|
||||
});
|
||||
let transport = Arc::new(GatedTransport::new());
|
||||
@@ -232,6 +234,7 @@ async fn discovery_uses_provider_capabilities_and_publishes_neutral_signals() {
|
||||
account("acct_native", "xai", "oauth"),
|
||||
]),
|
||||
records: Mutex::default(),
|
||||
last_generation: Mutex::default(),
|
||||
failed_provider,
|
||||
});
|
||||
let transport = Arc::new(TestTransport(Mutex::new(Vec::new())));
|
||||
@@ -329,6 +332,7 @@ async fn account_edits_preserve_observation_and_refresh_budget_until_connection_
|
||||
let accounts = Arc::new(TestAccounts {
|
||||
accounts: Mutex::new(vec![initial.clone()]),
|
||||
records: Mutex::default(),
|
||||
last_generation: Mutex::default(),
|
||||
failed_provider: None,
|
||||
});
|
||||
let transport = Arc::new(TestTransport(Mutex::new(Vec::new())));
|
||||
@@ -403,22 +407,29 @@ impl PeerTransport for TestTransport {
|
||||
.lock()
|
||||
.unwrap()
|
||||
.push(account.id().as_str().to_owned());
|
||||
let now = Utc::now();
|
||||
Ok(serde_json::to_vec(&serde_json::json!({
|
||||
"object":"cpr.peer", "schema_version":3,
|
||||
"observed_at":now.to_rfc3339(),
|
||||
"expires_at":(now + chrono::Duration::minutes(5)).to_rfc3339(),
|
||||
"capabilities":["key_usage"],
|
||||
"usage":{"status":"available","observed_at":now.to_rfc3339(),"data":{"unit":"USD","allowed":false,
|
||||
"windows":[{"key":"daily","total":"1","used":"1","remaining":"0","reset_at":(now + chrono::Duration::days(1)).to_rfc3339()}]}},
|
||||
"models":[]
|
||||
})).unwrap())
|
||||
Ok(peer_snapshot(false))
|
||||
}
|
||||
}
|
||||
|
||||
fn peer_snapshot(allowed: bool) -> Vec<u8> {
|
||||
let now = Utc::now();
|
||||
let (used, remaining) = if allowed { ("0", "1") } else { ("1", "0") };
|
||||
serde_json::to_vec(&serde_json::json!({
|
||||
"object":"cpr.peer", "schema_version":3,
|
||||
"observed_at":now.to_rfc3339(),
|
||||
"expires_at":(now + chrono::Duration::minutes(5)).to_rfc3339(),
|
||||
"capabilities":["key_usage", "key_limits"],
|
||||
"key_limits":{"max_concurrency":4},
|
||||
"usage":{"status":"available","observed_at":now.to_rfc3339(),"data":{"unit":"USD","allowed":allowed,
|
||||
"windows":[{"key":"daily","total":"1","used":used,"remaining":remaining,"reset_at":(now + chrono::Duration::days(1)).to_rfc3339()}]}},
|
||||
"models":[]
|
||||
})).unwrap()
|
||||
}
|
||||
|
||||
struct TestAccounts {
|
||||
accounts: Mutex<Vec<ProviderAccount>>,
|
||||
records: Mutex<BTreeMap<ProviderAccountId, QuotaObservation>>,
|
||||
last_generation: Mutex<BTreeMap<ProviderAccountId, SystemTime>>,
|
||||
failed_provider: Option<&'static str>,
|
||||
}
|
||||
|
||||
@@ -549,6 +560,22 @@ impl ProviderAccountStore for TestAccounts {
|
||||
.filter_map(|id| stored.get(id).cloned())
|
||||
.collect())
|
||||
}
|
||||
async fn accounts_used_since_quota(
|
||||
&self,
|
||||
snapshots: &[QuotaObservationVersion],
|
||||
) -> Result<Vec<ProviderAccountId>, StoreError> {
|
||||
let completed = self.last_generation.lock().unwrap();
|
||||
Ok(snapshots
|
||||
.iter()
|
||||
.filter(|s| {
|
||||
completed
|
||||
.get(&s.account_id)
|
||||
.is_some_and(|at| *at > s.observed_at)
|
||||
})
|
||||
.map(|s| s.account_id.clone())
|
||||
.collect())
|
||||
}
|
||||
|
||||
async fn compare_and_swap_quota(
|
||||
&self,
|
||||
observation: QuotaObservation,
|
||||
|
||||
@@ -48,11 +48,94 @@ async fn unsupported_detection_survives_restart_until_manual_rediscovery() {
|
||||
let discovered = restarted.service().refresh_quota(&id).await.unwrap();
|
||||
assert!(discovered.upstream.unwrap().discovered);
|
||||
assert_eq!(transport.requests.load(Ordering::SeqCst), 2);
|
||||
tokio::time::advance(Duration::from_secs(360)).await;
|
||||
cycle(&resumed_worker).await;
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn healthy_peer_refresh_requires_generation_after_an_aged_local_snapshot() {
|
||||
let (mut bundle, accounts, transport, id) = fixture(UpstreamInfoFailure::Unavailable);
|
||||
*transport.failure.lock().unwrap() = None;
|
||||
cycle(&worker(&mut bundle)).await;
|
||||
let initial = accounts.records.lock().unwrap()[&id].observed_at;
|
||||
|
||||
let mut restarted = initialize(accounts.clone(), transport.clone());
|
||||
let worker = worker(&mut restarted);
|
||||
accounts
|
||||
.last_generation
|
||||
.lock()
|
||||
.unwrap()
|
||||
.insert(id.clone(), initial + Duration::from_secs(1));
|
||||
cycle(&worker).await;
|
||||
assert_eq!(transport.requests.load(Ordering::SeqCst), 1);
|
||||
assert!(
|
||||
restarted
|
||||
.scheduling_source()
|
||||
.is_peer(&accounts.accounts.lock().unwrap()[0])
|
||||
);
|
||||
|
||||
let old = initial - Duration::from_secs(600);
|
||||
accounts
|
||||
.records
|
||||
.lock()
|
||||
.unwrap()
|
||||
.get_mut(&id)
|
||||
.unwrap()
|
||||
.observed_at = old;
|
||||
accounts
|
||||
.last_generation
|
||||
.lock()
|
||||
.unwrap()
|
||||
.insert(id.clone(), old);
|
||||
cycle(&worker).await;
|
||||
assert_eq!(transport.requests.load(Ordering::SeqCst), 1);
|
||||
|
||||
accounts
|
||||
.last_generation
|
||||
.lock()
|
||||
.unwrap()
|
||||
.insert(id.clone(), old + Duration::from_secs(1));
|
||||
cycle(&worker).await;
|
||||
tokio::time::advance(Duration::from_secs(600)).await;
|
||||
cycle(&worker).await;
|
||||
assert_eq!(transport.requests.load(Ordering::SeqCst), 2);
|
||||
restarted.service().refresh_quota(&id).await.unwrap();
|
||||
assert_eq!(transport.requests.load(Ordering::SeqCst), 3);
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn exhausted_peer_rechecks_at_reset_or_after_five_minutes_without_usage() {
|
||||
let (mut bundle, accounts, transport, id) = fixture(UpstreamInfoFailure::Unavailable);
|
||||
*transport.failure.lock().unwrap() = None;
|
||||
let worker = worker(&mut bundle);
|
||||
cycle(&worker).await;
|
||||
let now = SystemTime::now();
|
||||
let old = now - Duration::from_secs(600);
|
||||
let account = accounts.accounts.lock().unwrap()[0].clone();
|
||||
for (exhausted_at, reset_at, expected) in [
|
||||
(old, Some(now + Duration::from_secs(600)), 1),
|
||||
(old, Some(now), 2),
|
||||
(now, None, 2),
|
||||
(old, None, 3),
|
||||
] {
|
||||
accounts
|
||||
.records
|
||||
.lock()
|
||||
.unwrap()
|
||||
.get_mut(&id)
|
||||
.unwrap()
|
||||
.observed_at = old;
|
||||
accounts.accounts.lock().unwrap()[0] = account.clone().with_account_facts(
|
||||
true,
|
||||
CredentialState::Ready,
|
||||
QuotaState::exhausted(QuotaEvidence::ProviderDenied, exhausted_at, reset_at),
|
||||
None,
|
||||
None,
|
||||
);
|
||||
tokio::time::advance(Duration::from_secs(30)).await;
|
||||
cycle(&worker).await;
|
||||
assert_eq!(transport.requests.load(Ordering::SeqCst), expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn unsupported_detection_keeps_manual_refresh_throttling() {
|
||||
for retry_after in [None, Some(Duration::from_secs(90))] {
|
||||
@@ -382,12 +465,12 @@ fn fixture(
|
||||
let accounts = Arc::new(TestAccounts {
|
||||
accounts: Mutex::new(vec![record]),
|
||||
records: Mutex::default(),
|
||||
last_generation: Mutex::default(),
|
||||
failed_provider: None,
|
||||
});
|
||||
let transport = Arc::new(DetectionTransport {
|
||||
requests: AtomicUsize::new(0),
|
||||
failure: Mutex::new(Some(failure.into())),
|
||||
success: TestTransport(Mutex::default()),
|
||||
});
|
||||
(
|
||||
initialize(accounts.clone(), transport.clone()),
|
||||
@@ -432,15 +515,14 @@ async fn cycle(worker: &WorkerRegistration) {
|
||||
struct DetectionTransport {
|
||||
requests: AtomicUsize,
|
||||
failure: Mutex<Option<PeerFetchFailure>>,
|
||||
success: TestTransport,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl PeerTransport for DetectionTransport {
|
||||
async fn fetch(
|
||||
&self,
|
||||
account: &ProviderAccount,
|
||||
connection: &PeerConnection,
|
||||
_account: &ProviderAccount,
|
||||
_connection: &PeerConnection,
|
||||
) -> Result<Vec<u8>, PeerFetchFailure> {
|
||||
self.requests.fetch_add(1, Ordering::SeqCst);
|
||||
if let Some(failure) = self.failure.lock().unwrap().as_ref() {
|
||||
@@ -449,6 +531,6 @@ impl PeerTransport for DetectionTransport {
|
||||
retry_after: failure.retry_after,
|
||||
});
|
||||
}
|
||||
self.success.fetch(account, connection).await
|
||||
Ok(peer_snapshot(true))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -100,6 +100,20 @@ impl SnapshotControl for Fixture {
|
||||
|
||||
#[async_trait]
|
||||
impl ProxyStore for Fixture {
|
||||
async fn test_targets(
|
||||
&self,
|
||||
) -> gateway_admin::ports::store::AdminStoreResult<
|
||||
gateway_admin::model::proxies::ProxyTestTargets,
|
||||
> {
|
||||
unreachable!()
|
||||
}
|
||||
async fn replace_test_targets(
|
||||
&self,
|
||||
_: &gateway_admin::model::proxies::ProxyTestTargets,
|
||||
_: &gateway_admin::model::MutationContext,
|
||||
) -> gateway_admin::ports::store::AdminStoreResult<gateway_admin::model::Revision> {
|
||||
unreachable!()
|
||||
}
|
||||
async fn reserve_import(&self, _: &str) -> AdminStoreResult<ProxyImportReservation> {
|
||||
unreachable!()
|
||||
}
|
||||
|
||||
@@ -39,6 +39,20 @@ pub(super) struct TestPluginPorts;
|
||||
|
||||
#[async_trait]
|
||||
impl gateway_admin::ports::proxy::ProxyStore for TestPluginPorts {
|
||||
async fn test_targets(
|
||||
&self,
|
||||
) -> gateway_admin::ports::store::AdminStoreResult<
|
||||
gateway_admin::model::proxies::ProxyTestTargets,
|
||||
> {
|
||||
unreachable!()
|
||||
}
|
||||
async fn replace_test_targets(
|
||||
&self,
|
||||
_: &gateway_admin::model::proxies::ProxyTestTargets,
|
||||
_: &gateway_admin::model::MutationContext,
|
||||
) -> gateway_admin::ports::store::AdminStoreResult<gateway_admin::model::Revision> {
|
||||
unreachable!()
|
||||
}
|
||||
async fn reserve_import(
|
||||
&self,
|
||||
_: &str,
|
||||
|
||||
@@ -39,6 +39,20 @@ impl ProxyStore for TestProxies {
|
||||
Err(super::unavailable("proxy"))
|
||||
}
|
||||
|
||||
async fn test_targets(
|
||||
&self,
|
||||
) -> gateway_admin::ports::store::AdminStoreResult<
|
||||
gateway_admin::model::proxies::ProxyTestTargets,
|
||||
> {
|
||||
unreachable!()
|
||||
}
|
||||
async fn replace_test_targets(
|
||||
&self,
|
||||
_: &gateway_admin::model::proxies::ProxyTestTargets,
|
||||
_: &gateway_admin::model::MutationContext,
|
||||
) -> gateway_admin::ports::store::AdminStoreResult<gateway_admin::model::Revision> {
|
||||
unreachable!()
|
||||
}
|
||||
async fn reserve_import(
|
||||
&self,
|
||||
id: &str,
|
||||
@@ -194,6 +208,14 @@ async fn plugin_proxy_resolution_requires_enabled_configuration_without_account_
|
||||
|
||||
#[async_trait]
|
||||
impl ProxyProbe for TestProxies {
|
||||
async fn test_target(
|
||||
&self,
|
||||
_: &gateway_core::account::OutboundProxy,
|
||||
_: &str,
|
||||
) -> gateway_admin::model::proxies::TargetProbeResult {
|
||||
unreachable!()
|
||||
}
|
||||
|
||||
async fn test(&self, _: ProbeRoute<'_>, _: bool) -> ProxyTestResult {
|
||||
panic!("unexpected proxy probe")
|
||||
}
|
||||
@@ -333,6 +355,7 @@ async fn linked_accounts_share_plan_resolution_and_only_read_cached_quota() {
|
||||
.provider(provider.clone())
|
||||
.proxies(Arc::new(TestProxies {
|
||||
accounts: Some(vec![ProxyAccountRef {
|
||||
platform_icon: None,
|
||||
upstream: None,
|
||||
id: "acct_plan".to_owned(),
|
||||
name: "套餐测试".to_owned(),
|
||||
@@ -487,6 +510,14 @@ impl Drop for ActiveProbe<'_> {
|
||||
|
||||
#[async_trait]
|
||||
impl ProxyProbe for GatedProxyProbe {
|
||||
async fn test_target(
|
||||
&self,
|
||||
_: &gateway_core::account::OutboundProxy,
|
||||
_: &str,
|
||||
) -> gateway_admin::model::proxies::TargetProbeResult {
|
||||
unreachable!()
|
||||
}
|
||||
|
||||
async fn test(&self, _: ProbeRoute<'_>, _: bool) -> ProxyTestResult {
|
||||
self.active
|
||||
.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
|
||||
@@ -56,7 +56,10 @@ impl VisitMut for WireTypes {
|
||||
}
|
||||
let last = path.path.segments.last().unwrap().clone();
|
||||
*ty = match last.ident.to_string().as_str() {
|
||||
"DateTime" | "Tz" | "TokenPrice" | "AdminApiKey" => parse_quote!(String),
|
||||
"DateTime" | "Tz" | "TokenPrice" | "AdminApiKey" | "ProviderKind"
|
||||
| "PromptPattern" => {
|
||||
parse_quote!(String)
|
||||
}
|
||||
"Value" => parse_quote!(serde_json::Value),
|
||||
"OpaqueProviderData" => parse_quote!(serde_json::Map<String, serde_json::Value>),
|
||||
_ => Type::Path(syn::TypePath {
|
||||
@@ -80,6 +83,9 @@ fn contract_type(mut item: Item, name: &str) -> Item {
|
||||
| "ReplaceRuntimeSettings"
|
||||
| "AdminApiKeyMutation"
|
||||
| "RegeneratedAdminApiKey"
|
||||
| "PromptRewriteRule"
|
||||
| "PromptRewritePreviewRequest"
|
||||
| "PromptRewritePreviewResult"
|
||||
| "CodexPrivacyPolicy"
|
||||
| "PrivacyRule"
|
||||
| "PrivacyStep"
|
||||
@@ -113,6 +119,15 @@ fn contract_type(mut item: Item, name: &str) -> Item {
|
||||
if let Some(fields) = fields {
|
||||
for field in fields {
|
||||
field.vis = parse_quote!(pub);
|
||||
// 非空名称与前缀由宿主在接收设置时校验,SDK 只描述字符串合同
|
||||
if name == "PromptRewriteRule"
|
||||
&& field
|
||||
.ident
|
||||
.as_ref()
|
||||
.is_some_and(|id| id == "pattern" || id == "name")
|
||||
{
|
||||
field.attrs.retain(|attr| !attr.path().is_ident("serde"));
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Item::Enum(item) = &mut item {
|
||||
@@ -225,6 +240,23 @@ fn sdk_settings_contract_matches_host_declarations() {
|
||||
"AccountErrorOperator",
|
||||
][..],
|
||||
),
|
||||
(
|
||||
"../gateway-core/src/settings/prompt_rewrite.rs",
|
||||
&[
|
||||
"PromptRewriteRule",
|
||||
"PromptMatchMode",
|
||||
"PromptRewritePreviewRequest",
|
||||
"PromptRewritePreviewResult",
|
||||
][..],
|
||||
),
|
||||
(
|
||||
"../gateway-core/src/settings/websocket.rs",
|
||||
&["OpenAiWebSocketPoolSettings"][..],
|
||||
),
|
||||
(
|
||||
"../gateway-core/src/settings/openai.rs",
|
||||
&["OpenAiRequestSettings", "OpenAiRequestCountry"][..],
|
||||
),
|
||||
(
|
||||
"../gateway-core/src/settings/privacy.rs",
|
||||
&[
|
||||
@@ -254,7 +286,7 @@ fn sdk_settings_contract_matches_host_declarations() {
|
||||
),
|
||||
(
|
||||
"../gateway-core/src/account/location.rs",
|
||||
&["RequestLocation", "OpenAiRequestCountry"][..],
|
||||
&["RequestLocation"][..],
|
||||
),
|
||||
(
|
||||
"../gateway-core/src/account/scheduling.rs",
|
||||
|
||||
@@ -349,8 +349,8 @@ async fn settings_should_reject_zero_refresh_margin_before_store_call() {
|
||||
model_mappings: Default::default(),
|
||||
rotation_strategy: RotationStrategy::Smart,
|
||||
values: gateway_admin::model::settings::RuntimeSettingsValues {
|
||||
openai_oauth_guardian_review_model: true,
|
||||
openai_request_country: Default::default(),
|
||||
openai_websocket_pool: Default::default(),
|
||||
openai_request_settings: Default::default(),
|
||||
codex_privacy_policy: Default::default(),
|
||||
request_location_enabled: false,
|
||||
request_location: Default::default(),
|
||||
@@ -376,6 +376,7 @@ async fn settings_should_reject_zero_refresh_margin_before_store_call() {
|
||||
usage_retention_days: 31,
|
||||
ops_event_retention_days: 30,
|
||||
audit_retention_days: 30,
|
||||
prompt_rewrite_rules: Vec::new(),
|
||||
account_error_protection:
|
||||
gateway_core::account::AccountErrorProtection::default(),
|
||||
account_warmup_enabled: false,
|
||||
|
||||
@@ -2,6 +2,25 @@
|
||||
|
||||
use super::*;
|
||||
|
||||
pub(super) async fn validate_platform_icons(
|
||||
state: &impl crate::SessionState,
|
||||
names: &[&str],
|
||||
) -> Result<(), AdminError> {
|
||||
if names.iter().any(|name| !name.is_empty()) {
|
||||
let catalog = state
|
||||
.platform_icon_names()
|
||||
.await
|
||||
.map_err(|_| AdminError::service_unavailable())?;
|
||||
if names
|
||||
.iter()
|
||||
.any(|&name| !name.is_empty() && !catalog.contains(name))
|
||||
{
|
||||
return Err(map_wire_error(WireValidationError::new("platformIcon")));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_account_notes(notes: Option<&str>) -> Result<(), WireValidationError> {
|
||||
if notes.is_some_and(|notes| {
|
||||
notes.chars().count() > 500
|
||||
@@ -22,6 +41,8 @@ fn parse_provider(value: &str) -> Result<ProviderKind, WireValidationError> {
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct AccountImportSettingsRequest {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub platform_icon: Option<String>,
|
||||
pub name: Option<String>,
|
||||
pub notes: Option<String>,
|
||||
pub enabled: bool,
|
||||
@@ -52,6 +73,7 @@ impl AccountImportSettingsRequest {
|
||||
.name
|
||||
.map(|name| name.trim().to_owned())
|
||||
.filter(|name| !name.is_empty()),
|
||||
platform_icon: self.platform_icon,
|
||||
notes: self.notes,
|
||||
enabled: self.enabled,
|
||||
concurrency_limit: parse_concurrency_limit(self.concurrency_limit)?,
|
||||
@@ -213,6 +235,7 @@ fn validate_authorization_flow(
|
||||
#[derive(Clone, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct UpdateAccountRequest {
|
||||
pub platform_icon: Option<String>,
|
||||
pub connection: Option<AccountConnectionUpdateRequest>,
|
||||
pub outbound_proxy_id: Option<String>,
|
||||
pub account_id: String,
|
||||
@@ -253,6 +276,7 @@ impl UpdateAccountRequest {
|
||||
outbound_proxy: super::wire::proxy_selection(self.outbound_proxy_id)?,
|
||||
account_id: self.account_id,
|
||||
name: self.name.map(|name| name.trim().to_owned()),
|
||||
platform_icon: self.platform_icon,
|
||||
notes: self.notes,
|
||||
enabled: self.enabled,
|
||||
concurrency_limit: parse_concurrency_limit(self.concurrency_limit)?,
|
||||
|
||||
@@ -182,6 +182,15 @@ async fn import_accounts<S>(
|
||||
where
|
||||
S: SessionState + Send + Sync,
|
||||
{
|
||||
super::credentials::validate_platform_icons(
|
||||
&state,
|
||||
request
|
||||
.settings
|
||||
.as_ref()
|
||||
.and_then(|settings| settings.platform_icon.as_deref())
|
||||
.as_slice(),
|
||||
)
|
||||
.await?;
|
||||
let (provider, command) = request
|
||||
.into_command(auth.context().mutation_context())
|
||||
.map_err(map_wire_error)?;
|
||||
@@ -232,6 +241,15 @@ async fn complete_account_authorization<S>(
|
||||
where
|
||||
S: SessionState + Send + Sync,
|
||||
{
|
||||
super::credentials::validate_platform_icons(
|
||||
&state,
|
||||
request
|
||||
.settings
|
||||
.as_ref()
|
||||
.and_then(|settings| settings.platform_icon.as_deref())
|
||||
.as_slice(),
|
||||
)
|
||||
.await?;
|
||||
let (provider, command) = request
|
||||
.into_command(auth.context().mutation_context())
|
||||
.map_err(map_wire_error)?;
|
||||
@@ -255,6 +273,11 @@ async fn update_account<S>(
|
||||
where
|
||||
S: SessionState + Send + Sync,
|
||||
{
|
||||
super::credentials::validate_platform_icons(
|
||||
&state,
|
||||
request.platform_icon.as_deref().as_slice(),
|
||||
)
|
||||
.await?;
|
||||
let (command, connection) = request.into_command().map_err(map_wire_error)?;
|
||||
let context = auth.context().mutation_context();
|
||||
let result = if let Some(provider_material) = connection {
|
||||
|
||||
@@ -149,6 +149,12 @@ where
|
||||
if request.items.is_empty() || request.items.len() > MAX_IMPORT_TASK_ITEMS {
|
||||
return Err(map_wire_error(WireValidationError::new("items")));
|
||||
}
|
||||
let icons: Vec<_> = request
|
||||
.items
|
||||
.iter()
|
||||
.filter_map(|item| item.settings.as_ref()?.platform_icon.as_deref())
|
||||
.collect();
|
||||
super::credentials::validate_platform_icons(&state, &icons).await?;
|
||||
let encoded = serde_json::to_vec(&request.items)
|
||||
.map_err(|_| map_wire_error(WireValidationError::new("items")))?;
|
||||
let fingerprint = Sha256::digest(&encoded).into();
|
||||
|
||||
@@ -67,6 +67,7 @@ pub(super) fn account_view(
|
||||
time: crate::time::TimePresenter,
|
||||
) -> AccountView {
|
||||
let AccountDirectoryItem {
|
||||
platform_icon,
|
||||
account,
|
||||
capacity,
|
||||
capabilities,
|
||||
@@ -111,6 +112,7 @@ pub(super) fn account_view(
|
||||
let (mut quota, refresh_token_expires_at) = account_quota_view(quota, cooldown, now, time);
|
||||
quota.protection_rules = protection_rules;
|
||||
AccountView {
|
||||
platform_icon,
|
||||
quota_settings: account.quota_settings,
|
||||
auto_use_quota_credits: account.auto_use_quota_credits,
|
||||
upstream,
|
||||
|
||||
@@ -247,6 +247,7 @@ pub struct AccountSummaryView {
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AccountView {
|
||||
pub platform_icon: Option<String>,
|
||||
pub quota_settings: gateway_core::account::AccountQuotaSettings,
|
||||
pub auto_use_quota_credits: bool,
|
||||
pub upstream: Option<super::AccountUpstreamInfoView>,
|
||||
|
||||
@@ -153,6 +153,8 @@ impl ClientKeySort {
|
||||
#[derive(Clone, PartialEq, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct CreateClientKeyRequest {
|
||||
#[serde(default)]
|
||||
validity: gateway_core::policy::ClientKeyValidity,
|
||||
#[serde(default)]
|
||||
peer_sharing: gateway_core::policy::ClientPeerSharing,
|
||||
#[serde(default)]
|
||||
@@ -188,6 +190,7 @@ impl CreateClientKeyRequest {
|
||||
let request_profile_overrides =
|
||||
normalize_request_profile_overrides(self.provider_request_profile_overrides)?;
|
||||
Ok(CreateClientKey {
|
||||
validity: self.validity,
|
||||
peer_sharing: self.peer_sharing,
|
||||
request_profile_overrides,
|
||||
custom_key: self
|
||||
@@ -216,6 +219,7 @@ impl CreateClientKeyRequest {
|
||||
#[derive(Debug, Clone, PartialEq, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct UpdateClientKeyRequest {
|
||||
validity: Option<gateway_core::policy::ClientKeyValidity>,
|
||||
peer_sharing: Option<gateway_core::policy::ClientPeerSharing>,
|
||||
#[serde(default)]
|
||||
provider_request_profile_overrides: ProviderRequestProfileOverrideUpdates,
|
||||
@@ -241,6 +245,7 @@ impl UpdateClientKeyRequest {
|
||||
let request_profile_override_updates =
|
||||
normalize_request_profile_override_updates(self.provider_request_profile_overrides)?;
|
||||
Ok(UpdateClientKey {
|
||||
validity: self.validity,
|
||||
peer_sharing: self.peer_sharing,
|
||||
request_profile_override_updates,
|
||||
id: client_key_id(self.id, "clientKeyMutationNotFound")?,
|
||||
@@ -370,6 +375,10 @@ impl
|
||||
#[derive(Debug, Clone, PartialEq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ClientKeyView {
|
||||
validity: gateway_core::policy::ClientKeyValidity,
|
||||
validity_status: gateway_core::policy::ClientKeyValidityStatus,
|
||||
starts_at_display: Option<String>,
|
||||
expires_at_display: Option<String>,
|
||||
peer_sharing: gateway_core::policy::ClientPeerSharing,
|
||||
provider_request_profile_overrides: ProviderRequestProfileOverrides,
|
||||
id: String,
|
||||
@@ -407,6 +416,10 @@ impl From<(ClientKeyRecord, crate::time::TimePresenter)> for ClientKeyView {
|
||||
.collect::<ProviderRequestProfileOverrides>();
|
||||
Self {
|
||||
provider_request_profile_overrides,
|
||||
validity: record.validity,
|
||||
validity_status: record.validity.status_at(time.now()),
|
||||
starts_at_display: record.validity.starts_at.map(|start| time.datetime(&start)),
|
||||
expires_at_display: record.validity.expires_at.map(|end| time.datetime(&end)),
|
||||
peer_sharing: record.peer_sharing,
|
||||
id: record.id.to_string(),
|
||||
name: record.name,
|
||||
|
||||
@@ -276,6 +276,7 @@ pub(crate) fn usage_list_record_view(
|
||||
account_id: record.provider_account_ref,
|
||||
account_email: record.provider_account_email,
|
||||
account_name: record.provider_account_name,
|
||||
platform_icon: record.platform_icon,
|
||||
account_notes: record.provider_account_notes,
|
||||
account_plan_type: record.provider_account_plan_type,
|
||||
account_plan_type_display: record.provider_account_plan_type_display,
|
||||
@@ -940,6 +941,7 @@ pub(crate) fn dashboard_view(
|
||||
.email
|
||||
.clone()
|
||||
.unwrap_or_else(|| credential.name.clone()),
|
||||
platform_icon: credential.platform_icon,
|
||||
notes: credential.notes,
|
||||
plan_type: credential.plan_type.clone(),
|
||||
plan_type_display: credential
|
||||
@@ -1350,6 +1352,8 @@ pub(crate) fn diagnostics_view(
|
||||
.items
|
||||
.into_iter()
|
||||
.map(|item| DiagnosticItemView {
|
||||
providers: item.providers,
|
||||
platform_icon: item.platform_icon,
|
||||
key: item.key,
|
||||
authentication_kind: item.account_authentication_kind,
|
||||
name: if item.name == "__none__" {
|
||||
|
||||
@@ -86,6 +86,7 @@ pub struct ImageBillingView {
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct UsageListRecordView {
|
||||
pub platform_icon: Option<String>,
|
||||
pub error_origin: &'static str,
|
||||
pub client_status_code: Option<u16>,
|
||||
pub upstream_status_code: Option<u16>,
|
||||
@@ -432,6 +433,7 @@ pub enum DashboardAccountMetric {
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DashboardAccountUsageView {
|
||||
pub platform_icon: Option<String>,
|
||||
pub upstream: Option<crate::admin::accounts::AccountUpstreamInfoView>,
|
||||
pub id: String,
|
||||
pub provider: String,
|
||||
@@ -872,6 +874,8 @@ pub struct UsageCacheView {
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DiagnosticItemView {
|
||||
pub providers: Vec<String>,
|
||||
pub platform_icon: Option<String>,
|
||||
pub key: String,
|
||||
pub name: String,
|
||||
pub authentication_kind: Option<String>,
|
||||
|
||||
@@ -13,7 +13,7 @@ use gateway_admin::model::{
|
||||
AdminError as ServiceError, PageSize, Revision,
|
||||
proxies::{
|
||||
NewProxy, ProxyAccountListQuery, ProxyBatchResult, ProxyListQuery, ProxyMutation,
|
||||
ProxyRecord, ProxyTestResult, TestProxy, UpdateProxy,
|
||||
ProxyRecord, ProxyTestResult, ProxyTestTargets, TestProxy, UpdateProxy,
|
||||
},
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -152,6 +152,7 @@ impl From<ProxyTestResult> for ProxyTestView {
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct ProxyAccountView {
|
||||
platform_icon: Option<String>,
|
||||
upstream: Option<super::accounts::AccountUpstreamInfoView>,
|
||||
id: String,
|
||||
name: String,
|
||||
@@ -260,6 +261,11 @@ where
|
||||
.route("/api/admin/proxies/delete", post(delete::<S>))
|
||||
.route("/api/admin/proxies/test", post(test::<S>))
|
||||
.route("/api/admin/proxies/probe", post(probe::<S>))
|
||||
.route(
|
||||
"/api/admin/proxies/targets",
|
||||
get(test_targets::<S>).post(replace_test_targets::<S>),
|
||||
)
|
||||
.route("/api/admin/proxies/targets/test", post(test_target::<S>))
|
||||
}
|
||||
|
||||
fn revision(value: u64) -> Result<Revision, AdminError> {
|
||||
@@ -340,6 +346,7 @@ where
|
||||
.items
|
||||
.into_iter()
|
||||
.map(|account| ProxyAccountView {
|
||||
platform_icon: account.platform_icon,
|
||||
upstream: account.upstream.map(|info| {
|
||||
super::accounts::upstream_info_view(
|
||||
info,
|
||||
@@ -546,6 +553,75 @@ where
|
||||
))
|
||||
}
|
||||
|
||||
async fn test_targets<S>(
|
||||
_: AdminAuth,
|
||||
State(state): State<S>,
|
||||
) -> Result<impl IntoResponse, AdminError>
|
||||
where
|
||||
S: SessionState + Send + Sync,
|
||||
{
|
||||
let targets = state
|
||||
.admin_services()
|
||||
.proxies()
|
||||
.test_targets()
|
||||
.await
|
||||
.map_err(map_error)?;
|
||||
Ok(AdminResponse::new(
|
||||
StatusCode::OK,
|
||||
AdminEnvelope::ok(targets),
|
||||
))
|
||||
}
|
||||
|
||||
async fn replace_test_targets<S>(
|
||||
auth: AdminAuth,
|
||||
State(state): State<S>,
|
||||
AdminJson(settings): AdminJson<ProxyTestTargets>,
|
||||
) -> Result<impl IntoResponse, AdminError>
|
||||
where
|
||||
S: SessionState + Send + Sync,
|
||||
{
|
||||
let targets = state
|
||||
.admin_services()
|
||||
.proxies()
|
||||
.replace_test_targets(settings, &auth.context().mutation_context())
|
||||
.await
|
||||
.map_err(map_error)?;
|
||||
Ok(AdminResponse::new(
|
||||
StatusCode::OK,
|
||||
AdminEnvelope::ok(targets),
|
||||
))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
struct TargetTestRequest {
|
||||
proxy_id: String,
|
||||
target_name: String,
|
||||
revision: Revision,
|
||||
}
|
||||
|
||||
async fn test_target<S>(
|
||||
_: AdminAuth,
|
||||
State(state): State<S>,
|
||||
AdminJson(request): AdminJson<TargetTestRequest>,
|
||||
) -> Result<impl IntoResponse, AdminError>
|
||||
where
|
||||
S: SessionState + Send + Sync,
|
||||
{
|
||||
let (proxy_name, result) = state
|
||||
.admin_services()
|
||||
.proxies()
|
||||
.test_target(&request.proxy_id, &request.target_name, request.revision)
|
||||
.await
|
||||
.map_err(map_error)?;
|
||||
Ok(AdminResponse::new(
|
||||
StatusCode::OK,
|
||||
AdminEnvelope::ok(serde_json::json!({
|
||||
"proxyName": proxy_name, "result": result,
|
||||
})),
|
||||
))
|
||||
}
|
||||
|
||||
async fn probe<S>(
|
||||
_: AdminAuth,
|
||||
State(state): State<S>,
|
||||
|
||||
@@ -36,8 +36,8 @@ pub type ProviderRequestProfileUpdates =
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct RuntimeSettingsFields {
|
||||
pub openai_oauth_guardian_review_model: bool,
|
||||
pub openai_request_country: gateway_core::account::OpenAiRequestCountry,
|
||||
pub openai_websocket_pool: gateway_core::settings::OpenAiWebSocketPoolSettings,
|
||||
pub openai_request_settings: gateway_core::settings::OpenAiRequestSettings,
|
||||
pub codex_privacy_policy: gateway_core::settings::privacy::CodexPrivacyPolicy,
|
||||
pub request_location_enabled: bool,
|
||||
pub request_location: gateway_core::account::RequestLocation,
|
||||
@@ -62,6 +62,7 @@ pub struct RuntimeSettingsFields {
|
||||
pub usage_retention_days: u64,
|
||||
pub ops_event_retention_days: u64,
|
||||
pub audit_retention_days: u64,
|
||||
pub prompt_rewrite_rules: Vec<gateway_core::settings::prompt_rewrite::PromptRewriteRule>,
|
||||
pub account_error_protection: gateway_core::account::AccountErrorProtection,
|
||||
pub account_warmup_enabled: bool,
|
||||
pub account_warmup_cron: String,
|
||||
@@ -283,6 +284,10 @@ where
|
||||
post(preview_privacy::<S>),
|
||||
)
|
||||
.route("/api/admin/settings/update", post(update_settings::<S>))
|
||||
.route(
|
||||
"/api/admin/settings/prompt-rewrite/preview",
|
||||
post(preview_prompt_rewrite::<S>),
|
||||
)
|
||||
.route(
|
||||
"/api/admin/settings/client-downloads/codex-desktop/windows",
|
||||
get(codex_desktop_windows_downloads::<S>),
|
||||
@@ -581,7 +586,12 @@ fn map_wire_error(error: WireValidationError) -> AdminError {
|
||||
"settingsUsageRetentionOverflow" => "用量记录保留天数不合法".to_owned(),
|
||||
"settingsOpsRetentionOverflow" => "运维事件保留天数不合法".to_owned(),
|
||||
"settingsAuditRetentionOverflow" => "审计记录保留天数不合法".to_owned(),
|
||||
"openaiRequestCountry" => "自定义请求国家必须是两位大写 ASCII 字母".to_owned(),
|
||||
"openaiRequestSettings.residency" | "openaiRequestSettings.accountRoutingOverride" => {
|
||||
"数据驻留和账号路由必须是有效的单行请求头值".to_owned()
|
||||
}
|
||||
"openaiRequestSettings.requestCountry" => {
|
||||
"自定义请求国家必须是两位大写 ASCII 字母".to_owned()
|
||||
}
|
||||
"requestLocation" => "请求位置的国家代码、地区或城市不合法".to_owned(),
|
||||
"providerRequestProfiles" => "服务商客户端身份配置无效".to_owned(),
|
||||
"minCodexDesktopVersion" => "Codex Desktop 最低版本格式不合法".to_owned(),
|
||||
@@ -705,8 +715,8 @@ impl RuntimeSettingsFields {
|
||||
self,
|
||||
) -> Result<gateway_admin::model::settings::RuntimeSettingsValues, WireValidationError> {
|
||||
let values = gateway_admin::model::settings::RuntimeSettingsValues {
|
||||
openai_oauth_guardian_review_model: self.openai_oauth_guardian_review_model,
|
||||
openai_request_country: self.openai_request_country,
|
||||
openai_websocket_pool: self.openai_websocket_pool,
|
||||
openai_request_settings: self.openai_request_settings,
|
||||
codex_privacy_policy: self.codex_privacy_policy,
|
||||
request_location_enabled: self.request_location_enabled,
|
||||
request_location: self
|
||||
@@ -739,6 +749,7 @@ impl RuntimeSettingsFields {
|
||||
.map_err(|_| WireValidationError::new("settingsOpsRetentionOverflow"))?,
|
||||
audit_retention_days: u32::try_from(self.audit_retention_days)
|
||||
.map_err(|_| WireValidationError::new("settingsAuditRetentionOverflow"))?,
|
||||
prompt_rewrite_rules: self.prompt_rewrite_rules,
|
||||
account_error_protection: self.account_error_protection,
|
||||
account_warmup_enabled: self.account_warmup_enabled,
|
||||
account_warmup_cron: self.account_warmup_cron,
|
||||
@@ -756,8 +767,8 @@ impl RuntimeSettingsFields {
|
||||
impl From<gateway_admin::model::settings::RuntimeSettingsValues> for RuntimeSettingsFields {
|
||||
fn from(settings: gateway_admin::model::settings::RuntimeSettingsValues) -> Self {
|
||||
crate::admin::settings::RuntimeSettingsFields {
|
||||
openai_oauth_guardian_review_model: settings.openai_oauth_guardian_review_model,
|
||||
openai_request_country: settings.openai_request_country,
|
||||
openai_websocket_pool: settings.openai_websocket_pool,
|
||||
openai_request_settings: settings.openai_request_settings,
|
||||
codex_privacy_policy: settings.codex_privacy_policy,
|
||||
request_location_enabled: settings.request_location_enabled,
|
||||
request_location: settings.request_location,
|
||||
@@ -782,6 +793,7 @@ impl From<gateway_admin::model::settings::RuntimeSettingsValues> for RuntimeSett
|
||||
usage_retention_days: u64::from(settings.usage_retention_days),
|
||||
ops_event_retention_days: u64::from(settings.ops_event_retention_days),
|
||||
audit_retention_days: u64::from(settings.audit_retention_days),
|
||||
prompt_rewrite_rules: settings.prompt_rewrite_rules,
|
||||
account_error_protection: settings.account_error_protection,
|
||||
account_warmup_enabled: settings.account_warmup_enabled,
|
||||
account_warmup_cron: settings.account_warmup_cron,
|
||||
@@ -796,6 +808,7 @@ impl From<gateway_admin::model::settings::RuntimeSettingsValues> for RuntimeSett
|
||||
|
||||
fn settings_validation_error(field: &'static str) -> WireValidationError {
|
||||
WireValidationError::new(match field {
|
||||
"prompt_rewrite_rules" => "promptRewriteRules",
|
||||
"account_error_protection" => "accountErrorProtection",
|
||||
"account_warmup_enabled" => "accountWarmupEnabled",
|
||||
"account_warmup_model" => "accountWarmupModel",
|
||||
@@ -811,7 +824,15 @@ fn settings_validation_error(field: &'static str) -> WireValidationError {
|
||||
"max_waiting_per_key" => "maxWaitingPerKey",
|
||||
"min_codex_cli_version" => "minCodexCliVersion",
|
||||
"min_codex_desktop_version" => "minCodexDesktopVersion",
|
||||
"openai_request_country" => "openaiRequestCountry",
|
||||
"openai_websocket_pool.max_age_ms" => "openaiWebsocketPool.maxAgeMs",
|
||||
"openai_websocket_pool.max_connecting" => "openaiWebsocketPool.maxConnecting",
|
||||
"openai_websocket_pool.fast_path_budget_ms" => "openaiWebsocketPool.fastPathBudgetMs",
|
||||
"openai_websocket_pool.idle_timeout_ms" => "openaiWebsocketPool.idleTimeoutMs",
|
||||
"openai_request_settings.request_country" => "openaiRequestSettings.requestCountry",
|
||||
"openai_request_settings.residency" => "openaiRequestSettings.residency",
|
||||
"openai_request_settings.account_routing_override" => {
|
||||
"openaiRequestSettings.accountRoutingOverride"
|
||||
}
|
||||
"account_affinity" => "accountAffinity",
|
||||
"openai_guardian_reserved_concurrency" => "openaiGuardianReservedConcurrency",
|
||||
"session_affinity_ttl_hours" => "sessionAffinityTtlHours",
|
||||
@@ -846,3 +867,25 @@ where
|
||||
AdminEnvelope::ok(result),
|
||||
))
|
||||
}
|
||||
|
||||
async fn preview_prompt_rewrite<S>(
|
||||
State(state): State<S>,
|
||||
_auth: AdminAuth,
|
||||
AdminJson(request): AdminJson<
|
||||
gateway_core::settings::prompt_rewrite::PromptRewritePreviewRequest,
|
||||
>,
|
||||
) -> Result<impl IntoResponse, AdminError>
|
||||
where
|
||||
S: SessionState + Send + Sync,
|
||||
{
|
||||
let result = state
|
||||
.admin_services()
|
||||
.settings()
|
||||
.preview_prompt_rewrite(request)
|
||||
.await
|
||||
.map_err(map_service_error)?;
|
||||
Ok(AdminResponse::new(
|
||||
StatusCode::OK,
|
||||
AdminEnvelope::ok(result),
|
||||
))
|
||||
}
|
||||
|
||||
@@ -211,12 +211,15 @@ pub const fn gateway_error_contract(
|
||||
"rate_limit_error",
|
||||
"concurrency_queue_timeout",
|
||||
),
|
||||
GatewayErrorKind::RateLimited => (
|
||||
GatewayErrorKind::RateLimited
|
||||
| GatewayErrorKind::QuotaExhausted
|
||||
| GatewayErrorKind::KeyRateLimited
|
||||
| GatewayErrorKind::KeyConcurrencyLimited => (
|
||||
StatusCode::TOO_MANY_REQUESTS,
|
||||
"rate_limit_error",
|
||||
"rate_limit_exceeded",
|
||||
),
|
||||
GatewayErrorKind::BudgetExhausted => (
|
||||
GatewayErrorKind::AccountPoolQuotaExhausted | GatewayErrorKind::BudgetExhausted => (
|
||||
StatusCode::TOO_MANY_REQUESTS,
|
||||
"usage_limit_reached",
|
||||
"usage_limit_reached",
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Antigravity 桌面端与 CLI 的模型选择器识别及菜单投影
|
||||
//! Antigravity 桌面端与 CLI 的模型发现请求识别及目录投影
|
||||
|
||||
use axum::http::{HeaderMap, header::USER_AGENT};
|
||||
use gateway_core::routing::{AgentModelListing, ExecutableModelMetadata, PublicModelId};
|
||||
|
||||
@@ -20,7 +20,6 @@ pub(crate) struct CodexRequestHeaders {
|
||||
version: Option<String>,
|
||||
codex_window_id: Option<String>,
|
||||
parent_thread_id: Option<String>,
|
||||
turn_id: Option<String>,
|
||||
responses_lite: Option<String>,
|
||||
memgen_request: Option<String>,
|
||||
subagent: Option<String>,
|
||||
@@ -45,7 +44,6 @@ impl CodexRequestHeaders {
|
||||
version: header_string(headers, "version"),
|
||||
codex_window_id: header_string(headers, "x-codex-window-id"),
|
||||
parent_thread_id: header_string(headers, "x-codex-parent-thread-id"),
|
||||
turn_id: header_string(headers, "x-codex-turn-id"),
|
||||
responses_lite: header_string(headers, X_OPENAI_INTERNAL_CODEX_RESPONSES_LITE_HEADER),
|
||||
memgen_request: header_string(headers, X_OPENAI_MEMGEN_REQUEST_HEADER),
|
||||
subagent: header_string(headers, OPENAI_SUBAGENT_KEY),
|
||||
@@ -60,7 +58,6 @@ impl CodexRequestHeaders {
|
||||
("version", self.version.as_ref()),
|
||||
("codex_window_id", self.codex_window_id.as_ref()),
|
||||
("parent_thread_id", self.parent_thread_id.as_ref()),
|
||||
("turn_id", self.turn_id.as_ref()),
|
||||
("responses_lite", self.responses_lite.as_ref()),
|
||||
("memgen_request", self.memgen_request.as_ref()),
|
||||
] {
|
||||
|
||||
@@ -83,6 +83,7 @@ fn parse_route(resource: &str, query: Option<&str>) -> Result<GenerationInput, G
|
||||
endpoint,
|
||||
model: model.to_owned(),
|
||||
stream,
|
||||
decoded: None,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Gemini 模型目录复用冻结范围与原生协议能力,分页不扩大可见模型集合
|
||||
//! GenAI 模型目录复用冻结范围与原生协议能力,分页不扩大可见模型集合
|
||||
|
||||
use axum::{
|
||||
Json,
|
||||
@@ -10,6 +10,7 @@ use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
|
||||
use gateway_core::{
|
||||
engine::execution::AuthenticatedClient,
|
||||
operation::{GenerateRequest, Operation, ProtocolPayload, RawJsonPayload, TokenCountRequest},
|
||||
routing::PublicModelDescriptor,
|
||||
};
|
||||
use gateway_protocol::genai::GENAI_PROTOCOL;
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -85,12 +86,13 @@ async fn query_response(
|
||||
let agent_menu = model.is_none() && crate::data_plane::antigravity::uses_agent_menu(&headers);
|
||||
let mut input = RequestInput::query(endpoint.to_owned(), model.clone(), &headers);
|
||||
input.protocol = GENAI_PROTOCOL.to_owned();
|
||||
let response_state = state.clone();
|
||||
middleware::query_response(
|
||||
service.execution(),
|
||||
client,
|
||||
input,
|
||||
move |client| async move {
|
||||
match catalog(&client, agent_menu) {
|
||||
match catalog(response_state.data_plane(), &client, agent_menu).await {
|
||||
Ok(models) => match model {
|
||||
Some(model) => models
|
||||
.into_iter()
|
||||
@@ -111,7 +113,22 @@ async fn query_response(
|
||||
.await
|
||||
}
|
||||
|
||||
fn catalog(client: &AuthenticatedClient, agent_menu: bool) -> Result<Vec<Value>, ()> {
|
||||
async fn catalog(
|
||||
service: &crate::data_plane::service::DataPlaneService,
|
||||
client: &AuthenticatedClient,
|
||||
agent_menu: bool,
|
||||
) -> Result<Vec<Value>, ()> {
|
||||
let context = crate::middleware::current();
|
||||
let entries = service
|
||||
.execution()
|
||||
.client_model_catalog(
|
||||
client,
|
||||
GENAI_PROTOCOL,
|
||||
"",
|
||||
context.as_ref().and_then(|ctx| ctx.extensions.peer_route()),
|
||||
)
|
||||
.await
|
||||
.map_err(|_| ())?;
|
||||
let generate = Operation::Generate(
|
||||
GenerateRequest::from_protocol_payload(
|
||||
ProtocolPayload::json_object(GENAI_PROTOCOL, Map::new()).map_err(|_| ())?,
|
||||
@@ -128,36 +145,62 @@ fn catalog(client: &AuthenticatedClient, agent_menu: bool) -> Result<Vec<Value>,
|
||||
let snapshot = client.snapshot();
|
||||
let scope = client.policy().account_scope();
|
||||
let counted = snapshot.public_models_for_operation(scope, &count);
|
||||
let models = if agent_menu {
|
||||
let generated = snapshot.public_models_for_operation(scope, &generate);
|
||||
let menu = agent_menu.then(|| {
|
||||
crate::data_plane::antigravity::model_menu(
|
||||
snapshot.model_metadata_for_operation(scope, &generate),
|
||||
)
|
||||
} else {
|
||||
snapshot
|
||||
.public_models_for_operation(scope, &generate)
|
||||
.into_iter()
|
||||
.map(|model| {
|
||||
let name = model.as_str().to_owned();
|
||||
(model, name)
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
Ok(models
|
||||
.into_iter()
|
||||
.filter(|(model, _)| super::valid_segment(model.as_str()))
|
||||
.map(|(model, name)| {
|
||||
let mut methods = vec!["generateContent", "streamGenerateContent"];
|
||||
if counted.binary_search(&model).is_ok() {
|
||||
methods.push("countTokens");
|
||||
.enumerate()
|
||||
.map(|(order, (model, name))| (model, (order, name)))
|
||||
.collect::<std::collections::BTreeMap<_, _>>()
|
||||
});
|
||||
let mut models = Vec::new();
|
||||
for entry in entries {
|
||||
let (model, mut object) = match entry {
|
||||
PublicModelDescriptor::Native { model, payload } => {
|
||||
if payload.protocol() != GENAI_PROTOCOL {
|
||||
return Err(());
|
||||
}
|
||||
let object: Map<String, Value> =
|
||||
serde_json::from_slice(payload.body()).map_err(|_| ())?;
|
||||
(model, object)
|
||||
}
|
||||
// 上游尚未提供完整 Gemini 元数据,未知版本与 Token 上限保持缺失
|
||||
json!({
|
||||
"name": format!("models/{}", model.as_str()),
|
||||
"displayName": name,
|
||||
"supportedGenerationMethods": methods,
|
||||
})
|
||||
})
|
||||
.collect())
|
||||
PublicModelDescriptor::Adapted(profile) => {
|
||||
let name = menu
|
||||
.as_ref()
|
||||
.and_then(|menu| menu.get(profile.model()))
|
||||
.map(|(_, name)| name.as_str())
|
||||
.or_else(|| profile.presentation().display_name())
|
||||
.unwrap_or(profile.model().as_str());
|
||||
(
|
||||
profile.model().clone(),
|
||||
Map::from_iter([("displayName".into(), json!(name))]),
|
||||
)
|
||||
}
|
||||
};
|
||||
if generated.binary_search(&model).is_err() || !super::valid_segment(model.as_str()) {
|
||||
continue;
|
||||
}
|
||||
let order = if let Some(menu) = &menu {
|
||||
let Some((order, _)) = menu.get(&model) else {
|
||||
continue;
|
||||
};
|
||||
*order
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let mut methods = vec!["generateContent", "streamGenerateContent"];
|
||||
if counted.binary_search(&model).is_ok() {
|
||||
methods.push("countTokens");
|
||||
}
|
||||
// Cloud Code 模型对象完整保留,只适配 AGY Gateway 发现端点的资源名与调用方法
|
||||
object.insert("name".into(), json!(format!("models/{}", model.as_str())));
|
||||
object.insert("supportedGenerationMethods".into(), json!(methods));
|
||||
models.push((order, model, Value::Object(object)));
|
||||
}
|
||||
models.sort_unstable_by(|(a, ma, _), (b, mb, _)| (a, ma).cmp(&(b, mb)));
|
||||
Ok(models.into_iter().map(|(_, _, object)| object).collect())
|
||||
}
|
||||
|
||||
fn paginate(models: Vec<Value>, query: ModelsQuery) -> Response {
|
||||
|
||||
@@ -90,7 +90,7 @@ pub(crate) async fn execute_prepared_generation(
|
||||
peer_address,
|
||||
ingress_id,
|
||||
headers,
|
||||
input: generation,
|
||||
input: mut generation,
|
||||
middleware_body,
|
||||
} = request;
|
||||
let (client_ip, user_agent) = request_client_context(&headers, peer_address);
|
||||
@@ -120,6 +120,7 @@ pub(crate) async fn execute_prepared_generation(
|
||||
middleware_headers.remove(CONTENT_LENGTH);
|
||||
let endpoint = protocol.path();
|
||||
let stream_error = protocol.stream_error_encoder();
|
||||
let original_body = middleware_body.clone();
|
||||
let input = RequestInput {
|
||||
endpoint: endpoint.to_owned(),
|
||||
protocol: protocol.wire().to_owned(),
|
||||
@@ -143,17 +144,24 @@ pub(crate) async fn execute_prepared_generation(
|
||||
if wire_protocol != protocol.wire() {
|
||||
return Err(MiddlewareError::Rejected);
|
||||
}
|
||||
let decoded = generation
|
||||
.decode(
|
||||
// 只复用当前请求中未被改写的解码事实;设置和能力声明仍按最终请求应用
|
||||
let decoded = generation.decoded.take().filter(|_| {
|
||||
request_body == original_body && request_headers == middleware_headers
|
||||
});
|
||||
drop(original_body);
|
||||
let decoded = match decoded {
|
||||
Some(decoded) => decoded,
|
||||
None => generation.decode(
|
||||
&request_body,
|
||||
&request_headers,
|
||||
prepared
|
||||
.client()
|
||||
.snapshot()
|
||||
.responses_max_decompressed_body_bytes(),
|
||||
)?
|
||||
.with_client_context(client_ip, user_agent)
|
||||
.with_middleware_capabilities(&request)?;
|
||||
)?,
|
||||
}
|
||||
.with_client_context(client_ip, user_agent)
|
||||
.with_middleware_capabilities(&request)?;
|
||||
if decoded.metadata().stream() != stream {
|
||||
return Err(MiddlewareError::Rejected);
|
||||
}
|
||||
|
||||
@@ -28,8 +28,9 @@ impl GenerationEndpoint {
|
||||
pub(crate) fn input(self, request: DecodedGenerationRequest) -> GenerationInput {
|
||||
GenerationInput {
|
||||
endpoint: self,
|
||||
model: request.metadata.requested_model,
|
||||
model: request.metadata.requested_model.clone(),
|
||||
stream: request.metadata.stream,
|
||||
decoded: Some(request),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -64,6 +65,8 @@ pub(crate) struct GenerationInput {
|
||||
pub(super) endpoint: GenerationEndpoint,
|
||||
pub(super) model: String,
|
||||
pub(super) stream: bool,
|
||||
// GenAI 从 URL 取路由事实,直到 terminal 才首次解码正文
|
||||
pub(super) decoded: Option<DecodedGenerationRequest>,
|
||||
}
|
||||
|
||||
impl GenerationInput {
|
||||
|
||||
@@ -41,7 +41,7 @@ pub(crate) async fn models(
|
||||
Query(query): Query<ModelsQuery>,
|
||||
headers: HeaderMap,
|
||||
) -> Response {
|
||||
let anthropic = headers.contains_key("anthropic-version") || headers.contains_key("x-api-key");
|
||||
let anthropic = headers.contains_key("anthropic-version");
|
||||
let service = state.data_plane();
|
||||
let client = match authenticate_client(service, &headers, ClientKeyHeaders::Anthropic).await {
|
||||
Ok(client) => client,
|
||||
@@ -104,7 +104,7 @@ pub(crate) async fn model_detail(
|
||||
headers: HeaderMap,
|
||||
Path(model_id): Path<String>,
|
||||
) -> Response {
|
||||
let anthropic = headers.contains_key("anthropic-version") || headers.contains_key("x-api-key");
|
||||
let anthropic = headers.contains_key("anthropic-version");
|
||||
let service = state.data_plane();
|
||||
let client = match authenticate_client(service, &headers, ClientKeyHeaders::Anthropic).await {
|
||||
Ok(client) => client,
|
||||
|
||||
@@ -136,7 +136,7 @@ pub fn decode_request_with_headers(
|
||||
|
||||
/// 解码请求并返回已经解除 HTTP content encoding 的中间件正文
|
||||
///
|
||||
/// 外层中间件只接收有界的协议正文;terminal 会用中间件返回的正文重新解码,
|
||||
/// 外层中间件只接收有界的协议正文;terminal 在正文或请求头改写后重新解码,
|
||||
/// 因而不能把压缩字节与已经移除的传输编码语义混用
|
||||
pub(crate) fn decode_request_with_body(
|
||||
body: &[u8],
|
||||
|
||||
@@ -230,32 +230,33 @@ async fn serve_responses_websocket(socket: Socket, session: ResponsesWebSocketSe
|
||||
continue;
|
||||
}
|
||||
request_count = request_count.saturating_add(1);
|
||||
// 初步解码只取帧中的模型,实际执行使用该帧当前生效的请求头
|
||||
let model_hint =
|
||||
match decode_response_create_with_context(&payload, &OpenAiRequestHeaders::default()) {
|
||||
Ok(decoded) => Some(decoded.metadata().requested_model().to_owned()),
|
||||
Err(error) => {
|
||||
trace_rejected_request(
|
||||
&correlation_id,
|
||||
connection.id(),
|
||||
&payload,
|
||||
"decode",
|
||||
&error.to_string(),
|
||||
);
|
||||
if send_protocol_error(
|
||||
&mut connection,
|
||||
StatusCode::BAD_REQUEST,
|
||||
error.protocol_body(),
|
||||
&correlation_id,
|
||||
)
|
||||
.await
|
||||
== ForwardOutcome::Disconnect
|
||||
{
|
||||
break;
|
||||
}
|
||||
continue;
|
||||
let original_headers = raw_headers.clone();
|
||||
let request_headers = OpenAiRequestHeaders::from_headers(&original_headers)
|
||||
.with_downstream_websocket_connection_id(connection.id().to_owned());
|
||||
let decoded = match decode_response_create_with_context(&payload, &request_headers) {
|
||||
Ok(decoded) => decoded,
|
||||
Err(error) => {
|
||||
trace_rejected_request(
|
||||
&correlation_id,
|
||||
connection.id(),
|
||||
&payload,
|
||||
"decode",
|
||||
&error.to_string(),
|
||||
);
|
||||
if send_protocol_error(
|
||||
&mut connection,
|
||||
StatusCode::BAD_REQUEST,
|
||||
error.protocol_body(),
|
||||
&correlation_id,
|
||||
)
|
||||
.await
|
||||
== ForwardOutcome::Disconnect
|
||||
{
|
||||
break;
|
||||
}
|
||||
};
|
||||
continue;
|
||||
}
|
||||
};
|
||||
// deadline 与 Text 可能同时就绪;在任何上游执行开始前再次封住该竞争窗口
|
||||
if connection.is_expired() {
|
||||
trace_rejected_request(
|
||||
@@ -317,14 +318,15 @@ async fn serve_responses_websocket(socket: Socket, session: ResponsesWebSocketSe
|
||||
response_control = prepared.response_control();
|
||||
let capture = new_replay_capture();
|
||||
let validation = ResponseValidationFacts::default();
|
||||
let original_body = Bytes::from(payload);
|
||||
let input = RequestInput {
|
||||
endpoint: crate::data_plane::router::RESPONSES_PATH.to_owned(),
|
||||
protocol: OPENAI_PROTOCOL.to_owned(),
|
||||
operation: Some(OperationKind::Generate),
|
||||
transport: ClientTransport::WebSocket,
|
||||
model_hint,
|
||||
model_hint: Some(decoded.metadata().requested_model().to_owned()),
|
||||
headers: encode_headers(&raw_headers),
|
||||
body: Bytes::from(payload),
|
||||
body: original_body.clone(),
|
||||
};
|
||||
// 握手的轮次头只属于首次执行,复用连接时由各 response.create 携带本轮数据
|
||||
raw_headers.remove("x-codex-turn-state");
|
||||
@@ -353,15 +355,22 @@ async fn serve_responses_websocket(socket: Socket, session: ResponsesWebSocketSe
|
||||
if protocol != OPENAI_PROTOCOL {
|
||||
return Err(MiddlewareError::Rejected);
|
||||
}
|
||||
let payload =
|
||||
std::str::from_utf8(&body).map_err(|_| MiddlewareError::Rejected)?;
|
||||
let request_headers = OpenAiRequestHeaders::from_headers(&headers)
|
||||
.with_downstream_websocket_connection_id(
|
||||
connection_id_for_terminal.clone(),
|
||||
);
|
||||
let decoded = decode_response_create_with_context(payload, &request_headers)
|
||||
.map_err(|_| MiddlewareError::Rejected)?
|
||||
.with_client_context(client_ip, user_agent_for_terminal);
|
||||
// 帧正文或本轮请求头变化时重新解释,不能复用改写前的路由与续接事实
|
||||
let decoded = if body == original_body && headers == original_headers {
|
||||
decoded
|
||||
} else {
|
||||
drop(decoded);
|
||||
let payload =
|
||||
std::str::from_utf8(&body).map_err(|_| MiddlewareError::Rejected)?;
|
||||
let request_headers = OpenAiRequestHeaders::from_headers(&headers)
|
||||
.with_downstream_websocket_connection_id(
|
||||
connection_id_for_terminal.clone(),
|
||||
);
|
||||
decode_response_create_with_context(payload, &request_headers)
|
||||
.map_err(|_| MiddlewareError::Rejected)?
|
||||
}
|
||||
.with_client_context(client_ip, user_agent_for_terminal);
|
||||
drop(original_body);
|
||||
let decoded = replay_for_terminal
|
||||
.prepare(decoded)
|
||||
.with_middleware_capabilities(&request)?;
|
||||
|
||||
@@ -216,6 +216,7 @@ pub fn initialize(
|
||||
})
|
||||
};
|
||||
let state = ApiState {
|
||||
platform_icon_catalog: Arc::new(config.asset_directory.join("platform-icons.json")),
|
||||
admin,
|
||||
data_plane: DataPlaneService::new(execution, lifecycle),
|
||||
health: HealthStatus::new(probes, worker_health, diagnostics.clone()),
|
||||
@@ -337,6 +338,7 @@ pub enum ApiError {
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct ApiState {
|
||||
platform_icon_catalog: Arc<PathBuf>,
|
||||
admin: AdminServices,
|
||||
data_plane: DataPlaneService,
|
||||
health: HealthStatus,
|
||||
@@ -355,6 +357,11 @@ impl ApiState {
|
||||
}
|
||||
|
||||
impl SessionState for ApiState {
|
||||
async fn platform_icon_names(&self) -> std::io::Result<std::collections::HashSet<String>> {
|
||||
let bytes = tokio::fs::read(self.platform_icon_catalog.as_ref()).await?;
|
||||
Ok(serde_json::from_slice(&bytes)?)
|
||||
}
|
||||
|
||||
fn admin_services(&self) -> &AdminServices {
|
||||
&self.admin
|
||||
}
|
||||
|
||||
@@ -4,5 +4,8 @@ use gateway_admin::AdminServices;
|
||||
|
||||
/// 控制面 HTTP adapter 消费同一组用例;权限由各入口服务端校验
|
||||
pub trait SessionState {
|
||||
fn platform_icon_names(
|
||||
&self,
|
||||
) -> impl Future<Output = std::io::Result<std::collections::HashSet<String>>> + Send;
|
||||
fn admin_services(&self) -> &AdminServices;
|
||||
}
|
||||
|
||||
@@ -411,6 +411,7 @@ fn account_page_item(
|
||||
use gateway_core::account::resolve_account_status;
|
||||
|
||||
AccountPageItem {
|
||||
platform_icon: None,
|
||||
protection_rules: Vec::new(),
|
||||
account: AccountRecord {
|
||||
quota_paused: false,
|
||||
@@ -670,6 +671,67 @@ async fn connection_update_requires_admin_and_validates_before_calling_the_servi
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn account_icon_requires_a_known_preset_before_mutation() {
|
||||
let fixture = AdminTestFixture::new().await;
|
||||
fixture.auth.insert_session("valid-session");
|
||||
for (name, expected) in [
|
||||
("DeepSeek", StatusCode::SERVICE_UNAVAILABLE),
|
||||
("", StatusCode::SERVICE_UNAVAILABLE),
|
||||
("Unlisted", StatusCode::BAD_REQUEST),
|
||||
("https://example.invalid/logo.svg", StatusCode::BAD_REQUEST),
|
||||
] {
|
||||
let settings = serde_json::json!({
|
||||
"platformIcon": name, "enabled": true,
|
||||
"concurrencyLimit": null, "weight": 1, "groupIds": []
|
||||
});
|
||||
for (route, payload) in [
|
||||
(
|
||||
"update",
|
||||
serde_json::json!({
|
||||
"accountId": "acct_api", "platformIcon": name, "enabled": true,
|
||||
"concurrencyLimit": null, "weight": 1, "groupIds": []
|
||||
}),
|
||||
),
|
||||
(
|
||||
"import",
|
||||
serde_json::json!({"provider": "openai", "data": {}, "settings": settings}),
|
||||
),
|
||||
(
|
||||
"oauth/complete",
|
||||
serde_json::json!({
|
||||
"provider": "xai", "flowId": "flow-test", "callbackUrl": "code", "settings": settings
|
||||
}),
|
||||
),
|
||||
] {
|
||||
let request = Request::post(format!("/api/admin/accounts/{route}"))
|
||||
.header("x-request-id", "req_account_icon")
|
||||
.header(header::COOKIE, "cpr_session=valid-session")
|
||||
.header(header::CONTENT_TYPE, "application/json")
|
||||
.body(Body::from(payload.to_string()))
|
||||
.unwrap();
|
||||
let response = admin::router::<AdminTestState>()
|
||||
.with_state(fixture.state())
|
||||
.oneshot(request)
|
||||
.await
|
||||
.unwrap();
|
||||
let status = response.status();
|
||||
let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
|
||||
let body: serde_json::Value = serde_json::from_slice(&body).unwrap();
|
||||
if expected == StatusCode::BAD_REQUEST {
|
||||
assert_eq!(status, expected, "{route}: {name}");
|
||||
assert_eq!(body["message"], "platformIcon 字段不合法");
|
||||
} else if route == "update" {
|
||||
assert_eq!(status, expected, "{route}: {name}");
|
||||
} else {
|
||||
// 夹具 Provider 未实现导入和授权,合法图标应通过校验并到达 Provider
|
||||
assert_eq!(status, StatusCode::BAD_REQUEST, "{route}: {name}: {body}");
|
||||
assert_eq!(body["message"], "该服务商不支持此操作");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn personal_info_requires_admin_and_a_valid_account_query() {
|
||||
let fixture = AdminTestFixture::new().await;
|
||||
|
||||
@@ -491,6 +491,7 @@ fn client_key_responses_should_keep_shape_and_redact_creation_debug() {
|
||||
.expect("valid time");
|
||||
let view = ClientKeyView::from((
|
||||
gateway_admin::model::client_keys::ClientKeyRecord {
|
||||
validity: Default::default(),
|
||||
peer_sharing: Default::default(),
|
||||
request_profile_overrides: Default::default(),
|
||||
budget: Default::default(),
|
||||
|
||||
@@ -564,6 +564,7 @@ mod provider {
|
||||
last_error_message: None,
|
||||
};
|
||||
AccountPageItem {
|
||||
platform_icon: None,
|
||||
protection_rules: Vec::new(),
|
||||
capacity: gateway_admin::model::accounts::AccountCapacity {
|
||||
used_slots: None,
|
||||
|
||||
@@ -311,6 +311,10 @@ impl ClientDistributionResolver for StaticClientDistribution {
|
||||
pub(super) struct AdminTestState(AdminServices);
|
||||
|
||||
impl SessionState for AdminTestState {
|
||||
async fn platform_icon_names(&self) -> std::io::Result<std::collections::HashSet<String>> {
|
||||
Ok(["DeepSeek".to_owned()].into())
|
||||
}
|
||||
|
||||
fn admin_services(&self) -> &AdminServices {
|
||||
&self.0
|
||||
}
|
||||
@@ -1137,6 +1141,7 @@ impl ClientKeyStore for MemoryClientKeyStore {
|
||||
let now = Utc::now();
|
||||
Ok(Some(ClientKeySecret::new(
|
||||
ClientKeyRecord {
|
||||
validity: Default::default(),
|
||||
peer_sharing: Default::default(),
|
||||
request_profile_overrides: Default::default(),
|
||||
budget: Default::default(),
|
||||
@@ -1989,8 +1994,8 @@ fn test_runtime_settings() -> RuntimeSettings {
|
||||
rotation_strategy: RotationStrategy::Smart,
|
||||
updated_at: Utc::now(),
|
||||
values: gateway_admin::model::settings::RuntimeSettingsValues {
|
||||
openai_oauth_guardian_review_model: true,
|
||||
openai_request_country: Default::default(),
|
||||
openai_websocket_pool: Default::default(),
|
||||
openai_request_settings: Default::default(),
|
||||
codex_privacy_policy: Default::default(),
|
||||
request_location_enabled: false,
|
||||
request_location: Default::default(),
|
||||
@@ -2015,6 +2020,7 @@ fn test_runtime_settings() -> RuntimeSettings {
|
||||
usage_retention_days: 31,
|
||||
ops_event_retention_days: 30,
|
||||
audit_retention_days: 90,
|
||||
prompt_rewrite_rules: Vec::new(),
|
||||
account_error_protection: Default::default(),
|
||||
account_warmup_enabled: false,
|
||||
account_warmup_cron: "0 8 * * *".to_owned(),
|
||||
|
||||
@@ -748,9 +748,11 @@ async fn diagnostics_should_keep_stable_key_and_display_name_contract() {
|
||||
total_request_count: 4,
|
||||
items: vec![DiagnosticObservation {
|
||||
key: "acct_diag".to_owned(),
|
||||
account_provider_kind: Some("openai".to_owned()),
|
||||
providers: vec!["openai".to_owned()],
|
||||
platform_icon: Some("Adobe".to_owned()),
|
||||
account_authentication_kind: authentication_kind.map(str::to_owned),
|
||||
account_plan_type: plan_type.map(str::to_owned),
|
||||
account_plan_type_display: None,
|
||||
name: "diag@example.invalid".to_owned(),
|
||||
request_count: 2,
|
||||
success_count: 2,
|
||||
@@ -790,6 +792,8 @@ async fn diagnostics_should_keep_stable_key_and_display_name_contract() {
|
||||
value["data"]["items"][0]["accountUpstreamPeer"],
|
||||
json!(peer.map(|(d, o)| d && o))
|
||||
);
|
||||
assert_eq!(value["data"]["items"][0]["providers"], json!(["openai"]));
|
||||
assert_eq!(value["data"]["items"][0]["platformIcon"], "Adobe");
|
||||
assert_eq!(value["data"]["items"][0]["requestShare"], 0.5);
|
||||
assert_eq!(value["data"]["items"][0]["retryCount"], 3);
|
||||
assert_eq!(value["data"]["items"][0]["retryRate"], 0.5);
|
||||
@@ -980,6 +984,7 @@ async fn usage_route_projects_request_facts_and_billing() {
|
||||
.lock()
|
||||
.expect("usage records")
|
||||
.push(UsageListRecord {
|
||||
platform_icon: None,
|
||||
provider_account_upstream_peer: None,
|
||||
has_upstream_error: false,
|
||||
error_code: None,
|
||||
@@ -1093,6 +1098,12 @@ async fn usage_route_projects_request_facts_and_billing() {
|
||||
closed.error_message =
|
||||
Some("OpenAI WebSocket closed before a terminal response".to_owned());
|
||||
records.push(closed);
|
||||
let mut agy = records[0].clone();
|
||||
agy.id = "request_antigravity".to_owned();
|
||||
agy.provider_kind = Some("antigravity".to_owned());
|
||||
agy.provider_account_plan_type = Some("g1-pro-tier".to_owned());
|
||||
agy.provider_account_plan_type_display = Some("Pro subscription".to_owned());
|
||||
records.push(agy);
|
||||
}
|
||||
let response = observability::router::<AdminTestState>()
|
||||
.with_state(fixture.state())
|
||||
@@ -1112,6 +1123,11 @@ async fn usage_route_projects_request_facts_and_billing() {
|
||||
.expect("usage response body");
|
||||
let value: serde_json::Value = serde_json::from_slice(&body).expect("usage response JSON");
|
||||
|
||||
assert_eq!(value["data"]["items"][5]["accountPlanType"], "g1-pro-tier");
|
||||
assert_eq!(
|
||||
value["data"]["items"][5]["accountPlanTypeDisplay"],
|
||||
"Pro subscription"
|
||||
);
|
||||
assert!(value["data"]["items"][0]["errorCode"].is_null());
|
||||
assert!(value["data"]["items"][0]["errorMessage"].is_null());
|
||||
assert_eq!(value["data"]["items"][3]["errorCode"], "server_error");
|
||||
@@ -1248,6 +1264,7 @@ async fn usage_route_projects_request_facts_and_billing() {
|
||||
"$0.007"
|
||||
);
|
||||
|
||||
let value_before_peer_refresh = value["data"]["items"].as_array().unwrap();
|
||||
// 互联标识随当前摘要变化,重复请求共享同一账号,既有请求快照保持原值
|
||||
for peer in [
|
||||
Some((true, true)),
|
||||
@@ -1277,7 +1294,15 @@ async fn usage_route_projects_request_facts_and_billing() {
|
||||
json!(peer.map(|(d, o)| d && o))
|
||||
);
|
||||
assert_eq!(item["accountName"], "Snapshot Alpha");
|
||||
assert_eq!(item["accountPlanType"], "supergrok_plus");
|
||||
let old = value_before_peer_refresh
|
||||
.iter()
|
||||
.find(|old| old["id"] == item["id"])
|
||||
.unwrap();
|
||||
assert_eq!(item["accountPlanType"], old["accountPlanType"]);
|
||||
assert_eq!(
|
||||
item["accountPlanTypeDisplay"],
|
||||
old["accountPlanTypeDisplay"]
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1941,6 +1966,7 @@ async fn dashboard_summary_identifies_trend_metrics_and_account_usage_values() {
|
||||
.map(|(index, (requests, tokens, last_used_at))| {
|
||||
let account_id = format!("acct_metric_{index}");
|
||||
DashboardAccountUsage {
|
||||
platform_icon: None,
|
||||
upstream: None,
|
||||
account_id: account_id.clone(),
|
||||
provider_kind: "openai".to_owned(),
|
||||
@@ -2132,6 +2158,7 @@ async fn dashboard_relative_time_preserves_server_anchor_boundaries_and_deployme
|
||||
provider_accounts: Default::default(),
|
||||
trend: Vec::new(),
|
||||
account_usage: vec![DashboardAccountUsage {
|
||||
platform_icon: None,
|
||||
upstream: None,
|
||||
account_id: "acct_relative_time".to_owned(),
|
||||
provider_kind: "openai".to_owned(),
|
||||
|
||||
@@ -91,8 +91,71 @@ async fn proxy_location_rejects_invalid_and_incomplete_input() {
|
||||
assert!(created["data"][0]["data"]["record"]["location"].is_null());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn site_tests_use_saved_targets_and_preserve_the_exit_test() {
|
||||
let fixture = AdminTestFixture::new().await;
|
||||
fixture.auth.insert_session("valid-session");
|
||||
let path = "/api/admin/proxies/targets";
|
||||
assert_eq!(
|
||||
request(&fixture, path, None, false).await.0,
|
||||
StatusCode::UNAUTHORIZED
|
||||
);
|
||||
let (_, initial) = request(&fixture, path, None, true).await;
|
||||
let revision = &initial["data"]["revision"];
|
||||
let target = json!({"name":"ChatGPT","url":"https://chatgpt.com/cdn-cgi/trace"});
|
||||
for targets in [
|
||||
json!([{"name":"A","url":"http://example.org"}]),
|
||||
json!([{"name":"A","url":"https://user:pass@example.org"}]),
|
||||
json!([target, target]),
|
||||
] {
|
||||
let (status, _) = request(
|
||||
&fixture,
|
||||
path,
|
||||
Some(json!({"revision":revision,"targets":targets})),
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, StatusCode::BAD_REQUEST);
|
||||
}
|
||||
let settings = json!({"revision":revision,"targets":[target]});
|
||||
let (status, saved) = request(&fixture, path, Some(settings.clone()), true).await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
assert_eq!(
|
||||
request(&fixture, path, Some(settings), true).await.0,
|
||||
StatusCode::CONFLICT
|
||||
);
|
||||
let (status, _) = request(
|
||||
&fixture,
|
||||
"/api/admin/proxies/create",
|
||||
Some(json!([{"name":"Office","proxyUrl":"http://proxy.example:8080"}])),
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
let run_path = "/api/admin/proxies/targets/test";
|
||||
let mut run = json!({"proxyId":"proxy_test","targetName":"ChatGPT","revision":revision});
|
||||
assert_eq!(
|
||||
request(&fixture, run_path, Some(run.clone()), true).await.0,
|
||||
StatusCode::CONFLICT
|
||||
);
|
||||
run["revision"] = saved["data"]["revision"].clone();
|
||||
let (status, response) = request(&fixture, run_path, Some(run.clone()), true).await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
assert_eq!(
|
||||
response["data"],
|
||||
json!({"proxyName":"Office","result":{"kind":"http","status":403,"exitIp":null,"latencyMs":18}})
|
||||
);
|
||||
let (_, page) = request(&fixture, "/api/admin/proxies", None, true).await;
|
||||
assert!(page["data"]["items"][0]["lastTest"].is_null());
|
||||
run["targetName"] = json!("https://another.example");
|
||||
assert_eq!(
|
||||
request(&fixture, run_path, Some(run), true).await.0,
|
||||
StatusCode::NOT_FOUND
|
||||
);
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct MemoryProxies(Mutex<Vec<ProxyRecord>>);
|
||||
pub(super) struct MemoryProxies(Mutex<Vec<ProxyRecord>>, Mutex<Option<ProxyTestTargets>>);
|
||||
|
||||
#[tokio::test]
|
||||
async fn proxy_enabled_updates_preserve_connection_and_omitted_state() {
|
||||
@@ -153,6 +216,38 @@ impl ProxyStore for MemoryProxies {
|
||||
Ok(Revision::new(4).unwrap())
|
||||
}
|
||||
|
||||
async fn test_targets(&self) -> AdminStoreResult<ProxyTestTargets> {
|
||||
Ok(self
|
||||
.1
|
||||
.lock()
|
||||
.unwrap()
|
||||
.clone()
|
||||
.unwrap_or_else(|| ProxyTestTargets {
|
||||
revision: Revision::new(1).unwrap(),
|
||||
targets: vec![],
|
||||
}))
|
||||
}
|
||||
async fn replace_test_targets(
|
||||
&self,
|
||||
settings: &ProxyTestTargets,
|
||||
_: &MutationContext,
|
||||
) -> AdminStoreResult<Revision> {
|
||||
let mut saved = self.1.lock().unwrap();
|
||||
let current = saved.as_ref().map_or(1, |value| value.revision.get());
|
||||
if current != settings.revision.get() {
|
||||
return Err(AdminStoreError::new(
|
||||
AdminStoreErrorKind::StaleRevision,
|
||||
"proxy test targets",
|
||||
"stale revision",
|
||||
));
|
||||
}
|
||||
let revision = Revision::new(current + 1).unwrap();
|
||||
*saved = Some(ProxyTestTargets {
|
||||
revision,
|
||||
targets: settings.targets.clone(),
|
||||
});
|
||||
Ok(revision)
|
||||
}
|
||||
async fn reserve_import(
|
||||
&self,
|
||||
_: &str,
|
||||
@@ -192,6 +287,7 @@ impl ProxyStore for MemoryProxies {
|
||||
}
|
||||
Ok(ProxyAccountPage {
|
||||
items: vec![ProxyAccountRef {
|
||||
platform_icon: None,
|
||||
upstream: None,
|
||||
id: "acct_linked".to_owned(),
|
||||
name: "工作账号".to_owned(),
|
||||
@@ -348,6 +444,22 @@ pub(super) struct SuccessfulProbe;
|
||||
|
||||
#[async_trait]
|
||||
impl ProxyProbe for SuccessfulProbe {
|
||||
async fn test_target(
|
||||
&self,
|
||||
proxy: &gateway_core::account::OutboundProxy,
|
||||
endpoint: &str,
|
||||
) -> gateway_admin::model::proxies::TargetProbeResult {
|
||||
assert_eq!(proxy.expose_url(), "http://proxy.example:8080/");
|
||||
assert_eq!(endpoint, "https://chatgpt.com/cdn-cgi/trace");
|
||||
TargetProbeResult {
|
||||
latency_ms: 18,
|
||||
outcome: TargetProbeOutcome::Http {
|
||||
status: 403,
|
||||
exit_ip: None,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
async fn test(&self, proxy: ProbeRoute<'_>, detect_location: bool) -> ProxyTestResult {
|
||||
if let ProbeRoute::Proxy(proxy) = proxy {
|
||||
assert_eq!(
|
||||
@@ -458,7 +570,7 @@ async fn proxy_routes_save_reload_test_rename_and_delete_without_exposing_creden
|
||||
assert_eq!(
|
||||
linked["data"]["items"],
|
||||
json!([{
|
||||
"id":"acct_linked", "name":"工作账号", "email":"work@example.invalid",
|
||||
"id":"acct_linked", "name":"工作账号", "email":"work@example.invalid", "platformIcon":null,
|
||||
"provider":"openai", "enabled":true, "authenticationKind":"oauth",
|
||||
"planType":"plus", "planTypeDisplay":"Plus", "groups":[], "upstream":null
|
||||
}])
|
||||
|
||||
@@ -75,8 +75,8 @@ fn backup_settings_report_secret_presence_without_serializing_the_secret() {
|
||||
fn update_body() -> Value {
|
||||
json!({
|
||||
"configRevision": 7,
|
||||
"openaiOauthGuardianReviewModel": true,
|
||||
"openaiRequestCountry": {"mode": "follow_location"},
|
||||
"openaiWebsocketPool": {"maxAgeMs":3300000,"maxConnecting":8,"fastPathBudgetMs":800,"idleTimeoutMs":300000,"streamIdleTimeoutMs":300000},
|
||||
"openaiRequestSettings": {"requestCountry": {"mode":"follow_location"}, "oauthGuardianReviewModel":true,"residency": null, "accountRoutingOverride": null},
|
||||
"codexPrivacyPolicy": {"enabled":false,"onError":"skip_rule","rules":[]},
|
||||
"requestLocationEnabled": false,
|
||||
"requestLocation": {"country":"US", "region":"Ohio", "city":"Piketon", "timezone":"America/New_York"},
|
||||
@@ -106,6 +106,7 @@ fn update_body() -> Value {
|
||||
"usageRetentionDays": 31,
|
||||
"opsEventRetentionDays": 31,
|
||||
"auditRetentionDays": 91,
|
||||
"promptRewriteRules": [],
|
||||
"accountErrorProtection": gateway_core::account::AccountErrorProtection::default(),
|
||||
"accountWarmupEnabled": false,
|
||||
"accountWarmupCron": "0 8 * * *",
|
||||
@@ -289,6 +290,67 @@ async fn error_protection_rules_round_trip_and_invalid_policy_does_not_replace_t
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prompt_rewrite_requires_names_and_prefixes_and_rejects_unknown_fields() {
|
||||
let mut body = update_body();
|
||||
for rule in [
|
||||
json!({"name":"规则", "matchMode":"prefix", "pattern":"prefix", "replacement":"", "unknownField":["xai"]}),
|
||||
json!({"name":"规则", "matchMode":"prefix", "pattern":"", "replacement":""}),
|
||||
json!({"matchMode":"prefix", "pattern":"prefix", "replacement":""}),
|
||||
json!({"name":"规则", "pattern":"prefix", "replacement":""}),
|
||||
json!({"name":"规则", "matchMode":"unknown", "pattern":"prefix", "replacement":""}),
|
||||
json!({"name":"", "matchMode":"prefix", "pattern":"prefix", "replacement":""}),
|
||||
json!({"name":" ", "matchMode":"prefix", "pattern":"prefix", "replacement":""}),
|
||||
] {
|
||||
body["promptRewriteRules"] = json!([rule]);
|
||||
assert!(serde_json::from_value::<UpdateRuntimeSettingsRequest>(body.clone()).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn prompt_rewrite_preview_uses_runtime_matching_and_rejects_invalid_rules() {
|
||||
let fixture = AdminTestFixture::new().await;
|
||||
fixture.auth.insert_session("valid-session");
|
||||
let mut body = json!({
|
||||
"rule": {"name":"DSH", "matchMode":"regex", "pattern":"(?i)you are (DSH)", "replacement":"Agent $1"},
|
||||
"text":"You are DSH\nKeep this"
|
||||
});
|
||||
let response = app(fixture.state())
|
||||
.oneshot(request(
|
||||
Method::POST,
|
||||
"/api/admin/settings/prompt-rewrite/preview",
|
||||
Some(body.clone()),
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
assert_eq!(
|
||||
response_json(response).await["data"],
|
||||
json!({"matched":true,"output":"Agent DSH\nKeep this"})
|
||||
);
|
||||
body["rule"]["pattern"] = json!("[");
|
||||
let response = app(fixture.state())
|
||||
.oneshot(request(
|
||||
Method::POST,
|
||||
"/api/admin/settings/prompt-rewrite/preview",
|
||||
Some(body.clone()),
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
|
||||
let mut update = update_body();
|
||||
update["promptRewriteRules"] = json!([body["rule"].clone()]);
|
||||
let response = app(fixture.state())
|
||||
.oneshot(request(
|
||||
Method::POST,
|
||||
"/api/admin/settings/update",
|
||||
Some(update),
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn error_protection_requires_an_explicit_policy_in_settings_replacement() {
|
||||
let mut missing = update_body();
|
||||
@@ -575,8 +637,7 @@ fn settings_service_contract_flattens_values_and_rejects_unknown_fields() {
|
||||
command
|
||||
);
|
||||
for field in [
|
||||
"openai_oauth_guardian_review_model",
|
||||
"openai_request_country",
|
||||
"openai_request_settings",
|
||||
"reset_credit_on_low_weekly_quota",
|
||||
] {
|
||||
let mut incomplete = wire.clone();
|
||||
@@ -1473,28 +1534,39 @@ async fn runtime_settings_reject_incomplete_and_stale_replacements() {
|
||||
))
|
||||
};
|
||||
let initial = response_json(read().await.unwrap()).await["data"].clone();
|
||||
assert_eq!(initial["openaiOauthGuardianReviewModel"], true);
|
||||
assert_eq!(
|
||||
initial["openaiRequestCountry"],
|
||||
initial["openaiRequestSettings"]["oauthGuardianReviewModel"],
|
||||
true
|
||||
);
|
||||
assert_eq!(
|
||||
initial["openaiRequestSettings"]["requestCountry"],
|
||||
json!({"mode":"follow_location"})
|
||||
);
|
||||
let mut body = update_body();
|
||||
body["configRevision"] = initial["configRevision"].clone();
|
||||
body["openaiOauthGuardianReviewModel"] = json!(false);
|
||||
body["openaiRequestCountry"] = json!({"mode":"custom","country":"CA"});
|
||||
body["openaiRequestSettings"]["oauthGuardianReviewModel"] = json!(false);
|
||||
body["openaiRequestSettings"]["requestCountry"] = json!({"mode":"custom","country":"CA"});
|
||||
body["openaiRequestSettings"]["residency"] = json!("us");
|
||||
body["openaiRequestSettings"]["accountRoutingOverride"] = json!("us_cr");
|
||||
body["resetCreditOnLowWeeklyQuota"] = json!(true);
|
||||
let response = save(body.clone()).await.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
let saved = response_json(response).await["data"].clone();
|
||||
assert_eq!(saved["resetCreditOnLowWeeklyQuota"], true);
|
||||
assert_eq!(saved["openaiOauthGuardianReviewModel"], false);
|
||||
assert_eq!(saved["openaiRequestCountry"], body["openaiRequestCountry"]);
|
||||
assert_eq!(
|
||||
saved["openaiRequestSettings"]["oauthGuardianReviewModel"],
|
||||
false
|
||||
);
|
||||
assert_eq!(
|
||||
saved["openaiRequestSettings"]["requestCountry"],
|
||||
body["openaiRequestSettings"]["requestCountry"]
|
||||
);
|
||||
assert_eq!(
|
||||
saved["openaiRequestSettings"],
|
||||
body["openaiRequestSettings"]
|
||||
);
|
||||
|
||||
for field in [
|
||||
"openaiOauthGuardianReviewModel",
|
||||
"openaiRequestCountry",
|
||||
"resetCreditOnLowWeeklyQuota",
|
||||
] {
|
||||
for field in ["openaiRequestSettings", "resetCreditOnLowWeeklyQuota"] {
|
||||
let mut incomplete = update_body();
|
||||
incomplete["configRevision"] = saved["configRevision"].clone();
|
||||
incomplete.as_object_mut().unwrap().remove(field);
|
||||
@@ -1508,8 +1580,10 @@ async fn runtime_settings_reject_incomplete_and_stale_replacements() {
|
||||
StatusCode::UNPROCESSABLE_ENTITY
|
||||
);
|
||||
}
|
||||
body["openaiOauthGuardianReviewModel"] = json!(true);
|
||||
body["openaiRequestCountry"] = json!({"mode":"passthrough"});
|
||||
body["openaiRequestSettings"]["oauthGuardianReviewModel"] = json!(true);
|
||||
body["openaiRequestSettings"]["requestCountry"] = json!({"mode":"passthrough"});
|
||||
body["openaiRequestSettings"]["residency"] = Value::Null;
|
||||
body["openaiRequestSettings"]["accountRoutingOverride"] = Value::Null;
|
||||
assert_eq!(
|
||||
save(body.clone()).await.unwrap().status(),
|
||||
StatusCode::CONFLICT
|
||||
@@ -1520,9 +1594,16 @@ async fn runtime_settings_reject_incomplete_and_stale_replacements() {
|
||||
let response = save(body).await.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
let changed = response_json(response).await["data"].clone();
|
||||
assert_eq!(changed["openaiOauthGuardianReviewModel"], true);
|
||||
assert_eq!(
|
||||
changed["openaiRequestCountry"],
|
||||
changed["openaiRequestSettings"]["oauthGuardianReviewModel"],
|
||||
true
|
||||
);
|
||||
assert_eq!(
|
||||
changed["openaiRequestSettings"],
|
||||
json!({"requestCountry":{"mode":"passthrough"},"oauthGuardianReviewModel":true,"residency":null,"accountRoutingOverride":null})
|
||||
);
|
||||
assert_eq!(
|
||||
changed["openaiRequestSettings"]["requestCountry"],
|
||||
json!({"mode":"passthrough"})
|
||||
);
|
||||
}
|
||||
@@ -1541,14 +1622,14 @@ fn openai_request_settings_validate_modes_and_country_codes() {
|
||||
json!({"mode":"unknown"}),
|
||||
] {
|
||||
let mut body = update_body();
|
||||
body["openaiRequestCountry"] = invalid.clone();
|
||||
body["openaiRequestSettings"]["requestCountry"] = invalid.clone();
|
||||
if let Ok(request) = serde_json::from_value::<UpdateRuntimeSettingsRequest>(body) {
|
||||
assert!(request.validate().is_err(), "{invalid}");
|
||||
}
|
||||
}
|
||||
for invalid in [json!(null), json!("true"), json!(1)] {
|
||||
let mut body = update_body();
|
||||
body["openaiOauthGuardianReviewModel"] = invalid;
|
||||
body["openaiRequestSettings"]["oauthGuardianReviewModel"] = invalid;
|
||||
assert!(serde_json::from_value::<UpdateRuntimeSettingsRequest>(body).is_err());
|
||||
}
|
||||
}
|
||||
@@ -1732,3 +1813,64 @@ fn reset_credit_weekly_threshold_accepts_unset_and_zero_to_one_hundred() {
|
||||
assert!(serde_json::from_value::<UpdateRuntimeSettingsRequest>(body).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn openai_request_settings_validate_without_normalizing_values() {
|
||||
for value in [
|
||||
None,
|
||||
Some(""),
|
||||
Some("us"),
|
||||
Some("us_cr"),
|
||||
Some("custom-value"),
|
||||
Some(" US "),
|
||||
] {
|
||||
let mut body = update_body();
|
||||
body["openaiRequestSettings"]["residency"] = json!(value);
|
||||
body["openaiRequestSettings"]["accountRoutingOverride"] = json!(value);
|
||||
let request: UpdateRuntimeSettingsRequest = serde_json::from_value(body).unwrap();
|
||||
request.validate().unwrap();
|
||||
assert_eq!(
|
||||
request.values.openai_request_settings.residency.as_deref(),
|
||||
value
|
||||
);
|
||||
}
|
||||
for field in ["residency", "accountRoutingOverride"] {
|
||||
for value in ["us\r\nx-injected: true", "us\n", "\0", "国"] {
|
||||
let mut body = update_body();
|
||||
body["openaiRequestSettings"][field] = json!(value);
|
||||
let request: UpdateRuntimeSettingsRequest = serde_json::from_value(body).unwrap();
|
||||
assert!(request.validate().is_err());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn websocket_pool_settings_validate_numeric_boundaries() {
|
||||
for (field, values) in [
|
||||
(
|
||||
"maxAgeMs",
|
||||
vec![json!(0), json!(-1), json!(1.5), Value::Null],
|
||||
),
|
||||
("maxConnecting", vec![json!(0), json!(4294967296_u64)]),
|
||||
("fastPathBudgetMs", vec![json!(0), json!(15001)]),
|
||||
("idleTimeoutMs", vec![json!(0)]),
|
||||
("streamIdleTimeoutMs", vec![json!(-1), json!("300000")]),
|
||||
] {
|
||||
for value in values {
|
||||
let mut body = update_body();
|
||||
body["openaiWebsocketPool"][field] = value;
|
||||
let rejected = match serde_json::from_value::<UpdateRuntimeSettingsRequest>(body) {
|
||||
Ok(request) => request.validate().is_err(),
|
||||
Err(_) => true,
|
||||
};
|
||||
assert!(rejected, "invalid {field}");
|
||||
}
|
||||
}
|
||||
for budget in [1, 15000] {
|
||||
let mut body = update_body();
|
||||
body["openaiWebsocketPool"]["fastPathBudgetMs"] = json!(budget);
|
||||
body["openaiWebsocketPool"]["streamIdleTimeoutMs"] = json!(0);
|
||||
let request: UpdateRuntimeSettingsRequest = serde_json::from_value(body).unwrap();
|
||||
request.validate().unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -276,6 +276,33 @@ async fn request_middleware_sees_original_chat_and_preserves_the_endpoint() {
|
||||
assert_eq!(fixture.trace.commits.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn header_only_middleware_updates_the_decoded_session_context() {
|
||||
let middleware = Arc::new(RequestMiddleware {
|
||||
expected_operation: Some(gateway_core::operation::OperationKind::Generate),
|
||||
request_update: Some(|request| {
|
||||
let (protocol, mut headers, body) = request.clone().into_parts();
|
||||
headers.push(gateway_core::engine::middleware::MiddlewareHeader::new(
|
||||
"session-id",
|
||||
Bytes::from_static(b"rewritten-session"),
|
||||
));
|
||||
request
|
||||
.replace_parts(protocol, headers, body, None)
|
||||
.unwrap()
|
||||
}),
|
||||
..RequestMiddleware::default()
|
||||
});
|
||||
let mut execution = Execution::new(Session::new(vec![created(), completed("ok")]));
|
||||
execution.middleware = Some(middleware.frozen());
|
||||
let fixture = Fixture::with_execution(execution).await;
|
||||
let response = fixture.post(chat_request(false)).await;
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
assert_eq!(
|
||||
fixture.captured().context["session_id"],
|
||||
"rewritten-session"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn dropping_chat_body_cancels_and_finalizes_the_original_execution() {
|
||||
let mut session = Session::new(vec![created()]);
|
||||
|
||||
@@ -397,7 +397,7 @@ fn local_provider_capacity_exhaustion_should_map_to_service_unavailable() {
|
||||
);
|
||||
assert_eq!(
|
||||
projected.safe_message(),
|
||||
"All eligible upstream accounts are temporarily busy."
|
||||
"The gateway account pool is busy."
|
||||
);
|
||||
}
|
||||
|
||||
@@ -429,7 +429,7 @@ fn no_eligible_provider_account_should_preserve_safe_provider_detail() {
|
||||
);
|
||||
assert_eq!(
|
||||
gateway.safe_message(),
|
||||
"No upstream provider is available for this request."
|
||||
"The gateway found no eligible account for this request."
|
||||
);
|
||||
}
|
||||
|
||||
@@ -447,7 +447,7 @@ fn provider_infrastructure_failure_should_have_a_distinct_client_contract() {
|
||||
);
|
||||
assert_eq!(
|
||||
projected.safe_message(),
|
||||
"Upstream accounts are temporarily inaccessible."
|
||||
"Gateway account selection is temporarily unavailable."
|
||||
);
|
||||
}
|
||||
|
||||
@@ -462,7 +462,7 @@ fn no_eligible_provider_account_should_map_to_service_unavailable() {
|
||||
assert_eq!(projected.kind(), GatewayErrorKind::NoAvailableProvider);
|
||||
assert_eq!(
|
||||
projected.safe_message(),
|
||||
"No upstream provider is available for this request."
|
||||
"The gateway found no eligible account for this request."
|
||||
);
|
||||
}
|
||||
|
||||
@@ -525,31 +525,30 @@ fn engine_provider_credential_failures_should_not_impersonate_client_auth_failur
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn engine_provider_quota_exhaustion_should_use_the_retryable_capacity_contract() {
|
||||
fn provider_quota_exhaustion_preserves_its_kind_and_retryable_fallback() {
|
||||
let error = EngineError::Provider(ProviderError::new(
|
||||
ProviderErrorKind::QuotaExhausted,
|
||||
UpstreamSendState::Sent,
|
||||
));
|
||||
|
||||
let kind = gateway_error_from_engine(&error).kind();
|
||||
assert_eq!(kind.as_str(), "quota_exhausted");
|
||||
assert_eq!(
|
||||
gateway_error_from_engine(&error).kind(),
|
||||
GatewayErrorKind::RateLimited
|
||||
gateway_error_contract(kind),
|
||||
(
|
||||
StatusCode::TOO_MANY_REQUESTS,
|
||||
"rate_limit_error",
|
||||
"rate_limit_exceeded"
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn locally_exhausted_account_pool_returns_official_usage_limit_contract() {
|
||||
let error = EngineError::Provider(
|
||||
ProviderError::new(
|
||||
ProviderErrorKind::QuotaExhausted,
|
||||
UpstreamSendState::NotSent,
|
||||
)
|
||||
.with_client_visible_upstream_error(ClientVisibleUpstreamError::new(
|
||||
"All eligible accounts have exhausted their quota.",
|
||||
Some("usage_limit_reached".to_owned()),
|
||||
Some("usage_limit_reached".to_owned()),
|
||||
)),
|
||||
);
|
||||
let error = EngineError::Provider(ProviderError::new(
|
||||
ProviderErrorKind::AccountPoolQuotaExhausted,
|
||||
UpstreamSendState::NotSent,
|
||||
));
|
||||
let response = engine_error_response(&error);
|
||||
assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS);
|
||||
let body: serde_json::Value =
|
||||
|
||||
@@ -37,6 +37,7 @@ const BODY: &str = r#"{ "contents":[{"role":"user","parts":[{"text":"Read record
|
||||
#[derive(Default)]
|
||||
struct Execution {
|
||||
client: Option<AuthenticatedClient>,
|
||||
catalog: Option<Vec<gateway_core::routing::PublicModelDescriptor>>,
|
||||
session: Mutex<Option<Session>>,
|
||||
seen: Mutex<Option<PreparedExecutionRequest>>,
|
||||
}
|
||||
@@ -61,6 +62,37 @@ impl ExecutionService for Execution {
|
||||
fn public_models(&self, _: &AuthenticatedClient) -> Vec<PublicModelId> {
|
||||
vec![]
|
||||
}
|
||||
fn client_model_catalog<'a>(
|
||||
&'a self,
|
||||
client: &'a AuthenticatedClient,
|
||||
protocol: &'a str,
|
||||
_: &'a str,
|
||||
_: Option<&'a axum::http::HeaderValue>,
|
||||
) -> BoxFuture<
|
||||
'a,
|
||||
Result<
|
||||
Vec<gateway_core::routing::PublicModelDescriptor>,
|
||||
gateway_core::routing::ProviderCatalogUnavailable,
|
||||
>,
|
||||
> {
|
||||
use gateway_core::routing::{ModelPresentation, PublicModelDescriptor, PublicModelProfile};
|
||||
assert_eq!(protocol, GENAI_PROTOCOL);
|
||||
Box::pin(async {
|
||||
Ok(self.catalog.clone().unwrap_or_else(|| {
|
||||
client
|
||||
.snapshot()
|
||||
.public_models_for_scope(client.policy().account_scope())
|
||||
.into_iter()
|
||||
.map(|id| {
|
||||
PublicModelDescriptor::Adapted(PublicModelProfile::new(
|
||||
id,
|
||||
ModelPresentation::default(),
|
||||
))
|
||||
})
|
||||
.collect()
|
||||
}))
|
||||
})
|
||||
}
|
||||
fn contains_public_model(&self, _: &AuthenticatedClient, _: &PublicModelId) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
@@ -176,6 +176,10 @@ fn agent_menu_client() -> AuthenticatedClient {
|
||||
"model-b",
|
||||
BTreeMap::from([(account.clone(), listed(1, "Bee"))]),
|
||||
),
|
||||
(
|
||||
"gemini-3.1-flash-image",
|
||||
BTreeMap::from([(account.clone(), listed(2, "Image"))]),
|
||||
),
|
||||
(
|
||||
"model-hidden",
|
||||
BTreeMap::from([
|
||||
@@ -220,6 +224,23 @@ fn agent_menu_client() -> AuthenticatedClient {
|
||||
super::super::authenticated_client_from_snapshot(KEY, snapshot)
|
||||
}
|
||||
|
||||
fn catalog_client() -> AuthenticatedClient {
|
||||
let source = client();
|
||||
let settings =
|
||||
source
|
||||
.snapshot()
|
||||
.settings()
|
||||
.clone()
|
||||
.with_model_mappings(std::collections::BTreeMap::from([(
|
||||
"alias-a".into(),
|
||||
"model-a".into(),
|
||||
)]));
|
||||
super::super::authenticated_client_from_snapshot(
|
||||
KEY,
|
||||
source.snapshot().with_settings(&settings).unwrap(),
|
||||
)
|
||||
}
|
||||
|
||||
async fn agent_query(router: &axum::Router, path: &str, user_agent: &str) -> Value {
|
||||
let response = router
|
||||
.clone()
|
||||
@@ -236,6 +257,86 @@ async fn agent_query(router: &axum::Router, path: &str, user_agent: &str) -> Val
|
||||
serde_json::from_slice(&to_bytes(response.into_body(), 8192).await.unwrap()).unwrap()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn native_catalog_preserves_metadata_and_aliases_for_every_client() {
|
||||
use gateway_core::{operation::RawJsonPayload, routing::PublicModelDescriptor};
|
||||
let document = json!({
|
||||
"displayName":"Upstream Model", "tagTitle":"New", "tagDescription":"Leaving on Nov 30.",
|
||||
"maxTokens":1048576, "maxOutputTokens":65536,
|
||||
"future":{"capability":true},
|
||||
});
|
||||
let payload = RawJsonPayload::new(
|
||||
GENAI_PROTOCOL,
|
||||
serde_json::to_vec(&document).unwrap().into(),
|
||||
)
|
||||
.unwrap();
|
||||
let router = api_router(Arc::new(Execution {
|
||||
client: Some(catalog_client()),
|
||||
catalog: Some(
|
||||
["model-a", "model-b", "model-c", "alias-a"]
|
||||
.into_iter()
|
||||
.map(|id| PublicModelDescriptor::Native {
|
||||
model: PublicModelId::new(id).unwrap(),
|
||||
payload: payload.clone(),
|
||||
})
|
||||
.collect(),
|
||||
),
|
||||
..Default::default()
|
||||
}))
|
||||
.await;
|
||||
for agent in [
|
||||
"ordinary",
|
||||
"antigravity/hub/2.34.0",
|
||||
"antigravity/cli/1.5.18",
|
||||
] {
|
||||
let first = agent_query(&router, "/v1beta/models?pageSize=2", agent).await;
|
||||
let second = agent_query(
|
||||
&router,
|
||||
&format!(
|
||||
"/v1beta/models?pageSize=2&pageToken={}",
|
||||
first["nextPageToken"].as_str().unwrap()
|
||||
),
|
||||
agent,
|
||||
)
|
||||
.await;
|
||||
assert!(second.get("nextPageToken").is_none());
|
||||
let entries = first["models"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.chain(second["models"].as_array().unwrap());
|
||||
assert_eq!(
|
||||
entries
|
||||
.clone()
|
||||
.map(|v| v["name"].as_str().unwrap())
|
||||
.collect::<Vec<_>>(),
|
||||
[
|
||||
"models/alias-a",
|
||||
"models/model-a",
|
||||
"models/model-b",
|
||||
"models/model-c"
|
||||
]
|
||||
);
|
||||
for entry in entries {
|
||||
let detail = agent_query(
|
||||
&router,
|
||||
&format!("/v1beta/{}", entry["name"].as_str().unwrap()),
|
||||
agent,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(entry, &detail);
|
||||
for (key, expected) in document.as_object().unwrap() {
|
||||
assert_eq!(&entry[key], expected, "{key}");
|
||||
}
|
||||
assert_eq!(
|
||||
entry["supportedGenerationMethods"],
|
||||
json!(["generateContent", "streamGenerateContent", "countTokens"])
|
||||
);
|
||||
assert!(entry.get("inputTokenLimit").is_none());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn agent_menus_apply_scoped_visibility_names_and_order_before_pagination() {
|
||||
let router = api_router(Arc::new(Execution {
|
||||
@@ -273,7 +374,7 @@ async fn agent_menus_apply_scoped_visibility_names_and_order_before_pagination()
|
||||
names(&second),
|
||||
vec![
|
||||
(json!("models/model-b"), json!("Bee")),
|
||||
(json!("models/model-fallback"), json!("model-fallback")),
|
||||
(json!("models/gemini-3.1-flash-image"), json!("Image")),
|
||||
]
|
||||
);
|
||||
let third = agent_query(
|
||||
@@ -287,7 +388,10 @@ async fn agent_menus_apply_scoped_visibility_names_and_order_before_pagination()
|
||||
.await;
|
||||
assert_eq!(
|
||||
names(&third),
|
||||
vec![(json!("models/model-plain"), json!("model-plain"))]
|
||||
vec![
|
||||
(json!("models/model-fallback"), json!("model-fallback")),
|
||||
(json!("models/model-plain"), json!("model-plain")),
|
||||
]
|
||||
);
|
||||
assert!(third.get("nextPageToken").is_none());
|
||||
let detail = agent_query(&router, "/v1beta/models/model-hidden", agent).await;
|
||||
|
||||
@@ -39,6 +39,7 @@ pub(in crate::data_plane) struct RequestMiddleware {
|
||||
pub(in crate::data_plane) short_circuit_json: Option<Bytes>,
|
||||
pub(in crate::data_plane) settings:
|
||||
Option<fn(&mut gateway_core::routing::request_settings::ExecutionSettings)>,
|
||||
pub(in crate::data_plane) request_update: Option<fn(MiddlewareRequest) -> MiddlewareRequest>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
@@ -136,6 +137,9 @@ impl MiddlewarePlan for RequestMiddleware {
|
||||
Err(error) => return Box::pin(async move { Err(error) }),
|
||||
};
|
||||
}
|
||||
if let Some(update) = self.request_update {
|
||||
request = update(request);
|
||||
}
|
||||
Box::pin(async move {
|
||||
if let Some(body) = short_circuit_json {
|
||||
return Ok(MiddlewareResponse::new(
|
||||
|
||||
@@ -34,7 +34,9 @@ async fn anthropic_models_use_explicit_headers_and_cursor_pagination() {
|
||||
.clone()
|
||||
.oneshot(
|
||||
Request::get(path)
|
||||
.header(AUTHORIZATION, "Bearer sk_models_test")
|
||||
.header("x-api-key", "sk_models_test")
|
||||
.header("anthropic-version", "2023-06-01")
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
@@ -90,6 +92,7 @@ async fn anthropic_model_detail_keeps_public_model_access() {
|
||||
.oneshot(
|
||||
Request::get(path)
|
||||
.header("x-api-key", "sk_models_test")
|
||||
.header("anthropic-version", "2023-06-01")
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
@@ -296,6 +299,22 @@ impl ExecutionService for ModelsExecution {
|
||||
}
|
||||
}
|
||||
|
||||
fn authenticated_model_requests(path: &str) -> [Request<Body>; 3] {
|
||||
let api_key_request = Request::get(path)
|
||||
.header("x-api-key", "sk_models_test")
|
||||
.body(Body::empty())
|
||||
.expect("API key request");
|
||||
let mut dual_header_request = authorized_request(path);
|
||||
dual_header_request
|
||||
.headers_mut()
|
||||
.insert("x-api-key", "sk_models_test".parse().expect("API key"));
|
||||
[
|
||||
authorized_request(path),
|
||||
api_key_request,
|
||||
dual_header_request,
|
||||
]
|
||||
}
|
||||
|
||||
fn authorized_request(path: &str) -> Request<Body> {
|
||||
Request::get(path)
|
||||
.header(AUTHORIZATION, "Bearer sk_models_test")
|
||||
@@ -490,18 +509,20 @@ async fn native_catalog_failure_does_not_publish_a_synthetic_or_empty_success()
|
||||
requested_versions: Mutex::default(),
|
||||
middleware: None,
|
||||
});
|
||||
let response = api_router(execution)
|
||||
.await
|
||||
.oneshot(authorized_request("/v1/models?client_version=0.154.0"))
|
||||
.await
|
||||
.expect("response");
|
||||
assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
|
||||
let body = to_bytes(response.into_body(), usize::MAX)
|
||||
.await
|
||||
.expect("body");
|
||||
let value: serde_json::Value = serde_json::from_slice(&body).expect("JSON");
|
||||
assert_eq!(value["error"]["code"], "model_catalog_unavailable");
|
||||
assert!(value.get("models").is_none());
|
||||
for request in authenticated_model_requests("/v1/models?client_version=0.154.0") {
|
||||
let response = api_router(execution.clone())
|
||||
.await
|
||||
.oneshot(request)
|
||||
.await
|
||||
.expect("response");
|
||||
assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
|
||||
let body = to_bytes(response.into_body(), usize::MAX)
|
||||
.await
|
||||
.expect("body");
|
||||
let value: serde_json::Value = serde_json::from_slice(&body).expect("JSON");
|
||||
assert_eq!(value["error"]["code"], "model_catalog_unavailable");
|
||||
assert!(value.get("models").is_none());
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -781,52 +802,64 @@ async fn models_should_preserve_unknown_context_windows() {
|
||||
|
||||
#[tokio::test]
|
||||
async fn models_should_keep_the_codex_contract_when_profiles_are_empty() {
|
||||
let response = api_router(ModelsExecution::new())
|
||||
.await
|
||||
.oneshot(authorized_request("/v1/models?client_version=0.145.0"))
|
||||
.await
|
||||
.expect("list empty Codex models response");
|
||||
let body = to_bytes(response.into_body(), usize::MAX)
|
||||
.await
|
||||
.expect("read empty Codex models body");
|
||||
let value: serde_json::Value = serde_json::from_slice(&body).expect("Codex models JSON");
|
||||
for request in authenticated_model_requests("/v1/models?client_version=0.145.0") {
|
||||
let response = api_router(ModelsExecution::new())
|
||||
.await
|
||||
.oneshot(request)
|
||||
.await
|
||||
.expect("list empty Codex models response");
|
||||
let body = to_bytes(response.into_body(), usize::MAX)
|
||||
.await
|
||||
.expect("read empty Codex models body");
|
||||
let value: serde_json::Value = serde_json::from_slice(&body).expect("Codex models JSON");
|
||||
|
||||
assert_eq!(value, serde_json::json!({ "models": [] }));
|
||||
assert_eq!(value, serde_json::json!({ "models": [] }));
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn models_with_provider_profiles_should_keep_the_openai_list_contract() {
|
||||
let response = api_router(ModelsExecution::with_profiles())
|
||||
.await
|
||||
.oneshot(authorized_request("/v1/models"))
|
||||
.await
|
||||
.expect("list compatible models response");
|
||||
let body = to_bytes(response.into_body(), usize::MAX)
|
||||
.await
|
||||
.expect("read compatible models body");
|
||||
let value: serde_json::Value = serde_json::from_slice(&body).expect("models JSON");
|
||||
for request in authenticated_model_requests("/v1/models") {
|
||||
let response = api_router(ModelsExecution::with_profiles())
|
||||
.await
|
||||
.oneshot(request)
|
||||
.await
|
||||
.expect("list compatible models response");
|
||||
let body = to_bytes(response.into_body(), usize::MAX)
|
||||
.await
|
||||
.expect("read compatible models body");
|
||||
let value: serde_json::Value = serde_json::from_slice(&body).expect("models JSON");
|
||||
|
||||
assert_eq!(
|
||||
value,
|
||||
serde_json::json!({
|
||||
"object": "list",
|
||||
"data": [
|
||||
{"id":"model-a","object":"model","created":1700000000_i64,"owned_by":"gateway"},
|
||||
{"id":"model-b","object":"model","created":1700000000_i64,"owned_by":"gateway"}
|
||||
]
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
value,
|
||||
serde_json::json!({
|
||||
"object": "list",
|
||||
"data": [
|
||||
{"id":"model-a","object":"model","created":1700000000_i64,"owned_by":"gateway"},
|
||||
{"id":"model-b","object":"model","created":1700000000_i64,"owned_by":"gateway"}
|
||||
]
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn model_detail_should_keep_the_official_path_id_contract() {
|
||||
let response = api_router(ModelsExecution::new())
|
||||
.await
|
||||
.oneshot(authorized_request("/v1/models/model-a"))
|
||||
.await
|
||||
.expect("model detail response");
|
||||
for request in authenticated_model_requests("/v1/models/responses-only") {
|
||||
let response = api_router(ModelsExecution::new())
|
||||
.await
|
||||
.oneshot(request)
|
||||
.await
|
||||
.expect("model detail response");
|
||||
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
let body = to_bytes(response.into_body(), usize::MAX)
|
||||
.await
|
||||
.expect("model body");
|
||||
let value: serde_json::Value = serde_json::from_slice(&body).expect("model JSON");
|
||||
assert_eq!(value["id"], "responses-only");
|
||||
assert_eq!(value["object"], "model");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
||||
@@ -91,6 +91,7 @@ async fn fixture(sharing: ClientPeerSharing, plaintext: &str) -> (AdminTestFixtu
|
||||
last_error_message: None,
|
||||
};
|
||||
*fixture.account.lock().unwrap() = Some(AccountPageItem {
|
||||
platform_icon: None,
|
||||
protection_rules: Vec::new(),
|
||||
capacity: AccountCapacity {
|
||||
used_slots: None,
|
||||
|
||||
@@ -548,6 +548,64 @@ async fn opening_ids_stay_in_metadata_but_do_not_identify_initial_failures() {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn header_only_request_middleware_updates_websocket_turn_context() {
|
||||
let middleware = Arc::new(crate::data_plane::middleware::RequestMiddleware {
|
||||
expected_operation: Some(gateway_core::operation::OperationKind::Generate),
|
||||
request_update: Some(|request| {
|
||||
let (protocol, mut headers, body) = request.clone().into_parts();
|
||||
headers.push(gateway_core::engine::middleware::MiddlewareHeader::new(
|
||||
"x-codex-turn-state",
|
||||
Bytes::from_static(b"rewritten-turn"),
|
||||
));
|
||||
request
|
||||
.replace_parts(protocol, headers, body, None)
|
||||
.unwrap()
|
||||
}),
|
||||
..Default::default()
|
||||
});
|
||||
let trace = Arc::new(AtomicFailureTrace {
|
||||
middleware: Some(middleware.frozen()),
|
||||
initial_errors: Mutex::new(VecDeque::from([EngineError::Provider(upstream_failure(
|
||||
502,
|
||||
b"",
|
||||
Vec::new(),
|
||||
))])),
|
||||
..Default::default()
|
||||
});
|
||||
let (mut socket, _server) = connect(Arc::clone(&trace), Vec::new()).await;
|
||||
send_request(&mut socket).await;
|
||||
next_error(&mut socket).await;
|
||||
assert_eq!(
|
||||
trace.request_turn_headers.lock().unwrap().as_slice(),
|
||||
[[Some("rewritten-turn".to_owned()), None, None, None]]
|
||||
);
|
||||
socket.close(None).await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn request_middleware_cannot_reuse_decoded_facts_after_replacing_a_websocket_frame() {
|
||||
let middleware = Arc::new(crate::data_plane::middleware::RequestMiddleware {
|
||||
expected_operation: Some(gateway_core::operation::OperationKind::Generate),
|
||||
request_update: Some(|request| {
|
||||
let (protocol, headers, _) = request.clone().into_parts();
|
||||
request
|
||||
.replace_parts(protocol, headers, Bytes::from_static(b"{}"), None)
|
||||
.unwrap()
|
||||
}),
|
||||
..Default::default()
|
||||
});
|
||||
let trace = Arc::new(AtomicFailureTrace {
|
||||
middleware: Some(middleware.frozen()),
|
||||
..Default::default()
|
||||
});
|
||||
let (mut socket, _server) = connect(Arc::clone(&trace), Vec::new()).await;
|
||||
send_request(&mut socket).await;
|
||||
next_error(&mut socket).await;
|
||||
assert_eq!(trace.starts.load(Ordering::Acquire), 0);
|
||||
socket.close(None).await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn errors_on_a_reused_connection_keep_their_own_upstream_ids() {
|
||||
let errors = ["req_first", "req_second"].map(|request_id| {
|
||||
@@ -687,14 +745,9 @@ async fn initial_continuation_recovery_delivers_the_official_client_replay_signa
|
||||
#[tokio::test]
|
||||
async fn locally_exhausted_account_pool_sends_one_official_usage_limit_error() {
|
||||
let provider = ProviderError::new(
|
||||
ProviderErrorKind::QuotaExhausted,
|
||||
ProviderErrorKind::AccountPoolQuotaExhausted,
|
||||
UpstreamSendState::NotSent,
|
||||
)
|
||||
.with_client_visible_upstream_error(ClientVisibleUpstreamError::new(
|
||||
"All eligible accounts have exhausted their quota.",
|
||||
Some("usage_limit_reached".to_owned()),
|
||||
Some("usage_limit_reached".to_owned()),
|
||||
));
|
||||
);
|
||||
let error = initial_error(EngineError::Provider(provider), Vec::new()).await;
|
||||
assert_eq!(error["status"], 429);
|
||||
assert_eq!(error["error"]["type"], "usage_limit_reached");
|
||||
|
||||
@@ -18,6 +18,7 @@ pub(super) async fn fixture() -> AdminTestFixture {
|
||||
let fixture = key_fixture().await;
|
||||
let now = Utc::now();
|
||||
*fixture.client_key.lock().unwrap() = Some(ClientKeyRecord {
|
||||
validity: Default::default(),
|
||||
peer_sharing: Default::default(),
|
||||
request_profile_overrides: Default::default(),
|
||||
id: ClientApiKeyId::new("key-42").unwrap(),
|
||||
@@ -100,6 +101,7 @@ pub(super) async fn fixture() -> AdminTestFixture {
|
||||
|
||||
fn usage_record() -> UsageListRecord {
|
||||
UsageListRecord {
|
||||
platform_icon: None,
|
||||
provider_account_upstream_peer: None,
|
||||
has_upstream_error: false,
|
||||
error_code: None,
|
||||
|
||||
@@ -24,6 +24,7 @@ http = "1.5.0"
|
||||
http-body-util = "0.1.5"
|
||||
futures-timer = "3.0.3"
|
||||
gateway-protocol = { path = "../gateway-protocol" }
|
||||
regex-automata = "0.4.19"
|
||||
serde = { version = "1.0.228", features = ["derive", "rc"] }
|
||||
serde_json = { version = "1.0.150", features = ["arbitrary_precision", "preserve_order"] }
|
||||
sha2 = "0.11.0"
|
||||
|
||||
@@ -11,31 +11,6 @@ pub struct RequestLocation {
|
||||
pub timezone: chrono_tz::Tz,
|
||||
}
|
||||
|
||||
/// 独立选择 OpenAI 请求的国家字段,仅自定义模式需要国家代码
|
||||
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
|
||||
#[serde(tag = "mode", rename_all = "snake_case", deny_unknown_fields)]
|
||||
pub enum OpenAiRequestCountry {
|
||||
Default {},
|
||||
Passthrough {},
|
||||
FollowLocation {},
|
||||
Custom { country: String },
|
||||
}
|
||||
|
||||
impl Default for OpenAiRequestCountry {
|
||||
fn default() -> Self {
|
||||
Self::FollowLocation {}
|
||||
}
|
||||
}
|
||||
|
||||
impl OpenAiRequestCountry {
|
||||
pub fn validate(&self) -> Result<(), InvalidRequestLocation> {
|
||||
if let Self::Custom { country } = self {
|
||||
validate_country(country)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
|
||||
pub enum InvalidRequestLocation {
|
||||
#[error("country must contain two uppercase ASCII letters")]
|
||||
@@ -83,7 +58,7 @@ impl RequestLocation {
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_country(country: &str) -> Result<(), InvalidRequestLocation> {
|
||||
pub(crate) fn validate_country(country: &str) -> Result<(), InvalidRequestLocation> {
|
||||
if country.len() == 2 && country.bytes().all(|byte| byte.is_ascii_uppercase()) {
|
||||
Ok(())
|
||||
} else {
|
||||
|
||||
@@ -6,7 +6,8 @@ pub use error_protection::*;
|
||||
mod fast_mode;
|
||||
pub use fast_mode::FastMode;
|
||||
mod location;
|
||||
pub use location::{InvalidRequestLocation, OpenAiRequestCountry, RequestLocation};
|
||||
pub(crate) use location::validate_country;
|
||||
pub use location::{InvalidRequestLocation, RequestLocation};
|
||||
mod model;
|
||||
mod model_access;
|
||||
pub use model_access::{
|
||||
|
||||
@@ -817,6 +817,8 @@ pub struct AccountHistorySnapshot {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub plan_type_snapshot: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub plan_type_display_snapshot: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub notes_snapshot: Option<String>,
|
||||
}
|
||||
|
||||
@@ -828,6 +830,7 @@ impl AccountHistorySnapshot {
|
||||
email: account.email().map(str::to_owned),
|
||||
authentication_kind: account.authentication_kind().to_owned(),
|
||||
plan_type_snapshot: account.plan_type().map(str::to_owned),
|
||||
plan_type_display_snapshot: None,
|
||||
notes_snapshot: account.notes().map(str::to_owned),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -408,14 +408,8 @@ impl QueueRejection {
|
||||
#[must_use]
|
||||
pub fn gateway_error(self) -> crate::error::GatewayError {
|
||||
match self {
|
||||
Self::Full => crate::error::GatewayError::new(
|
||||
crate::error::GatewayErrorKind::ConcurrencyQueueFull,
|
||||
"Request queue is full.",
|
||||
),
|
||||
Self::Timeout => crate::error::GatewayError::new(
|
||||
crate::error::GatewayErrorKind::ConcurrencyQueueTimeout,
|
||||
"Request queue wait timed out.",
|
||||
),
|
||||
Self::Full => crate::error::GatewayError::concurrency_queue_full(),
|
||||
Self::Timeout => crate::error::GatewayError::concurrency_queue_timeout(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,10 +22,10 @@ use crate::engine::probe::AccountProbeTarget;
|
||||
use crate::engine::provider::{Provider, ProviderCallMetadata, ProviderRequest, ProviderStream};
|
||||
use crate::engine::{
|
||||
AccountAttemptContext, AttemptContext, AttemptRecord, AttemptTransport, AttemptTrigger,
|
||||
CommitRequirement, ContinuationAttempt, CoordinatedEvent, EngineError, ExecutionOutcome,
|
||||
ExecutionStore, GatewayEngine, IntermediateFailure, ModelRequestFailureObservation,
|
||||
ModelRequestFinalization, ModelRequestId, NewModelRequest, ProviderAccountStateOwner,
|
||||
RequestAttemptContext, UpstreamSendState,
|
||||
ClientReplayTrigger, CommitRequirement, ContinuationAttempt, CoordinatedEvent, EngineError,
|
||||
ExecutionOutcome, ExecutionStore, GatewayEngine, IntermediateFailure,
|
||||
ModelRequestFailureObservation, ModelRequestFinalization, ModelRequestId, NewModelRequest,
|
||||
ProviderAccountStateOwner, RequestAttemptContext, UpstreamSendState,
|
||||
};
|
||||
use crate::error::{
|
||||
ContinuationRecoveryDisposition, GatewayError, GatewayErrorKind, ProviderError,
|
||||
@@ -1064,10 +1064,7 @@ where
|
||||
}
|
||||
}
|
||||
let Some(candidate) = self.plan.candidates().get(self.candidate_index).cloned() else {
|
||||
let error = GatewayError::new(
|
||||
GatewayErrorKind::NoAvailableProvider,
|
||||
"No upstream service is available.",
|
||||
);
|
||||
let error = super::execution::gateway_error_from_engine(&EngineError::EmptyRoutingPlan);
|
||||
self.finish_failure(FailureFinalization {
|
||||
outcome: ExecutionOutcome::Failed,
|
||||
send_state: self.current_send_state(),
|
||||
@@ -1204,9 +1201,11 @@ where
|
||||
.with_response_control(self.response_control.clone())
|
||||
.with_request_profile(self.request_profiles.get(candidate.provider()).cloned())
|
||||
.with_fast_mode(self.plan.fast_mode())
|
||||
.with_prompt_rewrite_rules(self.plan.prompt_rewrite_rules(candidate.provider()))
|
||||
.with_pricing(self.plan.pricing())
|
||||
.with_request_location(self.plan.request_location().cloned())
|
||||
.with_openai_request_country(self.plan.openai_request_country().clone())
|
||||
.with_openai_websocket_pool(*self.plan.openai_websocket_pool())
|
||||
.with_openai_request_settings(self.plan.openai_request_settings().clone())
|
||||
.with_privacy(self.plan.privacy())
|
||||
.with_request_body_limit(self.plan.request_body_limit())
|
||||
.with_concurrency_wait_budget(self.concurrency_wait_budget.clone())
|
||||
@@ -1473,9 +1472,11 @@ where
|
||||
attempt_trace: &TraceContext,
|
||||
) -> Result<PullOutcome, EngineError> {
|
||||
attempt_trace.record_provider_failure(&error);
|
||||
if self.continuation_attempt == ContinuationAttempt::RotateForClientReplay
|
||||
&& error.continuation_recovery_disposition()
|
||||
== Some(ContinuationRecoveryDisposition::ClientReplayRequired)
|
||||
if matches!(
|
||||
self.continuation_attempt,
|
||||
ContinuationAttempt::RotateForClientReplay(_)
|
||||
) && error.continuation_recovery_disposition()
|
||||
== Some(ContinuationRecoveryDisposition::ClientReplayRequired)
|
||||
&& let Some(original) = self.last_retryable_failure.take()
|
||||
{
|
||||
// 迁移只改变客户端恢复指令;失败分类、发送事实与运维正文仍属于原请求
|
||||
@@ -1488,6 +1489,7 @@ where
|
||||
ProviderErrorKind::NoEligibleAccount
|
||||
| ProviderErrorKind::AccountCapacityUnavailable
|
||||
| ProviderErrorKind::QuotaExhausted
|
||||
| ProviderErrorKind::AccountPoolQuotaExhausted
|
||||
| ProviderErrorKind::ConcurrencyQueueFull
|
||||
| ProviderErrorKind::ConcurrencyQueueTimeout
|
||||
);
|
||||
@@ -1562,6 +1564,15 @@ where
|
||||
.expect("pending connection rotation");
|
||||
self.excluded_accounts.remove(&recovery.account);
|
||||
self.pending_retry = Some(recovery);
|
||||
} else if continuation_retry
|
||||
&& matches!(
|
||||
self.continuation_attempt,
|
||||
ContinuationAttempt::RotateForClientReplay(_)
|
||||
)
|
||||
{
|
||||
// 只有替代账号准入成功后才投影重放信号,空池仍返回原排队错误
|
||||
self.last_retryable_failure_events.clear();
|
||||
self.last_retryable_failure = Some(error);
|
||||
} else if candidate_retry {
|
||||
// 原账号只属于原 Provider,跨候选后不能拿旧钉选作恢复兜底
|
||||
self.connection_rotation = None;
|
||||
@@ -2260,7 +2271,9 @@ where
|
||||
&& !error.retry_is_prohibited()
|
||||
&& self.has_account_rotation_budget() =>
|
||||
{
|
||||
self.continuation_attempt = ContinuationAttempt::RotateForClientReplay;
|
||||
self.continuation_attempt = ContinuationAttempt::RotateForClientReplay(
|
||||
ClientReplayTrigger::UpstreamCapacity,
|
||||
);
|
||||
self.excluded_accounts
|
||||
.insert(current.metadata.provider_account_id().clone());
|
||||
}
|
||||
@@ -2300,27 +2313,23 @@ where
|
||||
self.excluded_accounts
|
||||
.insert(current.metadata.provider_account_id().clone());
|
||||
}
|
||||
ContinuationAttempt::None | ContinuationAttempt::RotateForClientReplay => return false,
|
||||
ContinuationAttempt::None | ContinuationAttempt::RotateForClientReplay(_) => {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// 原生续写的原账号在本地调度阶段已不可用时,交给 Provider 执行跨账号恢复
|
||||
///
|
||||
/// 这不是强制 Smart:下一次 attempt 仍使用请求配置的调度策略
|
||||
/// 只有网关持有
|
||||
/// 对应 Provider 的会话状态时才进入恢复;是否保留 native handle、执行 probe
|
||||
/// 或使用完整 transcript,由 Provider 自己的协议边界决定
|
||||
/// 仅恢复网关持有的会话状态,沿用冻结的调度策略和换号预算
|
||||
/// Provider 决定能否恢复原生状态,或仅允许客户端带完整历史重发
|
||||
fn prepare_unavailable_native_continuation_replay(&mut self, error: &ProviderError) -> bool {
|
||||
if self.account_selection.required_account().is_some()
|
||||
|| self.continuation_attempt != ContinuationAttempt::Native
|
||||
|| self.current_send_state() != UpstreamSendState::NotSent
|
||||
|| !matches!(
|
||||
error.kind(),
|
||||
ProviderErrorKind::NoEligibleAccount
|
||||
| ProviderErrorKind::AccountCapacityUnavailable
|
||||
| ProviderErrorKind::QuotaExhausted
|
||||
)
|
||||
|| self.replay_barrier_reached
|
||||
|| self.delivery_pending
|
||||
{
|
||||
return false;
|
||||
}
|
||||
@@ -2343,7 +2352,20 @@ where
|
||||
return false;
|
||||
}
|
||||
|
||||
self.continuation_attempt = ContinuationAttempt::ReplayAny;
|
||||
self.continuation_attempt = match error.kind() {
|
||||
ProviderErrorKind::ConcurrencyQueueTimeout
|
||||
if error.send_state() == UpstreamSendState::NotSent
|
||||
&& error.continuation_recovery_disposition()
|
||||
== Some(ContinuationRecoveryDisposition::ClientReplayRequired) =>
|
||||
{
|
||||
ContinuationAttempt::RotateForClientReplay(ClientReplayTrigger::AccountQueueTimeout)
|
||||
}
|
||||
ProviderErrorKind::NoEligibleAccount
|
||||
| ProviderErrorKind::AccountCapacityUnavailable
|
||||
| ProviderErrorKind::QuotaExhausted
|
||||
| ProviderErrorKind::AccountPoolQuotaExhausted => ContinuationAttempt::ReplayAny,
|
||||
_ => return false,
|
||||
};
|
||||
self.excluded_accounts.insert(pin.account().clone());
|
||||
true
|
||||
}
|
||||
|
||||
@@ -52,7 +52,7 @@ pub(super) fn map_routing_error(error: crate::validation::RoutingError) -> Gatew
|
||||
| crate::validation::RoutingError::NoCapableProviderEndpoint { .. }
|
||||
| crate::validation::RoutingError::EmptyAccountScope => GatewayError::new(
|
||||
GatewayErrorKind::NoAvailableProvider,
|
||||
"No provider can execute this request.",
|
||||
"The gateway has no eligible provider for this request.",
|
||||
),
|
||||
crate::validation::RoutingError::UnsupportedProviderEndpoint { .. } => GatewayError::new(
|
||||
GatewayErrorKind::Unsupported,
|
||||
@@ -77,7 +77,7 @@ pub fn gateway_error_from_engine(error: &EngineError) -> GatewayError {
|
||||
EngineError::EmptyRoutingPlan | EngineError::ProviderNotRegistered { .. } => {
|
||||
GatewayError::new(
|
||||
GatewayErrorKind::NoAvailableProvider,
|
||||
"No provider is available.",
|
||||
"The gateway has no available provider for this request.",
|
||||
)
|
||||
}
|
||||
EngineError::Store(source) => {
|
||||
|
||||
@@ -1396,11 +1396,20 @@ impl DefaultExecutionService {
|
||||
}
|
||||
ClientAdmissionDecision::Rejected(reason) => {
|
||||
admission.armed = false;
|
||||
if reason == ClientAdmissionRejection::RateLimited || policy.max_waiting == 0 {
|
||||
return Err(GatewayError::new(
|
||||
GatewayErrorKind::RateLimited,
|
||||
"Request exceeds client API key limits.",
|
||||
));
|
||||
match reason {
|
||||
ClientAdmissionRejection::RateLimited => {
|
||||
return Err(GatewayError::new(
|
||||
GatewayErrorKind::KeyRateLimited,
|
||||
"The API key's request rate limit was reached.",
|
||||
));
|
||||
}
|
||||
ClientAdmissionRejection::ConcurrencyLimited if policy.max_waiting == 0 => {
|
||||
return Err(GatewayError::new(
|
||||
GatewayErrorKind::KeyConcurrencyLimited,
|
||||
"The API key's concurrency limit was reached.",
|
||||
));
|
||||
}
|
||||
ClientAdmissionRejection::ConcurrencyLimited => {}
|
||||
}
|
||||
if waiting.elapsed().is_zero()
|
||||
&& let Some(budget) = &self.budget
|
||||
|
||||
@@ -16,6 +16,7 @@ pub mod nested;
|
||||
pub mod observation;
|
||||
pub mod policy;
|
||||
pub mod probe;
|
||||
mod prompt_rewrite;
|
||||
pub mod provider;
|
||||
pub mod response_control;
|
||||
pub mod upstream_adapter;
|
||||
@@ -252,6 +253,13 @@ impl ProviderAccountStateOwner {
|
||||
}
|
||||
}
|
||||
|
||||
/// 只能由客户端携带完整历史恢复的换号原因
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ClientReplayTrigger {
|
||||
UpstreamCapacity,
|
||||
AccountQueueTimeout,
|
||||
}
|
||||
|
||||
/// 当前 attempt 对 previous-response 的唯一处理方式
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ContinuationAttempt {
|
||||
@@ -269,7 +277,7 @@ pub enum ContinuationAttempt {
|
||||
/// 该枚举本身不证明客户端 input 完整,也不授权 Provider 清除 previous-response
|
||||
ReplayAny,
|
||||
/// 仅迁移账号绑定,随后要求客户端携带完整历史重放;不得发送当前增量输入
|
||||
RotateForClientReplay,
|
||||
RotateForClientReplay(ClientReplayTrigger),
|
||||
}
|
||||
|
||||
impl ContinuationAttempt {
|
||||
@@ -280,7 +288,7 @@ impl ContinuationAttempt {
|
||||
Self::Native => "native",
|
||||
Self::ReplayOwner => "replay_owner",
|
||||
Self::ReplayAny => "replay_any",
|
||||
Self::RotateForClientReplay => "rotate_for_client_replay",
|
||||
Self::RotateForClientReplay(_) => "rotate_for_client_replay",
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -317,10 +325,12 @@ pub struct RequestAttemptContext {
|
||||
request_body_limit: Option<usize>,
|
||||
lease_metadata: Option<Arc<crate::provider_ports::ProviderLeaseMetadata>>,
|
||||
response_control: Option<response_control::ResponseControl>,
|
||||
prompt_rewrite_rules: Option<Arc<crate::settings::prompt_rewrite::ProviderPromptRules>>,
|
||||
pricing: Arc<crate::metering::PricingOverrides>,
|
||||
request_profile: Option<crate::account::OpaqueProviderData>,
|
||||
fast_mode: FastMode,
|
||||
openai_request_country: crate::account::OpenAiRequestCountry,
|
||||
openai_websocket_pool: crate::settings::OpenAiWebSocketPoolSettings,
|
||||
openai_request_settings: crate::settings::OpenAiRequestSettings,
|
||||
request_location: Option<crate::account::RequestLocation>,
|
||||
privacy: Option<Arc<dyn crate::settings::privacy::CompiledPrivacyPolicy>>,
|
||||
request_id: ModelRequestId,
|
||||
@@ -388,6 +398,15 @@ impl RequestAttemptContext {
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn with_prompt_rewrite_rules(
|
||||
mut self,
|
||||
rules: Option<Arc<crate::settings::prompt_rewrite::ProviderPromptRules>>,
|
||||
) -> Self {
|
||||
self.prompt_rewrite_rules = rules;
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn with_pricing(mut self, pricing: Arc<crate::metering::PricingOverrides>) -> Self {
|
||||
self.pricing = pricing;
|
||||
@@ -419,11 +438,20 @@ impl RequestAttemptContext {
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn with_openai_request_country(
|
||||
pub fn with_openai_websocket_pool(
|
||||
mut self,
|
||||
country: crate::account::OpenAiRequestCountry,
|
||||
settings: crate::settings::OpenAiWebSocketPoolSettings,
|
||||
) -> Self {
|
||||
self.openai_request_country = country;
|
||||
self.openai_websocket_pool = settings;
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn with_openai_request_settings(
|
||||
mut self,
|
||||
settings: crate::settings::OpenAiRequestSettings,
|
||||
) -> Self {
|
||||
self.openai_request_settings = settings;
|
||||
self
|
||||
}
|
||||
|
||||
@@ -446,9 +474,11 @@ impl RequestAttemptContext {
|
||||
request_id,
|
||||
client_api_key_ref,
|
||||
request_profile: None,
|
||||
prompt_rewrite_rules: None,
|
||||
pricing: Arc::default(),
|
||||
fast_mode: FastMode::Default,
|
||||
openai_request_country: Default::default(),
|
||||
openai_websocket_pool: Default::default(),
|
||||
openai_request_settings: Default::default(),
|
||||
request_location: None,
|
||||
privacy: None,
|
||||
timing_started_at: Instant::now(),
|
||||
@@ -637,7 +667,7 @@ impl AttemptContext {
|
||||
.map(|owner| owner.account()),
|
||||
ContinuationAttempt::None
|
||||
| ContinuationAttempt::ReplayAny
|
||||
| ContinuationAttempt::RotateForClientReplay => None,
|
||||
| ContinuationAttempt::RotateForClientReplay(_) => None,
|
||||
});
|
||||
self.request.upstream_adapters.as_ref().map_or(
|
||||
Ok(upstream_adapter::UpstreamAdapterSelection::Native),
|
||||
@@ -726,8 +756,13 @@ impl AttemptContext {
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn openai_request_country(&self) -> &crate::account::OpenAiRequestCountry {
|
||||
&self.request.openai_request_country
|
||||
pub const fn openai_websocket_pool(&self) -> &crate::settings::OpenAiWebSocketPoolSettings {
|
||||
&self.request.openai_websocket_pool
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn openai_request_settings(&self) -> &crate::settings::OpenAiRequestSettings {
|
||||
&self.request.openai_request_settings
|
||||
}
|
||||
|
||||
/// 当前 attempt 的诊断关联;克隆后可传给后台 transport 任务
|
||||
@@ -809,6 +844,21 @@ impl AttemptContext {
|
||||
self.request.extension_scope()
|
||||
}
|
||||
|
||||
/// 计数由 Provider 解开入站封套后在现有正文上应用同一份规则
|
||||
pub fn rewrite_count_prompt(
|
||||
&self,
|
||||
protocol: &str,
|
||||
body: &mut serde_json::Map<String, serde_json::Value>,
|
||||
) {
|
||||
if let Some(rules) = &self.request.prompt_rewrite_rules
|
||||
&& let Some(edit) = gateway_protocol::prompt_rewrite::plan(protocol, body, |text| {
|
||||
rules.replace_prefix(text)
|
||||
})
|
||||
{
|
||||
edit.apply(body);
|
||||
}
|
||||
}
|
||||
|
||||
/// 在已选账号并持有其 lease 后,以 owned terminal 执行本次 retry 的中间件链
|
||||
///
|
||||
/// terminal 返回的 stream 仍须保持 cold;中间件不能取得 credential、发送状态、
|
||||
@@ -837,6 +887,12 @@ impl AttemptContext {
|
||||
} else {
|
||||
terminal
|
||||
};
|
||||
let terminal = match (&operation, &self.request.prompt_rewrite_rules) {
|
||||
(crate::operation::Operation::Generate(_), Some(rules)) => {
|
||||
prompt_rewrite::wrap(terminal, rules)
|
||||
}
|
||||
_ => terminal,
|
||||
};
|
||||
// 保护观察真正的 Provider terminal,先于 attempt 中间件的响应改写
|
||||
let terminal: provider::ProviderMiddlewareTerminal =
|
||||
if let Some(protection) = self.request.account_error_protection.clone() {
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
//! 在 attempt 中间件提交后应用所选平台的生成规则
|
||||
|
||||
use super::provider::ProviderMiddlewareTerminal;
|
||||
use crate::{operation::Operation, settings::prompt_rewrite::ProviderPromptRules};
|
||||
use std::sync::Arc;
|
||||
|
||||
pub(super) fn wrap(
|
||||
terminal: ProviderMiddlewareTerminal,
|
||||
rules: &Arc<ProviderPromptRules>,
|
||||
) -> ProviderMiddlewareTerminal {
|
||||
let rules = Arc::clone(rules);
|
||||
Box::new(move |mut operation, headers| {
|
||||
if let Operation::Generate(request) = &mut operation {
|
||||
let payload = request.protocol_payload();
|
||||
if let Some(edit) =
|
||||
gateway_protocol::prompt_rewrite::plan(payload.protocol(), payload.body(), |text| {
|
||||
rules.replace_prefix(text)
|
||||
})
|
||||
{
|
||||
request.apply_prompt_edit(edit);
|
||||
}
|
||||
}
|
||||
terminal(operation, headers)
|
||||
})
|
||||
}
|
||||
@@ -40,6 +40,8 @@ pub enum ProviderErrorKind {
|
||||
RateLimited,
|
||||
/// Credential 配额耗尽
|
||||
QuotaExhausted,
|
||||
/// 本地选号确认当前请求的全部可选账号额度耗尽
|
||||
AccountPoolQuotaExhausted,
|
||||
/// 仍有符合条件的账号,但它们暂时没有可调度容量
|
||||
AccountCapacityUnavailable,
|
||||
ConcurrencyQueueFull,
|
||||
@@ -82,6 +84,7 @@ impl ProviderErrorKind {
|
||||
Self::RequestPolicyDenied => "request_policy_denied",
|
||||
Self::RateLimited => "rate_limited",
|
||||
Self::QuotaExhausted => "quota_exhausted",
|
||||
Self::AccountPoolQuotaExhausted => "account_pool_quota_exhausted",
|
||||
Self::AccountCapacityUnavailable => "account_capacity_unavailable",
|
||||
Self::ConcurrencyQueueFull => "concurrency_queue_full",
|
||||
Self::ConcurrencyQueueTimeout => "concurrency_queue_timeout",
|
||||
@@ -1266,8 +1269,16 @@ pub enum GatewayErrorKind {
|
||||
ConcurrencyQueueTimeout,
|
||||
/// Provider 的本地账号基础设施不可用
|
||||
ProviderInfrastructureUnavailable,
|
||||
/// 上游限流
|
||||
/// 请求频率受限
|
||||
RateLimited,
|
||||
/// Provider 账号额度耗尽
|
||||
QuotaExhausted,
|
||||
/// 本地可选账号池额度耗尽
|
||||
AccountPoolQuotaExhausted,
|
||||
/// Client Key 每分钟请求数达到上限
|
||||
KeyRateLimited,
|
||||
/// Client Key 并发已满且未启用排队
|
||||
KeyConcurrencyLimited,
|
||||
/// 当前客户端 Key 的费用预算耗尽
|
||||
BudgetExhausted,
|
||||
/// 上游暂不可用
|
||||
@@ -1301,6 +1312,10 @@ impl GatewayErrorKind {
|
||||
Self::ConcurrencyQueueTimeout => "concurrency_queue_timeout",
|
||||
Self::ProviderInfrastructureUnavailable => "provider_infrastructure_unavailable",
|
||||
Self::RateLimited => "rate_limited",
|
||||
Self::QuotaExhausted => "quota_exhausted",
|
||||
Self::AccountPoolQuotaExhausted => "account_pool_quota_exhausted",
|
||||
Self::KeyRateLimited => "key_rate_limited",
|
||||
Self::KeyConcurrencyLimited => "key_concurrency_limited",
|
||||
Self::BudgetExhausted => "budget_exhausted",
|
||||
Self::UpstreamUnavailable => "upstream_unavailable",
|
||||
Self::MessageTooBig => "message_too_big",
|
||||
@@ -1366,6 +1381,20 @@ impl GatewayError {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) const fn concurrency_queue_full() -> Self {
|
||||
Self::new(
|
||||
GatewayErrorKind::ConcurrencyQueueFull,
|
||||
"The gateway request queue is full.",
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) const fn concurrency_queue_timeout() -> Self {
|
||||
Self::new(
|
||||
GatewayErrorKind::ConcurrencyQueueTimeout,
|
||||
"The request timed out in the gateway queue.",
|
||||
)
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn with_source(mut self, source: impl Into<ErrorSource>) -> Self {
|
||||
self.source = Some(source.into());
|
||||
@@ -1425,7 +1454,7 @@ impl GatewayError {
|
||||
),
|
||||
ProviderErrorKind::SessionPolicyRestricted => Self::new(
|
||||
GatewayErrorKind::InvalidRequest,
|
||||
"No accounts are available under this conversation's restrictions.",
|
||||
"Gateway session restrictions exclude all eligible accounts.",
|
||||
),
|
||||
ProviderErrorKind::ContinuationRecoveryRequired => Self::new(
|
||||
GatewayErrorKind::InvalidRequest,
|
||||
@@ -1443,29 +1472,30 @@ impl GatewayError {
|
||||
|| Self::new(GatewayErrorKind::PolicyDenied, "Request blocked by policy."),
|
||||
Self::from,
|
||||
),
|
||||
ProviderErrorKind::RateLimited | ProviderErrorKind::QuotaExhausted => Self::new(
|
||||
GatewayErrorKind::RateLimited,
|
||||
"Upstream capacity is temporarily unavailable.",
|
||||
ProviderErrorKind::RateLimited => {
|
||||
Self::new(GatewayErrorKind::RateLimited, "Request rate limit reached.")
|
||||
}
|
||||
ProviderErrorKind::QuotaExhausted => Self::new(
|
||||
GatewayErrorKind::QuotaExhausted,
|
||||
"Account quota is exhausted.",
|
||||
),
|
||||
ProviderErrorKind::ConcurrencyQueueFull => Self::new(
|
||||
GatewayErrorKind::ConcurrencyQueueFull,
|
||||
"Request queue is full.",
|
||||
),
|
||||
ProviderErrorKind::ConcurrencyQueueTimeout => Self::new(
|
||||
GatewayErrorKind::ConcurrencyQueueTimeout,
|
||||
"Request queue wait timed out.",
|
||||
ProviderErrorKind::AccountPoolQuotaExhausted => Self::new(
|
||||
GatewayErrorKind::AccountPoolQuotaExhausted,
|
||||
"No eligible gateway account has quota for this request.",
|
||||
),
|
||||
ProviderErrorKind::ConcurrencyQueueFull => Self::concurrency_queue_full(),
|
||||
ProviderErrorKind::ConcurrencyQueueTimeout => Self::concurrency_queue_timeout(),
|
||||
ProviderErrorKind::AccountCapacityUnavailable => Self::new(
|
||||
GatewayErrorKind::AccountCapacityUnavailable,
|
||||
"All eligible upstream accounts are temporarily busy.",
|
||||
"The gateway account pool is busy.",
|
||||
),
|
||||
ProviderErrorKind::NoEligibleAccount => Self::new(
|
||||
GatewayErrorKind::NoAvailableProvider,
|
||||
"No upstream provider is available for this request.",
|
||||
"The gateway found no eligible account for this request.",
|
||||
),
|
||||
ProviderErrorKind::ProviderInfrastructureUnavailable => Self::new(
|
||||
GatewayErrorKind::ProviderInfrastructureUnavailable,
|
||||
"Upstream accounts are temporarily inaccessible.",
|
||||
"Gateway account selection is temporarily unavailable.",
|
||||
),
|
||||
ProviderErrorKind::Timeout => {
|
||||
Self::new(GatewayErrorKind::Timeout, "Upstream request timed out.")
|
||||
|
||||
@@ -462,6 +462,23 @@ impl ClientTurn {
|
||||
}
|
||||
|
||||
impl GenerateRequest {
|
||||
/// 只在命中后对共享请求执行写时复制,重试持有的原请求仍可独立使用
|
||||
pub(crate) fn apply_prompt_edit(&mut self, edit: gateway_protocol::prompt_rewrite::PromptEdit) {
|
||||
let wire = match self.protocol_payload().raw_json_body() {
|
||||
Some(body) => {
|
||||
let Some(updated) = edit.wire(body) else {
|
||||
return;
|
||||
};
|
||||
Some(Bytes::from(updated))
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let payload = Arc::make_mut(&mut self.payload);
|
||||
edit.apply(&mut payload.protocol_payload.body);
|
||||
payload.protocol_payload.raw_json_body = wire;
|
||||
// 只编辑字符串内容,能力、角色与工具结构仍使用已有的 wire_facts
|
||||
}
|
||||
|
||||
/// 返回可信入口协议,直接转换只能更新当前 wire,不能改写请求来源
|
||||
#[must_use]
|
||||
pub fn source_protocol(&self) -> &str {
|
||||
@@ -923,7 +940,7 @@ impl Operation {
|
||||
}
|
||||
}
|
||||
|
||||
/// Responses 要求本轮执行托管搜索时,按账号快照选择搜索目标
|
||||
/// 请求强制执行托管搜索时,按账号目录选择搜索目标
|
||||
#[must_use]
|
||||
pub fn requires_web_search(&self) -> bool {
|
||||
matches!(self, Self::Generate(request) if {
|
||||
@@ -936,6 +953,16 @@ impl Operation {
|
||||
})
|
||||
}
|
||||
|
||||
/// 原生单次搜索可通过账号的搜索目标解析未选档的模型组
|
||||
#[must_use]
|
||||
pub fn is_native_web_search(&self) -> bool {
|
||||
matches!(self, Self::Generate(request) if {
|
||||
let payload = request.protocol_payload();
|
||||
payload.protocol() == gateway_protocol::genai::GENAI_PROTOCOL
|
||||
&& gateway_protocol::genai::is_standalone_web_search(payload.body(), payload.context())
|
||||
})
|
||||
}
|
||||
|
||||
/// 仅提取本次正文明确声明的推理档位,路由不继承 Provider 会话默认值
|
||||
pub(crate) fn requested_reasoning_effort(&self) -> Option<String> {
|
||||
let observation = match self {
|
||||
|
||||
@@ -93,6 +93,49 @@ impl fmt::Debug for PlaintextClientApiKey {
|
||||
}
|
||||
}
|
||||
|
||||
/// 密钥可用的绝对时间范围,包含起点、不包含终点
|
||||
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct ClientKeyValidity {
|
||||
pub starts_at: Option<chrono::DateTime<chrono::Utc>>,
|
||||
pub expires_at: Option<chrono::DateTime<chrono::Utc>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum ClientKeyValidityStatus {
|
||||
Scheduled,
|
||||
Active,
|
||||
Expired,
|
||||
}
|
||||
|
||||
impl ClientKeyValidity {
|
||||
#[must_use]
|
||||
pub fn is_valid(self) -> bool {
|
||||
match (self.starts_at, self.expires_at) {
|
||||
(None, None) => true,
|
||||
(Some(start), Some(end)) => start < end,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn status_at(self, now: chrono::DateTime<chrono::Utc>) -> ClientKeyValidityStatus {
|
||||
if self.expires_at.is_some_and(|end| now >= end) {
|
||||
ClientKeyValidityStatus::Expired
|
||||
} else if self.starts_at.is_some_and(|start| now < start) {
|
||||
ClientKeyValidityStatus::Scheduled
|
||||
} else {
|
||||
ClientKeyValidityStatus::Active
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn is_active(self) -> bool {
|
||||
self.status_at(chrono::Utc::now()) == ClientKeyValidityStatus::Active
|
||||
}
|
||||
}
|
||||
|
||||
/// 零表示对应维度不额外限制
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
@@ -122,6 +165,7 @@ pub struct ClientSettings {
|
||||
/// 从 `client_api_keys` 冻结的公开准入事实
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ClientPolicy {
|
||||
validity: ClientKeyValidity,
|
||||
peer_sharing: ClientPeerSharing,
|
||||
name_snapshot: Option<String>,
|
||||
defaults: Arc<ClientSettings>,
|
||||
@@ -168,6 +212,7 @@ impl ClientPolicy {
|
||||
limits: RateLimits,
|
||||
) -> Self {
|
||||
Self {
|
||||
validity: ClientKeyValidity::default(),
|
||||
peer_sharing: ClientPeerSharing::default(),
|
||||
name_snapshot: None,
|
||||
defaults: Arc::new(ClientSettings {
|
||||
@@ -183,6 +228,12 @@ impl ClientPolicy {
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn with_validity(mut self, validity: ClientKeyValidity) -> Self {
|
||||
self.validity = validity;
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn with_name_snapshot(mut self, name: Option<String>) -> Self {
|
||||
self.name_snapshot = name;
|
||||
@@ -233,17 +284,21 @@ impl ClientPolicy {
|
||||
self.limits
|
||||
}
|
||||
|
||||
/// 禁用的 Key 不接受新请求
|
||||
/// 每次准入按当前时间检查冻结的有效期
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Key 已禁用时返回稳定拒绝原因
|
||||
/// Key 已禁用或不在有效期内时返回拒绝原因
|
||||
pub fn authorize(&self) -> Result<(), PolicyError> {
|
||||
if self.enabled {
|
||||
if !self.enabled {
|
||||
Err(PolicyError::Denied {
|
||||
reason: "client API key is disabled",
|
||||
})
|
||||
} else if self.validity.is_active() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(PolicyError::Denied {
|
||||
reason: "client API key is disabled",
|
||||
reason: "client API key is outside its validity period",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,6 +13,13 @@ pub trait ProviderRuntimePolicyPort: Send + Sync {
|
||||
Box::pin(async { Ok(None) })
|
||||
}
|
||||
|
||||
/// 后台 OpenAI 操作读取当前全局请求设置
|
||||
fn load_openai_request_settings(
|
||||
&self,
|
||||
) -> BoxFuture<'_, Result<crate::settings::OpenAiRequestSettings, ProviderStoreError>> {
|
||||
Box::pin(async { Ok(Default::default()) })
|
||||
}
|
||||
|
||||
/// 原子推进预热执行游标,重启或时钟回拨后不重复领取已消费的时刻
|
||||
fn claim_warmup_slot<'a>(
|
||||
&'a self,
|
||||
|
||||
@@ -19,7 +19,7 @@ pub struct ReasoningModelVariant {
|
||||
pub accounts: BTreeSet<ProviderAccountId>,
|
||||
}
|
||||
|
||||
/// 上游账号的聊天菜单声明,未声明时仍可按模型 ID 发现
|
||||
/// 上游账号的客户端发现声明,未声明时仍可按模型 ID 发现
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub enum AgentModelListing {
|
||||
#[default]
|
||||
|
||||
@@ -162,6 +162,7 @@ pub struct ModelCapabilities {
|
||||
translated_generation_protocols: BTreeSet<&'static str>,
|
||||
reasoning_variants: BTreeMap<String, ReasoningModelVariant>,
|
||||
account_metadata: BTreeMap<crate::account::ProviderAccountId, AccountModelMetadata>,
|
||||
native_web_search_helper: Option<&'static str>,
|
||||
dedicated_web_search: Option<Arc<BTreeMap<crate::account::ProviderAccountId, UpstreamModelId>>>,
|
||||
}
|
||||
|
||||
@@ -440,6 +441,7 @@ impl ModelCapabilities {
|
||||
reasoning_variants: BTreeMap::new(),
|
||||
account_metadata: BTreeMap::new(),
|
||||
dedicated_web_search: None,
|
||||
native_web_search_helper: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -483,6 +485,17 @@ impl ModelCapabilities {
|
||||
self
|
||||
}
|
||||
|
||||
/// 原生客户端用固定辅助型号发起独立搜索,目标来自 Provider 的账号搜索目录
|
||||
#[must_use]
|
||||
pub fn with_native_web_search_helper(
|
||||
mut self,
|
||||
model: &'static str,
|
||||
targets: BTreeMap<crate::account::ProviderAccountId, UpstreamModelId>,
|
||||
) -> Self {
|
||||
self.native_web_search_helper = Some(model);
|
||||
self.with_dedicated_web_search(targets)
|
||||
}
|
||||
|
||||
/// 将请求形态 feature 的最终合法性判断交给上游 wire API
|
||||
#[must_use]
|
||||
pub const fn with_upstream_feature_validation(mut self) -> Self {
|
||||
@@ -656,6 +669,7 @@ pub struct DirectAccountModel<'a> {
|
||||
/// 已绑定 Provider 的请求候选;模型端点携带真实上游模型,原生端点不虚构模型
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ProviderCandidate {
|
||||
dedicated_web_search: bool,
|
||||
provider: ProviderKind,
|
||||
requires_direct_authentication: bool,
|
||||
upstream_model: Option<UpstreamModelId>,
|
||||
@@ -664,6 +678,12 @@ pub struct ProviderCandidate {
|
||||
}
|
||||
|
||||
impl ProviderCandidate {
|
||||
/// 搜索目标和账号范围已经由目录解析,Provider 依此选择上游请求类型
|
||||
#[must_use]
|
||||
pub const fn uses_dedicated_web_search(&self) -> bool {
|
||||
self.dedicated_web_search
|
||||
}
|
||||
|
||||
/// 模型按直连账号身份选择,Provider 必须在发送前核对实际凭据。
|
||||
#[must_use]
|
||||
pub const fn requires_direct_authentication(&self) -> bool {
|
||||
@@ -694,12 +714,14 @@ impl ProviderCandidate {
|
||||
/// 一次请求冻结的 Provider 尝试顺序
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct RoutingPlan {
|
||||
prompt_rewrite: Arc<crate::settings::prompt_rewrite::CompiledPromptRewrite>,
|
||||
account_error_protection: Arc<crate::account::CompiledAccountErrorProtection>,
|
||||
account_error_protection_revision: u64,
|
||||
request_body_limit: usize,
|
||||
max_retry_after: std::time::Duration,
|
||||
pricing: Arc<crate::metering::PricingOverrides>,
|
||||
openai_request_country: crate::account::OpenAiRequestCountry,
|
||||
openai_websocket_pool: crate::settings::OpenAiWebSocketPoolSettings,
|
||||
openai_request_settings: crate::settings::OpenAiRequestSettings,
|
||||
request_location: Option<crate::account::RequestLocation>,
|
||||
privacy: Option<Arc<dyn crate::settings::privacy::CompiledPrivacyPolicy>>,
|
||||
config_revision: ConfigRevision,
|
||||
@@ -711,6 +733,14 @@ pub struct RoutingPlan {
|
||||
}
|
||||
|
||||
impl RoutingPlan {
|
||||
#[must_use]
|
||||
pub fn prompt_rewrite_rules(
|
||||
&self,
|
||||
provider: &ProviderKind,
|
||||
) -> Option<Arc<crate::settings::prompt_rewrite::ProviderPromptRules>> {
|
||||
self.prompt_rewrite.for_provider(provider)
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn account_error_protection_revision(&self) -> u64 {
|
||||
self.account_error_protection_revision
|
||||
@@ -755,8 +785,13 @@ impl RoutingPlan {
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn openai_request_country(&self) -> &crate::account::OpenAiRequestCountry {
|
||||
&self.openai_request_country
|
||||
pub const fn openai_websocket_pool(&self) -> &crate::settings::OpenAiWebSocketPoolSettings {
|
||||
&self.openai_websocket_pool
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn openai_request_settings(&self) -> &crate::settings::OpenAiRequestSettings {
|
||||
&self.openai_request_settings
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
|
||||
@@ -10,8 +10,8 @@ use crate::account::{FastMode, ProviderAccountId};
|
||||
use crate::concurrency::ConcurrencyQueuePolicy;
|
||||
use crate::operation::{Operation, OperationKind};
|
||||
use crate::policy::{
|
||||
ClientApiKeyId, ClientPeerSharing, ClientPolicy, CodexClientMinVersions, PlaintextClientApiKey,
|
||||
RateLimits,
|
||||
ClientApiKeyId, ClientKeyValidity, ClientPeerSharing, ClientPolicy, CodexClientMinVersions,
|
||||
PlaintextClientApiKey, RateLimits,
|
||||
};
|
||||
use crate::settings::{SettingsValues, compiled::CompiledSettings};
|
||||
use crate::validation::RoutingError;
|
||||
@@ -30,6 +30,7 @@ type ModelCatalogAccounts = BTreeMap<ProviderKind, BTreeMap<String, BTreeSet<Pro
|
||||
/// Store 读取到的一个启用 Client API Key 策略事实
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct SnapshotClientPolicyFacts {
|
||||
validity: ClientKeyValidity,
|
||||
peer_sharing: ClientPeerSharing,
|
||||
name_snapshot: Option<String>,
|
||||
request_profiles: BTreeMap<ProviderKind, crate::account::OpaqueProviderData>,
|
||||
@@ -46,6 +47,12 @@ impl SnapshotClientPolicyFacts {
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn with_validity(mut self, validity: ClientKeyValidity) -> Self {
|
||||
self.validity = validity;
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn with_name_snapshot(mut self, name: Option<String>) -> Self {
|
||||
self.name_snapshot = name;
|
||||
@@ -69,6 +76,7 @@ impl SnapshotClientPolicyFacts {
|
||||
limits: RateLimits,
|
||||
) -> Self {
|
||||
Self {
|
||||
validity: ClientKeyValidity::default(),
|
||||
peer_sharing: ClientPeerSharing::default(),
|
||||
key_id,
|
||||
name_snapshot: None,
|
||||
@@ -634,6 +642,7 @@ async fn compile_runtime_snapshot(
|
||||
policy.limits,
|
||||
)
|
||||
.with_name_snapshot(policy.name_snapshot)
|
||||
.with_validity(policy.validity)
|
||||
.with_peer_sharing(policy.peer_sharing),
|
||||
);
|
||||
}
|
||||
@@ -1605,23 +1614,37 @@ impl RuntimeSnapshot {
|
||||
}
|
||||
|
||||
let requested_model = public_model.as_str();
|
||||
let explicitly_mapped = self
|
||||
.settings
|
||||
.values
|
||||
.model_mappings
|
||||
.contains_key(requested_model)
|
||||
|| self.model_alias(requested_model).is_some();
|
||||
let upstream_model = if let Some(direct) = direct_model {
|
||||
direct.clone()
|
||||
} else {
|
||||
let mapped_model = self.mapped_model(requested_model);
|
||||
if self
|
||||
.settings
|
||||
.values
|
||||
.model_mappings
|
||||
.contains_key(requested_model)
|
||||
|| self.model_alias(requested_model).is_some()
|
||||
{
|
||||
if explicitly_mapped {
|
||||
UpstreamModelId::new(mapped_model)
|
||||
} else {
|
||||
UpstreamModelId::from_client_wire(mapped_model)
|
||||
}
|
||||
.map_err(|_| RoutingError::InvalidIdentifier)?
|
||||
};
|
||||
if !explicitly_mapped
|
||||
&& enforce_routing_policy
|
||||
&& direct_model.is_none()
|
||||
&& operation.is_native_web_search()
|
||||
&& let Some(search) = self.native_web_search_candidates(
|
||||
&upstream_model,
|
||||
operation.protocol(),
|
||||
&account_scope,
|
||||
context,
|
||||
requirements.requested_output_tokens(),
|
||||
)
|
||||
{
|
||||
return Ok(self.model_plan(operation, account_scope, search?));
|
||||
}
|
||||
let grouped = self.providers.iter().any(|provider| {
|
||||
self.model_group(provider, upstream_model.as_str())
|
||||
.is_some()
|
||||
@@ -1643,6 +1666,7 @@ impl RuntimeSnapshot {
|
||||
|| account_scope.provider_kinds().clone(),
|
||||
|provider| BTreeSet::from([provider.clone()]),
|
||||
);
|
||||
let search = operation.requires_web_search();
|
||||
let mut invalid_variant = false;
|
||||
let mut group_model_denied = false;
|
||||
let mut search_unavailable = false;
|
||||
@@ -1665,216 +1689,238 @@ impl RuntimeSnapshot {
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let mut candidate_scope = Arc::clone(&account_scope);
|
||||
let upstream_model =
|
||||
if let Some(group) = self.model_group(provider, upstream_model.as_str()) {
|
||||
if group.match_operation(operation, &requirements).is_none() {
|
||||
continue;
|
||||
}
|
||||
let group = self.model_group(provider, upstream_model.as_str());
|
||||
let group_search_targets = group
|
||||
.and_then(|group| group.dedicated_web_search.as_deref())
|
||||
.filter(|_| operation.is_native_web_search());
|
||||
let mut search_variants = None;
|
||||
let source = if let Some(group) = group {
|
||||
if group.match_operation(operation, &requirements).is_none() {
|
||||
continue;
|
||||
}
|
||||
if group_search_targets.is_some() {
|
||||
// 独立搜索只执行搜索型号,任一获准的具体成员都能证明同账号的分组资格
|
||||
search_variants = Some(group.reasoning_variants.values());
|
||||
None
|
||||
} else {
|
||||
let effort = operation.requested_reasoning_effort();
|
||||
let Some(variant) = effort
|
||||
.as_ref()
|
||||
.and_then(|effort| group.reasoning_variants.get(effort))
|
||||
.and_then(|level| group.reasoning_variants.get(level))
|
||||
else {
|
||||
invalid_variant = true;
|
||||
continue;
|
||||
};
|
||||
// 空集合在 restricted_to 中表示不收窄,必须先拒绝没有来源的档位
|
||||
if variant.accounts.is_empty() {
|
||||
continue;
|
||||
}
|
||||
candidate_scope = Arc::new(
|
||||
account_scope
|
||||
.restricted_to(&BTreeSet::from([provider.clone()]), &variant.accounts),
|
||||
);
|
||||
&variant.model
|
||||
} else {
|
||||
&upstream_model
|
||||
};
|
||||
if enforce_routing_policy
|
||||
&& candidate_scope.groups_deny_model(Some(upstream_model.as_str()))
|
||||
{
|
||||
group_model_denied = true;
|
||||
continue;
|
||||
}
|
||||
// 强制 Provider 路由也不能扩大 Key 授权;管理诊断的目标账号由探测入口固定
|
||||
if enforce_routing_policy
|
||||
&& !candidate_scope.allows_provider_model(provider, upstream_model.as_str())
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let capabilities = self
|
||||
.provider_models
|
||||
.get(provider)
|
||||
.and_then(|models| models.get(upstream_model));
|
||||
// 原生入口不能借同名模型、发现型目录的匿名透传或插件声明跨协议分派
|
||||
if operation.requires_native_protocol()
|
||||
&& !capabilities.is_some_and(|model| {
|
||||
model
|
||||
.native_generation_protocols
|
||||
.contains(operation.protocol())
|
||||
})
|
||||
{
|
||||
continue;
|
||||
}
|
||||
// 直连模型需要原生能力,不能借用插件为同名模型声明的账号与能力。
|
||||
if direct_model.is_some() && capabilities.is_none() {
|
||||
continue;
|
||||
}
|
||||
let contributions: Vec<_> = self
|
||||
.contributed_models()
|
||||
.iter()
|
||||
.filter(|model| {
|
||||
direct_model.is_none()
|
||||
&& &model.provider == provider
|
||||
&& &model.id == public_model
|
||||
})
|
||||
.collect();
|
||||
let emulated_features = if contributions.is_empty() {
|
||||
match capabilities {
|
||||
Some(capabilities) => {
|
||||
let Some(emulated) = capabilities.match_operation(operation, &requirements)
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
emulated
|
||||
}
|
||||
// 固定账号诊断由指定 Provider 向上游核实,停用账号可能从未出现在公开目录
|
||||
None if enforce_routing_policy
|
||||
&& (known_model
|
||||
|| self.exhaustive_provider_catalogs.contains(provider)) =>
|
||||
{
|
||||
continue;
|
||||
}
|
||||
None => BTreeSet::new(),
|
||||
Some((&variant.model, Some(&variant.accounts)))
|
||||
}
|
||||
} else {
|
||||
let native =
|
||||
capabilities.and_then(|value| value.match_operation(operation, &requirements));
|
||||
let capable_accounts: BTreeSet<_> = contributions
|
||||
.iter()
|
||||
.filter(|model| {
|
||||
model.protocol == operation.protocol()
|
||||
&& model
|
||||
.capabilities
|
||||
.match_operation(operation, &requirements)
|
||||
.is_some()
|
||||
})
|
||||
.flat_map(|model| model.accounts.iter())
|
||||
.filter(|account| {
|
||||
candidate_scope.account_provider(account) == Some(provider)
|
||||
&& candidate_scope.allows_model(account, upstream_model.as_str())
|
||||
})
|
||||
.cloned()
|
||||
.collect();
|
||||
if native.is_some() {
|
||||
// 这些账号实际由适配器执行,不能借用同名原生模型的能力
|
||||
let mut restricted = candidate_scope.as_ref().clone();
|
||||
for account in contributions.iter().flat_map(|model| &model.accounts) {
|
||||
if !capable_accounts.contains(account) {
|
||||
restricted = restricted.excluding_account(account.clone());
|
||||
}
|
||||
}
|
||||
candidate_scope = Arc::new(restricted);
|
||||
} else {
|
||||
// restricted_to 的空集合表示不收窄,因此必须先拒绝空候选
|
||||
if capable_accounts.is_empty() {
|
||||
continue;
|
||||
}
|
||||
candidate_scope = Arc::new(
|
||||
candidate_scope.restricted_to(&Default::default(), &capable_accounts),
|
||||
);
|
||||
}
|
||||
if !candidate_scope.allows_provider_model(provider, upstream_model.as_str()) {
|
||||
Some((&upstream_model, None))
|
||||
};
|
||||
let sources = source.into_iter().chain(
|
||||
search_variants
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(|variant| (&variant.model, Some(&variant.accounts))),
|
||||
);
|
||||
let mut targets = BTreeMap::<_, BTreeSet<_>>::new();
|
||||
for (upstream_model, accounts) in sources {
|
||||
if accounts.is_some_and(BTreeSet::is_empty) {
|
||||
continue;
|
||||
}
|
||||
native.unwrap_or_default()
|
||||
};
|
||||
// 原生输出上限属于具体型号与账号,适配器账号沿用自己的能力合同
|
||||
if let (Some(requested), Some(model)) =
|
||||
(requirements.requested_output_tokens(), capabilities)
|
||||
{
|
||||
let mut excluded = model
|
||||
.account_metadata
|
||||
.iter()
|
||||
.filter_map(|(id, metadata)| {
|
||||
(metadata
|
||||
.max_output_tokens
|
||||
.is_some_and(|limit| requested > limit)
|
||||
&& !contributions
|
||||
.iter()
|
||||
.any(|adapter| adapter.accounts.contains(id))
|
||||
&& candidate_scope.allows(id))
|
||||
.then_some(id)
|
||||
let mut candidate_scope = accounts.map_or_else(
|
||||
|| Arc::clone(&account_scope),
|
||||
|accounts| {
|
||||
Arc::new(
|
||||
account_scope
|
||||
.restricted_to(&BTreeSet::from([provider.clone()]), accounts),
|
||||
)
|
||||
},
|
||||
);
|
||||
if enforce_routing_policy
|
||||
&& candidate_scope.groups_deny_model(Some(upstream_model.as_str()))
|
||||
{
|
||||
group_model_denied = true;
|
||||
continue;
|
||||
}
|
||||
// 强制 Provider 路由也不能扩大 Key 授权;管理诊断的目标账号由探测入口固定
|
||||
if enforce_routing_policy
|
||||
&& !candidate_scope.allows_provider_model(provider, upstream_model.as_str())
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let capabilities = self
|
||||
.provider_models
|
||||
.get(provider)
|
||||
.and_then(|models| models.get(upstream_model));
|
||||
// 原生入口不能借同名模型、发现型目录的匿名透传或插件声明跨协议分派
|
||||
if operation.requires_native_protocol()
|
||||
&& !capabilities.is_some_and(|model| {
|
||||
model
|
||||
.native_generation_protocols
|
||||
.contains(operation.protocol())
|
||||
})
|
||||
.peekable();
|
||||
if excluded.peek().is_some() {
|
||||
let mut narrowed = candidate_scope.as_ref().clone();
|
||||
narrowed.exclude_accounts(excluded.cloned());
|
||||
if !narrowed.allows_provider_model(provider, upstream_model.as_str()) {
|
||||
{
|
||||
continue;
|
||||
}
|
||||
// 直连模型需要原生能力,不能借用插件为同名模型声明的账号与能力。
|
||||
if direct_model.is_some() && capabilities.is_none() {
|
||||
continue;
|
||||
}
|
||||
let contributions: Vec<_> = self
|
||||
.contributed_models()
|
||||
.iter()
|
||||
.filter(|model| {
|
||||
direct_model.is_none()
|
||||
&& &model.provider == provider
|
||||
&& &model.id == public_model
|
||||
})
|
||||
.collect();
|
||||
let emulated_features = if contributions.is_empty() {
|
||||
match capabilities {
|
||||
Some(capabilities) => {
|
||||
let Some(emulated) =
|
||||
capabilities.match_operation(operation, &requirements)
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
emulated
|
||||
}
|
||||
// 固定账号诊断由指定 Provider 向上游核实,停用账号可能从未出现在公开目录
|
||||
None if enforce_routing_policy
|
||||
&& (known_model
|
||||
|| self.exhaustive_provider_catalogs.contains(provider)) =>
|
||||
{
|
||||
continue;
|
||||
}
|
||||
None => BTreeSet::new(),
|
||||
}
|
||||
} else {
|
||||
let native = capabilities
|
||||
.and_then(|value| value.match_operation(operation, &requirements));
|
||||
let capable_accounts: BTreeSet<_> = contributions
|
||||
.iter()
|
||||
.filter(|model| {
|
||||
model.protocol == operation.protocol()
|
||||
&& model
|
||||
.capabilities
|
||||
.match_operation(operation, &requirements)
|
||||
.is_some()
|
||||
})
|
||||
.flat_map(|model| model.accounts.iter())
|
||||
.filter(|account| {
|
||||
candidate_scope.account_provider(account) == Some(provider)
|
||||
&& candidate_scope.allows_model(account, upstream_model.as_str())
|
||||
})
|
||||
.cloned()
|
||||
.collect();
|
||||
if native.is_some() {
|
||||
// 这些账号实际由适配器执行,不能借用同名原生模型的能力
|
||||
let mut restricted = candidate_scope.as_ref().clone();
|
||||
for account in contributions.iter().flat_map(|model| &model.accounts) {
|
||||
if !capable_accounts.contains(account) {
|
||||
restricted = restricted.excluding_account(account.clone());
|
||||
}
|
||||
}
|
||||
candidate_scope = Arc::new(restricted);
|
||||
} else {
|
||||
// restricted_to 的空集合表示不收窄,因此必须先拒绝空候选
|
||||
if capable_accounts.is_empty() {
|
||||
continue;
|
||||
}
|
||||
candidate_scope = Arc::new(
|
||||
candidate_scope.restricted_to(&Default::default(), &capable_accounts),
|
||||
);
|
||||
}
|
||||
if !candidate_scope.allows_provider_model(provider, upstream_model.as_str()) {
|
||||
continue;
|
||||
}
|
||||
candidate_scope = Arc::new(narrowed);
|
||||
native.unwrap_or_default()
|
||||
};
|
||||
// 原生输出上限属于具体型号与账号,适配器账号沿用自己的能力合同
|
||||
if let (Some(requested), Some(model)) =
|
||||
(requirements.requested_output_tokens(), capabilities)
|
||||
{
|
||||
let mut excluded = model
|
||||
.account_metadata
|
||||
.iter()
|
||||
.filter_map(|(id, metadata)| {
|
||||
(metadata
|
||||
.max_output_tokens
|
||||
.is_some_and(|limit| requested > limit)
|
||||
&& !contributions
|
||||
.iter()
|
||||
.any(|adapter| adapter.accounts.contains(id))
|
||||
&& candidate_scope.allows(id))
|
||||
.then_some(id)
|
||||
})
|
||||
.peekable();
|
||||
if excluded.peek().is_some() {
|
||||
let mut narrowed = candidate_scope.as_ref().clone();
|
||||
narrowed.exclude_accounts(excluded.cloned());
|
||||
if !narrowed.allows_provider_model(provider, upstream_model.as_str()) {
|
||||
continue;
|
||||
}
|
||||
candidate_scope = Arc::new(narrowed);
|
||||
}
|
||||
}
|
||||
if let Some(model) = capabilities
|
||||
&& let Some(search_models) = group_search_targets
|
||||
.or(model.dedicated_web_search.as_deref().filter(|_| search))
|
||||
{
|
||||
// 仅目录中同时拥有请求型号和搜索目标的账号可执行本次搜索
|
||||
for account in model.account_metadata.keys() {
|
||||
if !candidate_scope.allows_model(account, upstream_model.as_str()) {
|
||||
continue;
|
||||
}
|
||||
let Some(target) = search_models.get(account) else {
|
||||
search_unavailable = true;
|
||||
continue;
|
||||
};
|
||||
if !candidate_scope.allows_model_pair(
|
||||
account,
|
||||
upstream_model.as_str(),
|
||||
target.as_str(),
|
||||
) {
|
||||
group_model_denied |=
|
||||
candidate_scope.groups_deny_model(Some(target.as_str()));
|
||||
continue;
|
||||
}
|
||||
if !self.search_target_fits(
|
||||
provider,
|
||||
account,
|
||||
target,
|
||||
requirements.requested_output_tokens(),
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
targets
|
||||
.entry((target, emulated_features.clone()))
|
||||
.or_default()
|
||||
.insert(account.clone());
|
||||
}
|
||||
continue;
|
||||
}
|
||||
candidates.push(ProviderCandidate {
|
||||
dedicated_web_search: false,
|
||||
requires_direct_authentication: direct_model.is_some(),
|
||||
provider: provider.clone(),
|
||||
upstream_model: Some(upstream_model.clone()),
|
||||
emulated_features,
|
||||
account_scope: candidate_scope,
|
||||
});
|
||||
}
|
||||
if operation.requires_web_search()
|
||||
&& let Some(model) = capabilities
|
||||
&& let Some(search_models) = &model.dedicated_web_search
|
||||
{
|
||||
// 仅目录中同时拥有请求型号和搜索目标的账号可执行本次搜索
|
||||
let mut targets = BTreeMap::<_, BTreeSet<_>>::new();
|
||||
for account in model.account_metadata.keys() {
|
||||
if !candidate_scope.allows_model(account, upstream_model.as_str()) {
|
||||
continue;
|
||||
}
|
||||
let Some(target) = search_models.get(account) else {
|
||||
search_unavailable = true;
|
||||
continue;
|
||||
};
|
||||
if !candidate_scope.allows_model_pair(
|
||||
account,
|
||||
upstream_model.as_str(),
|
||||
target.as_str(),
|
||||
) {
|
||||
group_model_denied |=
|
||||
candidate_scope.groups_deny_model(Some(target.as_str()));
|
||||
continue;
|
||||
}
|
||||
let limit = self
|
||||
.provider_models
|
||||
.get(provider)
|
||||
.and_then(|models| models.get(target))
|
||||
.and_then(|model| model.account_metadata.get(account))
|
||||
.and_then(|meta| meta.max_output_tokens);
|
||||
if requirements
|
||||
.requested_output_tokens()
|
||||
.zip(limit)
|
||||
.is_some_and(|(requested, limit)| requested > limit)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
targets.entry(target).or_default().insert(account.clone());
|
||||
}
|
||||
for (target, accounts) in targets {
|
||||
candidates.push(ProviderCandidate {
|
||||
requires_direct_authentication: direct_model.is_some(),
|
||||
provider: provider.clone(),
|
||||
upstream_model: Some(target.clone()),
|
||||
emulated_features: emulated_features.clone(),
|
||||
account_scope: Arc::new(
|
||||
candidate_scope.restricted_to(&Default::default(), &accounts),
|
||||
),
|
||||
});
|
||||
}
|
||||
continue;
|
||||
for ((target, emulated_features), accounts) in targets {
|
||||
candidates.push(ProviderCandidate {
|
||||
dedicated_web_search: true,
|
||||
requires_direct_authentication: direct_model.is_some(),
|
||||
provider: provider.clone(),
|
||||
upstream_model: Some(target.clone()),
|
||||
emulated_features,
|
||||
account_scope: Arc::new(
|
||||
account_scope.restricted_to(&Default::default(), &accounts),
|
||||
),
|
||||
});
|
||||
}
|
||||
candidates.push(ProviderCandidate {
|
||||
requires_direct_authentication: direct_model.is_some(),
|
||||
provider: provider.clone(),
|
||||
upstream_model: Some(upstream_model.clone()),
|
||||
emulated_features,
|
||||
account_scope: candidate_scope,
|
||||
});
|
||||
}
|
||||
|
||||
// 冷启动或目录不可读时不能按 Provider 名称猜测模型归属
|
||||
@@ -1912,14 +1958,112 @@ impl RuntimeSnapshot {
|
||||
});
|
||||
}
|
||||
|
||||
Ok(RoutingPlan {
|
||||
Ok(self.model_plan(operation, account_scope, candidates))
|
||||
}
|
||||
|
||||
fn search_target_fits(
|
||||
&self,
|
||||
provider: &ProviderKind,
|
||||
account: &ProviderAccountId,
|
||||
target: &UpstreamModelId,
|
||||
requested_tokens: Option<u64>,
|
||||
) -> bool {
|
||||
let limit = self
|
||||
.provider_models
|
||||
.get(provider)
|
||||
.and_then(|models| models.get(target))
|
||||
.and_then(|model| model.account_metadata.get(account))
|
||||
.and_then(|meta| meta.max_output_tokens);
|
||||
requested_tokens
|
||||
.zip(limit)
|
||||
.is_none_or(|(requested, limit)| requested <= limit)
|
||||
}
|
||||
|
||||
/// 辅助型号只标识搜索操作,账号与分组的模型权限按实际搜索目标判断
|
||||
fn native_web_search_candidates(
|
||||
&self,
|
||||
requested_model: &UpstreamModelId,
|
||||
protocol: &str,
|
||||
scope: &FrozenAccountScope,
|
||||
context: &RoutingContext,
|
||||
requested_tokens: Option<u64>,
|
||||
) -> Option<Result<Vec<ProviderCandidate>, RoutingError>> {
|
||||
let mut candidates = None;
|
||||
let mut group_denied = false;
|
||||
for provider in self.available_provider_kinds(scope, context) {
|
||||
let Some(models) = self.provider_models.get(provider) else {
|
||||
continue;
|
||||
};
|
||||
// 当前范围已有原生型号时仍走普通路由,其他协议的同名模型不能接管 GenAI
|
||||
if models
|
||||
.get(requested_model)
|
||||
.is_some_and(|model| model.native_generation_protocols.contains(protocol))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let Some(targets) = models.values().find_map(|model| {
|
||||
model
|
||||
.dedicated_web_search
|
||||
.as_deref()
|
||||
.filter(|_| model.native_web_search_helper == Some(requested_model.as_str()))
|
||||
}) else {
|
||||
continue;
|
||||
};
|
||||
let candidates = candidates.get_or_insert_with(Vec::new);
|
||||
let mut accounts_by_target = BTreeMap::<_, BTreeSet<_>>::new();
|
||||
for (account, target) in targets {
|
||||
if scope.account_provider(account) != Some(provider) || !scope.allows(account) {
|
||||
continue;
|
||||
}
|
||||
if !scope.allows_model(account, target.as_str()) {
|
||||
group_denied |= scope.groups_deny_model(Some(target.as_str()));
|
||||
continue;
|
||||
}
|
||||
if self.search_target_fits(provider, account, target, requested_tokens) {
|
||||
accounts_by_target
|
||||
.entry(target)
|
||||
.or_default()
|
||||
.insert(account.clone());
|
||||
}
|
||||
}
|
||||
for (target, accounts) in accounts_by_target {
|
||||
candidates.push(ProviderCandidate {
|
||||
dedicated_web_search: true,
|
||||
requires_direct_authentication: false,
|
||||
provider: provider.clone(),
|
||||
upstream_model: Some(target.clone()),
|
||||
emulated_features: BTreeSet::new(),
|
||||
account_scope: Arc::new(scope.restricted_to(&Default::default(), &accounts)),
|
||||
});
|
||||
}
|
||||
}
|
||||
candidates.map(|candidates| {
|
||||
if !candidates.is_empty() {
|
||||
Ok(candidates)
|
||||
} else if group_denied {
|
||||
Err(RoutingError::GroupModelDenied)
|
||||
} else {
|
||||
Err(RoutingError::WebSearchUnavailable)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn model_plan(
|
||||
&self,
|
||||
operation: &Operation,
|
||||
account_scope: Arc<FrozenAccountScope>,
|
||||
candidates: Vec<ProviderCandidate>,
|
||||
) -> RoutingPlan {
|
||||
RoutingPlan {
|
||||
request_body_limit: self.responses_max_decompressed_body_bytes(),
|
||||
max_retry_after: std::time::Duration::from_secs(u64::from(
|
||||
self.settings.values.max_retry_after_seconds,
|
||||
)),
|
||||
config_revision: self.revision,
|
||||
prompt_rewrite: Arc::clone(&self.settings.prompt_rewrite),
|
||||
pricing: Arc::clone(&self.settings.values.pricing),
|
||||
openai_request_country: self.settings.values.openai_request_country().clone(),
|
||||
openai_websocket_pool: *self.settings.values.openai_websocket_pool(),
|
||||
openai_request_settings: self.settings.values.openai_request_settings().clone(),
|
||||
request_location: self.settings.request_location.clone(),
|
||||
privacy: self.settings.privacy.clone(),
|
||||
account_error_protection: Arc::clone(&self.settings.account_error_protection),
|
||||
@@ -1933,7 +2077,7 @@ impl RuntimeSnapshot {
|
||||
.expect("constant request attempt limit is non-zero"),
|
||||
account_scope,
|
||||
candidates: Arc::from(candidates),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// 为 Provider 自有端点冻结请求计划
|
||||
@@ -1997,6 +2141,7 @@ impl RuntimeSnapshot {
|
||||
});
|
||||
}
|
||||
let candidate = ProviderCandidate {
|
||||
dedicated_web_search: false,
|
||||
requires_direct_authentication: false,
|
||||
provider: provider.clone(),
|
||||
upstream_model: upstream_model.cloned(),
|
||||
@@ -2009,8 +2154,10 @@ impl RuntimeSnapshot {
|
||||
self.settings.values.max_retry_after_seconds,
|
||||
)),
|
||||
config_revision: self.revision,
|
||||
prompt_rewrite: Arc::clone(&self.settings.prompt_rewrite),
|
||||
pricing: Arc::clone(&self.settings.values.pricing),
|
||||
openai_request_country: self.settings.values.openai_request_country().clone(),
|
||||
openai_websocket_pool: *self.settings.values.openai_websocket_pool(),
|
||||
openai_request_settings: self.settings.values.openai_request_settings().clone(),
|
||||
request_location: self.settings.request_location.clone(),
|
||||
privacy: self.settings.privacy.clone(),
|
||||
account_error_protection: Arc::clone(&self.settings.account_error_protection),
|
||||
|
||||
@@ -13,6 +13,7 @@ use crate::{
|
||||
#[derive(Debug, Clone)]
|
||||
pub(crate) struct CompiledSettings {
|
||||
pub(crate) values: SettingsValues,
|
||||
pub(crate) prompt_rewrite: std::sync::Arc<super::prompt_rewrite::CompiledPromptRewrite>,
|
||||
pub(crate) account_error_protection:
|
||||
std::sync::Arc<crate::account::CompiledAccountErrorProtection>,
|
||||
pub(crate) privacy: Option<std::sync::Arc<dyn super::privacy::CompiledPrivacyPolicy>>,
|
||||
@@ -40,6 +41,18 @@ impl CompiledSettings {
|
||||
.account_error_protection
|
||||
.validate()
|
||||
.map_err(|_| InvalidSettings)?;
|
||||
let prompt_rewrite = previous
|
||||
.filter(|prior| prior.values.prompt_rewrite_rules == settings.prompt_rewrite_rules)
|
||||
.map_or_else(
|
||||
|| {
|
||||
super::prompt_rewrite::CompiledPromptRewrite::new(std::sync::Arc::clone(
|
||||
&settings.prompt_rewrite_rules,
|
||||
))
|
||||
.map(std::sync::Arc::new)
|
||||
.map_err(|_| InvalidSettings)
|
||||
},
|
||||
|prior| Ok(prior.prompt_rewrite.clone()),
|
||||
)?;
|
||||
let account_error_protection = previous
|
||||
.filter(|previous| {
|
||||
previous.values.account_error_protection == settings.account_error_protection
|
||||
@@ -112,7 +125,11 @@ impl CompiledSettings {
|
||||
timeout: Duration::from_secs(u64::from(settings.key_queue_timeout_seconds)),
|
||||
};
|
||||
settings
|
||||
.openai_request_country
|
||||
.openai_request_settings
|
||||
.validate()
|
||||
.map_err(|_| InvalidSettings)?;
|
||||
settings
|
||||
.openai_websocket_pool
|
||||
.validate()
|
||||
.map_err(|_| InvalidSettings)?;
|
||||
let request_location = settings
|
||||
@@ -126,6 +143,7 @@ impl CompiledSettings {
|
||||
}
|
||||
}
|
||||
Ok(Self {
|
||||
prompt_rewrite,
|
||||
account_error_protection,
|
||||
account_selection_policy,
|
||||
client_queue_policy,
|
||||
|
||||
@@ -1,12 +1,17 @@
|
||||
//! 运行设置的纯值、校验与编译结果
|
||||
|
||||
pub(crate) mod compiled;
|
||||
mod openai;
|
||||
pub mod privacy;
|
||||
pub mod prompt_rewrite;
|
||||
pub mod request_profiles;
|
||||
mod values;
|
||||
mod websocket;
|
||||
pub use openai::{OpenAiRequestCountry, OpenAiRequestSettings};
|
||||
pub use values::{
|
||||
SettingsValues, client_min_versions, response_body_limit, validate_request_limits,
|
||||
};
|
||||
pub use websocket::OpenAiWebSocketPoolSettings;
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
#[error("request settings are invalid")]
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user