mirror of
https://github.com/zyycn/codex-proxy-rs.git
synced 2026-11-29 16:00:51 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2cbdd62b4e | ||
|
|
39cc23d2f0 | ||
|
|
102131056b | ||
|
|
c94a443620 | ||
|
|
ef870690e3 | ||
|
|
f4254104c9 | ||
|
|
36136728c6 | ||
|
|
0d731c5059 | ||
|
|
3fe4248fd6 | ||
|
|
3cc9c71ab5 | ||
|
|
2dc3ba8d56 | ||
|
|
7c16190936 | ||
|
|
c89152ce08 | ||
|
|
4b8825a28f | ||
|
|
95a89e9010 | ||
|
|
4fc8f836be | ||
|
|
ddd33da737 | ||
|
|
1d875def09 | ||
|
|
e6def7b634 | ||
|
|
f5d3c55d75 | ||
|
|
30487dfbf1 | ||
|
|
71cfdcb33e | ||
|
|
98954aefb6 | ||
|
|
c74c570228 | ||
|
|
fbf1aa1d9b |
@@ -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#验证)停止扩围;完成已获授权的剩余交付步骤并确认结果后结束
|
||||
|
||||
|
||||
+1
-1
@@ -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 正文代替实现自审与验证
|
||||
|
||||
| 技能 | 用途 | 调用示例 |
|
||||
| --- | --- | --- |
|
||||
|
||||
Generated
+1
@@ -1820,6 +1820,7 @@ dependencies = [
|
||||
"gateway-protocol",
|
||||
"http",
|
||||
"http-body-util",
|
||||
"regex-automata",
|
||||
"semver",
|
||||
"serde",
|
||||
"serde_json",
|
||||
|
||||
@@ -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>,
|
||||
|
||||
@@ -350,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,7 +1169,8 @@ 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>,
|
||||
@@ -1640,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>,
|
||||
|
||||
@@ -1319,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,
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -382,9 +382,11 @@ impl ObservabilityService for DefaultObservabilityService {
|
||||
account_authentication_kind: item.account_authentication_kind,
|
||||
account_plan_type_display: self.historical_plan_display(
|
||||
item.account_plan_type_display,
|
||||
item.account_provider_kind.as_deref(),
|
||||
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,
|
||||
|
||||
@@ -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,6 +128,7 @@ fn validate_settings(command: &ReplaceRuntimeSettings) -> Result<(), AdminError>
|
||||
)
|
||||
.map_err(|_| AdminError::invalid("运行时设置不满足约束"))?;
|
||||
command.values.validate().map_err(|field| match field {
|
||||
"prompt_rewrite_rules" => AdminError::invalid("正则表达式无效或超出编译大小限制"),
|
||||
"openai_websocket_pool.fast_path_budget_ms" => {
|
||||
AdminError::invalid("WS 建连等待时间须为 1–15000 毫秒")
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
@@ -1229,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(),
|
||||
@@ -1894,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(),
|
||||
@@ -1934,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(),
|
||||
@@ -4016,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(),
|
||||
|
||||
@@ -62,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(),
|
||||
|
||||
@@ -366,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(),
|
||||
@@ -450,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,
|
||||
@@ -541,7 +543,8 @@ 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,
|
||||
|
||||
@@ -355,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(),
|
||||
|
||||
@@ -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,15 @@ 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"][..],
|
||||
|
||||
@@ -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>,
|
||||
|
||||
@@ -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>,
|
||||
|
||||
@@ -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,
|
||||
@@ -345,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,
|
||||
|
||||
@@ -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>),
|
||||
@@ -744,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,
|
||||
@@ -787,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,
|
||||
@@ -801,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",
|
||||
@@ -859,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),
|
||||
))
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -2016,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,7 +748,8 @@ 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,
|
||||
@@ -791,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);
|
||||
@@ -981,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,
|
||||
@@ -1962,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(),
|
||||
@@ -2153,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(),
|
||||
|
||||
@@ -287,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(),
|
||||
@@ -569,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
|
||||
}])
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -101,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"
|
||||
|
||||
@@ -1201,6 +1201,7 @@ 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_websocket_pool(*self.plan.openai_websocket_pool())
|
||||
|
||||
@@ -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;
|
||||
@@ -324,6 +325,7 @@ 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,
|
||||
@@ -396,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;
|
||||
@@ -463,6 +474,7 @@ impl RequestAttemptContext {
|
||||
request_id,
|
||||
client_api_key_ref,
|
||||
request_profile: None,
|
||||
prompt_rewrite_rules: None,
|
||||
pricing: Arc::default(),
|
||||
fast_mode: FastMode::Default,
|
||||
openai_websocket_pool: Default::default(),
|
||||
@@ -832,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、发送状态、
|
||||
@@ -860,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)
|
||||
})
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -714,6 +714,7 @@ 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,
|
||||
@@ -732,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
|
||||
|
||||
@@ -2060,6 +2060,7 @@ 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_websocket_pool: *self.settings.values.openai_websocket_pool(),
|
||||
openai_request_settings: self.settings.values.openai_request_settings().clone(),
|
||||
@@ -2153,6 +2154,7 @@ 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_websocket_pool: *self.settings.values.openai_websocket_pool(),
|
||||
openai_request_settings: self.settings.values.openai_request_settings().clone(),
|
||||
|
||||
@@ -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
|
||||
@@ -130,6 +143,7 @@ impl CompiledSettings {
|
||||
}
|
||||
}
|
||||
Ok(Self {
|
||||
prompt_rewrite,
|
||||
account_error_protection,
|
||||
account_selection_policy,
|
||||
client_queue_policy,
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
pub(crate) mod compiled;
|
||||
mod openai;
|
||||
pub mod privacy;
|
||||
pub mod prompt_rewrite;
|
||||
pub mod request_profiles;
|
||||
mod values;
|
||||
mod websocket;
|
||||
|
||||
@@ -0,0 +1,253 @@
|
||||
//! 按目标上游索引并共享已编译规则,按配置顺序匹配系统提示词开头
|
||||
|
||||
use crate::identity::ProviderKind;
|
||||
use regex_automata::{
|
||||
Anchored, Input,
|
||||
meta::{BuildError, Regex},
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{
|
||||
borrow::Cow,
|
||||
collections::{BTreeMap, BTreeSet},
|
||||
fmt,
|
||||
sync::{Arc, OnceLock},
|
||||
};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum PromptMatchMode {
|
||||
Prefix,
|
||||
Regex,
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct PromptRewriteRule {
|
||||
#[serde(deserialize_with = "nonempty_name")]
|
||||
name: String,
|
||||
#[serde(default)]
|
||||
providers: BTreeSet<ProviderKind>,
|
||||
match_mode: PromptMatchMode,
|
||||
pattern: PromptPattern,
|
||||
replacement: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Serialize, Deserialize)]
|
||||
#[serde(transparent)]
|
||||
struct PromptPattern {
|
||||
#[serde(deserialize_with = "nonempty_pattern")]
|
||||
text: String,
|
||||
// API、管理用例和持久化边界校验同一份不可变规则时,共用编译结果
|
||||
#[serde(skip)]
|
||||
regex: OnceLock<Result<Arc<Regex>, Box<BuildError>>>,
|
||||
}
|
||||
|
||||
impl PromptPattern {
|
||||
fn regex(&self) -> Result<&Arc<Regex>, Box<BuildError>> {
|
||||
self.regex
|
||||
.get_or_init(|| Regex::new(&self.text).map(Arc::new).map_err(Box::new))
|
||||
.as_ref()
|
||||
.map_err(Clone::clone)
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for PromptPattern {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.text == other.text
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for PromptPattern {}
|
||||
|
||||
#[derive(Clone, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct PromptRewritePreviewRequest {
|
||||
pub rule: PromptRewriteRule,
|
||||
pub text: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Serialize, Deserialize)]
|
||||
pub struct PromptRewritePreviewResult {
|
||||
pub matched: bool,
|
||||
pub output: String,
|
||||
}
|
||||
|
||||
impl PromptRewriteRule {
|
||||
fn compile(&self) -> Result<CompiledRule, Box<BuildError>> {
|
||||
Ok(CompiledRule {
|
||||
matcher: match self.match_mode {
|
||||
PromptMatchMode::Prefix => Matcher::Prefix(self.pattern.text.clone()),
|
||||
PromptMatchMode::Regex if self.replacement.contains('$') => {
|
||||
Matcher::RegexCaptures(Arc::clone(self.pattern.regex()?))
|
||||
}
|
||||
PromptMatchMode::Regex => Matcher::Regex(Arc::clone(self.pattern.regex()?)),
|
||||
},
|
||||
replacement: self.replacement.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn validate(&self) -> Result<(), Box<BuildError>> {
|
||||
if self.match_mode == PromptMatchMode::Regex {
|
||||
self.pattern.regex()?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn preview(&self, text: &str) -> Result<PromptRewritePreviewResult, Box<BuildError>> {
|
||||
let compiled = self.compile()?;
|
||||
let result = compiled.replace_prefix(text);
|
||||
Ok(PromptRewritePreviewResult {
|
||||
matched: result.is_some(),
|
||||
output: result.unwrap_or(Cow::Borrowed(text)).into_owned(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
enum Matcher {
|
||||
Prefix(String),
|
||||
Regex(Arc<Regex>),
|
||||
RegexCaptures(Arc<Regex>),
|
||||
}
|
||||
|
||||
struct CompiledRule {
|
||||
matcher: Matcher,
|
||||
replacement: String,
|
||||
}
|
||||
|
||||
// 编译后的表达式和替换内容同样可能包含敏感提示词,不输出到诊断日志
|
||||
impl fmt::Debug for CompiledRule {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("CompiledRule").finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl CompiledRule {
|
||||
fn replace_prefix<'a>(&self, text: &'a str) -> Option<Cow<'a, str>> {
|
||||
let (end, replacement) = match &self.matcher {
|
||||
Matcher::Prefix(pattern) => {
|
||||
text.strip_prefix(pattern)?;
|
||||
(pattern.len(), Cow::Borrowed(self.replacement.as_str()))
|
||||
}
|
||||
Matcher::RegexCaptures(regex) => {
|
||||
// 使用引擎的起始位置约束,不拼接表达式,避免分组与注释改变边界
|
||||
let mut captures = regex.create_captures();
|
||||
regex.captures(Input::new(text).anchored(Anchored::Yes), &mut captures);
|
||||
let matched = captures.get_match()?;
|
||||
let mut expanded = String::new();
|
||||
captures.interpolate_string_into(text, &self.replacement, &mut expanded);
|
||||
(matched.end(), Cow::Owned(expanded))
|
||||
}
|
||||
Matcher::Regex(regex) => (
|
||||
regex.find(Input::new(text).anchored(Anchored::Yes))?.end(),
|
||||
Cow::Borrowed(self.replacement.as_str()),
|
||||
),
|
||||
};
|
||||
if text[..end] == *replacement {
|
||||
return Some(Cow::Borrowed(text));
|
||||
}
|
||||
let mut updated = match replacement {
|
||||
Cow::Owned(expanded) => expanded,
|
||||
Cow::Borrowed(literal) => {
|
||||
let mut updated = String::with_capacity(literal.len() + (text.len() - end));
|
||||
updated.push_str(literal);
|
||||
updated
|
||||
}
|
||||
};
|
||||
updated.push_str(&text[end..]);
|
||||
Some(Cow::Owned(updated))
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for PromptRewriteRule {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("PromptRewriteRule")
|
||||
.field("providers", &self.providers)
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
fn nonempty_name<'de, D: serde::Deserializer<'de>>(de: D) -> Result<String, D::Error> {
|
||||
let name = String::deserialize(de)?;
|
||||
if name.trim().is_empty() {
|
||||
return Err(serde::de::Error::custom("规则名称不能为空"));
|
||||
}
|
||||
Ok(name)
|
||||
}
|
||||
|
||||
fn nonempty_pattern<'de, D: serde::Deserializer<'de>>(de: D) -> Result<String, D::Error> {
|
||||
let pattern = String::deserialize(de)?;
|
||||
if pattern.is_empty() {
|
||||
return Err(serde::de::Error::custom("匹配文本不能为空"));
|
||||
}
|
||||
Ok(pattern)
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct ProviderPromptRules {
|
||||
rules: Arc<[CompiledRule]>,
|
||||
global: Arc<BTreeSet<usize>>,
|
||||
scoped: BTreeSet<usize>,
|
||||
}
|
||||
|
||||
impl ProviderPromptRules {
|
||||
pub fn replace_prefix(&self, text: &str) -> Option<String> {
|
||||
// 命中但内容未变化也必须终止,不能落到后续规则
|
||||
match self
|
||||
.global
|
||||
.union(&self.scoped)
|
||||
.map(|&index| &self.rules[index])
|
||||
.find_map(|rule| rule.replace_prefix(text))?
|
||||
{
|
||||
Cow::Borrowed(_) => None,
|
||||
Cow::Owned(updated) => Some(updated),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub struct CompiledPromptRewrite {
|
||||
all: Option<Arc<ProviderPromptRules>>,
|
||||
by_provider: BTreeMap<ProviderKind, Arc<ProviderPromptRules>>,
|
||||
}
|
||||
|
||||
impl CompiledPromptRewrite {
|
||||
pub fn new(rules: Arc<[PromptRewriteRule]>) -> Result<Self, Box<BuildError>> {
|
||||
let mut global = BTreeSet::new();
|
||||
let mut scoped = BTreeMap::<_, BTreeSet<_>>::new();
|
||||
for (index, rule) in rules.iter().enumerate() {
|
||||
if rule.providers.is_empty() {
|
||||
global.insert(index);
|
||||
} else {
|
||||
for provider in &rule.providers {
|
||||
scoped.entry(provider.clone()).or_default().insert(index);
|
||||
}
|
||||
}
|
||||
}
|
||||
let rules: Arc<[CompiledRule]> = rules
|
||||
.iter()
|
||||
.map(PromptRewriteRule::compile)
|
||||
.collect::<Result<_, _>>()?;
|
||||
let global = Arc::new(global);
|
||||
let selection = |scoped| {
|
||||
Arc::new(ProviderPromptRules {
|
||||
rules: Arc::clone(&rules),
|
||||
global: Arc::clone(&global),
|
||||
scoped,
|
||||
})
|
||||
};
|
||||
Ok(Self {
|
||||
all: (!global.is_empty()).then(|| selection(BTreeSet::new())),
|
||||
by_provider: scoped
|
||||
.into_iter()
|
||||
.map(|(id, indices)| (id, selection(indices)))
|
||||
.collect(),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn for_provider(&self, provider: &ProviderKind) -> Option<Arc<ProviderPromptRules>> {
|
||||
self.by_provider
|
||||
.get(provider)
|
||||
.or(self.all.as_ref())
|
||||
.cloned()
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,8 @@ use crate::identity::ProviderKind;
|
||||
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct SettingsValues {
|
||||
#[serde(default)]
|
||||
pub(crate) prompt_rewrite_rules: Arc<[super::prompt_rewrite::PromptRewriteRule]>,
|
||||
#[serde(default)]
|
||||
pub(crate) account_error_protection: crate::account::AccountErrorProtection,
|
||||
#[serde(skip, default = "initial_protection_revision")]
|
||||
@@ -45,6 +47,15 @@ fn initial_protection_revision() -> u64 {
|
||||
}
|
||||
|
||||
impl SettingsValues {
|
||||
#[must_use]
|
||||
pub fn with_prompt_rewrite_rules(
|
||||
mut self,
|
||||
rules: Vec<super::prompt_rewrite::PromptRewriteRule>,
|
||||
) -> Self {
|
||||
self.prompt_rewrite_rules = rules.into();
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn with_account_error_protection_revision(mut self, revision: u64) -> Self {
|
||||
self.account_error_protection_revision = revision;
|
||||
@@ -222,6 +233,7 @@ impl SettingsValues {
|
||||
min_codex_cli_version: Option<String>,
|
||||
) -> Self {
|
||||
Self {
|
||||
prompt_rewrite_rules: Default::default(),
|
||||
account_error_protection: Default::default(),
|
||||
account_error_protection_revision: 1,
|
||||
request_profiles: Arc::default(),
|
||||
|
||||
@@ -16,6 +16,7 @@ mod policy;
|
||||
mod provider_ports;
|
||||
mod routing;
|
||||
mod runtime;
|
||||
mod settings;
|
||||
mod task;
|
||||
mod upstream;
|
||||
|
||||
|
||||
@@ -437,3 +437,30 @@ fn chat_source_survives_the_one_authorized_wire_translation() {
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unmatched_prompt_prefixes_do_not_allocate_for_large_histories() {
|
||||
use gateway_core::{identity::ProviderKind, settings::prompt_rewrite::CompiledPromptRewrite};
|
||||
use gateway_protocol::prompt_rewrite::plan;
|
||||
let body = serde_json::json!({"instructions": "Custom instructions", "input": "x".repeat(1024 * 1024)});
|
||||
let body = body.as_object().unwrap();
|
||||
let rules = CompiledPromptRewrite::new(
|
||||
serde_json::from_value(json!([{
|
||||
"name":"客户端身份", "matchMode":"prefix", "pattern":"Unknown", "replacement":"Changed"
|
||||
}]))
|
||||
.unwrap(),
|
||||
)
|
||||
.unwrap()
|
||||
.for_provider(&ProviderKind::new("openai").unwrap())
|
||||
.unwrap();
|
||||
let stats = allocation_counter::measure(|| {
|
||||
for _ in 0..1000 {
|
||||
assert!(
|
||||
plan("openai", std::hint::black_box(body), |text| rules
|
||||
.replace_prefix(text))
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
});
|
||||
assert_eq!(stats.count_total, 0);
|
||||
}
|
||||
|
||||
@@ -1817,6 +1817,77 @@ fn withdrawn_provider_keeps_accounts_without_becoming_a_route_or_expanding_group
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prompt_rules_are_selected_once_by_upstream_and_keep_global_order() {
|
||||
let snapshot = super::snapshot();
|
||||
let plan_for = |rules| {
|
||||
let configured = snapshot
|
||||
.with_settings(&snapshot.settings().clone().with_prompt_rewrite_rules(rules))
|
||||
.unwrap();
|
||||
configured
|
||||
.plan(
|
||||
&PublicModelId::new("gpt-5.4").unwrap(),
|
||||
&super::operation(),
|
||||
configured.all_account_scope(),
|
||||
&Default::default(),
|
||||
)
|
||||
.unwrap()
|
||||
};
|
||||
let openai = ProviderKind::new("openai").unwrap();
|
||||
let agy = ProviderKind::new("antigravity").unwrap();
|
||||
let xai = ProviderKind::new("xai").unwrap();
|
||||
let scoped = |targets, prefix| {
|
||||
serde_json::from_value(
|
||||
serde_json::json!({"name": "客户端身份", "providers": targets, "matchMode":"prefix", "pattern": prefix, "replacement": ""}),
|
||||
)
|
||||
.unwrap()
|
||||
};
|
||||
let only_agy = plan_for(vec![scoped(vec!["antigravity"], "example"); 20]);
|
||||
assert!(only_agy.prompt_rewrite_rules(&openai).is_none());
|
||||
let selected = only_agy.prompt_rewrite_rules(&agy).unwrap();
|
||||
assert_eq!(
|
||||
selected.replace_prefix("example suffix").as_deref(),
|
||||
Some(" suffix")
|
||||
);
|
||||
assert!(Arc::ptr_eq(
|
||||
&selected,
|
||||
&only_agy.prompt_rewrite_rules(&agy).unwrap()
|
||||
));
|
||||
|
||||
let mixed = plan_for(vec![
|
||||
scoped(vec![], "shared first"),
|
||||
scoped(vec!["xai", "antigravity"], "shared"),
|
||||
scoped(vec![], "sh"),
|
||||
]);
|
||||
for provider in [&agy, &xai] {
|
||||
let rules = mixed.prompt_rewrite_rules(provider).unwrap();
|
||||
assert_eq!(rules.replace_prefix("shared first!").as_deref(), Some("!"));
|
||||
assert_eq!(
|
||||
rules.replace_prefix("shared second").as_deref(),
|
||||
Some(" second")
|
||||
);
|
||||
}
|
||||
let global = mixed.prompt_rewrite_rules(&openai).unwrap();
|
||||
assert_eq!(
|
||||
global.replace_prefix("shared second").as_deref(),
|
||||
Some("ared second")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prompt_rewrite_invalid_regex_cannot_replace_a_working_snapshot() {
|
||||
let snapshot = super::snapshot();
|
||||
let rules = serde_json::from_value(serde_json::json!([{
|
||||
"name":"DSH", "matchMode":"regex", "pattern":"[", "replacement":""
|
||||
}]))
|
||||
.unwrap();
|
||||
assert!(
|
||||
snapshot
|
||||
.with_settings(&snapshot.settings().clone().with_prompt_rewrite_rules(rules))
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn routing_plans_share_frozen_pricing_after_a_new_snapshot_is_published() {
|
||||
use gateway_core::{metering::PricingOverrides, runtime::RuntimeSnapshotHandle};
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
//! 运行设置的行为测试
|
||||
|
||||
mod prompt_rewrite;
|
||||
@@ -0,0 +1,129 @@
|
||||
//! 预览与转发共享匹配语义,配置编译错误不进入运行快照
|
||||
|
||||
use gateway_core::{
|
||||
identity::ProviderKind,
|
||||
settings::prompt_rewrite::{CompiledPromptRewrite, PromptRewriteRule},
|
||||
};
|
||||
use serde_json::json;
|
||||
|
||||
fn rule(mode: &str, pattern: &str, replacement: &str) -> PromptRewriteRule {
|
||||
serde_json::from_value(json!({
|
||||
"name": "测试规则", "matchMode": mode, "pattern": pattern,
|
||||
"replacement": replacement, "providers": []
|
||||
}))
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prompt_rewrite_preview_and_runtime_share_captures_flags_and_prefix_semantics() {
|
||||
for (mode, pattern, replacement, input, expected, matched) in [
|
||||
(
|
||||
"regex",
|
||||
r"(?is)you are (?<agent>\w+).*?END",
|
||||
"Agent: ${agent} / $1 / $$",
|
||||
"You are DSH\nbody\nEND\n用户内容",
|
||||
"Agent: DSH / DSH / $\n用户内容",
|
||||
true,
|
||||
),
|
||||
(
|
||||
"regex",
|
||||
r"(?m)^DSH|Other",
|
||||
"New",
|
||||
"Before\nDSH",
|
||||
"Before\nDSH",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"regex",
|
||||
r"DSH|Other",
|
||||
"New",
|
||||
"Before Other",
|
||||
"Before Other",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"regex",
|
||||
r"^",
|
||||
"Start: ",
|
||||
"用户内容",
|
||||
"Start: 用户内容",
|
||||
true,
|
||||
),
|
||||
(
|
||||
"regex",
|
||||
r"(?x)(DSH) # identity",
|
||||
"$1 revised",
|
||||
"DSH suffix",
|
||||
"DSH revised suffix",
|
||||
true,
|
||||
),
|
||||
("regex", r"(DSH)", "$1", "DSH suffix", "DSH suffix", true),
|
||||
("prefix", "DSH.*", "$1", "DSH.* suffix", "$1 suffix", true),
|
||||
(
|
||||
"regex",
|
||||
r"(?s)DSH.*?END\n",
|
||||
"",
|
||||
"DSH\nidentity\nEND\n用户内容",
|
||||
"用户内容",
|
||||
true,
|
||||
),
|
||||
] {
|
||||
let rule = rule(mode, pattern, replacement);
|
||||
let preview = rule.preview(input).unwrap();
|
||||
assert_eq!(preview.matched, matched, "{pattern}");
|
||||
assert_eq!(preview.output, expected, "{pattern}");
|
||||
let compiled = CompiledPromptRewrite::new(vec![rule].into()).unwrap();
|
||||
let runtime = compiled
|
||||
.for_provider(&ProviderKind::new("antigravity").unwrap())
|
||||
.unwrap();
|
||||
let updated = runtime.replace_prefix(input);
|
||||
assert_eq!(updated.as_deref().unwrap_or(input), expected, "{pattern}");
|
||||
assert_eq!(updated.is_some(), expected != input);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prompt_rewrite_noop_first_match_stops_following_rules() {
|
||||
let compiled = CompiledPromptRewrite::new(
|
||||
vec![
|
||||
rule("regex", "(DSH)", "$1"),
|
||||
rule("prefix", "DSH", "Changed"),
|
||||
]
|
||||
.into(),
|
||||
)
|
||||
.unwrap();
|
||||
let rules = compiled
|
||||
.for_provider(&ProviderKind::new("openai").unwrap())
|
||||
.unwrap();
|
||||
assert_eq!(rules.replace_prefix("DSH suffix"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prompt_rewrite_rejects_invalid_unsupported_and_oversized_regexes() {
|
||||
for pattern in ["[", "DSH)|Other(?:", r"(?=DSH)", r"(DSH)\1", "a{100000000}"] {
|
||||
let rule = rule("regex", pattern, "");
|
||||
assert!(rule.validate().is_err());
|
||||
assert!(rule.preview("DSH").is_err());
|
||||
assert!(CompiledPromptRewrite::new(vec![rule.clone()].into()).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeated_validation_of_unchanged_rules_does_not_allocate() {
|
||||
for mode in ["prefix", "regex"] {
|
||||
let rule = rule(mode, "(DSH)", "$1 revised");
|
||||
rule.validate().unwrap();
|
||||
let allocations = allocation_counter::measure(|| rule.validate().unwrap());
|
||||
assert_eq!(allocations.count_total, 0, "{mode}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prompt_rewrite_debug_hides_patterns_and_replacements() {
|
||||
let rule = rule("regex", "private-pattern", "private-replacement");
|
||||
let compiled = CompiledPromptRewrite::new(vec![rule.clone()].into()).unwrap();
|
||||
for diagnostic in [format!("{rule:?}"), format!("{compiled:?}")] {
|
||||
assert!(!diagnostic.contains("private-pattern"));
|
||||
assert!(!diagnostic.contains("private-replacement"));
|
||||
}
|
||||
}
|
||||
@@ -349,7 +349,7 @@ HTTP 总入口统一包裹原生路由,`dispatch_http` 复用同一路由与
|
||||
|
||||
`Load` 返回完整运行设置与 `config_revision`。`ReplaceRuntimeSettings::from(settings)` 保留该版本并构造更新命令;
|
||||
`Replace` 接收 `(MutationContext, ReplaceRuntimeSettings)`,通过已有校验、事务、审计和快照发布保存设置。
|
||||
每次写入都必须提供 `openai_request_settings`、`openai_websocket_pool` 和 `reset_credit_on_low_weekly_quota`。
|
||||
每次写入都必须提供 `openai_request_settings`、`openai_websocket_pool`、`reset_credit_on_low_weekly_quota` 和 `prompt_rewrite_rules`。清空提示词改写规则时提交空数组,范围与顺序见[提示词改写](../../../../../docs/api.md#提示词改写)。
|
||||
版本过期返回 `ServiceError { kind: "conflict", message }`。读取结果的普通改写不会持久化,也不会回滚已经提交的事务
|
||||
|
||||
`accounts::GetResetCreditAutomation` 接收账号 ID,返回 `ResetCreditAutomationStatus`:开关、全局提前分钟数、
|
||||
|
||||
@@ -57,6 +57,33 @@ pub enum AccountErrorOperator {
|
||||
Equals,
|
||||
Contains,
|
||||
}
|
||||
#[derive(Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct PromptRewriteRule {
|
||||
pub name: String,
|
||||
#[serde(default)]
|
||||
pub providers: BTreeSet<String>,
|
||||
pub match_mode: PromptMatchMode,
|
||||
pub pattern: String,
|
||||
pub replacement: String,
|
||||
}
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum PromptMatchMode {
|
||||
Prefix,
|
||||
Regex,
|
||||
}
|
||||
#[derive(Clone, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct PromptRewritePreviewRequest {
|
||||
pub rule: PromptRewriteRule,
|
||||
pub text: String,
|
||||
}
|
||||
#[derive(Clone, Serialize, Deserialize)]
|
||||
pub struct PromptRewritePreviewResult {
|
||||
pub matched: bool,
|
||||
pub output: String,
|
||||
}
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct OpenAiWebSocketPoolSettings {
|
||||
@@ -188,6 +215,7 @@ pub struct RuntimeSettings {
|
||||
pub usage_retention_days: u32,
|
||||
pub ops_event_retention_days: u32,
|
||||
pub audit_retention_days: u32,
|
||||
pub prompt_rewrite_rules: Vec<PromptRewriteRule>,
|
||||
pub account_error_protection: AccountErrorProtection,
|
||||
pub account_warmup_enabled: bool,
|
||||
pub account_warmup_cron: String,
|
||||
@@ -230,6 +258,7 @@ pub struct ReplaceRuntimeSettings {
|
||||
pub usage_retention_days: u32,
|
||||
pub ops_event_retention_days: u32,
|
||||
pub audit_retention_days: u32,
|
||||
pub prompt_rewrite_rules: Vec<PromptRewriteRule>,
|
||||
pub account_error_protection: AccountErrorProtection,
|
||||
pub account_warmup_enabled: bool,
|
||||
pub account_warmup_cron: String,
|
||||
@@ -349,6 +378,12 @@ impl Operation for Load {
|
||||
type Input = ();
|
||||
type Output = RuntimeSettings;
|
||||
}
|
||||
pub struct PreviewPromptRewrite;
|
||||
impl Operation for PreviewPromptRewrite {
|
||||
const NAME: &'static str = "settings.preview_prompt_rewrite";
|
||||
type Input = PromptRewritePreviewRequest;
|
||||
type Output = PromptRewritePreviewResult;
|
||||
}
|
||||
pub struct PreviewPrivacyPolicy;
|
||||
impl Operation for PreviewPrivacyPolicy {
|
||||
const NAME: &'static str = "settings.preview_privacy_policy";
|
||||
@@ -444,6 +479,7 @@ impl From<RuntimeSettings> for ReplaceRuntimeSettings {
|
||||
usage_retention_days: settings.usage_retention_days,
|
||||
ops_event_retention_days: settings.ops_event_retention_days,
|
||||
audit_retention_days: 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,
|
||||
|
||||
@@ -18,7 +18,7 @@ http = "1.5.0"
|
||||
httpdate = "1.0.3"
|
||||
memchr = "2.8.3"
|
||||
serde = { version = "1.0.228", features = ["derive"] }
|
||||
serde_json = { version = "1.0.150", features = ["arbitrary_precision", "preserve_order"] }
|
||||
serde_json = { version = "1.0.150", features = ["arbitrary_precision", "preserve_order", "raw_value"] }
|
||||
thiserror = "2.0.18"
|
||||
uuid = { version = "1.23.3", features = ["v4"] }
|
||||
|
||||
|
||||
@@ -14,4 +14,4 @@ pub use response::{
|
||||
pub const GENAI_PROTOCOL: &str = "genai";
|
||||
|
||||
mod tokens;
|
||||
pub use tokens::{CountTokensError, count_tokens_request};
|
||||
pub use tokens::{CountTokensError, count_tokens_request, into_count_tokens_request};
|
||||
|
||||
@@ -8,15 +8,31 @@ use thiserror::Error;
|
||||
#[error("generateContentRequest must be a JSON object.")]
|
||||
pub struct CountTokensError;
|
||||
|
||||
fn wrapped_field(request: &Map<String, Value>) -> Option<&'static str> {
|
||||
["generateContentRequest", "generate_content_request"]
|
||||
.into_iter()
|
||||
.find(|key| request.contains_key(*key))
|
||||
}
|
||||
|
||||
/// 完整生成请求存在时,以它作为计数输入,外层 contents 不参与计数
|
||||
pub fn count_tokens_request(
|
||||
request: &Map<String, Value>,
|
||||
) -> Result<&Map<String, Value>, CountTokensError> {
|
||||
match request
|
||||
.get("generateContentRequest")
|
||||
.or_else(|| request.get("generate_content_request"))
|
||||
{
|
||||
Some(value) => value.as_object().ok_or(CountTokensError),
|
||||
match wrapped_field(request) {
|
||||
Some(key) => request[key].as_object().ok_or(CountTokensError),
|
||||
None => Ok(request),
|
||||
}
|
||||
}
|
||||
|
||||
/// 取出计数正文供上游适配,无需复制历史和工具
|
||||
pub fn into_count_tokens_request(
|
||||
mut request: Map<String, Value>,
|
||||
) -> Result<Map<String, Value>, CountTokensError> {
|
||||
match wrapped_field(&request) {
|
||||
Some(key) => match request.remove(key) {
|
||||
Some(Value::Object(body)) => Ok(body),
|
||||
_ => Err(CountTokensError),
|
||||
},
|
||||
None => Ok(request),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,3 +24,6 @@ pub mod peer;
|
||||
|
||||
/// Chat Completions 直接转换
|
||||
pub mod chat_completions;
|
||||
|
||||
/// 原生协议与 Chat 的系统指令定位及局部替换
|
||||
pub mod prompt_rewrite;
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
//! 定位生成正文的首条系统指令,同时维护已解析正文和原始 JSON
|
||||
|
||||
mod wire;
|
||||
|
||||
use serde_json::{Map, Value};
|
||||
|
||||
type Path = &'static [&'static str];
|
||||
|
||||
/// 已定位的文本字段及替换结果
|
||||
pub struct PromptEdit {
|
||||
content: Path,
|
||||
tail: Path,
|
||||
text: String,
|
||||
}
|
||||
|
||||
/// 未命中时仅借用系统文本,不复制会话历史
|
||||
pub fn plan(
|
||||
protocol: &str,
|
||||
body: &Map<String, Value>,
|
||||
replace: impl FnOnce(&str) -> Option<String>,
|
||||
) -> Option<PromptEdit> {
|
||||
use crate::{
|
||||
anthropic::ANTHROPIC_PROTOCOL, chat_completions::CHAT_PROTOCOL, genai::GENAI_PROTOCOL,
|
||||
openai::OPENAI_PROTOCOL,
|
||||
};
|
||||
let (content, value, types): (Path, _, &[&str]) = match protocol {
|
||||
OPENAI_PROTOCOL | CHAT_PROTOCOL => {
|
||||
if let Some(value) = body.get("instructions").filter(|v| !v.is_null()) {
|
||||
(&["instructions"], value, &["text", "input_text"])
|
||||
} else {
|
||||
let path: Path = if protocol == CHAT_PROTOCOL {
|
||||
&["messages", "0", "content"]
|
||||
} else {
|
||||
&["input", "0", "content"]
|
||||
};
|
||||
let first = body.get(path[0])?.get(0)?;
|
||||
if !matches!(first.get("role")?.as_str()?, "system" | "developer")
|
||||
|| first
|
||||
.get("type")
|
||||
.is_some_and(|v| v.as_str() != Some("message"))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
(path, first.get("content")?, &["text", "input_text"])
|
||||
}
|
||||
}
|
||||
ANTHROPIC_PROTOCOL => (&["system"], body.get("system")?, &["text"]),
|
||||
GENAI_PROTOCOL => {
|
||||
let path: Path = if body.contains_key("systemInstruction") {
|
||||
&["systemInstruction", "parts", "0", "text"]
|
||||
} else {
|
||||
&["system_instruction", "parts", "0", "text"]
|
||||
};
|
||||
let value = body.get(path[0])?.get("parts")?.get(0)?.get("text")?;
|
||||
return Some(PromptEdit {
|
||||
content: path,
|
||||
tail: &[],
|
||||
text: replace(value.as_str()?)?,
|
||||
});
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
let (tail, text): (Path, _) = if let Some(parts) = value.as_array() {
|
||||
let first = parts.first()?;
|
||||
if !types.contains(&first.get("type")?.as_str()?) {
|
||||
return None;
|
||||
}
|
||||
(&["0", "text"], first.get("text")?.as_str()?)
|
||||
} else {
|
||||
(&[], value.as_str()?)
|
||||
};
|
||||
Some(PromptEdit {
|
||||
content,
|
||||
tail,
|
||||
text: replace(text)?,
|
||||
})
|
||||
}
|
||||
|
||||
impl PromptEdit {
|
||||
/// 将编辑应用于定位时使用的正文
|
||||
pub fn apply(self, body: &mut Map<String, Value>) {
|
||||
let Some(mut field) = body.get_mut(self.content[0]) else {
|
||||
return;
|
||||
};
|
||||
for &key in self.content[1..].iter().chain(self.tail) {
|
||||
let Some(child) = (if key == "0" {
|
||||
field.get_mut(0)
|
||||
} else {
|
||||
field.get_mut(key)
|
||||
}) else {
|
||||
return;
|
||||
};
|
||||
field = child;
|
||||
}
|
||||
*field = Value::String(self.text);
|
||||
}
|
||||
|
||||
/// 只编码目标字符串,保留其他字段的原始字节
|
||||
pub fn wire(&self, body: &[u8]) -> Option<Vec<u8>> {
|
||||
let mut raw = serde_json::from_slice(body).ok()?;
|
||||
for &key in self.content.iter().chain(self.tail) {
|
||||
raw = if key == "0" {
|
||||
wire::first(raw)?
|
||||
} else {
|
||||
wire::field(raw, key)?
|
||||
};
|
||||
}
|
||||
let start = raw.get().as_ptr() as usize - body.as_ptr() as usize;
|
||||
let mut out = Vec::with_capacity(body.len() - raw.get().len() + self.text.len() + 2);
|
||||
out.extend_from_slice(&body[..start]);
|
||||
serde_json::to_writer(&mut out, &self.text).ok()?;
|
||||
out.extend_from_slice(&body[start + raw.get().len()..]);
|
||||
Some(out)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
//! 只借用路径命中的 JSON 字段,跳过无关值,不展开工具或历史
|
||||
|
||||
use serde::{
|
||||
Deserialize, Deserializer,
|
||||
de::{IgnoredAny, MapAccess, Visitor},
|
||||
};
|
||||
use serde_json::value::RawValue;
|
||||
use std::{borrow::Cow, fmt};
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Text<'a>(#[serde(borrow)] Cow<'a, str>);
|
||||
|
||||
pub(super) fn first(raw: &RawValue) -> Option<&RawValue> {
|
||||
let array = raw.get().strip_prefix('[')?;
|
||||
serde_json::Deserializer::from_str(array)
|
||||
.into_iter::<&RawValue>()
|
||||
.next()?
|
||||
.ok()
|
||||
}
|
||||
|
||||
pub(super) fn field<'a>(raw: &'a RawValue, name: &str) -> Option<&'a RawValue> {
|
||||
struct Field<'a>(&'a str);
|
||||
impl<'de> Visitor<'de> for Field<'_> {
|
||||
type Value = Option<&'de RawValue>;
|
||||
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
formatter.write_str("a JSON object")
|
||||
}
|
||||
fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
|
||||
let mut found = None;
|
||||
while let Some(key) = map.next_key::<Text<'_>>()? {
|
||||
if key.0 == self.0 {
|
||||
found = Some(map.next_value()?);
|
||||
} else {
|
||||
map.next_value::<IgnoredAny>()?;
|
||||
}
|
||||
}
|
||||
Ok(found)
|
||||
}
|
||||
}
|
||||
serde_json::Deserializer::from_str(raw.get())
|
||||
.deserialize_map(Field(name))
|
||||
.ok()
|
||||
.flatten()
|
||||
}
|
||||
@@ -32,9 +32,7 @@ pub fn token_count_observation(
|
||||
context: &Map<String, Value>,
|
||||
) -> RequestObservation {
|
||||
let body = if protocol == GENAI_PROTOCOL {
|
||||
body.get("generateContentRequest")
|
||||
.and_then(Value::as_object)
|
||||
.unwrap_or(body)
|
||||
genai::count_tokens_request(body).unwrap_or(body)
|
||||
} else {
|
||||
body
|
||||
};
|
||||
|
||||
@@ -4,6 +4,7 @@ mod anthropic;
|
||||
mod genai;
|
||||
mod http;
|
||||
mod openai;
|
||||
mod prompt_rewrite;
|
||||
mod request;
|
||||
|
||||
mod chat_completions;
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
//! 各协议的系统指令位置、首条命中与其余 wire 字节保留
|
||||
|
||||
use gateway_protocol::prompt_rewrite::plan;
|
||||
mod wire;
|
||||
|
||||
#[test]
|
||||
fn unmatched_quoted_and_unknown_content_passes_through() {
|
||||
for (protocol, body) in [
|
||||
(
|
||||
"openai",
|
||||
r#"{"instructions":"quote: abc","input":[{"role":"system","content":"abc"}]}"#,
|
||||
),
|
||||
(
|
||||
"openai",
|
||||
r#"{"input":[{"type":"function_call","role":"system","content":"abc"}]}"#,
|
||||
),
|
||||
(
|
||||
"chat_completions",
|
||||
r#"{"messages":[{"role":"user","content":"abc"},{"role":"developer","content":"abc"}]}"#,
|
||||
),
|
||||
(
|
||||
"genai",
|
||||
r#"{"contents":[{"role":"user","parts":[{"text":"abc"}]}]}"#,
|
||||
),
|
||||
(
|
||||
"genai",
|
||||
r#"{"systemInstruction":{"parts":[{"text":"untouched"}]},"generateContentRequest":{"systemInstruction":{"parts":[{"text":"abc"}]}}}"#,
|
||||
),
|
||||
(
|
||||
"anthropic",
|
||||
r#"{"system":[{"type":"custom","text":"abc"}]}"#,
|
||||
),
|
||||
("other", r#"{"instructions":"abc"}"#),
|
||||
] {
|
||||
let body = serde_json::from_str(body).unwrap();
|
||||
assert!(
|
||||
plan(protocol, &body, |text| text
|
||||
.strip_prefix("abc")
|
||||
.map(str::to_owned))
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
//! 各协议的系统指令位置、首条命中与其余 wire 字节保留
|
||||
|
||||
use gateway_protocol::prompt_rewrite::plan;
|
||||
use serde_json::Map;
|
||||
|
||||
#[test]
|
||||
fn rewrites_only_the_authoritative_text_and_preserves_wire_bytes() {
|
||||
for (protocol, instruction) in [
|
||||
(
|
||||
"chat_completions",
|
||||
r#""messages":[{"role":"system","content":"First\n规则"},{"role":"user","content":"First\n规则"}]"#,
|
||||
),
|
||||
(
|
||||
"openai",
|
||||
r#""instructions":"First\n规则","input":[{"role":"developer","content":"First\n规则"}]"#,
|
||||
),
|
||||
(
|
||||
"openai",
|
||||
r#""input":[{"type":"message","role":"developer","content":[{"type":"input_text","text":"First\n规则","extra":7}]}]"#,
|
||||
),
|
||||
("anthropic", r#""system":"First\n规则""#),
|
||||
(
|
||||
"anthropic",
|
||||
r#""system":[{"type":"text","text":"First\n规则","cache_control":{"type":"ephemeral"}},{"type":"text","text":"First\n规则"}]"#,
|
||||
),
|
||||
(
|
||||
"genai",
|
||||
r#""systemInstruction":{"parts":[{"text":"First\n规则"},{"text":"First\n规则"}]}"#,
|
||||
),
|
||||
(
|
||||
"genai",
|
||||
r#""system_instruction":{"parts":[{"text":"First\n规则"}]}"#,
|
||||
),
|
||||
] {
|
||||
let body = format!(
|
||||
r#"{{"unknown":1e+08, {instruction}, "unknown":12345678901234567890123456789}}"#
|
||||
);
|
||||
let parsed: Map<_, _> = serde_json::from_str(&body).unwrap();
|
||||
let edit = plan(protocol, &parsed, |text| {
|
||||
text.strip_prefix("First\n")
|
||||
.map(|suffix| format!("Changed\n{suffix}"))
|
||||
})
|
||||
.unwrap();
|
||||
let wire = edit.wire(body.as_bytes()).unwrap();
|
||||
let mut edited = parsed;
|
||||
edit.apply(&mut edited);
|
||||
assert_eq!(edited, serde_json::from_slice::<Map<_, _>>(&wire).unwrap());
|
||||
assert_eq!(wire, body.replacen("First", "Changed", 1).as_bytes());
|
||||
}
|
||||
}
|
||||
@@ -21,6 +21,10 @@ fn token_count_observation_uses_the_nested_generation_request() {
|
||||
serde_json::json!({"generationConfig":{"thinkingConfig":{"thinkingLevel":"HIGH"}},"generateContentRequest":{"contents":[]}}),
|
||||
None,
|
||||
),
|
||||
(
|
||||
serde_json::json!({"generate_content_request":{"generation_config":{"thinking_config":{"thinking_level":"HIGH"}}}}),
|
||||
Some("high"),
|
||||
),
|
||||
] {
|
||||
let observation = gateway_protocol::request::token_count_observation(
|
||||
"genai",
|
||||
|
||||
@@ -120,6 +120,7 @@ impl SettingsStore for AdminSettingsStoreAdapter {
|
||||
"min_codex_desktop_version".to_owned(),
|
||||
"min_codex_cli_version".to_owned(),
|
||||
"retention".to_owned(),
|
||||
"prompt_rewrite_rules_json".to_owned(),
|
||||
"account_error_protection".to_owned(),
|
||||
],
|
||||
),
|
||||
|
||||
@@ -772,8 +772,8 @@ impl ClientKeyStore for PgAdminClientKeyStore {
|
||||
.ok_or_else(|| admin_store_error(ENTITY, StoreError::NotFound {
|
||||
source: None, entity: ENTITY, id: id.as_str().to_owned()
|
||||
}))?;
|
||||
let rows: Vec<(String, String, Option<String>, String)> = sqlx::query_as(
|
||||
"select a.id, a.name, a.email, a.provider_kind from provider_accounts a
|
||||
let rows: Vec<(String, String, Option<String>, String, Option<String>)> = sqlx::query_as(
|
||||
"select a.id, a.name, a.email, a.provider_kind, a.platform_icon from provider_accounts a
|
||||
where a.id > $1
|
||||
and ($2 = '' or strpos(lower(a.name), lower($2)) > 0
|
||||
or strpos(lower(coalesce(a.email, '')), lower($2)) > 0)
|
||||
@@ -793,12 +793,15 @@ impl ClientKeyStore for PgAdminClientKeyStore {
|
||||
let items: Vec<_> = rows
|
||||
.into_iter()
|
||||
.take(usize::from(PAGE_SIZE))
|
||||
.map(|(id, name, email, provider)| BudgetReferenceAccount {
|
||||
id,
|
||||
name,
|
||||
email,
|
||||
provider,
|
||||
})
|
||||
.map(
|
||||
|(id, name, email, provider, platform_icon)| BudgetReferenceAccount {
|
||||
platform_icon,
|
||||
id,
|
||||
name,
|
||||
email,
|
||||
provider,
|
||||
},
|
||||
)
|
||||
.collect();
|
||||
let next_cursor = items.last().filter(|_| has_more).map(|row| row.id.clone());
|
||||
Ok(BudgetReferenceAccountPage { items, next_cursor })
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
use super::*;
|
||||
|
||||
const PROVIDER_SET: &str = "coalesce(array_agg(distinct provider_kind) filter(where provider_kind <> ''), '{}'::text[]) as providers,";
|
||||
|
||||
/// 输入 matching 提供分组键、指标输入列及 is_completed_usage
|
||||
/// 精确分位数在整个结果组内计算,不把局部分位数合并成新的分位数
|
||||
pub(super) fn push_fact_aggregation(
|
||||
@@ -16,6 +18,7 @@ pub(super) fn push_fact_aggregation(
|
||||
DistributionRead::Full,
|
||||
None,
|
||||
None,
|
||||
false,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -26,6 +29,7 @@ pub(super) fn push_fact_aggregation_selected(
|
||||
distributions: DistributionRead,
|
||||
counter_names: Option<&[&str]>,
|
||||
distribution_names: Option<&[&str]>,
|
||||
model_providers: bool,
|
||||
) {
|
||||
if read_costs && matches!(distributions, DistributionRead::Statistics) {
|
||||
push_fact_statistics_by_currency(query, counter_names, distribution_names);
|
||||
@@ -35,6 +39,9 @@ pub(super) fn push_fact_aggregation_selected(
|
||||
let statistics_only = matches!(distributions, DistributionRead::Statistics);
|
||||
let counters = selected_counter_expressions(counter_names);
|
||||
query.push(", counted as (select output_bucket,name,max(started_at) filter(where is_completed_usage) as last_used_at,");
|
||||
if model_providers {
|
||||
query.push(PROVIDER_SET);
|
||||
}
|
||||
push_counter_object(query, &counters);
|
||||
query.push(" as counts");
|
||||
if read_distributions && (exact_percentiles || statistics_only) {
|
||||
@@ -51,21 +58,16 @@ pub(super) fn push_fact_aggregation_selected(
|
||||
// 空币种仍参与场景费用,金额为空的实际费用继续在展开后排除
|
||||
query.push(", cost_groups as (select output_bucket,name,cost_currency,sum(cost_amount) as cost_amount,sum(standard_cost_amount) as standard_cost_amount,sum(no_cache_cost_amount) as no_cache_cost_amount from matching where is_completed_usage group by output_bucket,name,cost_currency), cost_values as (select output_bucket,name,currency,sum(amount)::text as amount from cost_groups cross join lateral (values (cost_currency,cost_amount),('standard_usd',standard_cost_amount),('no_cache_usd',no_cache_cost_amount)) cost(currency,amount) where currency is not null and amount is not null group by output_bucket,name,currency), merged_costs as (select output_bucket,name,jsonb_object_agg(currency,amount) as costs from cost_values group by output_bucket,name)");
|
||||
}
|
||||
if !read_distributions {
|
||||
query.push(" select c.output_bucket as bucket_start,c.name,c.counts,c.last_used_at,'{}'::jsonb as distributions,'{}'::jsonb as exact_percentiles,");
|
||||
query.push(if read_costs {
|
||||
"coalesce(k.costs,'{}'::jsonb)"
|
||||
} else {
|
||||
"'{}'::jsonb"
|
||||
});
|
||||
query.push(" as costs from counted c");
|
||||
if read_costs {
|
||||
query.push(" left join merged_costs k using(output_bucket,name)");
|
||||
if !read_distributions || exact_percentiles || statistics_only {
|
||||
query.push(" select c.output_bucket as bucket_start,c.name,c.counts,c.last_used_at,");
|
||||
if model_providers {
|
||||
query.push("c.providers,");
|
||||
}
|
||||
return;
|
||||
}
|
||||
if exact_percentiles || statistics_only {
|
||||
query.push(" select c.output_bucket as bucket_start,c.name,c.counts,c.last_used_at,c.distributions,c.exact_percentiles,");
|
||||
query.push(if read_distributions {
|
||||
"c.distributions,c.exact_percentiles,"
|
||||
} else {
|
||||
"'{}'::jsonb as distributions,'{}'::jsonb as exact_percentiles,"
|
||||
});
|
||||
query.push(if read_costs {
|
||||
"coalesce(k.costs,'{}'::jsonb)"
|
||||
} else {
|
||||
@@ -99,6 +101,9 @@ pub(super) fn push_fact_aggregation_selected(
|
||||
query.push(" from sample_stats s");
|
||||
query.push(" left join merged_bins b using(output_bucket,name,metric)");
|
||||
query.push(" group by s.output_bucket,s.name) select c.output_bucket as bucket_start,c.name,c.counts,c.last_used_at,");
|
||||
if model_providers {
|
||||
query.push("c.providers,");
|
||||
}
|
||||
query.push(if read_costs {
|
||||
"coalesce(k.costs,'{}'::jsonb)"
|
||||
} else {
|
||||
@@ -133,6 +138,7 @@ fn push_fact_statistics_by_currency(
|
||||
true,
|
||||
counter_names,
|
||||
distribution_names,
|
||||
false,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -322,6 +328,7 @@ pub(super) fn push_summary_aggregation(
|
||||
costs: bool,
|
||||
counter_names: Option<&[&str]>,
|
||||
distribution_names: Option<&[&str]>,
|
||||
model_providers: bool,
|
||||
) {
|
||||
push_summary_aggregation_from(
|
||||
query,
|
||||
@@ -330,6 +337,7 @@ pub(super) fn push_summary_aggregation(
|
||||
costs,
|
||||
counter_names,
|
||||
distribution_names,
|
||||
model_providers,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -341,6 +349,7 @@ fn push_summary_aggregation_from(
|
||||
costs: bool,
|
||||
counter_names: Option<&[&str]>,
|
||||
distribution_names: Option<&[&str]>,
|
||||
model_providers: bool,
|
||||
) {
|
||||
let distributions = !matches!(distribution_read, DistributionRead::None);
|
||||
// 每个源汇总只展开一次固定指标,避免按指标键放大行数再排序
|
||||
@@ -359,6 +368,9 @@ fn push_summary_aggregation_from(
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
query.push(", grouped as (select output_bucket,name,max(last_used_at) as last_used_at,");
|
||||
if model_providers {
|
||||
query.push(PROVIDER_SET);
|
||||
}
|
||||
push_counter_object(query, &counters);
|
||||
query
|
||||
.push(" as counts from ")
|
||||
@@ -404,6 +416,9 @@ fn push_summary_aggregation_from(
|
||||
}
|
||||
}
|
||||
query.push(" select g.output_bucket as bucket_start,g.name,g.last_used_at,g.counts,");
|
||||
if model_providers {
|
||||
query.push("g.providers,");
|
||||
}
|
||||
query.push(if costs {
|
||||
"coalesce(k.costs,'{}'::jsonb)"
|
||||
} else {
|
||||
@@ -475,6 +490,14 @@ pub(super) fn fact_dimension_sql(dimension: Option<DiagnosticDimension>) -> &'st
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn summary_provider_column(collection: &str) -> &'static str {
|
||||
if matches!(collection, "account_model" | "key_model") {
|
||||
"dimensions[2]"
|
||||
} else {
|
||||
"dimensions[1]"
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn summary_dimension_sql(
|
||||
collection: &str,
|
||||
dimension: Option<DiagnosticDimension>,
|
||||
@@ -483,7 +506,10 @@ pub(super) fn summary_dimension_sql(
|
||||
match dimension {
|
||||
None => "''::text".to_owned(),
|
||||
Some(DiagnosticDimension::Provider) => {
|
||||
format!("coalesce(nullif(dimensions[{}],''),'unrouted')", 1 + offset)
|
||||
format!(
|
||||
"coalesce(nullif({},''),'unrouted')",
|
||||
summary_provider_column(collection)
|
||||
)
|
||||
}
|
||||
Some(DiagnosticDimension::Model) => format!(
|
||||
"coalesce(nullif(dimensions[{}],''),dimensions[{}],'')",
|
||||
|
||||
@@ -81,7 +81,14 @@ impl AnalyticsSnapshot<'_> {
|
||||
granularity,
|
||||
boundaries.as_deref(),
|
||||
);
|
||||
q.push(format!(" as output_bucket,{name} as name,counts,costs from request_analytics_1h where collection=")).push_bind(AGGREGATE_COLLECTION).push(" and bucket_start >= ").push_bind(range.start).push(" and bucket_start < ").push_bind(range.end);
|
||||
let model_providers =
|
||||
dimension == Some(DiagnosticDimension::Model) && account_models.is_none();
|
||||
let provider = if model_providers {
|
||||
"dimensions[1] as provider_kind,"
|
||||
} else {
|
||||
""
|
||||
};
|
||||
q.push(format!(" as output_bucket,{name} as name,{provider}counts,costs from request_analytics_1h where collection=")).push_bind(AGGREGATE_COLLECTION).push(" and bucket_start >= ").push_bind(range.start).push(" and bucket_start < ").push_bind(range.end);
|
||||
for (index, value) in [
|
||||
(1, &filter.provider_kind),
|
||||
(2, &filter.model),
|
||||
@@ -124,7 +131,14 @@ impl AnalyticsSnapshot<'_> {
|
||||
if selection.costs {
|
||||
q.push(" union all select output_bucket,name,'cost',c.key,c.value::numeric from matching cross join lateral jsonb_each_text(costs) c");
|
||||
}
|
||||
q.push("), totals as (select output_bucket,name,kind,key,sum(value)::text as value from entries group by output_bucket,name,kind,key) select output_bucket,name,jsonb_object_agg(key,value) filter(where kind='count') as counts,jsonb_object_agg(key,value) filter(where kind='cost') as costs from totals group by output_bucket,name");
|
||||
if model_providers {
|
||||
q.push(" union all select distinct output_bucket,name,'provider',provider_kind,0::numeric from matching where provider_kind <> ''");
|
||||
}
|
||||
q.push("), totals as (select output_bucket,name,kind,key,sum(value)::text as value from entries group by output_bucket,name,kind,key) select output_bucket,name,jsonb_object_agg(key,value) filter(where kind='count') as counts,jsonb_object_agg(key,value) filter(where kind='cost') as costs");
|
||||
if model_providers {
|
||||
q.push(",array_agg(key) filter(where kind='provider') as providers");
|
||||
}
|
||||
q.push(" from totals group by output_bucket,name");
|
||||
let mut rows = q.build().fetch(&mut *self.tx);
|
||||
while let Some(row) = rows
|
||||
.try_next()
|
||||
@@ -140,6 +154,11 @@ impl AnalyticsSnapshot<'_> {
|
||||
}
|
||||
let key = (get(&row, "output_bucket")?, name);
|
||||
let state = states.entry(key).or_default();
|
||||
if model_providers {
|
||||
state
|
||||
.providers
|
||||
.extend(get::<Option<Vec<String>>>(&row, "providers")?.unwrap_or_default());
|
||||
}
|
||||
let counts =
|
||||
get::<Option<sqlx::types::Json<BTreeMap<String, String>>>>(&row, "counts")?
|
||||
.map(|v| v.0)
|
||||
|
||||
@@ -104,6 +104,7 @@ impl AnalyticsSnapshot<'_> {
|
||||
"unavailable_count",
|
||||
]),
|
||||
None,
|
||||
false,
|
||||
);
|
||||
sql.push(") fact_parts");
|
||||
}
|
||||
|
||||
@@ -22,6 +22,9 @@ pub(crate) struct MetricState {
|
||||
pub(super) distributions: BTreeMap<String, Histogram>,
|
||||
pub(super) costs: BTreeMap<String, String>,
|
||||
pub(super) last_used_at: Option<DateTime<Utc>>,
|
||||
// 模型诊断查询时从分组维度提取,不写入持久化指标
|
||||
#[serde(skip)]
|
||||
pub(super) providers: BTreeSet<String>,
|
||||
#[serde(skip)]
|
||||
exact_percentiles: Option<BTreeMap<String, Vec<Option<f64>>>>,
|
||||
}
|
||||
@@ -38,6 +41,7 @@ impl MetricState {
|
||||
)?
|
||||
.0,
|
||||
last_used_at: get(row, "last_used_at")?,
|
||||
providers: BTreeSet::new(),
|
||||
exact_percentiles: None,
|
||||
})
|
||||
}
|
||||
@@ -125,6 +129,7 @@ impl MetricState {
|
||||
if self.count("request_count") == 0 {
|
||||
self.exact_percentiles.clone_from(&other.exact_percentiles);
|
||||
}
|
||||
self.providers.extend(other.providers.iter().cloned());
|
||||
self.last_used_at = self.last_used_at.max(other.last_used_at);
|
||||
for (name, count) in &other.counts {
|
||||
self.increment(name, *count)?;
|
||||
|
||||
@@ -634,7 +634,8 @@ impl<'a> AnalyticsSnapshot<'a> {
|
||||
observations.push(DiagnosticObservation {
|
||||
key: key.clone(),
|
||||
name: key,
|
||||
account_provider_kind: None,
|
||||
providers: state.providers.iter().cloned().collect(),
|
||||
platform_icon: None,
|
||||
account_authentication_kind: None,
|
||||
account_plan_type: None,
|
||||
account_plan_type_display: None,
|
||||
@@ -671,9 +672,9 @@ impl<'a> AnalyticsSnapshot<'a> {
|
||||
.map(|item| item.key.clone())
|
||||
.collect::<Vec<_>>();
|
||||
let statement = if dimension == DiagnosticDimension::Account {
|
||||
"select requested.id, historical.provider_kind, historical.provider_account_authentication_kind_snapshot as authentication_kind, historical.provider_account_plan_type_snapshot as plan_type, historical.provider_account_plan_type_display_snapshot as plan_type_display, coalesce(historical.provider_account_email_snapshot,historical.provider_account_name_snapshot,requested.id) as name from unnest($1::text[]) requested(id) left join lateral (select provider_kind,provider_account_authentication_kind_snapshot,provider_account_plan_type_snapshot,provider_account_plan_type_display_snapshot,provider_account_email_snapshot,provider_account_name_snapshot from model_request_observations mr where mr.provider_account_ref=requested.id order by mr.started_at desc,mr.id desc limit 1) historical on true"
|
||||
"select requested.id, coalesce(historical.provider_kind,a.provider_kind) as provider_kind, a.platform_icon, historical.provider_account_authentication_kind_snapshot as authentication_kind, historical.provider_account_plan_type_snapshot as plan_type, historical.provider_account_plan_type_display_snapshot as plan_type_display, coalesce(historical.provider_account_email_snapshot,historical.provider_account_name_snapshot,requested.id) as name from unnest($1::text[]) requested(id) left join provider_accounts a on a.id=requested.id left join lateral (select provider_kind,provider_account_authentication_kind_snapshot,provider_account_plan_type_snapshot,provider_account_plan_type_display_snapshot,provider_account_email_snapshot,provider_account_name_snapshot from model_request_observations mr where mr.provider_account_ref=requested.id order by mr.started_at desc,mr.id desc limit 1) historical on true"
|
||||
} else {
|
||||
"select requested.id, null::text as provider_kind, null::text as authentication_kind, null::text as plan_type, null::text as plan_type_display, coalesce(historical.client_api_key_name_snapshot,requested.id) as name from unnest($1::text[]) requested(id) left join lateral (select client_api_key_name_snapshot from model_request_observations mr where mr.client_api_key_ref=requested.id order by mr.started_at desc,mr.id desc limit 1) historical on true"
|
||||
"select requested.id, null::text as provider_kind, null::text as platform_icon, null::text as authentication_kind, null::text as plan_type, null::text as plan_type_display, coalesce(historical.client_api_key_name_snapshot,requested.id) as name from unnest($1::text[]) requested(id) left join lateral (select client_api_key_name_snapshot from model_request_observations mr where mr.client_api_key_ref=requested.id order by mr.started_at desc,mr.id desc limit 1) historical on true"
|
||||
};
|
||||
let labels = sqlx::query(statement)
|
||||
.bind(ids)
|
||||
@@ -684,7 +685,10 @@ impl<'a> AnalyticsSnapshot<'a> {
|
||||
let id: String = get(&row, "id")?;
|
||||
if let Some(item) = observations.iter_mut().find(|item| item.key == id) {
|
||||
item.name = get(&row, "name")?;
|
||||
item.account_provider_kind = get(&row, "provider_kind")?;
|
||||
item.providers = get::<Option<String>>(&row, "provider_kind")?
|
||||
.into_iter()
|
||||
.collect();
|
||||
item.platform_icon = get(&row, "platform_icon")?;
|
||||
item.account_authentication_kind = get(&row, "authentication_kind")?;
|
||||
item.account_plan_type = get(&row, "plan_type")?;
|
||||
item.account_plan_type_display = get(&row, "plan_type_display")?;
|
||||
@@ -951,6 +955,7 @@ impl<'a> AnalyticsSnapshot<'a> {
|
||||
let read_distributions = !matches!(distributions, DistributionRead::None);
|
||||
filter.validate()?;
|
||||
self.require_visible(Some(range))?;
|
||||
let model_providers = dimension == Some(DiagnosticDimension::Model);
|
||||
let selected = collection_for(filter, dimension);
|
||||
let boundaries = if granularity == Some(ObservationGranularity::Day) {
|
||||
Some(calendar_buckets(range, timezone)?)
|
||||
@@ -1004,7 +1009,15 @@ impl<'a> AnalyticsSnapshot<'a> {
|
||||
} else {
|
||||
"'{}'::jsonb as distributions"
|
||||
};
|
||||
query.push(format!(" as output_bucket,{name} as name,outcome,counts,{costs},{distribution_sql},last_used_at from {table} a where collection="))
|
||||
let provider = if model_providers {
|
||||
format!(
|
||||
"{} as provider_kind,",
|
||||
aggregate::summary_provider_column(collection)
|
||||
)
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
query.push(format!(" as output_bucket,{name} as name,{provider}outcome,counts,{costs},{distribution_sql},last_used_at from {table} a where collection="))
|
||||
.push_bind(collection).push(" and schema_version=").push_bind(SCHEMA_VERSION)
|
||||
.push(" and histogram_version=").push_bind(HISTOGRAM_VERSION);
|
||||
push_summary_buckets(&mut query, &buckets, seconds);
|
||||
@@ -1032,6 +1045,7 @@ impl<'a> AnalyticsSnapshot<'a> {
|
||||
read_costs,
|
||||
counters,
|
||||
distribution_names,
|
||||
model_providers,
|
||||
);
|
||||
let mut rows = query.build().fetch(&mut *self.tx);
|
||||
while let Some(row) = rows
|
||||
@@ -1041,7 +1055,11 @@ impl<'a> AnalyticsSnapshot<'a> {
|
||||
{
|
||||
let bucket = get(&row, "bucket_start")?;
|
||||
let name = get(&row, "name")?;
|
||||
let state = MetricState::decode(&row)?;
|
||||
let mut state = MetricState::decode(&row)?;
|
||||
if model_providers {
|
||||
state.providers =
|
||||
get::<Vec<String>>(&row, "providers")?.into_iter().collect();
|
||||
}
|
||||
result.entry((bucket, name)).or_default().merge(&state)?;
|
||||
}
|
||||
}
|
||||
@@ -1124,6 +1142,7 @@ impl<'a> AnalyticsSnapshot<'a> {
|
||||
distributions,
|
||||
counters,
|
||||
distribution_names,
|
||||
model_providers,
|
||||
);
|
||||
let mut rows = query.build().fetch(&mut *self.tx);
|
||||
while let Some(row) = rows
|
||||
@@ -1132,10 +1151,13 @@ impl<'a> AnalyticsSnapshot<'a> {
|
||||
.map_err(|error| postgres_unavailable("aggregate analytics facts", error))?
|
||||
{
|
||||
let key = (get(&row, "bucket_start")?, get(&row, "name")?);
|
||||
let state = MetricState::decode_aggregate(
|
||||
let mut state = MetricState::decode_aggregate(
|
||||
&row,
|
||||
exact && matches!(distributions, DistributionRead::Full),
|
||||
)?;
|
||||
if model_providers {
|
||||
state.providers = get::<Vec<String>>(&row, "providers")?.into_iter().collect();
|
||||
}
|
||||
if exact {
|
||||
result.insert(key, state);
|
||||
} else {
|
||||
|
||||
@@ -111,6 +111,7 @@ pub(crate) async fn declare_usage_statistics(
|
||||
DistributionRead::None,
|
||||
Some(&names),
|
||||
None,
|
||||
false,
|
||||
);
|
||||
query.push(") facts");
|
||||
}
|
||||
|
||||
@@ -107,15 +107,15 @@ impl PgRequestAnalyticsRepository {
|
||||
order by pending.oldest_pending_at, pending.request_id limit ($1::bigint - (select count(*) from live))
|
||||
) select request_id, change_version from live union all select request_id, change_version from oldest")
|
||||
.bind(i64::from(batch_size)).fetch_all(&mut *transaction).await.map_err(|error| postgres_unavailable("load analytics request queue", error))?;
|
||||
let mut jobs = Vec::with_capacity(rows.len());
|
||||
let mut ids = Vec::<String>::with_capacity(rows.len());
|
||||
let mut versions = Vec::<i64>::with_capacity(rows.len());
|
||||
for row in rows {
|
||||
jobs.push(ProjectionJob { id: get(&row,"request_id")?, version: get(&row,"change_version")? });
|
||||
ids.push(get(&row,"request_id")?);
|
||||
versions.push(get(&row,"change_version")?);
|
||||
}
|
||||
self.project_batch(&mut transaction, &jobs).await?;
|
||||
result.projected_requests = jobs.len() as u64;
|
||||
self.project_batch(&mut transaction, &ids).await?;
|
||||
result.projected_requests = ids.len() as u64;
|
||||
result.backfilled_requests = self.backfill(&mut transaction, batch_size).await?;
|
||||
let ids = jobs.iter().map(|job|job.id.clone()).collect::<Vec<_>>();
|
||||
let versions = jobs.iter().map(|job|job.version).collect::<Vec<_>>();
|
||||
if result.projected_requests + result.backfilled_requests > 0 {
|
||||
publish_generation(&mut transaction, true).await?;
|
||||
}
|
||||
@@ -153,38 +153,35 @@ impl PgRequestAnalyticsRepository {
|
||||
async fn project_batch(
|
||||
&self,
|
||||
tx: &mut sqlx::Transaction<'_, Postgres>,
|
||||
jobs: &[ProjectionJob],
|
||||
ids: &[String],
|
||||
) -> StoreResult<()> {
|
||||
if jobs.is_empty() {
|
||||
if ids.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let ids = jobs.iter().map(|job| job.id.clone()).collect::<Vec<_>>();
|
||||
let versions = jobs.iter().map(|job| job.version).collect::<Vec<_>>();
|
||||
let previous = sqlx::query(sqlx::AssertSqlSafe(format!(
|
||||
"{} where mr.id=any($1::text[])",
|
||||
fact_select()
|
||||
)))
|
||||
.bind(&ids)
|
||||
.bind(ids)
|
||||
.fetch_all(&mut **tx)
|
||||
.await
|
||||
.map_err(|error| postgres_unavailable("read previous analytics contributions", error))?;
|
||||
sqlx::query("delete from request_analytics_facts where id=any($1::text[])")
|
||||
.bind(&ids)
|
||||
.bind(ids)
|
||||
.execute(&mut **tx)
|
||||
.await
|
||||
.map_err(|error| postgres_unavailable("replace analytics facts", error))?;
|
||||
sqlx::query(PROJECT_REQUEST)
|
||||
.bind(&ids)
|
||||
.bind(versions)
|
||||
.bind(ids)
|
||||
.execute(&mut **tx)
|
||||
.await
|
||||
.map_err(|error| postgres_unavailable("project analytics facts", error))?;
|
||||
self.project_billing_batch(tx, &ids).await?;
|
||||
self.project_billing_batch(tx, ids).await?;
|
||||
let current = sqlx::query(sqlx::AssertSqlSafe(format!(
|
||||
"{} where mr.id=any($1::text[])",
|
||||
fact_select()
|
||||
)))
|
||||
.bind(&ids)
|
||||
.bind(ids)
|
||||
.fetch_all(&mut **tx)
|
||||
.await
|
||||
.map_err(|error| postgres_unavailable("read current analytics contributions", error))?;
|
||||
@@ -204,7 +201,7 @@ impl PgRequestAnalyticsRepository {
|
||||
return Ok(0);
|
||||
}
|
||||
let mut query = QueryBuilder::<Postgres>::new(
|
||||
"select id,started_at,nextval('request_analytics_change_version') as version,exists(select 1 from request_analytics_facts f where f.id=model_requests.id) as projected from model_requests",
|
||||
"select id,started_at,exists(select 1 from request_analytics_facts f where f.id=model_requests.id) as projected from model_requests",
|
||||
);
|
||||
// 首批与后续批次使用两种明确的计划,避免可空游标的 OR 使通用计划退化为全索引过滤
|
||||
if let Some(start) = get::<Option<DateTime<Utc>>>(&state, "backfill_cursor_started_at")? {
|
||||
@@ -225,17 +222,14 @@ impl PgRequestAnalyticsRepository {
|
||||
.fetch_all(&mut **tx)
|
||||
.await
|
||||
.map_err(|error| postgres_unavailable("read analytics backfill batch", error))?;
|
||||
let mut jobs = Vec::with_capacity(rows.len());
|
||||
let mut ids = Vec::<String>::with_capacity(rows.len());
|
||||
for row in &rows {
|
||||
if get::<bool>(row, "projected")? {
|
||||
continue;
|
||||
}
|
||||
jobs.push(ProjectionJob {
|
||||
id: get(row, "id")?,
|
||||
version: get(row, "version")?,
|
||||
});
|
||||
ids.push(get(row, "id")?);
|
||||
}
|
||||
self.project_batch(tx, &jobs).await?;
|
||||
self.project_batch(tx, &ids).await?;
|
||||
if let Some(last) = rows.last() {
|
||||
sqlx::query("update request_analytics_build_state set backfill_cursor_started_at = $1, backfill_cursor_id = $2, coverage_start = $1 + interval '1 microsecond' where singleton")
|
||||
.bind(get::<DateTime<Utc>>(last,"started_at")?).bind(get::<String>(last,"id")?).execute(&mut **tx).await.map_err(|error| postgres_unavailable("save analytics backfill cursor", error))?;
|
||||
@@ -377,11 +371,6 @@ pub(super) fn collections(
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
struct ProjectionJob {
|
||||
id: String,
|
||||
version: i64,
|
||||
}
|
||||
|
||||
async fn publish_generation(
|
||||
tx: &mut sqlx::Transaction<'_, Postgres>,
|
||||
facts_changed: bool,
|
||||
@@ -391,4 +380,4 @@ async fn publish_generation(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
const PROJECT_REQUEST: &str = "insert into request_analytics_facts (id, started_at, completed_at, client_api_key_ref, provider_account_ref, routing_group_refs, operation, provider_kind, requested_model_id, upstream_model_id, outcome, client_status_code, upstream_status_code, client_transport, upstream_transport, attempt_count, client_response_id, upstream_response_id, upstream_request_id, recovered_at, downstream_committed_at, request_kind, image_generation_requested, image_generation_succeeded, error_kind, input_tokens, output_tokens, cached_input_tokens, cache_write_input_tokens, reasoning_output_tokens, image_input_tokens, image_output_tokens, total_tokens, cost_source, cost_currency, cost_amount, first_token_ms, latency_ms, admission_decision_ms, account_selection_wait_ms, upstream_response_ms, capacity_used_slots, capacity_total_slots, source_version, ops_failure_count, ops_rate_limited_count, ops_auth_failure_count, ops_provider_5xx_count) select mr.id, mr.started_at, mr.completed_at, mr.client_api_key_ref, mr.provider_account_ref, array(select distinct group_ref from unnest(mr.routing_group_refs) group_ref order by group_ref), mr.operation, mr.provider_kind, mr.requested_model_id, mr.upstream_model_id, mr.outcome, mr.client_status_code, mr.upstream_status_code, mr.client_transport, mr.upstream_transport, mr.attempt_count, mr.client_response_id, mr.upstream_response_id, mr.upstream_request_id, mr.recovered_at, mr.downstream_committed_at, mr.request_kind, mr.image_generation_requested, mr.image_generation_succeeded, mr.error_kind, mr.input_tokens, mr.output_tokens, mr.cached_input_tokens, mr.cache_write_input_tokens, mr.reasoning_output_tokens, mr.image_input_tokens, mr.image_output_tokens, mr.total_tokens, mr.cost_source, mr.cost_currency, mr.cost_amount, mr.first_token_ms, mr.latency_ms, mr.admission_decision_ms, mr.account_selection_wait_ms, mr.upstream_response_ms, mr.capacity_used_slots, mr.capacity_total_slots, job.version, ops.failure_count, ops.rate_limited_count, ops.auth_failure_count, ops.provider_5xx_count from unnest($1::text[],$2::bigint[]) job(id,version) join model_request_observations mr on mr.id=job.id cross join lateral (select count(*)::bigint as failure_count, count(*) filter(where failure_kind in ('rate_limited','quota_exhausted') or status_code=429)::bigint as rate_limited_count, count(*) filter(where failure_kind in ('authentication','authorization','invalid_credential') or status_code in (401,403))::bigint as auth_failure_count, count(*) filter(where status_code between 500 and 599)::bigint as provider_5xx_count from ops_events where model_request_id=mr.id) ops returning id, started_at";
|
||||
const PROJECT_REQUEST: &str = "insert into request_analytics_facts (id, started_at, completed_at, client_api_key_ref, provider_account_ref, routing_group_refs, operation, provider_kind, requested_model_id, upstream_model_id, outcome, client_status_code, upstream_status_code, client_transport, upstream_transport, attempt_count, client_response_id, upstream_response_id, upstream_request_id, recovered_at, downstream_committed_at, request_kind, image_generation_requested, image_generation_succeeded, error_kind, input_tokens, output_tokens, cached_input_tokens, cache_write_input_tokens, reasoning_output_tokens, image_input_tokens, image_output_tokens, total_tokens, cost_source, cost_currency, cost_amount, first_token_ms, latency_ms, admission_decision_ms, account_selection_wait_ms, upstream_response_ms, capacity_used_slots, capacity_total_slots, ops_failure_count, ops_rate_limited_count, ops_auth_failure_count, ops_provider_5xx_count) select mr.id, mr.started_at, mr.completed_at, mr.client_api_key_ref, mr.provider_account_ref, array(select distinct group_ref from unnest(mr.routing_group_refs) group_ref order by group_ref), mr.operation, mr.provider_kind, mr.requested_model_id, mr.upstream_model_id, mr.outcome, mr.client_status_code, mr.upstream_status_code, mr.client_transport, mr.upstream_transport, mr.attempt_count, mr.client_response_id, mr.upstream_response_id, mr.upstream_request_id, mr.recovered_at, mr.downstream_committed_at, mr.request_kind, mr.image_generation_requested, mr.image_generation_succeeded, mr.error_kind, mr.input_tokens, mr.output_tokens, mr.cached_input_tokens, mr.cache_write_input_tokens, mr.reasoning_output_tokens, mr.image_input_tokens, mr.image_output_tokens, mr.total_tokens, mr.cost_source, mr.cost_currency, mr.cost_amount, mr.first_token_ms, mr.latency_ms, mr.admission_decision_ms, mr.account_selection_wait_ms, mr.upstream_response_ms, mr.capacity_used_slots, mr.capacity_total_slots, ops.failure_count, ops.rate_limited_count, ops.auth_failure_count, ops.provider_5xx_count from unnest($1::text[]) job(id) join model_request_observations mr on mr.id=job.id cross join lateral (select count(*)::bigint as failure_count, count(*) filter(where failure_kind in ('rate_limited','quota_exhausted') or status_code=429)::bigint as rate_limited_count, count(*) filter(where failure_kind in ('authentication','authorization','invalid_credential') or status_code in (401,403))::bigint as auth_failure_count, count(*) filter(where status_code between 500 and 599)::bigint as provider_5xx_count from ops_events where model_request_id=mr.id) ops returning id, started_at";
|
||||
|
||||
@@ -139,6 +139,7 @@ pub(crate) fn admin_dashboard_account_usage(
|
||||
authentication_kind: usage.authentication_kind,
|
||||
name: usage.name,
|
||||
email: usage.email,
|
||||
platform_icon: usage.platform_icon,
|
||||
notes: usage.notes,
|
||||
plan_type: usage.plan_type,
|
||||
plan_type_display: None,
|
||||
@@ -279,7 +280,8 @@ fn admin_diagnostic_observation(
|
||||
admin_observability::DiagnosticObservation {
|
||||
key: observation.key,
|
||||
name: observation.name,
|
||||
account_provider_kind: observation.account_provider_kind,
|
||||
providers: observation.providers,
|
||||
platform_icon: observation.platform_icon,
|
||||
account_authentication_kind: observation.account_authentication_kind,
|
||||
account_plan_type: observation.account_plan_type,
|
||||
account_plan_type_display: observation.account_plan_type_display,
|
||||
@@ -389,6 +391,7 @@ pub(crate) fn usage_list_record_from_row(
|
||||
provider_account_ref: get(row, "provider_account_ref")?,
|
||||
provider_account_name: get(row, "provider_account_name")?,
|
||||
provider_account_email: get(row, "provider_account_email")?,
|
||||
platform_icon: get(row, "platform_icon")?,
|
||||
provider_account_notes: get(row, "provider_account_notes")?,
|
||||
provider_account_upstream_peer: None,
|
||||
provider_account_plan_type: get(row, "provider_account_plan_type")?,
|
||||
|
||||
@@ -228,6 +228,7 @@ pub use gateway_admin::model::observability::AccountRequestBucket as ProviderAcc
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ProviderAccountUsageObservation {
|
||||
pub platform_icon: Option<String>,
|
||||
pub account_id: String,
|
||||
pub provider_kind: String,
|
||||
pub authentication_kind: String,
|
||||
@@ -383,7 +384,8 @@ 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>,
|
||||
|
||||
@@ -14,7 +14,9 @@ pub(crate) async fn provider_account_usage(
|
||||
}
|
||||
|
||||
// 账号卡片先确定有限候选,避免为少量账号聚合整个历史范围
|
||||
let mut statement = QueryBuilder::<Postgres>::new("select pa.* from provider_accounts pa");
|
||||
let mut statement = QueryBuilder::<Postgres>::new(
|
||||
"select pa.*, pa.platform_icon as platform_icon from provider_accounts pa",
|
||||
);
|
||||
if let Some(account_ids) = &query.account_ids {
|
||||
statement
|
||||
.push(" where pa.id=any(")
|
||||
@@ -85,6 +87,7 @@ pub(crate) async fn provider_account_usage(
|
||||
authentication_kind: get(&row, "authentication_kind")?,
|
||||
name: get(&row, "name")?,
|
||||
email: get(&row, "email")?,
|
||||
platform_icon: get(&row, "platform_icon")?,
|
||||
notes: get(&row, "notes")?,
|
||||
plan_type: get(&row, "plan_type")?,
|
||||
request_count: state.count("completed_request_count"),
|
||||
|
||||
@@ -136,6 +136,7 @@ pub(crate) const USAGE_LIST_RECORD_SELECT: &str =
|
||||
mr.provider_kind, mr.provider_account_ref,
|
||||
mr.provider_account_name_snapshot as provider_account_name,
|
||||
mr.provider_account_email_snapshot as provider_account_email,
|
||||
(select a.platform_icon from provider_accounts a where a.id = mr.provider_account_ref) as platform_icon,
|
||||
mr.provider_account_notes_snapshot as provider_account_notes,
|
||||
mr.provider_account_plan_type_snapshot as provider_account_plan_type,
|
||||
mr.provider_account_plan_type_display_snapshot as provider_account_plan_type_display,
|
||||
|
||||
@@ -264,8 +264,8 @@ impl PluginStore for PgPluginStore {
|
||||
.map_err(|error| admin_store_error("plugin", error))?;
|
||||
let mut platforms = metadata.platforms.clone();
|
||||
platforms.sort();
|
||||
let row = sqlx::query("insert into plugin_artifacts (sha256, plugin_id, version, metadata_json, source_json, outbound_proxy_id, archive) values ($1,$2,$3,$4,$5,$6,$7) returning metadata_json, source_json, installed_at, accepted_at")
|
||||
.bind(&metadata.sha256).bind(&metadata.plugin_id).bind(&metadata.version)
|
||||
let row = sqlx::query("insert into plugin_artifacts (sha256, plugin_id, metadata_json, source_json, outbound_proxy_id, archive) values ($1,$2,$3,$4,$5,$6) returning metadata_json, source_json, installed_at, accepted_at")
|
||||
.bind(&metadata.sha256).bind(&metadata.plugin_id)
|
||||
.bind(sqlx::types::Json(&metadata)).bind(sqlx::types::Json(&source))
|
||||
.bind(outbound_proxy.map(|proxy| proxy.id)).bind(artifact.archive.as_ref())
|
||||
.fetch_one(&mut *transaction).await.map_err(|error| {
|
||||
|
||||
@@ -343,13 +343,13 @@ impl AccountStore for PgAdminAccountStore {
|
||||
let item_ids = page
|
||||
.accounts
|
||||
.iter()
|
||||
.map(|account| account.id.clone())
|
||||
.map(|(account, _)| account.id.clone())
|
||||
.collect::<Vec<_>>();
|
||||
let mut groups_by_account = self.account_groups_by_account(&item_ids).await?;
|
||||
let items = page
|
||||
.accounts
|
||||
.into_iter()
|
||||
.map(|summary| {
|
||||
.map(|(summary, platform_icon)| {
|
||||
let account_id = summary.id.clone();
|
||||
let projection = account_status_projection(
|
||||
&summary,
|
||||
@@ -359,6 +359,7 @@ impl AccountStore for PgAdminAccountStore {
|
||||
let mut account = admin_account_record(summary)?;
|
||||
account.groups = groups_by_account.remove(&account_id).unwrap_or_default();
|
||||
Ok(AccountPageItem {
|
||||
platform_icon,
|
||||
protection_rules: runtime
|
||||
.protection_rules
|
||||
.get(&account.id)
|
||||
@@ -404,9 +405,9 @@ impl AccountStore for PgAdminAccountStore {
|
||||
.await?;
|
||||
let mut account = admin_account_record(record.summary)?;
|
||||
account.groups = groups.remove(&account_id).unwrap_or_default();
|
||||
let default_concurrency: i64 = sqlx::query_scalar(
|
||||
"select max_concurrent_per_account from runtime_settings where id = 1",
|
||||
)
|
||||
let (default_concurrency, platform_icon): (i64, Option<String>) = sqlx::query_as(
|
||||
"select s.max_concurrent_per_account, (select a.platform_icon from provider_accounts a where a.id = $1) from runtime_settings s where s.id = 1",
|
||||
).bind(&account_id)
|
||||
.fetch_one(&self.pool)
|
||||
.await
|
||||
.map_err(|source| {
|
||||
@@ -423,6 +424,7 @@ impl AccountStore for PgAdminAccountStore {
|
||||
)
|
||||
})?;
|
||||
Ok(Some(AccountPageItem {
|
||||
platform_icon,
|
||||
protection_rules: runtime
|
||||
.protection_rules
|
||||
.get(&account_id)
|
||||
@@ -675,6 +677,9 @@ impl AccountStore for PgAdminAccountStore {
|
||||
if command.outbound_proxy.is_some() {
|
||||
changed_fields.push("outbound_proxy".to_owned());
|
||||
}
|
||||
if command.platform_icon.is_some() {
|
||||
changed_fields.push("platform_icon".to_owned());
|
||||
}
|
||||
if command.notes.is_some() {
|
||||
changed_fields.push("notes".to_owned());
|
||||
}
|
||||
@@ -689,6 +694,7 @@ impl AccountStore for PgAdminAccountStore {
|
||||
quota_settings: None,
|
||||
auto_use_quota_credits: None,
|
||||
name: command.name,
|
||||
platform_icon: command.platform_icon,
|
||||
notes: command.notes,
|
||||
enabled: Some(command.enabled),
|
||||
concurrency_limit: Some(command.concurrency_limit),
|
||||
@@ -800,6 +806,7 @@ impl AccountStore for PgAdminAccountStore {
|
||||
quota_settings: command.quota_settings,
|
||||
auto_use_quota_credits: command.auto_use_quota_credits,
|
||||
name: None,
|
||||
platform_icon: None,
|
||||
notes: None,
|
||||
enabled: command.enabled,
|
||||
concurrency_limit: command.concurrency_limit,
|
||||
@@ -944,6 +951,9 @@ pub(super) fn prepare_import(
|
||||
if let Some(settings) = &settings {
|
||||
changed_fields
|
||||
.extend(["enabled", "concurrency_limit", "weight", "group_ids"].map(str::to_owned));
|
||||
if settings.platform_icon.is_some() {
|
||||
changed_fields.push("platform_icon".to_owned());
|
||||
}
|
||||
if settings.notes.is_some() {
|
||||
changed_fields.push("notes".to_owned());
|
||||
}
|
||||
@@ -1038,6 +1048,9 @@ pub(super) fn prepare_rotation(
|
||||
if settings.outbound_proxy.is_some() {
|
||||
changed_fields.push("outbound_proxy".to_owned());
|
||||
}
|
||||
if settings.platform_icon.is_some() {
|
||||
changed_fields.push("platform_icon".to_owned());
|
||||
}
|
||||
if settings.notes.is_some() {
|
||||
changed_fields.push("notes".to_owned());
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@ use super::*;
|
||||
pub(crate) struct AdminAccountPageRows {
|
||||
pub(crate) config_revision: AdminRevision,
|
||||
pub(crate) default_concurrency: u64,
|
||||
pub(crate) accounts: Vec<ProviderAccountSummary>,
|
||||
pub(crate) accounts: Vec<(ProviderAccountSummary, Option<String>)>,
|
||||
pub(crate) total: u64,
|
||||
pub(crate) summary: AccountSummary,
|
||||
}
|
||||
@@ -105,7 +105,7 @@ pub(crate) async fn load_admin_account_page(
|
||||
from runtime_settings
|
||||
where id = 1
|
||||
)
|
||||
select coalesce(p.enabled, true) as outbound_proxy_enabled, coalesce(p.max_websocket_connections, 0) as outbound_proxy_max_websocket_connections, p.auto_location, p.detected_location_json, p.location_country, p.location_region, p.location_city, p.location_timezone, a.outbound_proxy_id, a.outbound_proxy_url, a.id, a.provider_kind, a.name, a.notes, a.email, a.upstream_user_id,
|
||||
select coalesce(p.enabled, true) as outbound_proxy_enabled, coalesce(p.max_websocket_connections, 0) as outbound_proxy_max_websocket_connections, p.auto_location, p.detected_location_json, p.location_country, p.location_region, p.location_city, p.location_timezone, a.outbound_proxy_id, a.outbound_proxy_url, a.id, a.provider_kind, a.name, a.notes, a.platform_icon as platform_icon, a.email, a.upstream_user_id,
|
||||
a.upstream_account_id, a.plan_type, a.authentication_kind,
|
||||
a.credential_revision, a.has_refresh_token, a.access_token_expires_at,
|
||||
a.next_refresh_at, a.enabled, a.quota_settings, a.quota_paused, a.auto_use_quota_credits, a.concurrency_limit, a.weight, a.model_access_json,
|
||||
@@ -201,7 +201,10 @@ pub(crate) async fn load_admin_account_page(
|
||||
.flatten()
|
||||
.map(|_| row)
|
||||
})
|
||||
.map(account_summary_from_row)
|
||||
.map(|row| {
|
||||
let icon = get(&row, "platform_icon")?;
|
||||
Ok((account_summary_from_row(row)?, icon))
|
||||
})
|
||||
.collect::<StoreResult<Vec<_>>>()
|
||||
.map_err(|error| admin_store_error(ENTITY, error))?;
|
||||
Ok(AdminAccountPageRows {
|
||||
|
||||
@@ -64,11 +64,14 @@ impl PgProviderAccountRepository {
|
||||
observation: &AccountCatalogObservation,
|
||||
document: &[u8],
|
||||
) -> Result<bool, CoreStoreError> {
|
||||
// 相同正文复用旧 TOAST 值,定期复查只更新账号观测,减少正文重写及 WAL
|
||||
let result = sqlx::query("insert into provider_account_model_catalogs (account_id, credential_revision, plan_type, observed_at, document, etag)
|
||||
select a.id, a.credential_revision, a.plan_type, $4, $5, $6 from provider_accounts a
|
||||
where a.id=$1 and a.credential_revision=$2 and a.plan_type is not distinct from $3 for share
|
||||
on conflict (account_id) do update set credential_revision=excluded.credential_revision, plan_type=excluded.plan_type,
|
||||
etag=excluded.etag, observed_at=excluded.observed_at, document=excluded.document
|
||||
etag=excluded.etag, observed_at=excluded.observed_at, document=case
|
||||
when provider_account_model_catalogs.document_hash=excluded.document_hash
|
||||
then provider_account_model_catalogs.document else excluded.document end
|
||||
where provider_account_model_catalogs.credential_revision < excluded.credential_revision or
|
||||
(provider_account_model_catalogs.credential_revision=excluded.credential_revision and provider_account_model_catalogs.observed_at <= excluded.observed_at)")
|
||||
.bind(observation.account_id.as_str()).bind(i64::try_from(observation.revision.get()).map_err(|_|CoreStoreError::new(CoreStoreErrorKind::InvalidData))?)
|
||||
|
||||
@@ -570,6 +570,7 @@ impl ProviderAccountAdminRepository for PgProviderAccountRepository {
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
set_platform_icon(&mut transaction, &command.account_ids, command.platform_icon.as_deref()).await?;
|
||||
if let Some(notes) = command.notes.as_deref() {
|
||||
update_provider_account_notes_in_transaction(
|
||||
&mut transaction,
|
||||
@@ -685,6 +686,21 @@ async fn update_provider_account_name_in_transaction(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn set_platform_icon(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
ids: &[String],
|
||||
icon: Option<&str>,
|
||||
) -> StoreResult<()> {
|
||||
let Some(icon) = icon else { return Ok(()) };
|
||||
sqlx::query("update provider_accounts set platform_icon = nullif($2, '') where id = any($1)")
|
||||
.bind(ids)
|
||||
.bind(icon)
|
||||
.execute(&mut **transaction)
|
||||
.await
|
||||
.map_err(|source| postgres_unavailable("set account platform icon", source))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn update_provider_account_notes_in_transaction(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
account_ids: &[String],
|
||||
@@ -1165,6 +1181,7 @@ pub(super) async fn import_provider_accounts_in_transaction(
|
||||
&settings.group_ids,
|
||||
)
|
||||
.await?;
|
||||
set_platform_icon(transaction, &unique_ids, settings.platform_icon.as_deref()).await?;
|
||||
if let Some(notes) = settings.notes.as_deref() {
|
||||
update_provider_account_notes_in_transaction(transaction, &unique_ids, notes).await?;
|
||||
}
|
||||
@@ -1236,6 +1253,7 @@ pub(super) async fn rotate_provider_account_admin_in_transaction(
|
||||
.await?;
|
||||
replace_account_group_assignments_in_transaction(transaction, ids, &settings.group_ids)
|
||||
.await?;
|
||||
set_platform_icon(transaction, ids, settings.platform_icon.as_deref()).await?;
|
||||
if let Some(notes) = settings.notes.as_deref() {
|
||||
update_provider_account_notes_in_transaction(transaction, ids, notes).await?;
|
||||
}
|
||||
|
||||
@@ -252,6 +252,7 @@ impl fmt::Debug for RotateProviderAccount {
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct BatchUpdateProviderAccountsAdmin {
|
||||
pub platform_icon: Option<String>,
|
||||
pub pauses: gateway_admin::model::accounts::PreparedQuotaPauses,
|
||||
pub quota_settings: Option<gateway_core::account::AccountQuotaSettings>,
|
||||
pub auto_use_quota_credits: Option<bool>,
|
||||
|
||||
@@ -542,7 +542,7 @@ impl ProxyStore for PgProxyRepository {
|
||||
})
|
||||
})?;
|
||||
let mut items = sqlx::query(
|
||||
"select id, name, email, provider_kind, authentication_kind, plan_type, enabled from provider_accounts
|
||||
"select id, name, email, provider_kind, authentication_kind, plan_type, enabled, a.platform_icon as platform_icon from provider_accounts a
|
||||
where outbound_proxy_id = $1 and (strpos(lower(name), lower($2)) > 0
|
||||
or strpos(lower(coalesce(email, '')), lower($2)) > 0)
|
||||
order by name, id limit $3 offset $4",
|
||||
@@ -557,6 +557,7 @@ impl ProxyStore for PgProxyRepository {
|
||||
.into_iter()
|
||||
.map(|row| {
|
||||
Ok(ProxyAccountRef {
|
||||
platform_icon: row.try_get("platform_icon").map_err(|source| invalid().with_source(source))?,
|
||||
upstream: None,
|
||||
id: row.try_get("id").map_err(|source| invalid().with_source(source))?,
|
||||
name: row.try_get("name").map_err(|source| invalid().with_source(source))?,
|
||||
|
||||
@@ -135,6 +135,7 @@ impl RuntimeSettingsRepository for PgRuntimeSettingsRepository {
|
||||
&self,
|
||||
update: RuntimeSettingsUpdate,
|
||||
) -> StoreResult<Revision> {
|
||||
update.validate()?;
|
||||
let mut transaction = self
|
||||
.pool
|
||||
.begin()
|
||||
@@ -156,7 +157,7 @@ pub(crate) async fn load_runtime_settings_from_pool(pool: &PgPool) -> StoreResul
|
||||
rotation_strategy, smart_scheduling_json, quota_reset_window_weights_json, model_mappings_json, usage_retention_days, ops_event_retention_days,
|
||||
audit_retention_days, min_codex_desktop_version,
|
||||
min_codex_cli_version, updated_at, responses_max_decompressed_body_bytes, max_waiting_per_key, max_waiting_per_account, key_queue_timeout_seconds, account_queue_timeout_seconds, switch_account_on_queue_failure, max_retry_after_seconds, openai_guardian_reserved_concurrency, openai_request_settings_json, openai_websocket_pool_json, account_affinity, max_account_rotations, session_affinity_ttl_hours,
|
||||
account_error_protection_json, account_error_protection_revision,
|
||||
prompt_rewrite_rules_json, account_error_protection_json, account_error_protection_revision,
|
||||
account_warmup_enabled, account_warmup_cron, account_warmup_model, reset_credit_lead_minutes, reset_credit_max_weekly_remaining_percent, reset_credit_on_low_weekly_quota
|
||||
from runtime_settings where id = 1",
|
||||
)
|
||||
@@ -359,7 +360,7 @@ pub(crate) async fn load_runtime_settings_in_transaction(
|
||||
rotation_strategy, smart_scheduling_json, quota_reset_window_weights_json, model_mappings_json, usage_retention_days, ops_event_retention_days,
|
||||
audit_retention_days, min_codex_desktop_version,
|
||||
min_codex_cli_version, updated_at, responses_max_decompressed_body_bytes, max_waiting_per_key, max_waiting_per_account, key_queue_timeout_seconds, account_queue_timeout_seconds, switch_account_on_queue_failure, max_retry_after_seconds, openai_guardian_reserved_concurrency, openai_request_settings_json, openai_websocket_pool_json, account_affinity, max_account_rotations, session_affinity_ttl_hours,
|
||||
account_error_protection_json, account_error_protection_revision,
|
||||
prompt_rewrite_rules_json, account_error_protection_json, account_error_protection_revision,
|
||||
account_warmup_enabled, account_warmup_cron, account_warmup_model, reset_credit_lead_minutes, reset_credit_max_weekly_remaining_percent, reset_credit_on_low_weekly_quota
|
||||
from runtime_settings where id = 1",
|
||||
)
|
||||
@@ -378,7 +379,6 @@ pub(crate) async fn update_runtime_settings_in_transaction(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
update: &RuntimeSettingsUpdate,
|
||||
) -> StoreResult<Revision> {
|
||||
update.validate()?;
|
||||
let previous_reset_settings: (i32, Option<i32>, bool) = sqlx::query_as(
|
||||
"select reset_credit_lead_minutes, reset_credit_max_weekly_remaining_percent, reset_credit_on_low_weekly_quota from runtime_settings where id = 1 for update",
|
||||
)
|
||||
@@ -446,6 +446,7 @@ pub(crate) async fn update_runtime_settings_in_transaction(
|
||||
quota_reset_window_weights_json = $35,
|
||||
openai_request_settings_json = $36,
|
||||
openai_websocket_pool_json = $37,
|
||||
prompt_rewrite_rules_json = $38,
|
||||
updated_at = now()
|
||||
where id = 1
|
||||
returning config_revision",
|
||||
@@ -495,6 +496,7 @@ pub(crate) async fn update_runtime_settings_in_transaction(
|
||||
.bind(sqlx::types::Json(update.values.quota_reset_window_weights))
|
||||
.bind(sqlx::types::Json(&update.values.openai_request_settings))
|
||||
.bind(sqlx::types::Json(&update.values.openai_websocket_pool))
|
||||
.bind(sqlx::types::Json(&update.values.prompt_rewrite_rules))
|
||||
.fetch_optional(&mut **transaction)
|
||||
.await
|
||||
.map_err(|source| postgres_unavailable("update runtime settings in transaction", source))?
|
||||
@@ -596,6 +598,8 @@ struct RuntimeSettingsRow {
|
||||
session_affinity_ttl_hours: i64,
|
||||
responses_max_decompressed_body_bytes: i64,
|
||||
account_error_protection_revision: i64,
|
||||
prompt_rewrite_rules_json:
|
||||
sqlx::types::Json<Vec<gateway_core::settings::prompt_rewrite::PromptRewriteRule>>,
|
||||
account_error_protection_json: sqlx::types::Json<gateway_core::account::AccountErrorProtection>,
|
||||
account_warmup_enabled: bool,
|
||||
account_warmup_cron: String,
|
||||
@@ -667,6 +671,7 @@ fn runtime_settings_from_row(row: RuntimeSettingsRow) -> StoreResult<RuntimeSett
|
||||
responses_max_decompressed_body_bytes: to_u64(
|
||||
row.responses_max_decompressed_body_bytes,
|
||||
)?,
|
||||
prompt_rewrite_rules: row.prompt_rewrite_rules_json.0,
|
||||
account_error_protection: row.account_error_protection_json.0,
|
||||
account_warmup_enabled: row.account_warmup_enabled,
|
||||
account_warmup_cron: row.account_warmup_cron,
|
||||
|
||||
@@ -223,6 +223,8 @@ struct SnapshotSettingsRow {
|
||||
pricing_overrides_json: sqlx::types::Json<gateway_core::metering::PricingOverrides>,
|
||||
config_revision: i64,
|
||||
account_error_protection_revision: i64,
|
||||
prompt_rewrite_rules_json:
|
||||
sqlx::types::Json<Vec<gateway_core::settings::prompt_rewrite::PromptRewriteRule>>,
|
||||
account_error_protection_json: sqlx::types::Json<gateway_core::account::AccountErrorProtection>,
|
||||
max_concurrent_per_account: i64,
|
||||
smart_scheduling_json: sqlx::types::Json<gateway_core::account::SmartSchedulingConfig>,
|
||||
@@ -257,7 +259,7 @@ async fn load_settings(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
) -> StoreResult<(Revision, SettingsValues)> {
|
||||
let row = sqlx::query_as::<_, SnapshotSettingsRow>(
|
||||
"select config_revision, account_error_protection_revision, account_error_protection_json, max_concurrent_per_account, rotation_strategy, smart_scheduling_json, quota_reset_window_weights_json, model_mappings_json, min_codex_desktop_version, min_codex_cli_version, max_waiting_per_key, max_waiting_per_account, key_queue_timeout_seconds, account_queue_timeout_seconds, switch_account_on_queue_failure, max_retry_after_seconds, openai_guardian_reserved_concurrency, openai_request_settings_json, openai_websocket_pool_json, account_affinity, max_account_rotations, session_affinity_ttl_hours, request_location_json, request_location_enabled, codex_privacy_policy_json, responses_max_decompressed_body_bytes, provider_request_profiles_json, pricing_overrides_json, pricing_synced_json from runtime_settings where id = 1",
|
||||
"select config_revision, prompt_rewrite_rules_json, account_error_protection_revision, account_error_protection_json, max_concurrent_per_account, rotation_strategy, smart_scheduling_json, quota_reset_window_weights_json, model_mappings_json, min_codex_desktop_version, min_codex_cli_version, max_waiting_per_key, max_waiting_per_account, key_queue_timeout_seconds, account_queue_timeout_seconds, switch_account_on_queue_failure, max_retry_after_seconds, openai_guardian_reserved_concurrency, openai_request_settings_json, openai_websocket_pool_json, account_affinity, max_account_rotations, session_affinity_ttl_hours, request_location_json, request_location_enabled, codex_privacy_policy_json, responses_max_decompressed_body_bytes, provider_request_profiles_json, pricing_overrides_json, pricing_synced_json from runtime_settings where id = 1",
|
||||
)
|
||||
.fetch_optional(&mut **transaction)
|
||||
.await
|
||||
@@ -306,6 +308,7 @@ async fn load_settings(
|
||||
})
|
||||
.with_request_location(row.request_location_json.0, row.request_location_enabled)
|
||||
.with_codex_privacy_policy(row.codex_privacy_policy_json.0)
|
||||
.with_prompt_rewrite_rules(row.prompt_rewrite_rules_json.0)
|
||||
.with_account_error_protection(row.account_error_protection_json.0)
|
||||
.with_account_error_protection_revision(to_u64(row.account_error_protection_revision)?)
|
||||
.with_concurrency_queues(
|
||||
|
||||
@@ -526,6 +526,7 @@ async fn seed_group_cost_snapshot(
|
||||
routing_group_ids: &[&str],
|
||||
cost_amount: &str,
|
||||
) {
|
||||
// 费用归属不依赖请求耗时,避免午夜后回退一分钟将今日夹具写入前一天
|
||||
let routing_group_refs: Vec<String> = routing_group_ids
|
||||
.iter()
|
||||
.map(|id| (*id).to_owned())
|
||||
@@ -534,7 +535,7 @@ async fn seed_group_cost_snapshot(
|
||||
"insert into model_requests (
|
||||
id, client_api_key_ref, operation, client_transport, requested_model_id, provider_kind, provider_account_ref, upstream_model_id, upstream_transport, attempt_count, upstream_send_state, downstream_committed_at, outcome, client_status_code, upstream_status_code, total_tokens, cost_source, cost_amount, cost_currency, started_at, recovery_lease_expires_at, completed_at, request_observation_json
|
||||
) values (
|
||||
$1, 'key-group-history', 'responses', 'http_sse', 'gpt-group', 'openai', $2, 'gpt-group', 'http_sse', 1, 'sent', now(), 'succeeded', 200, 200, 10, 'provider_reported', $4::numeric, 'USD', now() - interval '1 minute', now() + interval '5 minutes', now(),
|
||||
$1, 'key-group-history', 'responses', 'http_sse', 'gpt-group', 'openai', $2, 'gpt-group', 'http_sse', 1, 'sent', now(), 'succeeded', 200, 200, 10, 'provider_reported', $4::numeric, 'USD', now(), now() + interval '5 minutes', now(),
|
||||
jsonb_strip_nulls(jsonb_build_object(
|
||||
'request', jsonb_build_object(
|
||||
'configRevision', 1,
|
||||
|
||||
@@ -395,7 +395,7 @@ async fn health_counters_match_for_rollups_and_facts_without_counting_recovery_o
|
||||
("health_recovered", "failed", 502),
|
||||
] {
|
||||
seed(&database.pool, id, start + TimeDelta::minutes(5), &[]).await;
|
||||
sqlx::query("update model_requests set outcome=$2,client_status_code=$3 where id=$1")
|
||||
sqlx::query("update model_requests set outcome=$2,client_status_code=$3,provider_kind=case when $1='health_success' then 'xai' else 'openai' end where id=$1")
|
||||
.bind(id)
|
||||
.bind(outcome)
|
||||
.bind(status)
|
||||
@@ -459,6 +459,7 @@ async fn health_counters_match_for_rollups_and_facts_without_counting_recovery_o
|
||||
assert_eq!(diagnostic.total_request_count, 5);
|
||||
assert_eq!(diagnostic.items.len(), 1);
|
||||
let counts = &diagnostic.items[0];
|
||||
assert_eq!(counts.providers, ["openai", "xai"]);
|
||||
assert_eq!(
|
||||
(
|
||||
counts.request_count,
|
||||
|
||||
@@ -449,7 +449,7 @@ async fn extrema_rebuild_reads_only_its_bucket_when_history_is_large() {
|
||||
}
|
||||
drain_analytics(&pool).await;
|
||||
// 只扩充其他时间桶的事实,规划器拿到真实行数后不能再为一个分组扫描全部历史
|
||||
sqlx::query("insert into request_analytics_facts select ('history_'||n)::text as id,(f.started_at-make_interval(hours=>n/1000+2))::timestamptz,f.completed_at-make_interval(hours=>n/1000+2),f.client_api_key_ref,f.provider_account_ref,f.routing_group_refs,f.operation,f.provider_kind,f.requested_model_id,f.upstream_model_id,f.outcome,f.client_status_code,f.upstream_status_code,f.client_transport,f.upstream_transport,f.attempt_count,null,null,null,f.recovered_at,f.downstream_committed_at,f.request_kind,f.image_generation_requested,f.image_generation_succeeded,f.error_kind,f.input_tokens,f.output_tokens,f.cached_input_tokens,f.cache_write_input_tokens,f.reasoning_output_tokens,f.image_input_tokens,f.image_output_tokens,f.total_tokens,f.cost_source,f.cost_currency,f.cost_amount,f.first_token_ms,f.latency_ms,f.admission_decision_ms,f.account_selection_wait_ms,f.upstream_response_ms,f.capacity_used_slots,f.capacity_total_slots,f.standard_cost_amount,f.no_cache_cost_amount,f.source_version,f.schema_version,f.ops_failure_count,f.ops_rate_limited_count,f.ops_auth_failure_count,f.ops_provider_5xx_count from request_analytics_facts f cross join generate_series(1,300000) n where f.id='rebuild_range_2'")
|
||||
sqlx::query("insert into request_analytics_facts select ('history_'||n)::text as id,(f.started_at-make_interval(hours=>n/1000+2))::timestamptz,f.completed_at-make_interval(hours=>n/1000+2),f.client_api_key_ref,f.provider_account_ref,f.routing_group_refs,f.operation,f.provider_kind,f.requested_model_id,f.upstream_model_id,f.outcome,f.client_status_code,f.upstream_status_code,f.client_transport,f.upstream_transport,f.attempt_count,null,null,null,f.recovered_at,f.downstream_committed_at,f.request_kind,f.image_generation_requested,f.image_generation_succeeded,f.error_kind,f.input_tokens,f.output_tokens,f.cached_input_tokens,f.cache_write_input_tokens,f.reasoning_output_tokens,f.image_input_tokens,f.image_output_tokens,f.total_tokens,f.cost_source,f.cost_currency,f.cost_amount,f.first_token_ms,f.latency_ms,f.admission_decision_ms,f.account_selection_wait_ms,f.upstream_response_ms,f.capacity_used_slots,f.capacity_total_slots,f.standard_cost_amount,f.no_cache_cost_amount,f.schema_version,f.ops_failure_count,f.ops_rate_limited_count,f.ops_auth_failure_count,f.ops_provider_5xx_count from request_analytics_facts f cross join generate_series(1,300000) n where f.id='rebuild_range_2'")
|
||||
.execute(&pool).await.unwrap();
|
||||
sqlx::query("analyze request_analytics_facts")
|
||||
.execute(&pool)
|
||||
|
||||
@@ -34,7 +34,7 @@ async fn business_backup_restores_core_state_and_usage_without_request_history()
|
||||
insert into client_api_key_budget_windows values('restore_key',now(),now()+interval '1 day',now(),now()+interval '7 days',2.5,9.5);
|
||||
insert into client_api_key_charge_events(request_id,client_api_key_id,amount_usd,completed_at) values('native_a','restore_key',2.5,now());
|
||||
insert into plugin_update_sources(plugin_id,source_json) values('backup.test','{}');
|
||||
insert into plugin_artifacts(sha256,plugin_id,version,metadata_json,source_json,archive,accepted_at) values(repeat('a',64),'backup.test','1.0.0','{}','{}',decode('010203','hex'),now());
|
||||
insert into plugin_artifacts(sha256,plugin_id,metadata_json,source_json,archive,accepted_at) values(repeat('a',64),'backup.test','{\"version\":\"1.0.0\"}','{}',decode('010203','hex'),now());
|
||||
update runtime_settings set usage_retention_days=3;
|
||||
update model_requests set cost_source='provider_reported',cost_amount=0.5,cost_currency='USD';
|
||||
insert into request_analytics_1h(bucket_start,collection,dimensions,outcome,schema_version,histogram_version,counts,costs,distributions)
|
||||
|
||||
@@ -31,6 +31,7 @@ async fn import_name_only_overrides_a_single_account_and_keeps_batch_names() {
|
||||
.import_provider_accounts(ImportProviderAccounts {
|
||||
outbound_proxy: None,
|
||||
settings: Some(AccountImportSettings {
|
||||
platform_icon: None,
|
||||
name: name.map(str::to_owned),
|
||||
notes: None,
|
||||
model_access: Default::default(),
|
||||
@@ -769,3 +770,166 @@ async fn reset_credit_automation_persists_pending_checks_cas_and_follows_account
|
||||
);
|
||||
database.close().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn platform_icon_is_owned_by_account_and_survives_credential_changes() {
|
||||
use gateway_admin::model::accounts::AccountImportSettings;
|
||||
|
||||
let Some(database) = TestDatabase::create("account_icon").await else {
|
||||
return;
|
||||
};
|
||||
let repository = PgProviderAccountRepository::new(database.pool.clone());
|
||||
let api_account = |id: &str, identity: &str| {
|
||||
let mut record = account(id, identity);
|
||||
record.authentication_kind = "api_key".to_owned();
|
||||
record.provider_credentials_json = JsonObject::try_from_value(
|
||||
"provider_credentials_json",
|
||||
serde_json::json!({
|
||||
"base_url": "https://example.invalid/v1",
|
||||
"api_key": "test-key"
|
||||
}),
|
||||
256 * 1024,
|
||||
)
|
||||
.unwrap();
|
||||
record
|
||||
};
|
||||
for id in ["acct_first", "acct_second"] {
|
||||
repository
|
||||
.insert_provider_account(api_account(id, id))
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
let store = admin_account_store(&database.pool);
|
||||
let context = MutationContext {
|
||||
actor: MutationActor::System,
|
||||
request_id: "account-icon".to_owned(),
|
||||
};
|
||||
let mut edit = UpdateAccount {
|
||||
account_id: "acct_first".to_owned(),
|
||||
platform_icon: Some("DeepSeek".to_owned()),
|
||||
name: None,
|
||||
notes: None,
|
||||
enabled: true,
|
||||
concurrency_limit: None,
|
||||
weight: gateway_core::account::AccountWeight::DEFAULT,
|
||||
model_access: None,
|
||||
group_ids: vec![],
|
||||
outbound_proxy: None,
|
||||
};
|
||||
let icon_for = async |id: &str| {
|
||||
store
|
||||
.load_account(id, AccountRuntimeSnapshot::default())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.platform_icon
|
||||
};
|
||||
store.update_account(edit.clone(), &context).await.unwrap();
|
||||
assert_eq!(icon_for("acct_first").await.as_deref(), Some("DeepSeek"));
|
||||
assert!(icon_for("acct_second").await.is_none());
|
||||
edit.account_id = "acct_second".to_owned();
|
||||
edit.platform_icon = Some("Claude".to_owned());
|
||||
store.update_account(edit.clone(), &context).await.unwrap();
|
||||
assert_eq!(icon_for("acct_first").await.as_deref(), Some("DeepSeek"));
|
||||
|
||||
// 省略整份设置或仅省略图标,都保留已有账号的选择;新账号不继承同地址图标
|
||||
for (index, settings) in [
|
||||
None,
|
||||
Some(AccountImportSettings {
|
||||
platform_icon: None,
|
||||
name: None,
|
||||
notes: None,
|
||||
enabled: true,
|
||||
concurrency_limit: None,
|
||||
weight: gateway_core::account::AccountWeight::DEFAULT,
|
||||
model_access: None,
|
||||
group_ids: vec![],
|
||||
}),
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
repository
|
||||
.import_provider_accounts(ImportProviderAccounts {
|
||||
outbound_proxy: None,
|
||||
settings,
|
||||
scope: ProviderAccountAdminScope {
|
||||
provider_kind: "openai".to_owned(),
|
||||
},
|
||||
accounts: vec![
|
||||
api_account("acct_candidate", "acct_first"),
|
||||
api_account("acct_new", "acct_new"),
|
||||
],
|
||||
audit: audit(
|
||||
&format!("audit_icon_import_{index}"),
|
||||
"import",
|
||||
"provider_accounts",
|
||||
),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(icon_for("acct_first").await.as_deref(), Some("DeepSeek"));
|
||||
assert!(icon_for("acct_new").await.is_none());
|
||||
}
|
||||
let mut credential = credential_update("acct_first", 3, "rotated");
|
||||
credential.provider_credentials_json = JsonObject::try_from_value(
|
||||
"provider_credentials_json",
|
||||
serde_json::json!({
|
||||
"base_url": "https://other.example.invalid/v2",
|
||||
"api_key": "rotated-key"
|
||||
}),
|
||||
256 * 1024,
|
||||
)
|
||||
.unwrap();
|
||||
repository
|
||||
.rotate_provider_account(RotateProviderAccount {
|
||||
settings: None,
|
||||
scope: ProviderAccountAdminScope {
|
||||
provider_kind: "openai".to_owned(),
|
||||
},
|
||||
profile: profile("acct_first", "first"),
|
||||
replacement_identity: None,
|
||||
credential,
|
||||
audit: audit("audit_icon_rotate", "rotate", "acct_first"),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(icon_for("acct_first").await.as_deref(), Some("DeepSeek"));
|
||||
|
||||
edit.account_id = "acct_first".to_owned();
|
||||
edit.platform_icon = Some("Gemini".to_owned());
|
||||
let before = repository
|
||||
.load_provider_account("acct_first")
|
||||
.await
|
||||
.unwrap();
|
||||
// 审计失败发生在图标写入之后,凭据和图标必须一起回滚
|
||||
assert!(
|
||||
repository
|
||||
.rotate_provider_account(RotateProviderAccount {
|
||||
settings: Some(edit.clone()),
|
||||
scope: ProviderAccountAdminScope {
|
||||
provider_kind: "openai".to_owned()
|
||||
},
|
||||
profile: profile("acct_first", "failed"),
|
||||
replacement_identity: None,
|
||||
credential: credential_update("acct_first", 4, "failed"),
|
||||
audit: audit("audit_icon_rotate", "rotate", "acct_first"),
|
||||
})
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert_eq!(
|
||||
repository
|
||||
.load_provider_account("acct_first")
|
||||
.await
|
||||
.unwrap(),
|
||||
before
|
||||
);
|
||||
assert_eq!(icon_for("acct_first").await.as_deref(), Some("DeepSeek"));
|
||||
|
||||
edit.platform_icon = Some(String::new());
|
||||
store.update_account(edit, &context).await.unwrap();
|
||||
assert!(icon_for("acct_first").await.is_none());
|
||||
assert_eq!(icon_for("acct_second").await.as_deref(), Some("Claude"));
|
||||
database.close().await;
|
||||
}
|
||||
|
||||
@@ -426,6 +426,7 @@ async fn reauthorization_replay_keeps_the_committed_revision_and_later_profile_e
|
||||
)),
|
||||
);
|
||||
let rename = UpdateAccount {
|
||||
platform_icon: None,
|
||||
account_id: id.to_string(),
|
||||
name: Some("renamed team".to_owned()),
|
||||
notes: None,
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user