mirror of
https://github.com/zyycn/codex-proxy-rs.git
synced 2026-12-04 16:01:04 +00:00
Compare commits
41
Commits
v3.61.0
...
v3.61.1-rc.5
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f43e1f95c3 | ||
|
|
21cf139c96 | ||
|
|
7d6e4cc4e7 | ||
|
|
2ddcd7c936 | ||
|
|
c71e6176c5 | ||
|
|
28d3e3c2cb | ||
|
|
dd793a84ab | ||
|
|
5ed8b626d7 | ||
|
|
96d8b25d0b | ||
|
|
a193de4eba | ||
|
|
e296bef65e | ||
|
|
89092272a1 | ||
|
|
09f3b39bbc | ||
|
|
7591845f74 | ||
|
|
67ac8fd067 | ||
|
|
b232e367fc | ||
|
|
0bdaa29907 | ||
|
|
cc798e33a1 | ||
|
|
6eabda047c | ||
|
|
3c560b9276 | ||
|
|
77c42cea98 | ||
|
|
dd234c3619 | ||
|
|
b5e691c63d | ||
|
|
2d0a52096a | ||
|
|
47620e217a | ||
|
|
48aeccd0e0 | ||
|
|
bdc618701b | ||
|
|
acd76a09dc | ||
|
|
808387442b | ||
|
|
5bc4e3e5c8 | ||
|
|
7e98130cac | ||
|
|
2821a5e3bd | ||
|
|
6a6a167d41 | ||
|
|
cffb6b35d2 | ||
|
|
17e50df06f | ||
|
|
f2d95cc3fa | ||
|
|
e4f6e1d4e3 | ||
|
|
66f650f097 | ||
|
|
ca4d02068a | ||
|
|
d185a639a9 | ||
|
|
3078dd9993 |
No files matched your search
@@ -16,6 +16,8 @@ description: Codex Proxy RS 的需求评估、排障、开发、代码审查与
|
||||
|
||||
评估功能建议、排障、开发和审查时,先按[问题与方案依据](../../../CONTRIBUTING.md#问题与方案依据)核实使用者要完成什么、当前行为造成了什么影响。反馈直接给出改法时,先弄清提出这个改法的原因
|
||||
|
||||
先确定正常使用时应得到的结果。设计校验、回退或故障恢复时,同时看它防住的具体风险和它可能挡住的正常用法。按协议、隔离要求和实际部署条件选择对正常路径影响最小的做法。只在假设的部署场景下才需要的处理,留到有相应需求时再做
|
||||
|
||||
排查故障时,从症状沿实际调用链回溯,定位行为最早偏离预期的环节,用源码、诊断或对照复现说明触发条件如何导致结果。原因尚未确定时,区分已知事实与假设,指出哪项证据能区分可能原因。确认根因后,在负责该行为的模块修复,用原触发场景验证
|
||||
|
||||
涉及 Codex 时,以对应版本的官方源码核实客户端行为,默认透明转发,只做必要适配。建议宿主接管已有决定时,指出需要它介入的网关职责或实际约束。若只是个别部署希望采用不同策略,说明不建议内置的原因。实现可行性不能证明宿主应当承担这项需求
|
||||
@@ -56,7 +58,7 @@ description: Codex Proxy RS 的需求评估、排障、开发、代码审查与
|
||||
- 移动或重命名测试时,核对受影响的场景覆盖是否保留;涉及子进程调用或名称过滤时,同步更新调用入口并实际运行,确认目标用例确实执行且行为断言通过
|
||||
- 清理只证明旧字段、旧路由或旧实现已经消失的用例与附带断言;未知字段校验使用合法请求基线加无业务含义的未知字段,避免因缺少必填项等其他错误而误通过
|
||||
- 同一层对同一行为的重复覆盖合并为清晰的场景矩阵,复用相邻测试夹具;跨层测试确有不同职责或失败路径时保留,不为统一而扩大测试辅助抽象
|
||||
- 断言可观察的行为与业务不变量,避免复述结构体赋值、罗列表列或字段清单、匹配 SQL 文本与源码布局
|
||||
- 断言可观察的行为与业务不变量,避免复述实现细节。验收上游兼容行为时,先从对应版本的上游实现确定预期,再核对网关对同一输入的处理。例如历史应增量续接时,要看出站请求是否只含预期的增量,因为回退全量也可能返回成功
|
||||
- 维护项目明确要求的架构边界检查;发现漏检时,对照规则核实扫描范围、排除项与被检查的依赖关系,优先补齐现有检查中能稳定判定的缺口
|
||||
- 当前协议兼容、数据读取兼容、安全边界、并发和资源生命周期仍需覆盖,不按 `old`、`legacy` 等名称机械删除,也不能用改名代替无效用例清理
|
||||
- 不在仓库中新增或保留迁移 SQL 专项测试,包括迁移文本、schema 演变与指定版本升级用例;需要验证迁移执行、数据保留或回滚时,在临时目录编写一次性验证并使用隔离数据库,测试通过即可,临时脚本不纳入维护测试集
|
||||
|
||||
@@ -30,6 +30,8 @@
|
||||
|
||||
验证前按[界面验证](../../../../CONTRIBUTING.md#界面验证)明确本次受影响的用户路径、状态和通过条件。局部修改围绕受影响区域及相关操作验收;主题、窗口尺寸和空/加载/错误状态仅在受影响时补充,共用主题或基础组件变更按主题规范扩大范围
|
||||
|
||||
沿实际操作验证待确认、执行中、完成、失败与取消等受影响阶段,同时检查当前弹层和背景区域,核对应该出现的反馈与不应出现的状态。必要时延迟模拟响应以观察过渡状态,不能仅凭请求成功或截图齐全判定交互通过
|
||||
|
||||
通过后按[验证停止条件](../../../../CONTRIBUTING.md#验证)收尾;只有新改动、失败或未解疑点时补验相关部分。补交截图或 PR 材料时复用仍有效的运行证据
|
||||
|
||||
## 交付前
|
||||
@@ -42,7 +44,7 @@
|
||||
- **样式与状态**:是否使用对应 Token 与 utility,局部样式是否符合适用边界,受影响的主题、窄屏及交互状态是否正确
|
||||
- **模块归属**从调用方核对公开入口。页面或多文件组件通过 `index.vue` 提供界面,其他页面复用整页时引用所属模块的布局入口,独立复用的业务组件按领域放置
|
||||
- **Provider 边界**涉及账号操作、身份配置或定价时,沿接口响应、控件和提交载荷追踪同一条规则。服务端决定的能力使用接口字段,Provider 专属表单解释自己的字段,多个页面共用的编辑流程只维护一份。按[前端职责](../../../../docs/architecture.md#34-前端模块职责)核对归属
|
||||
- **查询与动作**:区分首次加载、刷新、分页、单行与批量操作,核对 loading、禁用状态的影响范围;沿用请求层错误处理,不在页面叠加同一错误的提示
|
||||
- **查询与动作**:区分首次加载、刷新、分页、单行与批量操作,明确当前动作的反馈归属及其他控件的禁用范围,避免同一动作在前后景重复显示执行反馈。待确认不等于已提交,复用交互时重新核对 loading、进度与结果的显示条件是否适用于当前动作;沿用请求层错误处理,不在页面叠加同一错误的提示
|
||||
- **运行证据**:按界面验证核对截图与实际交互,证据对应当前实现;页面 PR 的可访问图片和 Draft 条件按该节执行
|
||||
|
||||
交付简述所复用的页面或组件、实际验证范围及缺口;环境不足时如实说明,不能仅凭构建、源码或截图推断未验证的行为
|
||||
@@ -12,7 +12,7 @@
|
||||
[](https://github.com/zyycn/codex-proxy-rs/pkgs/container/codex-proxy-rs)
|
||||
[](LICENSE)
|
||||
|
||||
[快速预览](#快速预览) · [快速开始](#快速开始) · [文档](#文档) · [社区](#社区) · [贡献者](#贡献者) · [Star History](#star-history) · [支持项目](#支持项目) · [许可证](#许可证)
|
||||
[快速预览](#快速预览) · [快速开始](#快速开始) · [文档](#文档) · [贡献者](#贡献者) · [Star History](#star-history) · [社区](#社区) · [支持项目](#支持项目) · [许可证](#许可证)
|
||||
|
||||
</div>
|
||||
|
||||
@@ -49,12 +49,6 @@ curl -fsSL https://raw.githubusercontent.com/zyycn/codex-proxy-rs/main/deploy/in
|
||||
| 开发宿主 | [开发与源码联调](docs/development.md) · [系统架构](docs/architecture.md) · [管理端主题](docs/theme.md) · [数据库迁移](backend/migrations/README.md) |
|
||||
| 参与协作 | [贡献、审查与验证](CONTRIBUTING.md) |
|
||||
|
||||
## 社区
|
||||
|
||||
问题反馈与功能建议请使用 [GitHub Issues](https://github.com/zyycn/codex-proxy-rs/issues),填写要求见 [贡献说明](CONTRIBUTING.md#提交-issue)
|
||||
|
||||
感谢 [LINUX DO](https://linux.do) 社区提供开放、友善的技术交流平台
|
||||
|
||||
## 贡献者
|
||||
|
||||
[<img src="https://contrib.rocks/image?repo=zyycn/codex-proxy-rs&columns=10" alt="查看 GitHub 贡献者列表" width="480">](https://github.com/zyycn/codex-proxy-rs/graphs/contributors)
|
||||
@@ -68,6 +62,18 @@ curl -fsSL https://raw.githubusercontent.com/zyycn/codex-proxy-rs/main/deploy/in
|
||||
</picture>
|
||||
</a>
|
||||
|
||||
## 社区
|
||||
|
||||
点击或扫码加入 Telegram 群 [小酒馆][telegram-group]
|
||||
|
||||
[<img src="docs/community/telegram-qr.png" alt="扫码加入小酒馆 Telegram 群" width="138">][telegram-group]
|
||||
|
||||
[telegram-group]: https://t.me/+9tk761zbNAMyNWY9
|
||||
|
||||
问题反馈与功能建议请使用 [GitHub Issues](https://github.com/zyycn/codex-proxy-rs/issues),填写要求见 [贡献说明](CONTRIBUTING.md#提交-issue)
|
||||
|
||||
感谢 [LINUX DO](https://linux.do) 社区提供开放、友善的技术交流平台
|
||||
|
||||
## 支持项目
|
||||
|
||||
如果 Codex Proxy RS 帮助到你了,欢迎请我喝杯咖啡 ☕
|
||||
|
||||
Generated
+20
@@ -1887,6 +1887,7 @@ dependencies = [
|
||||
"tracing",
|
||||
"tracing-appender",
|
||||
"tracing-subscriber",
|
||||
"uuid",
|
||||
"wiremock",
|
||||
"yaml-rust2 0.13.2",
|
||||
]
|
||||
@@ -2707,6 +2708,12 @@ version = "0.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154"
|
||||
|
||||
[[package]]
|
||||
name = "lzma-rust2"
|
||||
version = "0.26.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4c7861572250348d13073a9035c6a83f3e583ec9a76a65ce92f338fe1107d8f5"
|
||||
|
||||
[[package]]
|
||||
name = "lzma-sys"
|
||||
version = "0.1.20"
|
||||
@@ -3404,6 +3411,7 @@ dependencies = [
|
||||
"reqwest",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sevenz-rust2",
|
||||
"sha2",
|
||||
"tar",
|
||||
"tempfile",
|
||||
@@ -4185,6 +4193,18 @@ dependencies = [
|
||||
"stable_deref_trait",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sevenz-rust2"
|
||||
version = "0.27.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2e668242e054ba8b7360918104c30c6685bdedf847909a784cf267d002f40a6a"
|
||||
dependencies = [
|
||||
"crc32fast",
|
||||
"js-sys",
|
||||
"lzma-rust2",
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sha1"
|
||||
version = "0.10.7"
|
||||
|
||||
@@ -79,7 +79,11 @@ impl Providers {
|
||||
)
|
||||
.await?;
|
||||
environment.host.report_startup_ready("OpenAI Provider");
|
||||
let antigravity = provider_antigravity::initialize(ports.clone())?;
|
||||
let antigravity = provider_antigravity::initialize(
|
||||
ports.clone(),
|
||||
environment.host.runtime_data_dir().join("antigravity"),
|
||||
)
|
||||
.await?;
|
||||
environment
|
||||
.host
|
||||
.report_startup_ready("Antigravity Provider");
|
||||
|
||||
@@ -263,10 +263,11 @@ impl ScheduledTask for FreezeRecoveryTask {
|
||||
context: WorkerCycleContext,
|
||||
) -> futures::future::BoxFuture<'_, Result<(), WorkerTaskError>> {
|
||||
Box::pin(async move {
|
||||
if context.cancellation().is_cancelled() {
|
||||
return Ok(());
|
||||
}
|
||||
self.run_cycle_inner().await;
|
||||
// 中止在途探测,避免把停机当成探测失败而延长冻结
|
||||
context
|
||||
.cancellation()
|
||||
.run_until_cancelled(self.run_cycle_inner())
|
||||
.await;
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
@@ -92,6 +92,9 @@ pub struct AccountListQuery {
|
||||
/// Admin query service 从运行态存储取得的当前账号冷却快照
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct AccountRuntimeSnapshot {
|
||||
/// 模型维度冷却独立于整账号冷却,不能据此阻断其他模型
|
||||
pub model_cooldowns:
|
||||
BTreeMap<String, Vec<gateway_core::provider_ports::ProviderScopedCooldown>>,
|
||||
pub protection_rules: BTreeMap<String, Vec<gateway_core::account::AccountProtectionMatch>>,
|
||||
pub cooldown: BTreeMap<String, gateway_core::account::AccountCooldown>,
|
||||
/// `None` 表示实时 lease 存储不可用;`Some` 中未出现的账号当前使用量为零
|
||||
@@ -223,6 +226,7 @@ pub struct AccountPage {
|
||||
/// 同一状态快照下的账号事实与唯一状态投影
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct AccountPageItem {
|
||||
pub model_cooldowns: Vec<gateway_core::provider_ports::ProviderScopedCooldown>,
|
||||
pub platform_icon: Option<String>,
|
||||
pub protection_rules: Vec<gateway_core::account::AccountProtectionMatch>,
|
||||
pub account: AccountRecord,
|
||||
|
||||
@@ -698,7 +698,7 @@ pub struct PreparedCredentialRotationFacts {
|
||||
pub plan_type: Option<String>,
|
||||
/// Token 刷新保留提交时的资料,不以准备阶段的副本覆盖新套餐
|
||||
pub preserve_profile: bool,
|
||||
/// 连接配置变更保留当前凭据健康状态与错误事实
|
||||
/// 凭据或连接配置更新保留提交时的健康状态与错误事实
|
||||
pub preserve_credential_state: bool,
|
||||
pub preserve_access_token_expiry: bool,
|
||||
pub provider_material: ProviderDocument,
|
||||
@@ -722,7 +722,7 @@ impl PreparedCredentialRotation {
|
||||
Self { facts, guard }
|
||||
}
|
||||
|
||||
/// 仅修改连接配置时,不把配置更新视为凭据恢复成功
|
||||
/// 更新本身不能证明账号已恢复时,保留提交时的状态
|
||||
#[must_use]
|
||||
pub fn preserving_credential_state(mut self) -> Self {
|
||||
self.facts.preserve_credential_state = true;
|
||||
@@ -1319,6 +1319,7 @@ impl fmt::Debug for ProviderExport {
|
||||
/// 统一账号目录的一行完整结果
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct AccountDirectoryItem {
|
||||
pub model_cooldowns: Vec<gateway_core::provider_ports::ProviderScopedCooldown>,
|
||||
pub platform_icon: Option<String>,
|
||||
pub protection_rules: Vec<gateway_core::account::AccountProtectionMatch>,
|
||||
pub account: AccountRecord,
|
||||
|
||||
@@ -50,6 +50,8 @@ pub struct SystemUpdatePolicy {
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct SystemVersion {
|
||||
pub version: String,
|
||||
pub instance_id: String,
|
||||
pub restart_supported: bool,
|
||||
pub git_sha: String,
|
||||
pub build_time: String,
|
||||
pub deployment_mode: String,
|
||||
|
||||
@@ -55,37 +55,44 @@ impl ScheduledTask for ResetCreditAutomationTask {
|
||||
context: WorkerCycleContext,
|
||||
) -> futures::future::BoxFuture<'_, Result<(), WorkerTaskError>> {
|
||||
Box::pin(async move {
|
||||
let settings = self
|
||||
.settings
|
||||
.load_runtime_settings()
|
||||
context
|
||||
.cancellation()
|
||||
.run_until_cancelled(self.run_due())
|
||||
.await
|
||||
.map_err(|_| WorkerTaskError::safe("重置卡设置读取失败"))?;
|
||||
// 单轮有界,积压沿到期顺序继续;并发复用已有账号刷新配置
|
||||
let due = self
|
||||
.store
|
||||
.due_reset_credit_automations(Utc::now(), 100)
|
||||
.await
|
||||
.map_err(|_| WorkerTaskError::safe("重置卡计划读取失败"))?;
|
||||
let work = futures::stream::iter(due)
|
||||
.map(|account_id| async move {
|
||||
let id = ProviderAccountId::new(account_id.clone())
|
||||
.map_err(|_| WorkerTaskError::safe("重置卡账号 ID 不合法"))?;
|
||||
if let Err(error) = self.accounts.reconcile_reset_credit_automation(id).await {
|
||||
tracing::warn!(
|
||||
account_id,
|
||||
error_kind = error.kind().as_str(),
|
||||
"自动重置卡任务失败"
|
||||
);
|
||||
}
|
||||
Ok::<_, WorkerTaskError>(())
|
||||
})
|
||||
.buffer_unordered(settings.values.refresh_concurrency.max(1) as usize)
|
||||
.collect::<Vec<_>>();
|
||||
tokio::select! {
|
||||
() = context.cancellation().cancelled() => {},
|
||||
_ = tokio::time::timeout(Duration::from_secs(30), work) => {},
|
||||
}
|
||||
Ok(())
|
||||
.unwrap_or(Ok(()))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl ResetCreditAutomationTask {
|
||||
async fn run_due(&self) -> Result<(), WorkerTaskError> {
|
||||
let settings = self
|
||||
.settings
|
||||
.load_runtime_settings()
|
||||
.await
|
||||
.map_err(|_| WorkerTaskError::safe("重置卡设置读取失败"))?;
|
||||
// 单轮有界,积压沿到期顺序继续;并发复用已有账号刷新配置
|
||||
let due = self
|
||||
.store
|
||||
.due_reset_credit_automations(Utc::now(), 100)
|
||||
.await
|
||||
.map_err(|_| WorkerTaskError::safe("重置卡计划读取失败"))?;
|
||||
let work = futures::stream::iter(due)
|
||||
.map(|account_id| async move {
|
||||
let id = ProviderAccountId::new(account_id.clone())
|
||||
.map_err(|_| WorkerTaskError::safe("重置卡账号 ID 不合法"))?;
|
||||
if let Err(error) = self.accounts.reconcile_reset_credit_automation(id).await {
|
||||
tracing::warn!(
|
||||
account_id,
|
||||
error_kind = error.kind().as_str(),
|
||||
"自动重置卡任务失败"
|
||||
);
|
||||
}
|
||||
Ok::<_, WorkerTaskError>(())
|
||||
})
|
||||
.buffer_unordered(settings.values.refresh_concurrency.max(1) as usize)
|
||||
.collect::<Vec<_>>();
|
||||
let _ = tokio::time::timeout(Duration::from_secs(30), work).await;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -513,6 +513,7 @@ impl DefaultAccountsService {
|
||||
lookback,
|
||||
);
|
||||
Ok(AccountDirectoryItem {
|
||||
model_cooldowns: stored.model_cooldowns,
|
||||
platform_icon: stored.platform_icon,
|
||||
protection_rules: stored.protection_rules,
|
||||
capacity: super::peer_link::upstream::account_capacity(
|
||||
@@ -648,6 +649,7 @@ impl AccountsService for DefaultAccountsService {
|
||||
lookback,
|
||||
);
|
||||
Ok(AccountDirectoryItem {
|
||||
model_cooldowns: item.model_cooldowns,
|
||||
platform_icon: item.platform_icon,
|
||||
protection_rules: item.protection_rules,
|
||||
capacity: crate::model::accounts::AccountCapacity {
|
||||
|
||||
@@ -315,6 +315,7 @@ impl AccountRuntimeStore for FakeRuntimeStore {
|
||||
) -> AdminStoreResult<AccountRuntimeSnapshot> {
|
||||
*self.requested_accounts.lock().expect("requested accounts") = account_ids.to_vec();
|
||||
Ok(AccountRuntimeSnapshot {
|
||||
model_cooldowns: BTreeMap::new(),
|
||||
protection_rules: std::collections::BTreeMap::new(),
|
||||
cooldown: BTreeMap::from([(
|
||||
"acct_limited".to_owned(),
|
||||
|
||||
@@ -740,6 +740,7 @@ impl FakeAccountStore {
|
||||
last_error_message: account.last_error_message.clone(),
|
||||
};
|
||||
AccountPageItem {
|
||||
model_cooldowns: Vec::new(),
|
||||
platform_icon: None,
|
||||
protection_rules: Vec::new(),
|
||||
capacity: gateway_admin::model::accounts::AccountCapacity {
|
||||
|
||||
@@ -27,6 +27,8 @@ impl SystemOperations for RecordingSystemOperations {
|
||||
}
|
||||
Ok(SystemVersion {
|
||||
version: "1.0.0".to_owned(),
|
||||
instance_id: "test-instance".to_owned(),
|
||||
restart_supported: false,
|
||||
git_sha: "unknown".to_owned(),
|
||||
build_time: "unknown".to_owned(),
|
||||
deployment_mode: "source".to_owned(),
|
||||
|
||||
@@ -67,6 +67,7 @@ pub(super) fn account_view(
|
||||
time: crate::time::TimePresenter,
|
||||
) -> AccountView {
|
||||
let AccountDirectoryItem {
|
||||
model_cooldowns,
|
||||
platform_icon,
|
||||
account,
|
||||
capacity,
|
||||
@@ -111,6 +112,17 @@ pub(super) fn account_view(
|
||||
.map(|value| super::upstream_info::view(value, now, time));
|
||||
let (mut quota, refresh_token_expires_at) = account_quota_view(quota, cooldown, now, time);
|
||||
quota.protection_rules = protection_rules;
|
||||
quota.model_rate_limits = model_cooldowns
|
||||
.into_iter()
|
||||
.map(|cooldown| {
|
||||
let until: DateTime<Utc> = cooldown.until().into();
|
||||
AccountModelRateLimitView {
|
||||
model: cooldown.scope().value().to_owned(),
|
||||
until: time.rfc3339(&until),
|
||||
until_display: time.datetime(&until),
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
AccountView {
|
||||
platform_icon,
|
||||
quota_settings: account.quota_settings,
|
||||
@@ -271,6 +283,7 @@ pub(super) fn account_quota_view(
|
||||
let recovery_probe_required = cooldown.is_some_and(|value| value.kind.requires_probe());
|
||||
(
|
||||
AccountQuotaView {
|
||||
model_rate_limits: Vec::new(),
|
||||
paused_windows: quota.paused_windows,
|
||||
refreshed_at: quota.observed_at.map(|value| time.rfc3339(&value)),
|
||||
refreshed_at_relative: quota
|
||||
|
||||
@@ -382,6 +382,7 @@ pub use crate::admin::account_groups::AccountGroupRefView;
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AccountQuotaView {
|
||||
pub model_rate_limits: Vec<AccountModelRateLimitView>,
|
||||
pub paused_windows: Vec<String>,
|
||||
pub refreshed_at: Option<String>,
|
||||
pub refreshed_at_relative: Option<crate::time::RelativeTimeView>,
|
||||
@@ -397,6 +398,14 @@ pub struct AccountQuotaView {
|
||||
pub credits: Option<AccountQuotaCreditsView>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AccountModelRateLimitView {
|
||||
pub model: String,
|
||||
pub until: String,
|
||||
pub until_display: String,
|
||||
}
|
||||
|
||||
/// 上游点数安全视图,不透出额度响应中的其他 Provider 字段
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
|
||||
@@ -81,6 +81,8 @@ impl UpdateRequest {
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct SystemVersionView {
|
||||
version: String,
|
||||
instance_id: String,
|
||||
restart_supported: bool,
|
||||
git_sha: String,
|
||||
build_time: String,
|
||||
deployment_mode: String,
|
||||
@@ -97,6 +99,8 @@ impl From<SystemVersion> for SystemVersionView {
|
||||
Self {
|
||||
deployment_mode_label: deployment_mode_label(&version.deployment_mode).to_owned(),
|
||||
version: version.version,
|
||||
instance_id: version.instance_id,
|
||||
restart_supported: version.restart_supported,
|
||||
git_sha: version.git_sha,
|
||||
build_time: version.build_time,
|
||||
deployment_mode: version.deployment_mode,
|
||||
|
||||
@@ -119,22 +119,24 @@ pub fn gateway_error_response(error: &GatewayError) -> Response {
|
||||
}
|
||||
let mut response = (status, Json(body)).into_response();
|
||||
response.extensions_mut().insert(error.clone());
|
||||
if let Some(delay) = error.retry_after()
|
||||
&& let Ok(value) = HeaderValue::from_str(
|
||||
&delay
|
||||
.as_secs()
|
||||
.saturating_add(u64::from(delay.subsec_nanos() > 0))
|
||||
.max(1)
|
||||
.to_string(),
|
||||
)
|
||||
{
|
||||
if let Some(seconds) = retry_after_seconds(error) {
|
||||
response
|
||||
.headers_mut()
|
||||
.insert(axum::http::header::RETRY_AFTER, value);
|
||||
.insert(axum::http::header::RETRY_AFTER, HeaderValue::from(seconds));
|
||||
}
|
||||
response
|
||||
}
|
||||
|
||||
/// HTTP 和 WS 的等待秒数均向上取整,避免客户端在冷却到期前重新发起请求
|
||||
pub(crate) fn retry_after_seconds(error: &GatewayError) -> Option<u64> {
|
||||
error.retry_after().map(|delay| {
|
||||
delay
|
||||
.as_secs()
|
||||
.saturating_add(u64::from(delay.subsec_nanos() > 0))
|
||||
.max(1)
|
||||
})
|
||||
}
|
||||
|
||||
/// Gateway 错误稳定映射,供 HTTP、SSE 和 WebSocket 共用
|
||||
#[must_use]
|
||||
pub const fn gateway_error_contract(
|
||||
|
||||
@@ -11,6 +11,7 @@ use gateway_core::{
|
||||
error::ProviderErrorKind,
|
||||
policy::{ClientVersionRejection, CodexClientKind},
|
||||
};
|
||||
use gateway_protocol::http::preferred_response_request_id;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
pub use gateway_core::engine::execution::gateway_error_from_engine;
|
||||
@@ -170,8 +171,8 @@ pub fn engine_error_response(error: &EngineError) -> Response {
|
||||
};
|
||||
response.headers_mut().append(name, value);
|
||||
}
|
||||
if !response.headers().contains_key("x-request-id")
|
||||
&& !response.headers().contains_key("x-oai-request-id")
|
||||
if preferred_response_request_id(|name| response.headers().get(name)?.to_str().ok())
|
||||
.is_none()
|
||||
&& let Some(request_id) = error.upstream_request_id()
|
||||
&& let Ok(value) = HeaderValue::from_str(request_id.as_str())
|
||||
{
|
||||
|
||||
@@ -665,7 +665,7 @@ fn engine_error_response_with_headers(
|
||||
response_headers: &[ProviderResponseHeader],
|
||||
) -> Response {
|
||||
let response = engine_error_response(error);
|
||||
let failure_request_ids = ["x-request-id", "x-oai-request-id"]
|
||||
let failure_request_ids = gateway_protocol::http::RESPONSE_REQUEST_ID_HEADERS
|
||||
.into_iter()
|
||||
.flat_map(|name| {
|
||||
response
|
||||
@@ -678,8 +678,9 @@ fn engine_error_response_with_headers(
|
||||
.collect::<Vec<_>>();
|
||||
// 失败后仍须交付已采集的 turn state;只隔离 opening 身份,不丢弃会话状态
|
||||
let mut response = apply_provider_response_headers(response, response_headers);
|
||||
response.headers_mut().remove("x-request-id");
|
||||
response.headers_mut().remove("x-oai-request-id");
|
||||
for name in gateway_protocol::http::RESPONSE_REQUEST_ID_HEADERS {
|
||||
response.headers_mut().remove(name);
|
||||
}
|
||||
for (name, value) in failure_request_ids {
|
||||
response.headers_mut().append(name, value);
|
||||
}
|
||||
|
||||
@@ -37,11 +37,11 @@ pub(crate) fn with_model_request_id(
|
||||
let usable = |value: &HeaderValue| value.to_str().is_ok_and(|id| !id.trim().is_empty());
|
||||
if !headers.get("x-request-id").is_some_and(usable) {
|
||||
// 只有别名时沿用同一个上游值,避免外层 middleware 再填入入口 ID
|
||||
let client_id = headers
|
||||
.get("x-oai-request-id")
|
||||
.filter(|value| usable(value))
|
||||
.unwrap_or(&gateway_id)
|
||||
.clone();
|
||||
let client_id = gateway_protocol::http::preferred_response_request_id(|name| {
|
||||
headers.get(name)?.to_str().ok()
|
||||
})
|
||||
.and_then(|value| HeaderValue::from_str(value).ok())
|
||||
.unwrap_or_else(|| gateway_id.clone());
|
||||
headers.insert("x-request-id", client_id);
|
||||
}
|
||||
headers.insert("x-gateway-request-id", gateway_id);
|
||||
|
||||
@@ -7,6 +7,7 @@ use crate::{
|
||||
auth::{ClientKeyHeaders, authenticate_client, client_access_error_response},
|
||||
error::gateway_error_response,
|
||||
generation::{GenerationEndpoint, GenerationHttpRequest, execute_prepared_generation},
|
||||
router::IngressStarted,
|
||||
},
|
||||
};
|
||||
use axum::{
|
||||
@@ -15,18 +16,43 @@ use axum::{
|
||||
http::{HeaderMap, StatusCode},
|
||||
response::Response,
|
||||
};
|
||||
use std::net::SocketAddr;
|
||||
use std::{net::SocketAddr, time::Instant};
|
||||
|
||||
/// `POST /v1/responses`
|
||||
pub(crate) async fn responses(
|
||||
State(state): State<ApiState>,
|
||||
connect_info: Option<Extension<ConnectInfo<SocketAddr>>>,
|
||||
ingress_id: Option<Extension<tower_http::request_id::RequestId>>,
|
||||
ingress_started: Option<Extension<IngressStarted>>,
|
||||
headers: HeaderMap,
|
||||
body: Bytes,
|
||||
) -> Response {
|
||||
// Bytes extractor 已读完传输正文;此时尚未认证、解压或解析 JSON
|
||||
let mut encodings = headers.get_all(axum::http::header::CONTENT_ENCODING).iter();
|
||||
let encoding = match (encodings.next(), encodings.next()) {
|
||||
(None, _) => "identity",
|
||||
(Some(value), None) => value
|
||||
.to_str()
|
||||
.ok()
|
||||
.and_then(|value| {
|
||||
["identity", "gzip", "deflate", "zstd"]
|
||||
.into_iter()
|
||||
.find(|known| known.eq_ignore_ascii_case(value.trim()))
|
||||
})
|
||||
.unwrap_or("other"),
|
||||
_ => "other",
|
||||
};
|
||||
tracing::info!(target: "request_trace", stage = "http.body.received",
|
||||
receive_ms = ingress_started.map(|Extension(start)| start.0.elapsed().as_millis()),
|
||||
encoded_bytes = body.len(), content_encoding = encoding,
|
||||
"HTTP request body received");
|
||||
let service = state.data_plane().clone();
|
||||
let client = match authenticate_client(&service, &headers, ClientKeyHeaders::Bearer).await {
|
||||
let started = Instant::now();
|
||||
let authentication = authenticate_client(&service, &headers, ClientKeyHeaders::Bearer).await;
|
||||
tracing::info!(target: "request_trace", stage = "http.auth.finished",
|
||||
auth_ms = started.elapsed().as_millis(), accepted = authentication.is_ok(),
|
||||
"HTTP request authentication finished");
|
||||
let client = match authentication {
|
||||
Ok(client) => client,
|
||||
Err(error) => return client_access_error_response(error),
|
||||
};
|
||||
@@ -42,7 +68,12 @@ pub(crate) async fn responses(
|
||||
}
|
||||
};
|
||||
let execution = service.execution();
|
||||
let prepared = match execution.prepare_execution(client).await {
|
||||
let started = Instant::now();
|
||||
let preparation = execution.prepare_execution(client).await;
|
||||
tracing::info!(target: "request_trace", stage = "http.execution.prepared",
|
||||
prepare_ms = started.elapsed().as_millis(), accepted = preparation.is_ok(),
|
||||
"HTTP execution preparation finished");
|
||||
let prepared = match preparation {
|
||||
Ok(prepared) => prepared,
|
||||
Err(error) => return gateway_error_response(&error),
|
||||
};
|
||||
|
||||
@@ -143,9 +143,20 @@ pub(crate) fn decode_request_with_body(
|
||||
headers: &HeaderMap,
|
||||
max_decompressed_bytes: usize,
|
||||
) -> Result<(DecodedGenerationRequest, Bytes), RequestDecodeError> {
|
||||
let body = decompress_request_body(body, headers, max_decompressed_bytes)?;
|
||||
let decoded = decode_request_inner(&body, &OpenAiRequestHeaders::from_headers(headers))?;
|
||||
Ok((decoded, Bytes::copy_from_slice(&body)))
|
||||
let started = std::time::Instant::now();
|
||||
let decompressed = decompress_request_body(body, headers, max_decompressed_bytes);
|
||||
tracing::info!(target: "request_trace", stage = "http.body.decompressed",
|
||||
decompress_ms = started.elapsed().as_millis(),
|
||||
decoded_bytes = decompressed.as_ref().ok().map(|body| body.len()),
|
||||
accepted = decompressed.is_ok(), "HTTP request body decompressed");
|
||||
let body = decompressed?;
|
||||
let started = std::time::Instant::now();
|
||||
let decoded = decode_request_inner(&body, &OpenAiRequestHeaders::from_headers(headers))
|
||||
.map(|decoded| (decoded, Bytes::copy_from_slice(&body)));
|
||||
tracing::info!(target: "request_trace", stage = "http.body.decoded",
|
||||
decode_ms = started.elapsed().as_millis(), accepted = decoded.is_ok(),
|
||||
"HTTP request body decoded");
|
||||
decoded
|
||||
}
|
||||
|
||||
pub(super) fn decode_request_inner(
|
||||
|
||||
@@ -8,6 +8,7 @@ use axum::http::{HeaderName, HeaderValue, StatusCode};
|
||||
use gateway_core::engine::EngineError;
|
||||
use gateway_core::error::ProviderErrorKind;
|
||||
use gateway_core::event::ProviderResponseHeader;
|
||||
use gateway_protocol::http::{RESPONSE_REQUEST_ID_HEADERS, preferred_response_request_id};
|
||||
use serde_json::{Map, Value, json};
|
||||
use thiserror::Error;
|
||||
|
||||
@@ -119,9 +120,12 @@ pub(super) fn response_metadata_event(
|
||||
response_headers: &[ProviderResponseHeader],
|
||||
) -> String {
|
||||
let mut headers = response_event_headers(response_headers);
|
||||
let client_request_id = preferred_response_request_id(|name| headers.get(name)?.as_str())
|
||||
.unwrap_or(request_id)
|
||||
.to_owned();
|
||||
headers
|
||||
.entry("x-request-id".to_owned())
|
||||
.or_insert_with(|| Value::String(request_id.to_owned()));
|
||||
.or_insert(Value::String(client_request_id));
|
||||
json!({
|
||||
"type": "response.metadata",
|
||||
"headers": headers,
|
||||
@@ -149,7 +153,7 @@ fn response_event_headers(response_headers: &[ProviderResponseHeader]) -> Map<St
|
||||
let Ok(value) = std::str::from_utf8(header.value()) else {
|
||||
continue;
|
||||
};
|
||||
if matches!(name.as_str(), "x-request-id" | "x-oai-request-id")
|
||||
if RESPONSE_REQUEST_ID_HEADERS.contains(&name.as_str())
|
||||
&& (value.trim().is_empty() || http_value.to_str().is_err())
|
||||
{
|
||||
continue;
|
||||
@@ -181,9 +185,13 @@ pub(super) fn initial_engine_error_event(
|
||||
response_event_headers(response_headers)
|
||||
};
|
||||
if upstream.is_none() {
|
||||
if let Some(seconds) = crate::client_error::retry_after_seconds(&gateway) {
|
||||
headers.insert("retry-after".to_owned(), Value::String(seconds.to_string()));
|
||||
}
|
||||
// 会话 opening 身份不证明当前失败属于该请求;仅保留其他允许的会话头
|
||||
headers.remove("x-request-id");
|
||||
headers.remove("x-oai-request-id");
|
||||
for name in RESPONSE_REQUEST_ID_HEADERS {
|
||||
headers.remove(name);
|
||||
}
|
||||
}
|
||||
let status = if provider
|
||||
.is_some_and(|error| error.kind() == ProviderErrorKind::UpstreamCapacityUnavailable)
|
||||
@@ -221,7 +229,7 @@ pub(super) fn initial_engine_error_event(
|
||||
}
|
||||
|
||||
fn has_request_id(headers: &Map<String, Value>) -> bool {
|
||||
headers.contains_key("x-request-id") || headers.contains_key("x-oai-request-id")
|
||||
preferred_response_request_id(|name| headers.get(name)?.as_str()).is_some()
|
||||
}
|
||||
|
||||
pub(super) fn error_event(
|
||||
|
||||
@@ -46,6 +46,10 @@ pub(crate) fn router() -> Router<ApiState> {
|
||||
.merge(super::provider_endpoints::router())
|
||||
}
|
||||
|
||||
/// 在读取正文前保存入口时刻,交给端点区分接收与执行耗时
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) struct IngressStarted(pub(crate) std::time::Instant);
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) enum DataPlaneNamespace {
|
||||
V1,
|
||||
|
||||
@@ -19,7 +19,7 @@ use serde_json::json;
|
||||
use tower_http::request_id::RequestId;
|
||||
|
||||
use crate::client_error::{AccessRejection, ProtocolErrorBody};
|
||||
use crate::data_plane::router::DataPlaneNamespace;
|
||||
use crate::data_plane::router::{DataPlaneNamespace, IngressStarted};
|
||||
|
||||
pub(crate) async fn record_ingress(
|
||||
State(diagnostics): State<Arc<dyn OperationalDiagnostics>>,
|
||||
@@ -29,6 +29,9 @@ pub(crate) async fn record_ingress(
|
||||
let Some(namespace) = DataPlaneNamespace::for_path(request.uri().path()) else {
|
||||
return next.run(request).await;
|
||||
};
|
||||
request
|
||||
.extensions_mut()
|
||||
.insert(IngressStarted(std::time::Instant::now()));
|
||||
let correlation_id = request
|
||||
.extensions()
|
||||
.get::<RequestId>()
|
||||
|
||||
@@ -255,6 +255,18 @@ async fn account_cooldown_returns_an_instant_and_server_formatted_recovery() {
|
||||
last_error_message: None,
|
||||
};
|
||||
let mut item = account_page_item(facts, now, "oauth");
|
||||
let model_until = now + Duration::seconds(8);
|
||||
item.model_cooldowns = vec![gateway_core::provider_ports::ProviderScopedCooldown::new(
|
||||
gateway_core::account::ProviderAccountId::new(item.account.id.clone()).unwrap(),
|
||||
gateway_core::account::CredentialRevision::new(
|
||||
item.account.credential_revision.get(),
|
||||
)
|
||||
.unwrap(),
|
||||
gateway_core::provider_ports::ProviderCooldownScope::upstream_model(
|
||||
gateway_core::routing::UpstreamModelId::new("gpt-5.4").unwrap(),
|
||||
),
|
||||
model_until.into(),
|
||||
)];
|
||||
if kind.is_error_protection() {
|
||||
item.protection_rules = vec![gateway_core::account::AccountProtectionMatch {
|
||||
id: "removed-rule".to_owned(),
|
||||
@@ -278,6 +290,14 @@ async fn account_cooldown_returns_an_instant_and_server_formatted_recovery() {
|
||||
let body = to_bytes(response.into_body(), 32768).await.unwrap();
|
||||
let value: serde_json::Value = serde_json::from_slice(&body).unwrap();
|
||||
let quota = &value["data"]["items"][0]["quota"];
|
||||
assert_eq!(
|
||||
quota["modelRateLimits"],
|
||||
serde_json::json!([{
|
||||
"model": "gpt-5.4",
|
||||
"until": zone.local(model_until).to_rfc3339(),
|
||||
"untilDisplay": zone.local(model_until).format("%Y-%m-%d %H:%M:%S").to_string(),
|
||||
}])
|
||||
);
|
||||
if kind.is_error_protection() {
|
||||
assert_eq!(quota["rateLimitReason"], "error_protection");
|
||||
assert_eq!(
|
||||
@@ -411,6 +431,7 @@ fn account_page_item(
|
||||
use gateway_core::account::resolve_account_status;
|
||||
|
||||
AccountPageItem {
|
||||
model_cooldowns: Vec::new(),
|
||||
platform_icon: None,
|
||||
protection_rules: Vec::new(),
|
||||
account: AccountRecord {
|
||||
|
||||
@@ -564,6 +564,7 @@ mod provider {
|
||||
last_error_message: None,
|
||||
};
|
||||
AccountPageItem {
|
||||
model_cooldowns: Vec::new(),
|
||||
platform_icon: None,
|
||||
protection_rules: Vec::new(),
|
||||
capacity: gateway_admin::model::accounts::AccountCapacity {
|
||||
|
||||
@@ -1484,6 +1484,7 @@ impl AccountRuntimeStore for UnusedStore {
|
||||
|
||||
async fn active_rate_limits(&self) -> AdminStoreResult<AccountRuntimeSnapshot> {
|
||||
Ok(AccountRuntimeSnapshot {
|
||||
model_cooldowns: BTreeMap::new(),
|
||||
cooldown: BTreeMap::new(),
|
||||
protection_rules: BTreeMap::new(),
|
||||
in_flight: Some(BTreeMap::new()),
|
||||
@@ -1492,6 +1493,7 @@ impl AccountRuntimeStore for UnusedStore {
|
||||
|
||||
async fn account_runtime(&self, _: &[String]) -> AdminStoreResult<AccountRuntimeSnapshot> {
|
||||
Ok(AccountRuntimeSnapshot {
|
||||
model_cooldowns: BTreeMap::new(),
|
||||
cooldown: BTreeMap::new(),
|
||||
protection_rules: BTreeMap::new(),
|
||||
in_flight: Some(BTreeMap::new()),
|
||||
|
||||
@@ -24,6 +24,27 @@ use tower::ServiceExt as _;
|
||||
|
||||
use super::{AdminTestFixture, AdminTestState, unavailable_system};
|
||||
|
||||
#[tokio::test]
|
||||
async fn version_should_expose_runtime_identity_and_restart_capability() {
|
||||
let fixture = crate::support::key_fixture().await;
|
||||
fixture.auth.insert_session("valid-session");
|
||||
let response = app(fixture.state())
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.uri("/api/admin/system/version")
|
||||
.header(header::COOKIE, "cpr_session=valid-session")
|
||||
.header("x-request-id", "req_system_version")
|
||||
.body(Body::empty())
|
||||
.expect("version request"),
|
||||
)
|
||||
.await
|
||||
.expect("version response");
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
let body = crate::support::response_json(response).await;
|
||||
assert_eq!(body["data"]["instanceId"], "test-instance");
|
||||
assert_eq!(body["data"]["restartSupported"], true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn update_detail_query_should_default_to_no_refresh_and_reject_unknown_fields() {
|
||||
let query: UpdateDetailQuery = serde_json::from_str("{}").expect("empty query object");
|
||||
|
||||
@@ -256,12 +256,21 @@ async fn request_middleware_sees_original_chat_and_preserves_the_endpoint() {
|
||||
let mut execution = Execution::new(Session::new(vec![created(), completed("ok")]));
|
||||
execution.middleware = Some(middleware.frozen());
|
||||
let fixture = Fixture::with_execution(execution).await;
|
||||
let response = fixture.post(chat_request(false)).await;
|
||||
let mut request = chat_request(false);
|
||||
request["stream_options"] = json!({"include_usage":true});
|
||||
request["messages"] = json!([
|
||||
{"role":"developer","content":"brief"},
|
||||
{"role":"system","content":null},
|
||||
{"role":"assistant","tool_calls":[]},
|
||||
{"role":"user","content":[{"type":"text","text":null},{"type":"text","text":"hello"}]},
|
||||
{"role":"tool","name":"notifications","namespace":"agent","content":"notice"}
|
||||
]);
|
||||
let response = fixture.post(request.clone()).await;
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
let downstream = json_body(response).await;
|
||||
assert_eq!(downstream["object"], "chat.completion");
|
||||
let observed = middleware.requests.lock().unwrap();
|
||||
assert_eq!(observed.as_slice(), [chat_request(false)]);
|
||||
assert_eq!(observed.as_slice(), [request]);
|
||||
assert_eq!(
|
||||
middleware.inner.endpoints.lock().unwrap().as_slice(),
|
||||
[PATH]
|
||||
|
||||
@@ -384,10 +384,14 @@ fn engine_provider_error_should_preserve_retry_classification() {
|
||||
|
||||
#[test]
|
||||
fn local_provider_capacity_exhaustion_should_map_to_service_unavailable() {
|
||||
let error = EngineError::Provider(ProviderError::new(
|
||||
ProviderErrorKind::AccountCapacityUnavailable,
|
||||
UpstreamSendState::NotSent,
|
||||
));
|
||||
let error = EngineError::Provider(
|
||||
ProviderError::new(
|
||||
ProviderErrorKind::AccountCapacityUnavailable,
|
||||
UpstreamSendState::NotSent,
|
||||
)
|
||||
.with_retry_after(std::time::Duration::from_millis(7100)),
|
||||
);
|
||||
assert_eq!(engine_error_response(&error).headers()["retry-after"], "8");
|
||||
|
||||
let projected = gateway_error_from_engine(&error);
|
||||
assert_eq!(
|
||||
@@ -396,16 +400,16 @@ fn local_provider_capacity_exhaustion_should_map_to_service_unavailable() {
|
||||
);
|
||||
assert_eq!(
|
||||
projected.safe_message(),
|
||||
"The gateway account pool is busy."
|
||||
"No eligible account currently has capacity for this request."
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_eligible_provider_account_should_preserve_safe_provider_detail() {
|
||||
#[tokio::test]
|
||||
async fn no_eligible_provider_account_should_preserve_safe_provider_detail() {
|
||||
let detail = ClientVisibleUpstreamError::new(
|
||||
"no account is eligible for the requested model",
|
||||
Some("no_eligible_account".to_owned()),
|
||||
Some("account_unavailable_error".to_owned()),
|
||||
"This request requires an upstream WebSocket.",
|
||||
Some("websocket_account_unavailable".to_owned()),
|
||||
None,
|
||||
);
|
||||
let error = EngineError::Provider(
|
||||
ProviderError::new(
|
||||
@@ -419,17 +423,24 @@ fn no_eligible_provider_account_should_preserve_safe_provider_detail() {
|
||||
assert_eq!(gateway.kind(), GatewayErrorKind::NoAvailableProvider);
|
||||
assert_eq!(
|
||||
gateway.client_message(),
|
||||
"no account is eligible for the requested model"
|
||||
"This request requires an upstream WebSocket."
|
||||
);
|
||||
assert_eq!(gateway.client_error_code(), Some("no_eligible_account"));
|
||||
assert_eq!(
|
||||
gateway.client_error_type(),
|
||||
Some("account_unavailable_error")
|
||||
gateway.client_error_code(),
|
||||
Some("websocket_account_unavailable")
|
||||
);
|
||||
assert_eq!(gateway.client_error_type(), None);
|
||||
assert_eq!(
|
||||
gateway.safe_message(),
|
||||
"The gateway found no eligible account for this request."
|
||||
);
|
||||
let response = engine_error_response(&error);
|
||||
assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
|
||||
let body: serde_json::Value =
|
||||
serde_json::from_slice(&to_bytes(response.into_body(), usize::MAX).await.unwrap()).unwrap();
|
||||
assert_eq!(body["error"]["type"], "server_error");
|
||||
assert_eq!(body["error"]["code"], "websocket_account_unavailable");
|
||||
assert_eq!(body["error"]["message"], gateway.client_message());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -508,6 +519,7 @@ fn engine_provider_unsupported_capability_should_remain_unsupported() {
|
||||
|
||||
#[test]
|
||||
fn engine_provider_credential_failures_should_not_impersonate_client_auth_failures() {
|
||||
let mut messages = std::collections::HashSet::new();
|
||||
for kind in [
|
||||
ProviderErrorKind::Unauthorized,
|
||||
ProviderErrorKind::PermissionDenied,
|
||||
@@ -516,11 +528,19 @@ fn engine_provider_credential_failures_should_not_impersonate_client_auth_failur
|
||||
let mapped = gateway_error_from_engine(&error);
|
||||
|
||||
assert_eq!(mapped.kind(), GatewayErrorKind::UpstreamUnavailable);
|
||||
assert_eq!(
|
||||
mapped.safe_message(),
|
||||
"The upstream account cannot access the service."
|
||||
assert!(
|
||||
mapped
|
||||
.safe_message()
|
||||
.to_lowercase()
|
||||
.contains("upstream account")
|
||||
);
|
||||
messages.insert(mapped.safe_message().to_owned());
|
||||
}
|
||||
assert_eq!(
|
||||
messages.len(),
|
||||
2,
|
||||
"authentication and permission failures must be distinguishable"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -577,19 +597,29 @@ fn engine_provider_timeout_and_cancellation_should_remain_distinct() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn engine_provider_runtime_failures_should_collapse_to_safe_unavailability() {
|
||||
fn engine_provider_runtime_failures_preserve_the_cause_without_exposing_internal_details() {
|
||||
let mut messages = std::collections::HashSet::new();
|
||||
for kind in [
|
||||
ProviderErrorKind::Transport,
|
||||
ProviderErrorKind::Protocol,
|
||||
ProviderErrorKind::Unavailable,
|
||||
ProviderErrorKind::ProcessTerminated,
|
||||
] {
|
||||
let error = EngineError::Provider(ProviderError::new(kind, UpstreamSendState::Ambiguous));
|
||||
let error = EngineError::Provider(
|
||||
ProviderError::new(kind, UpstreamSendState::Ambiguous)
|
||||
.with_source(std::io::Error::other("PRIVATE_ENDPOINT_AND_CREDENTIAL")),
|
||||
);
|
||||
|
||||
let projected = gateway_error_from_engine(&error);
|
||||
assert_eq!(projected.kind(), GatewayErrorKind::UpstreamUnavailable);
|
||||
assert_eq!(projected.safe_message(), "Upstream service is unavailable.");
|
||||
assert!(!projected.client_message().contains("PRIVATE_"));
|
||||
messages.insert(projected.client_message().to_owned());
|
||||
}
|
||||
assert_eq!(
|
||||
messages.len(),
|
||||
4,
|
||||
"different failure causes must remain distinguishable"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -334,7 +334,7 @@ async fn request_settings_reach_query_terminal_without_mutating_authenticated_ba
|
||||
runtime["account_queue_timeout_seconds"] = serde_json::json!(30);
|
||||
runtime["switch_account_on_queue_failure"] = serde_json::json!(false);
|
||||
settings.runtime = serde_json::from_value(runtime).unwrap();
|
||||
settings.fast_mode = FastMode::Disabled;
|
||||
settings.fast_mode = Some(FastMode::Disabled);
|
||||
}),
|
||||
..Default::default()
|
||||
}));
|
||||
@@ -355,8 +355,12 @@ async fn request_settings_reach_query_terminal_without_mutating_authenticated_ba
|
||||
"model-a"
|
||||
);
|
||||
assert_ne!(
|
||||
execution.client.policy().account_scope().fast_mode(),
|
||||
FastMode::Disabled
|
||||
execution
|
||||
.client
|
||||
.policy()
|
||||
.account_scope()
|
||||
.fast_mode_override(),
|
||||
Some(FastMode::Disabled)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -91,6 +91,7 @@ async fn fixture(sharing: ClientPeerSharing, plaintext: &str) -> (AdminTestFixtu
|
||||
last_error_message: None,
|
||||
};
|
||||
*fixture.account.lock().unwrap() = Some(AccountPageItem {
|
||||
model_cooldowns: Vec::new(),
|
||||
platform_icon: None,
|
||||
protection_rules: Vec::new(),
|
||||
capacity: AccountCapacity {
|
||||
|
||||
@@ -3300,6 +3300,12 @@ async fn response_ids_are_provider_and_client_independent() {
|
||||
(&[], MODEL_REQUEST_ID),
|
||||
(&[("x-request-id", "upstream-primary")], "upstream-primary"),
|
||||
(&[("x-oai-request-id", "upstream-alias")], "upstream-alias"),
|
||||
(
|
||||
&[("x-openai-request-id", "upstream-openai")],
|
||||
"upstream-openai",
|
||||
),
|
||||
(&[("x-ms-request-id", "upstream-ms")], "upstream-ms"),
|
||||
(&[("cf-ray", "trace-only")], MODEL_REQUEST_ID),
|
||||
(
|
||||
&[
|
||||
("x-request-id", "upstream-primary"),
|
||||
@@ -3315,6 +3321,22 @@ async fn response_ids_are_provider_and_client_independent() {
|
||||
"upstream-alias",
|
||||
),
|
||||
(&[("x-request-id", "")], MODEL_REQUEST_ID),
|
||||
(
|
||||
&[
|
||||
("x-request-id", "é"),
|
||||
("x-oai-request-id", " "),
|
||||
("x-openai-request-id", ""),
|
||||
("x-ms-request-id", "upstream-ms"),
|
||||
],
|
||||
"upstream-ms",
|
||||
),
|
||||
(
|
||||
&[
|
||||
("x-openai-request-id", "upstream-openai"),
|
||||
("x-ms-request-id", "upstream-ms"),
|
||||
],
|
||||
"upstream-openai",
|
||||
),
|
||||
];
|
||||
for provider in ["openai", "xai"] {
|
||||
for streaming in [false, true] {
|
||||
@@ -3343,6 +3365,11 @@ async fn response_ids_are_provider_and_client_independent() {
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
assert_eq!(response.headers()["x-request-id"], *expected);
|
||||
assert_eq!(response.headers()["x-gateway-request-id"], MODEL_REQUEST_ID);
|
||||
for (name, value) in *upstream_headers {
|
||||
if *name != "x-request-id" {
|
||||
assert_eq!(response.headers()[*name].as_bytes(), value.as_bytes());
|
||||
}
|
||||
}
|
||||
assert!(
|
||||
!to_bytes(response.into_body(), 64 * 1024)
|
||||
.await
|
||||
@@ -3359,7 +3386,12 @@ async fn failure_ids_prefer_the_actual_error_over_session_headers() {
|
||||
let admin = crate::admin::AdminTestFixture::new().await.services;
|
||||
for provider in ["openai", "xai"] {
|
||||
for streaming in [false, true] {
|
||||
for upstream_headers in [vec![], headers(&[("x-oai-request-id", "actual-error")])] {
|
||||
for upstream_headers in [
|
||||
vec![],
|
||||
headers(&[("x-oai-request-id", "actual-error")]),
|
||||
headers(&[("x-openai-request-id", "actual-error")]),
|
||||
headers(&[("x-ms-request-id", "actual-error")]),
|
||||
] {
|
||||
let expected = if upstream_headers.is_empty() {
|
||||
MODEL_REQUEST_ID
|
||||
} else {
|
||||
@@ -3367,7 +3399,7 @@ async fn failure_ids_prefer_the_actual_error_over_session_headers() {
|
||||
};
|
||||
let raw =
|
||||
Bytes::from_static(br#"{"error":{"message":"synthetic upstream detail"}}"#);
|
||||
let error =
|
||||
let mut error =
|
||||
ProviderError::new(ProviderErrorKind::InvalidRequest, UpstreamSendState::Sent)
|
||||
.with_client_visible_upstream_response(
|
||||
ClientVisibleUpstreamResponse::new(
|
||||
@@ -3377,12 +3409,25 @@ async fn failure_ids_prefer_the_actual_error_over_session_headers() {
|
||||
)
|
||||
.with_headers(upstream_headers),
|
||||
);
|
||||
if expected == "actual-error" {
|
||||
// 最终响应头优先于错误对象中残留的旧观测 ID
|
||||
error = error.with_upstream_request_id(OpaqueUpstreamValue::new("stale-fact"));
|
||||
}
|
||||
let session = failed_session(streaming, EngineError::Provider(error))
|
||||
.with_response_headers(headers(&[("x-request-id", "earlier-session")]));
|
||||
.with_response_headers(headers(&[
|
||||
("x-request-id", "earlier-session"),
|
||||
("x-openai-request-id", "earlier-openai"),
|
||||
("x-ms-request-id", "earlier-ms"),
|
||||
]));
|
||||
let response = response(&admin, provider, session, streaming).await;
|
||||
assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
|
||||
assert_eq!(response.headers()["x-request-id"], expected);
|
||||
assert_eq!(response.headers()["x-gateway-request-id"], MODEL_REQUEST_ID);
|
||||
for name in ["x-openai-request-id", "x-ms-request-id"] {
|
||||
if let Some(value) = response.headers().get(name) {
|
||||
assert_eq!(value, "actual-error");
|
||||
}
|
||||
}
|
||||
assert_eq!(to_bytes(response.into_body(), 4096).await.unwrap(), raw);
|
||||
}
|
||||
|
||||
@@ -3394,12 +3439,16 @@ async fn failure_ids_prefer_the_actual_error_over_session_headers() {
|
||||
.with_response_headers(headers(&[
|
||||
("x-request-id", "earlier-session"),
|
||||
("x-oai-request-id", "earlier-alias"),
|
||||
("x-openai-request-id", "earlier-openai"),
|
||||
("x-ms-request-id", "earlier-ms"),
|
||||
]));
|
||||
let response = response(&admin, provider, session, streaming).await;
|
||||
assert_eq!(response.status(), StatusCode::BAD_GATEWAY);
|
||||
assert_eq!(response.headers()["x-request-id"], "body-read-error");
|
||||
assert_eq!(response.headers().get_all("x-request-id").iter().count(), 1);
|
||||
assert!(response.headers().get("x-oai-request-id").is_none());
|
||||
assert!(response.headers().get("x-openai-request-id").is_none());
|
||||
assert!(response.headers().get("x-ms-request-id").is_none());
|
||||
assert_eq!(response.headers()["x-gateway-request-id"], MODEL_REQUEST_ID);
|
||||
}
|
||||
}
|
||||
@@ -3414,12 +3463,16 @@ async fn local_execution_failure_uses_the_existing_model_id() {
|
||||
failed_session(streaming, EngineError::Deadline).with_response_headers(headers(&[
|
||||
("x-request-id", "opening-primary"),
|
||||
("x-oai-request-id", "opening-alias"),
|
||||
("x-openai-request-id", "opening-openai"),
|
||||
("x-ms-request-id", "opening-ms"),
|
||||
("x-codex-turn-state", "retained-turn-state"),
|
||||
]));
|
||||
let response = response(&admin, provider, session, streaming).await;
|
||||
assert_eq!(response.headers()["x-request-id"], MODEL_REQUEST_ID);
|
||||
assert_eq!(response.headers()["x-gateway-request-id"], MODEL_REQUEST_ID);
|
||||
assert!(response.headers().get("x-oai-request-id").is_none());
|
||||
assert!(response.headers().get("x-openai-request-id").is_none());
|
||||
assert!(response.headers().get("x-ms-request-id").is_none());
|
||||
assert_eq!(
|
||||
response.headers()["x-codex-turn-state"],
|
||||
"retained-turn-state"
|
||||
|
||||
@@ -369,23 +369,25 @@ async fn classified_capacity_error_without_special_code_returns_retryable_websoc
|
||||
|
||||
#[tokio::test]
|
||||
async fn final_failure_headers_take_precedence_over_observed_opening_headers() {
|
||||
let provider = upstream_failure(403, b"", vec![header("x-oai-request-id", b"req_final")])
|
||||
.with_status(502)
|
||||
.with_upstream_request_id(OpaqueUpstreamValue::new("req_stale_fact"));
|
||||
let error = initial_error(
|
||||
EngineError::Provider(provider),
|
||||
vec![
|
||||
header("x-request-id", b"req_old_opening"),
|
||||
header("x-codex-turn-state", b"old-turn-state"),
|
||||
],
|
||||
)
|
||||
.await;
|
||||
assert_eq!(error["status"], 403);
|
||||
assert_eq!(error["headers"]["x-oai-request-id"], "req_final");
|
||||
assert!(error["headers"].get("x-request-id").is_none());
|
||||
assert!(!error.to_string().contains("req_old_opening"));
|
||||
assert!(!error.to_string().contains("req_stale_fact"));
|
||||
assert!(!error.to_string().contains("old-turn-state"));
|
||||
for name in ["x-oai-request-id", "x-openai-request-id", "x-ms-request-id"] {
|
||||
let provider = upstream_failure(403, b"", vec![header(name, b"req_final")])
|
||||
.with_status(502)
|
||||
.with_upstream_request_id(OpaqueUpstreamValue::new("req_stale_fact"));
|
||||
let error = initial_error(
|
||||
EngineError::Provider(provider),
|
||||
vec![
|
||||
header("x-request-id", b"req_old_opening"),
|
||||
header("x-codex-turn-state", b"old-turn-state"),
|
||||
],
|
||||
)
|
||||
.await;
|
||||
assert_eq!(error["status"], 403);
|
||||
assert_eq!(error["headers"][name], "req_final");
|
||||
assert!(error["headers"].get("x-request-id").is_none());
|
||||
assert!(!error.to_string().contains("req_old_opening"));
|
||||
assert!(!error.to_string().contains("req_stale_fact"));
|
||||
assert!(!error.to_string().contains("old-turn-state"));
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -398,6 +400,8 @@ async fn provider_failure_facts_survive_without_a_complete_http_response() {
|
||||
vec![
|
||||
header("x-request-id", b"req_old"),
|
||||
header("x-oai-request-id", b"req_old_alias"),
|
||||
header("x-openai-request-id", b"req_old_openai"),
|
||||
header("x-ms-request-id", b"req_old_ms"),
|
||||
header("x-codex-turn-state", b"observed-turn-state"),
|
||||
],
|
||||
)
|
||||
@@ -409,9 +413,11 @@ async fn provider_failure_facts_survive_without_a_complete_http_response() {
|
||||
"observed-turn-state"
|
||||
);
|
||||
assert!(error["headers"].get("x-oai-request-id").is_none());
|
||||
assert!(error["headers"].get("x-openai-request-id").is_none());
|
||||
assert!(error["headers"].get("x-ms-request-id").is_none());
|
||||
assert_eq!(
|
||||
error["error"]["message"],
|
||||
"Upstream service is unavailable."
|
||||
"Communication with the upstream service failed."
|
||||
);
|
||||
}
|
||||
|
||||
@@ -511,6 +517,8 @@ async fn opening_ids_stay_in_metadata_but_do_not_identify_initial_failures() {
|
||||
vec![
|
||||
header("x-request-id", b"req_old_opening"),
|
||||
header("x-oai-request-id", b"req_observed"),
|
||||
header("x-openai-request-id", b"req_observed_openai"),
|
||||
header("x-ms-request-id", b"req_observed_ms"),
|
||||
header("x-codex-turn-state", b"observed-turn-state"),
|
||||
header("x-future-header", b"future-value"),
|
||||
],
|
||||
@@ -525,6 +533,8 @@ async fn opening_ids_stay_in_metadata_but_do_not_identify_initial_failures() {
|
||||
"headers": {
|
||||
"x-request-id": "req_old_opening",
|
||||
"x-oai-request-id": "req_observed",
|
||||
"x-openai-request-id": "req_observed_openai",
|
||||
"x-ms-request-id": "req_observed_ms",
|
||||
"x-codex-turn-state": "observed-turn-state",
|
||||
"x-future-header": "future-value",
|
||||
},
|
||||
@@ -548,6 +558,46 @@ async fn opening_ids_stay_in_metadata_but_do_not_identify_initial_failures() {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn metadata_prefers_readable_upstream_aliases_before_the_model_id() {
|
||||
let cases: &[(&str, &[u8], Option<&str>)] = &[
|
||||
("x-oai-request-id", b"req_oai", Some("req_oai")),
|
||||
("X-OpenAI-Request-ID", b"req_openai", Some("req_openai")),
|
||||
("x-ms-request-id", b"req_ms", Some("req_ms")),
|
||||
("x-ms-request-id", b" \t ", None),
|
||||
("x-ms-request-id", b"\xc3\xa9", None),
|
||||
];
|
||||
for (name, value, expected) in cases {
|
||||
let trace = Arc::new(AtomicFailureTrace {
|
||||
initial_errors: Mutex::new(VecDeque::from([EngineError::Deadline])),
|
||||
..AtomicFailureTrace::default()
|
||||
});
|
||||
let (mut socket, _server) = connect(
|
||||
Arc::clone(&trace),
|
||||
vec![header("x-request-id", b"\xff"), header(name, value)],
|
||||
)
|
||||
.await;
|
||||
send_request(&mut socket).await;
|
||||
let metadata = next_event(&mut socket).await;
|
||||
assert_eq!(metadata["type"], "response.metadata");
|
||||
let model_id = trace.prepared_request_id.lock().unwrap().clone().unwrap();
|
||||
assert_eq!(
|
||||
metadata["headers"]["x-request-id"],
|
||||
expected.unwrap_or(&model_id)
|
||||
);
|
||||
assert_eq!(
|
||||
metadata["headers"][name.to_ascii_lowercase()].as_str(),
|
||||
*expected
|
||||
);
|
||||
let error = next_event(&mut socket).await;
|
||||
assert_eq!(error["type"], "error");
|
||||
assert_eq!(error["headers"]["x-request-id"], "req_ws_atomic");
|
||||
assert_eq!(error["headers"]["x-gateway-request-id"], "req_ws_atomic");
|
||||
assert!(error["headers"].get(name.to_ascii_lowercase()).is_none());
|
||||
socket.close(None).await.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn header_only_request_middleware_updates_websocket_turn_context() {
|
||||
let middleware = Arc::new(crate::data_plane::middleware::RequestMiddleware {
|
||||
@@ -746,13 +796,38 @@ async fn initial_continuation_recovery_delivers_the_official_client_replay_signa
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn locally_exhausted_account_pool_sends_one_official_usage_limit_error() {
|
||||
let provider = ProviderError::new(
|
||||
async fn account_selection_errors_distinguish_quota_from_websocket_requirements() {
|
||||
let exhausted = ProviderError::new(
|
||||
ProviderErrorKind::AccountPoolQuotaExhausted,
|
||||
UpstreamSendState::NotSent,
|
||||
);
|
||||
let error = initial_error(EngineError::Provider(provider), Vec::new()).await;
|
||||
assert_eq!(error["status"], 429);
|
||||
assert_eq!(error["error"]["type"], "usage_limit_reached");
|
||||
assert_eq!(error["error"]["code"], "usage_limit_reached");
|
||||
let incompatible = ProviderError::new(
|
||||
ProviderErrorKind::NoEligibleAccount,
|
||||
UpstreamSendState::NotSent,
|
||||
)
|
||||
.with_client_visible_upstream_error(ClientVisibleUpstreamError::new(
|
||||
"This request requires an upstream WebSocket.",
|
||||
Some("websocket_account_unavailable".to_owned()),
|
||||
None,
|
||||
));
|
||||
for (provider, status, kind, code) in [
|
||||
(exhausted, 429, "usage_limit_reached", "usage_limit_reached"),
|
||||
(
|
||||
incompatible,
|
||||
503,
|
||||
"server_error",
|
||||
"websocket_account_unavailable",
|
||||
),
|
||||
] {
|
||||
let error = initial_error(EngineError::Provider(provider), Vec::new()).await;
|
||||
assert_eq!(error["status"], status);
|
||||
assert_eq!(error["error"]["type"], kind);
|
||||
assert_eq!(error["error"]["code"], code);
|
||||
if status == 503 {
|
||||
assert_eq!(
|
||||
error["error"]["message"],
|
||||
"This request requires an upstream WebSocket."
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -313,6 +313,7 @@ fn response_create_should_reject_non_boolean_stream_without_disclosing_body_valu
|
||||
|
||||
#[derive(Default)]
|
||||
struct AtomicFailureTrace {
|
||||
prepared_request_id: Mutex<Option<String>>,
|
||||
starts: AtomicUsize,
|
||||
next_calls: AtomicUsize,
|
||||
committed: AtomicBool,
|
||||
@@ -414,8 +415,9 @@ struct AtomicFailureExecution {
|
||||
impl ExecutionService for AtomicFailureExecution {
|
||||
fn middleware_plan(
|
||||
&self,
|
||||
_: &gateway_core::engine::execution::PreparedRootExecution,
|
||||
prepared: &gateway_core::engine::execution::PreparedRootExecution,
|
||||
) -> Option<gateway_core::engine::middleware::FrozenMiddlewarePlan> {
|
||||
*self.trace.prepared_request_id.lock().unwrap() = Some(prepared.request_id().to_string());
|
||||
self.trace.middleware.clone()
|
||||
}
|
||||
|
||||
|
||||
@@ -255,3 +255,71 @@ async fn original_rejected_request_is_dumped_only_when_explicitly_enabled() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn responses_ingress_separates_body_receipt_from_decompression_and_decoding() {
|
||||
use std::io::Write as _;
|
||||
use tracing::instrument::WithSubscriber as _;
|
||||
|
||||
let recorder = Recorder {
|
||||
dump_enabled: false,
|
||||
events: Arc::default(),
|
||||
};
|
||||
let events = recorder.events.clone();
|
||||
let decoded = json!({"model":42,"input":"SENSITIVE_CONTENT".repeat(1024)}).to_string();
|
||||
let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast());
|
||||
encoder.write_all(decoded.as_bytes()).unwrap();
|
||||
let encoded = encoder.finish().unwrap();
|
||||
let encoded_len = encoded.len();
|
||||
assert!(encoded_len < decoded.len());
|
||||
async {
|
||||
let (router, _) = fixture().await;
|
||||
let body = Body::from_stream(futures::stream::once(async move {
|
||||
tokio::time::sleep(std::time::Duration::from_millis(40)).await;
|
||||
Ok::<_, std::io::Error>(encoded)
|
||||
}));
|
||||
let response = router
|
||||
.oneshot(
|
||||
Request::post("/v1/responses")
|
||||
.header("authorization", "Bearer unused-client-route-key")
|
||||
.header("content-encoding", "gzip")
|
||||
.body(body)
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
|
||||
}
|
||||
.with_subscriber(recorder)
|
||||
.await;
|
||||
let events = events.lock().unwrap();
|
||||
let phases = events
|
||||
.iter()
|
||||
.filter(|event| {
|
||||
event.get("stage").is_some_and(|stage| {
|
||||
stage.starts_with("http.body.") || stage == "http.auth.finished"
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(
|
||||
phases
|
||||
.iter()
|
||||
.map(|event| event["stage"].as_str())
|
||||
.collect::<Vec<_>>(),
|
||||
[
|
||||
"http.body.received",
|
||||
"http.auth.finished",
|
||||
"http.body.decompressed",
|
||||
"http.body.decoded",
|
||||
]
|
||||
);
|
||||
assert!(phases[0]["receive_ms"].parse::<u64>().unwrap() >= 30);
|
||||
assert_eq!(phases[0]["encoded_bytes"], encoded_len.to_string());
|
||||
assert_eq!(phases[0]["content_encoding"], "gzip");
|
||||
assert_eq!(phases[2]["decoded_bytes"], decoded.len().to_string());
|
||||
assert_eq!(phases[2]["accepted"], "true");
|
||||
assert_eq!(phases[3]["accepted"], "false");
|
||||
assert!(events.iter().flat_map(|event| event.values()).all(|value| {
|
||||
!value.contains("SENSITIVE_CONTENT") && !value.contains("unused-client-route-key")
|
||||
}));
|
||||
}
|
||||
@@ -91,6 +91,8 @@ impl SystemOperations for VersionSystem {
|
||||
async fn version(&self) -> Result<SystemVersion, SystemOperationError> {
|
||||
Ok(SystemVersion {
|
||||
version: "3.7.0".to_owned(),
|
||||
instance_id: "test-instance".to_owned(),
|
||||
restart_supported: true,
|
||||
git_sha: "internal-revision".to_owned(),
|
||||
build_time: "internal-build-time".to_owned(),
|
||||
deployment_mode: "binary".to_owned(),
|
||||
|
||||
@@ -108,6 +108,7 @@ pub struct RuntimeAccountDirectory {
|
||||
providers_with_accounts: BTreeSet<ProviderKind>,
|
||||
providers_by_group: BTreeMap<AccountGroupId, BTreeSet<ProviderKind>>,
|
||||
group_model_access: BTreeMap<AccountGroupId, AccountModelAccess>,
|
||||
group_fast_modes: BTreeMap<AccountGroupId, FastMode>,
|
||||
}
|
||||
|
||||
impl RuntimeAccountDirectory {
|
||||
@@ -129,6 +130,7 @@ impl RuntimeAccountDirectory {
|
||||
providers_with_accounts,
|
||||
providers_by_group,
|
||||
group_model_access: BTreeMap::new(),
|
||||
group_fast_modes: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -141,6 +143,12 @@ impl RuntimeAccountDirectory {
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn with_group_fast_modes(mut self, policies: BTreeMap<AccountGroupId, FastMode>) -> Self {
|
||||
self.group_fast_modes = policies;
|
||||
self
|
||||
}
|
||||
|
||||
pub(crate) fn accounts_in_group(
|
||||
&self,
|
||||
group: &AccountGroupId,
|
||||
@@ -288,7 +296,7 @@ impl ClientRoutingScope {
|
||||
pub struct FrozenAccountScope {
|
||||
allow_image_generation: bool,
|
||||
allow_subagents: bool,
|
||||
fast_mode: FastMode,
|
||||
fast_mode_override: Option<FastMode>,
|
||||
request_profiles: BTreeMap<ProviderKind, super::OpaqueProviderData>,
|
||||
directory: Arc<RuntimeAccountDirectory>,
|
||||
client_scope: ClientRoutingScope,
|
||||
@@ -355,16 +363,34 @@ impl FrozenAccountScope {
|
||||
self
|
||||
}
|
||||
|
||||
/// Key 绑定分组的冻结 Fast 策略,与账号成员资格无关
|
||||
/// 显式请求覆盖独立于分组策略;None 表示按选中账号的有效分组计算
|
||||
#[must_use]
|
||||
pub const fn with_fast_mode(mut self, fast_mode: FastMode) -> Self {
|
||||
self.fast_mode = fast_mode;
|
||||
pub const fn with_fast_mode_override(mut self, fast_mode: Option<FastMode>) -> Self {
|
||||
self.fast_mode_override = fast_mode;
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn fast_mode(&self) -> FastMode {
|
||||
self.fast_mode
|
||||
pub const fn fast_mode_override(&self) -> Option<FastMode> {
|
||||
self.fast_mode_override
|
||||
}
|
||||
|
||||
/// 只合并当前 Key 授权该账号与模型的启用分组,换号仍使用同一冻结目录
|
||||
#[must_use]
|
||||
pub fn fast_mode_for_account(
|
||||
&self,
|
||||
account_id: &ProviderAccountId,
|
||||
upstream_model: &str,
|
||||
) -> FastMode {
|
||||
if let Some(mode) = self.fast_mode_override {
|
||||
return mode;
|
||||
}
|
||||
let Some(account) = self.directory.account(account_id) else {
|
||||
return FastMode::Default;
|
||||
};
|
||||
self.matching_groups(account, |access| access.allows(upstream_model))
|
||||
.filter_map(|id| self.directory.group_fast_modes.get(id))
|
||||
.fold(FastMode::Default, |mode, other| mode.merge(*other))
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
@@ -376,7 +402,7 @@ impl FrozenAccountScope {
|
||||
Self {
|
||||
allow_image_generation: true,
|
||||
allow_subagents: true,
|
||||
fast_mode: FastMode::Default,
|
||||
fast_mode_override: None,
|
||||
request_profiles: BTreeMap::new(),
|
||||
directory,
|
||||
client_scope,
|
||||
@@ -460,18 +486,31 @@ impl FrozenAccountScope {
|
||||
}
|
||||
match &self.client_scope {
|
||||
ClientRoutingScope::AllAccounts => true,
|
||||
ClientRoutingScope::Restricted { .. } => {
|
||||
self.matching_groups(account, accepts).next().is_some()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn matching_groups<'a>(
|
||||
&'a self,
|
||||
account: &'a RuntimeAccount,
|
||||
accepts: impl Fn(&AccountModelAccess) -> bool + 'a,
|
||||
) -> impl Iterator<Item = &'a AccountGroupId> {
|
||||
let enabled = match &self.client_scope {
|
||||
ClientRoutingScope::AllAccounts => None,
|
||||
ClientRoutingScope::Restricted {
|
||||
enabled_group_ids, ..
|
||||
} => account
|
||||
.group_ids()
|
||||
.intersection(enabled_group_ids)
|
||||
.any(|id| {
|
||||
self.directory
|
||||
.group_model_access
|
||||
.get(id)
|
||||
.is_none_or(&accepts)
|
||||
}),
|
||||
}
|
||||
} => Some(enabled_group_ids),
|
||||
};
|
||||
account.group_ids().iter().filter(move |id| {
|
||||
enabled.is_some_and(|groups| groups.contains(*id))
|
||||
&& self
|
||||
.directory
|
||||
.group_model_access
|
||||
.get(*id)
|
||||
.is_none_or(&accepts)
|
||||
})
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
|
||||
@@ -1200,7 +1200,6 @@ where
|
||||
.with_lease_metadata(Arc::clone(&self.lease_metadata))
|
||||
.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())
|
||||
|
||||
@@ -48,11 +48,17 @@ pub(super) fn map_routing_error(error: crate::validation::RoutingError) -> Gatew
|
||||
"Mapped model unavailable for this API key. Check the model mapping."
|
||||
},
|
||||
),
|
||||
crate::validation::RoutingError::NoCapableProvider { .. }
|
||||
| crate::validation::RoutingError::NoCapableProviderEndpoint { .. }
|
||||
| crate::validation::RoutingError::EmptyAccountScope => GatewayError::new(
|
||||
crate::validation::RoutingError::NoCapableProvider { .. } => GatewayError::new(
|
||||
GatewayErrorKind::NoAvailableProvider,
|
||||
"The gateway has no eligible provider for this request.",
|
||||
"The gateway cannot select a provider for this model and the requested capabilities.",
|
||||
),
|
||||
crate::validation::RoutingError::NoCapableProviderEndpoint { .. } => GatewayError::new(
|
||||
GatewayErrorKind::NoAvailableProvider,
|
||||
"No eligible provider is available for the requested API endpoint.",
|
||||
),
|
||||
crate::validation::RoutingError::EmptyAccountScope => GatewayError::new(
|
||||
GatewayErrorKind::NoAvailableProvider,
|
||||
"This API key has no accounts in its scope. Add accounts or check its enabled account groups.",
|
||||
),
|
||||
crate::validation::RoutingError::UnsupportedProviderEndpoint { .. } => GatewayError::new(
|
||||
GatewayErrorKind::Unsupported,
|
||||
|
||||
@@ -330,7 +330,6 @@ pub struct RequestAttemptContext {
|
||||
prompt_rewrite_rules: Option<Arc<crate::settings::prompt_rewrite::ProviderPromptRules>>,
|
||||
pricing: Arc<crate::metering::PricingOverrides>,
|
||||
request_profile: Option<crate::account::OpaqueProviderData>,
|
||||
fast_mode: FastMode,
|
||||
openai_websocket_pool: crate::settings::OpenAiWebSocketPoolSettings,
|
||||
openai_request_settings: crate::settings::OpenAiRequestSettings,
|
||||
request_location: Option<crate::account::RequestLocation>,
|
||||
@@ -424,12 +423,6 @@ impl RequestAttemptContext {
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn with_fast_mode(mut self, fast_mode: FastMode) -> Self {
|
||||
self.fast_mode = fast_mode;
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn with_privacy(
|
||||
mut self,
|
||||
@@ -478,7 +471,6 @@ impl RequestAttemptContext {
|
||||
request_profile: None,
|
||||
prompt_rewrite_rules: None,
|
||||
pricing: Arc::default(),
|
||||
fast_mode: FastMode::Default,
|
||||
openai_websocket_pool: Default::default(),
|
||||
openai_request_settings: Default::default(),
|
||||
request_location: None,
|
||||
@@ -743,8 +735,14 @@ impl AttemptContext {
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn fast_mode(&self) -> FastMode {
|
||||
self.request.fast_mode
|
||||
pub fn fast_mode_for_account(
|
||||
&self,
|
||||
account: &ProviderAccountId,
|
||||
upstream_model: &str,
|
||||
) -> FastMode {
|
||||
self.account_scope().map_or(FastMode::Default, |scope| {
|
||||
scope.fast_mode_for_account(account, upstream_model)
|
||||
})
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
|
||||
@@ -1436,14 +1436,14 @@ impl GatewayError {
|
||||
pub(crate) const fn concurrency_queue_full() -> Self {
|
||||
Self::new(
|
||||
GatewayErrorKind::ConcurrencyQueueFull,
|
||||
"The gateway request queue is full.",
|
||||
"The gateway concurrency queue is full.",
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) const fn concurrency_queue_timeout() -> Self {
|
||||
Self::new(
|
||||
GatewayErrorKind::ConcurrencyQueueTimeout,
|
||||
"The request timed out in the gateway queue.",
|
||||
"Timed out waiting for available concurrency in the gateway.",
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1516,20 +1516,25 @@ impl GatewayError {
|
||||
GatewayErrorKind::Unsupported,
|
||||
"Requested capability is unsupported.",
|
||||
),
|
||||
ProviderErrorKind::Unauthorized | ProviderErrorKind::PermissionDenied => Self::new(
|
||||
ProviderErrorKind::Unauthorized => Self::new(
|
||||
GatewayErrorKind::UpstreamUnavailable,
|
||||
"The upstream account cannot access the service.",
|
||||
"Upstream account authentication failed.",
|
||||
),
|
||||
ProviderErrorKind::PermissionDenied => Self::new(
|
||||
GatewayErrorKind::UpstreamUnavailable,
|
||||
"The upstream account does not have permission for this request.",
|
||||
),
|
||||
ProviderErrorKind::RequestPolicyDenied => error.denied_group_feature.map_or_else(
|
||||
|| Self::new(GatewayErrorKind::PolicyDenied, "Request blocked by policy."),
|
||||
Self::from,
|
||||
),
|
||||
ProviderErrorKind::RateLimited => {
|
||||
Self::new(GatewayErrorKind::RateLimited, "Request rate limit reached.")
|
||||
}
|
||||
ProviderErrorKind::RateLimited => Self::new(
|
||||
GatewayErrorKind::RateLimited,
|
||||
"Upstream request rate limit reached.",
|
||||
),
|
||||
ProviderErrorKind::QuotaExhausted => Self::new(
|
||||
GatewayErrorKind::QuotaExhausted,
|
||||
"Account quota is exhausted.",
|
||||
"Upstream account quota is exhausted.",
|
||||
),
|
||||
ProviderErrorKind::AccountPoolQuotaExhausted => Self::new(
|
||||
GatewayErrorKind::AccountPoolQuotaExhausted,
|
||||
@@ -1539,7 +1544,7 @@ impl GatewayError {
|
||||
ProviderErrorKind::ConcurrencyQueueTimeout => Self::concurrency_queue_timeout(),
|
||||
ProviderErrorKind::AccountCapacityUnavailable => Self::new(
|
||||
GatewayErrorKind::AccountCapacityUnavailable,
|
||||
"The gateway account pool is busy.",
|
||||
"No eligible account currently has capacity for this request.",
|
||||
),
|
||||
ProviderErrorKind::NoEligibleAccount => Self::new(
|
||||
GatewayErrorKind::NoAvailableProvider,
|
||||
@@ -1559,16 +1564,33 @@ impl GatewayError {
|
||||
ProviderErrorKind::Cancelled => {
|
||||
Self::new(GatewayErrorKind::Cancelled, "Request was cancelled.")
|
||||
}
|
||||
ProviderErrorKind::Transport
|
||||
| ProviderErrorKind::Protocol
|
||||
| ProviderErrorKind::Unavailable
|
||||
| ProviderErrorKind::UpstreamCapacityUnavailable
|
||||
| ProviderErrorKind::ProcessTerminated => Self::new(
|
||||
ProviderErrorKind::Transport => Self::new(
|
||||
GatewayErrorKind::UpstreamUnavailable,
|
||||
"Communication with the upstream service failed.",
|
||||
),
|
||||
ProviderErrorKind::Protocol => Self::new(
|
||||
GatewayErrorKind::UpstreamUnavailable,
|
||||
"Upstream protocol handling failed.",
|
||||
),
|
||||
ProviderErrorKind::ProcessTerminated => Self::new(
|
||||
GatewayErrorKind::UpstreamUnavailable,
|
||||
"The gateway stopped before the request completed.",
|
||||
),
|
||||
ProviderErrorKind::UpstreamCapacityUnavailable => Self::new(
|
||||
GatewayErrorKind::UpstreamUnavailable,
|
||||
"The upstream service has no capacity for this request.",
|
||||
),
|
||||
ProviderErrorKind::Unavailable => Self::new(
|
||||
GatewayErrorKind::UpstreamUnavailable,
|
||||
"Upstream service is unavailable.",
|
||||
),
|
||||
};
|
||||
let mut gateway = gateway;
|
||||
if gateway.kind() == GatewayErrorKind::AccountCapacityUnavailable
|
||||
&& let Some(delay) = error.retry_after()
|
||||
{
|
||||
gateway = gateway.with_retry_after(delay);
|
||||
}
|
||||
if gateway.kind() == GatewayErrorKind::InvalidRequest
|
||||
&& let Some(details) = error
|
||||
.failure_observation
|
||||
|
||||
@@ -5,6 +5,7 @@ use std::sync::{Arc, OnceLock};
|
||||
use std::time::{Duration, SystemTime};
|
||||
|
||||
use event_listener::Event;
|
||||
use futures::FutureExt as _;
|
||||
use futures::future::{BoxFuture, pending};
|
||||
use futures_timer::Delay;
|
||||
|
||||
@@ -142,6 +143,14 @@ impl CancellationToken {
|
||||
self.reason().is_some()
|
||||
}
|
||||
|
||||
/// 取消优先于同时就绪的工作,只用于可安全丢弃的 future
|
||||
pub async fn run_until_cancelled<T>(&self, work: impl Future<Output = T>) -> Option<T> {
|
||||
futures::select_biased! {
|
||||
() = self.cancelled().fuse() => None,
|
||||
result = work.fuse() => Some(result),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn cancelled(&self) {
|
||||
if self.is_cancelled() {
|
||||
return;
|
||||
|
||||
@@ -158,7 +158,7 @@ impl RateLimits {
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ClientSettings {
|
||||
pub request_profiles: BTreeMap<ProviderKind, OpaqueProviderData>,
|
||||
pub fast_mode: FastMode,
|
||||
pub fast_mode_override: Option<FastMode>,
|
||||
pub limits: RateLimits,
|
||||
}
|
||||
|
||||
@@ -185,18 +185,18 @@ impl ClientPolicy {
|
||||
pub(crate) fn with_settings(
|
||||
mut self,
|
||||
profiles: &BTreeMap<ProviderKind, OpaqueProviderData>,
|
||||
fast_mode: FastMode,
|
||||
fast_mode_override: Option<FastMode>,
|
||||
limits: RateLimits,
|
||||
) -> Self {
|
||||
if self.account_scope.request_profiles() != profiles
|
||||
|| self.account_scope.fast_mode() != fast_mode
|
||||
|| self.account_scope.fast_mode_override() != fast_mode_override
|
||||
{
|
||||
self.account_scope = Arc::new(
|
||||
self.account_scope
|
||||
.as_ref()
|
||||
.clone()
|
||||
.with_request_profiles(profiles.clone())
|
||||
.with_fast_mode(fast_mode),
|
||||
.with_fast_mode_override(fast_mode_override),
|
||||
);
|
||||
}
|
||||
self.limits = limits;
|
||||
@@ -217,7 +217,7 @@ impl ClientPolicy {
|
||||
name_snapshot: None,
|
||||
defaults: Arc::new(ClientSettings {
|
||||
request_profiles: account_scope.request_profiles().clone(),
|
||||
fast_mode: account_scope.fast_mode(),
|
||||
fast_mode_override: account_scope.fast_mode_override(),
|
||||
limits,
|
||||
}),
|
||||
key_id,
|
||||
|
||||
@@ -113,6 +113,7 @@ pub struct ProviderScopedCooldown {
|
||||
credential_revision: CredentialRevision,
|
||||
scope: ProviderCooldownScope,
|
||||
until: SystemTime,
|
||||
rate_limited_until: Option<SystemTime>,
|
||||
}
|
||||
|
||||
impl ProviderScopedCooldown {
|
||||
@@ -128,6 +129,7 @@ impl ProviderScopedCooldown {
|
||||
credential_revision,
|
||||
scope,
|
||||
until,
|
||||
rate_limited_until: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -141,6 +143,18 @@ impl ProviderScopedCooldown {
|
||||
self.credential_revision
|
||||
}
|
||||
|
||||
/// 选号冷却可能还包含模型拒绝;目录只展示实际限流期限
|
||||
#[must_use]
|
||||
pub fn with_rate_limited_until(mut self, until: Option<SystemTime>) -> Self {
|
||||
self.rate_limited_until = until.map(|until| until.min(self.until));
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn rate_limited_until(&self) -> Option<SystemTime> {
|
||||
self.rate_limited_until
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn scope(&self) -> &ProviderCooldownScope {
|
||||
&self.scope
|
||||
|
||||
@@ -23,7 +23,7 @@ use std::fmt;
|
||||
use std::num::{NonZeroU32, NonZeroU64};
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::account::{AccountSelectionPolicy, FastMode};
|
||||
use crate::account::AccountSelectionPolicy;
|
||||
use crate::operation::{CapabilityRequirements, Feature, OperationKind};
|
||||
use crate::validation::{IdentifierError, RoutingError, validate_text};
|
||||
|
||||
@@ -767,11 +767,6 @@ impl RoutingPlan {
|
||||
Arc::clone(&self.pricing)
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn fast_mode(&self) -> FastMode {
|
||||
self.account_scope.fast_mode()
|
||||
}
|
||||
|
||||
/// 本次请求冻结的已编译规则,重试不读取新的全局策略
|
||||
#[must_use]
|
||||
pub fn privacy(&self) -> Option<Arc<dyn crate::settings::privacy::CompiledPrivacyPolicy>> {
|
||||
|
||||
@@ -19,7 +19,8 @@ use crate::settings::{InvalidSettings, SettingsValues};
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct ExecutionSettings {
|
||||
pub runtime: SettingsValues,
|
||||
pub fast_mode: FastMode,
|
||||
/// None 按选中账号的有效分组解析;Some(Default) 显式跟随客户端
|
||||
pub fast_mode: Option<FastMode>,
|
||||
pub client_limits: RateLimits,
|
||||
/// null 表示不限制总时长;显式时限从请求开始计时,改写不重置计时原点
|
||||
pub timeout_ms: Option<u64>,
|
||||
@@ -38,7 +39,7 @@ struct ExecutionOverrides {
|
||||
defaults: Arc<ClientSettings>,
|
||||
client_key_id: String,
|
||||
input: Arc<ExecutionSettings>,
|
||||
fast_mode: Option<SettingOverride<FastMode>>,
|
||||
fast_mode: Option<SettingOverride<Option<FastMode>>>,
|
||||
client_limits: Option<SettingOverride<RateLimits>>,
|
||||
timeout_ms: Option<SettingOverride<Option<u64>>>,
|
||||
}
|
||||
@@ -186,9 +187,10 @@ impl RequestSettings {
|
||||
#[must_use]
|
||||
pub fn apply_policy(&self, policy: ClientPolicy) -> ClientPolicy {
|
||||
let values = self.resolve_execution(policy.key_id().as_str(), policy.defaults(), None);
|
||||
let fast_mode = self.fast_mode_override(policy.key_id().as_str(), policy.defaults());
|
||||
policy.with_settings(
|
||||
values.runtime.request_profiles(),
|
||||
values.fast_mode,
|
||||
fast_mode,
|
||||
values.client_limits,
|
||||
)
|
||||
}
|
||||
@@ -247,9 +249,7 @@ impl RequestSettings {
|
||||
}
|
||||
ExecutionSettings {
|
||||
runtime,
|
||||
fast_mode: overrides
|
||||
.and_then(|scope| scope.fast_mode.as_ref())
|
||||
.map_or(defaults.fast_mode, |change| change.value),
|
||||
fast_mode: self.fast_mode_override(key, defaults),
|
||||
client_limits: overrides
|
||||
.and_then(|scope| scope.client_limits.as_ref())
|
||||
.map_or(defaults.limits, |change| change.value),
|
||||
@@ -259,6 +259,15 @@ impl RequestSettings {
|
||||
}
|
||||
}
|
||||
|
||||
fn fast_mode_override(&self, key: &str, defaults: &ClientSettings) -> Option<FastMode> {
|
||||
self.execution
|
||||
.as_ref()
|
||||
.filter(|scope| scope.client_key_id == key)
|
||||
.and_then(|scope| scope.fast_mode.as_ref())
|
||||
.map(|change| change.value)
|
||||
.unwrap_or(defaults.fast_mode_override)
|
||||
}
|
||||
|
||||
pub(crate) fn execution_deadline(
|
||||
&self,
|
||||
key: &ClientApiKeyId,
|
||||
|
||||
@@ -583,12 +583,19 @@ async fn compile_runtime_snapshot(
|
||||
.map(|group| (group.id.clone(), std::mem::take(&mut group.model_access)))
|
||||
.collect();
|
||||
let account_directory = Arc::new(
|
||||
RuntimeAccountDirectory::new(accounts).with_group_model_access(group_model_access),
|
||||
RuntimeAccountDirectory::new(accounts)
|
||||
.with_group_model_access(group_model_access)
|
||||
.with_group_fast_modes(
|
||||
groups
|
||||
.values()
|
||||
.filter(|group| group.enabled && group.fast_mode != FastMode::Default)
|
||||
.map(|group| (group.id.clone(), group.fast_mode))
|
||||
.collect(),
|
||||
),
|
||||
);
|
||||
|
||||
let mut client_policies = Vec::with_capacity(facts.client_policies.len());
|
||||
for policy in facts.client_policies {
|
||||
let mut fast_mode = FastMode::Default;
|
||||
let mut allow_image_generation = true;
|
||||
let mut allow_subagents = true;
|
||||
let account_scope = if policy.group_ids.is_empty() {
|
||||
@@ -607,8 +614,7 @@ async fn compile_runtime_snapshot(
|
||||
let group = groups
|
||||
.get(&group_id)
|
||||
.ok_or(RuntimeSnapshotCompileError::InvalidData)?;
|
||||
// 停用只影响选号,仍绑定的分组继续贡献请求策略
|
||||
fast_mode = fast_mode.merge(group.fast_mode);
|
||||
// 功能权限仍按 Key 合并,停用分组不解除生图和子代理限制
|
||||
allow_image_generation &= group.allow_image_generation;
|
||||
allow_subagents &= group.allow_subagents;
|
||||
bound_groups.push(RoutingGroupSnapshot::new(
|
||||
@@ -635,7 +641,6 @@ async fn compile_runtime_snapshot(
|
||||
account_scope
|
||||
.with_image_generation(allow_image_generation)
|
||||
.with_subagents(allow_subagents)
|
||||
.with_fast_mode(fast_mode)
|
||||
.with_request_profiles(policy.request_profiles),
|
||||
),
|
||||
true,
|
||||
|
||||
@@ -399,14 +399,13 @@ struct RuntimeSnapshotReconciliationTask {
|
||||
}
|
||||
|
||||
impl ScheduledTask for RuntimeSnapshotReconciliationTask {
|
||||
fn run_cycle(
|
||||
&self,
|
||||
_context: WorkerCycleContext,
|
||||
) -> BoxFuture<'_, Result<(), WorkerTaskError>> {
|
||||
fn run_cycle(&self, context: WorkerCycleContext) -> BoxFuture<'_, Result<(), WorkerTaskError>> {
|
||||
Box::pin(async move {
|
||||
self.publisher
|
||||
.refresh_with_mode(RefreshMode::Reconcile)
|
||||
context
|
||||
.cancellation()
|
||||
.run_until_cancelled(self.publisher.refresh_with_mode(RefreshMode::Reconcile))
|
||||
.await
|
||||
.transpose()
|
||||
.map(|_| ())
|
||||
.map_err(|source| {
|
||||
WorkerTaskError::safe("runtime snapshot reconciliation failed")
|
||||
@@ -430,10 +429,12 @@ impl DaemonTask for RuntimeSnapshotSubscriptionTask {
|
||||
let cancellation = context.cancellation();
|
||||
let mut retry_delay = INITIAL_BACKOFF;
|
||||
loop {
|
||||
if cancellation.is_cancelled() {
|
||||
let Some(subscription) = cancellation
|
||||
.run_until_cancelled(self.subscriptions.subscribe_snapshot_revisions())
|
||||
.await
|
||||
else {
|
||||
return Ok(());
|
||||
}
|
||||
let subscription = self.subscriptions.subscribe_snapshot_revisions().await;
|
||||
};
|
||||
let mut subscription = match subscription {
|
||||
Ok(subscription) => {
|
||||
retry_delay = INITIAL_BACKOFF;
|
||||
@@ -456,7 +457,13 @@ impl DaemonTask for RuntimeSnapshotSubscriptionTask {
|
||||
};
|
||||
match notified {
|
||||
Some(Ok(_)) => {
|
||||
let _ = self.publisher.refresh().await;
|
||||
if cancellation
|
||||
.run_until_cancelled(self.publisher.refresh())
|
||||
.await
|
||||
.is_none()
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
Some(Err(_)) | None => break,
|
||||
}
|
||||
|
||||
@@ -1138,26 +1138,12 @@ fn plan_with_location(
|
||||
operation: &Operation,
|
||||
account_selection_policy: AccountSelectionPolicy,
|
||||
request_location: gateway_core::account::RequestLocation,
|
||||
) -> RoutingPlan {
|
||||
plan_with_location_and_fast_policy(
|
||||
operation,
|
||||
account_selection_policy,
|
||||
request_location,
|
||||
FastMode::Default,
|
||||
)
|
||||
}
|
||||
|
||||
fn plan_with_location_and_fast_policy(
|
||||
operation: &Operation,
|
||||
account_selection_policy: AccountSelectionPolicy,
|
||||
request_location: gateway_core::account::RequestLocation,
|
||||
fast_mode: FastMode,
|
||||
) -> RoutingPlan {
|
||||
plan_with_profiles(
|
||||
operation,
|
||||
account_selection_policy,
|
||||
request_location,
|
||||
fast_mode,
|
||||
FastMode::Default,
|
||||
Default::default(),
|
||||
)
|
||||
}
|
||||
@@ -1255,7 +1241,7 @@ fn plan_with_protection(
|
||||
operation,
|
||||
Arc::new(
|
||||
FrozenAccountScope::new(directory, ClientRoutingScope::all_accounts())
|
||||
.with_fast_mode(fast_mode)
|
||||
.with_fast_mode_override(Some(fast_mode))
|
||||
.with_request_profiles(profiles),
|
||||
),
|
||||
&RoutingContext {
|
||||
@@ -6414,6 +6400,8 @@ fn deadline_before_first_event_is_persisted_as_failed_attempt() {
|
||||
|
||||
#[test]
|
||||
fn global_location_and_group_fast_policy_reach_every_account_retry() {
|
||||
use gateway_core::routing::{AccountGroupId, RoutingGroupSnapshot};
|
||||
|
||||
for mode in [
|
||||
FastMode::Default,
|
||||
FastMode::Enabled,
|
||||
@@ -6425,12 +6413,67 @@ fn global_location_and_group_fast_policy_reach_every_account_retry() {
|
||||
timezone: "Asia/Tokyo".parse().unwrap(),
|
||||
..Default::default()
|
||||
};
|
||||
let route_plan = plan_with_location_and_fast_policy(
|
||||
&operation,
|
||||
plan(&operation).account_selection_policy(),
|
||||
location.clone(),
|
||||
mode,
|
||||
let kind = ProviderKind::new("openai").unwrap();
|
||||
let first_group = AccountGroupId::new(format!("grp_{:032x}", 1)).unwrap();
|
||||
let second_group = AccountGroupId::new(format!("grp_{:032x}", 2)).unwrap();
|
||||
let second_mode = if mode == FastMode::Disabled {
|
||||
FastMode::Default
|
||||
} else {
|
||||
FastMode::Disabled
|
||||
};
|
||||
let directory = Arc::new(
|
||||
RuntimeAccountDirectory::new(
|
||||
[
|
||||
("acct_first", first_group.clone()),
|
||||
("acct_second", second_group.clone()),
|
||||
]
|
||||
.into_iter()
|
||||
.map(|(account, group)| {
|
||||
(
|
||||
ProviderAccountId::new(account).unwrap(),
|
||||
RuntimeAccount::new(kind.clone(), BTreeSet::from([group])),
|
||||
)
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
.with_group_fast_modes(BTreeMap::from([
|
||||
(first_group.clone(), mode),
|
||||
(second_group.clone(), second_mode),
|
||||
])),
|
||||
);
|
||||
let scope = Arc::new(FrozenAccountScope::new(
|
||||
Arc::clone(&directory),
|
||||
ClientRoutingScope::restricted(
|
||||
vec![
|
||||
RoutingGroupSnapshot::new(first_group.clone(), "A".into()),
|
||||
RoutingGroupSnapshot::new(second_group.clone(), "B".into()),
|
||||
],
|
||||
BTreeSet::from([first_group, second_group]),
|
||||
BTreeSet::from([kind.clone()]),
|
||||
)
|
||||
.unwrap(),
|
||||
));
|
||||
let route_plan = RuntimeSnapshot::new(
|
||||
ConfigRevision::new(1).unwrap(),
|
||||
gateway_core::settings::SettingsValues::new(2, "smart", Default::default(), None, None)
|
||||
.with_request_location(location.clone(), true),
|
||||
vec![kind.clone()],
|
||||
vec![ProviderModel::new(
|
||||
kind,
|
||||
UpstreamModelId::new("gpt-5").unwrap(),
|
||||
ModelCapabilities::new(BTreeSet::from([operation.kind()]), Some(32_000)),
|
||||
)],
|
||||
Vec::new(),
|
||||
)
|
||||
.unwrap()
|
||||
.with_account_directory(directory)
|
||||
.plan(
|
||||
&PublicModelId::new("gpt-5").unwrap(),
|
||||
&operation,
|
||||
Arc::clone(&scope),
|
||||
&RoutingContext::default(),
|
||||
)
|
||||
.unwrap();
|
||||
let (coordinator, _, provider) = coordinator(vec![
|
||||
Script::Stream {
|
||||
account_id: "acct_first",
|
||||
@@ -6459,12 +6502,17 @@ fn global_location_and_group_fast_policy_reach_every_account_retry() {
|
||||
block_on(session.commit_downstream(Some(200))).unwrap();
|
||||
let contexts = provider.contexts.lock().unwrap();
|
||||
assert_eq!(contexts.len(), 2);
|
||||
assert!(
|
||||
contexts
|
||||
.iter()
|
||||
.all(|context| context.request_location() == Some(&location)
|
||||
&& context.fast_mode() == mode)
|
||||
);
|
||||
for (context, account, expected) in [
|
||||
(&contexts[0], "acct_first", mode),
|
||||
(&contexts[1], "acct_second", second_mode),
|
||||
] {
|
||||
assert_eq!(context.request_location(), Some(&location));
|
||||
assert!(Arc::ptr_eq(context.account_scope().unwrap(), &scope));
|
||||
assert_eq!(
|
||||
context.fast_mode_for_account(&ProviderAccountId::new(account).unwrap(), "gpt-5"),
|
||||
expected,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -3068,8 +3068,14 @@ impl Provider for ChargedProvider {
|
||||
request: ProviderRequest,
|
||||
context: AttemptContext,
|
||||
) -> Result<ProviderStream, ProviderError> {
|
||||
self.policies.lock().unwrap().push(context.fast_mode());
|
||||
let candidate = request.candidate();
|
||||
self.policies
|
||||
.lock()
|
||||
.unwrap()
|
||||
.push(context.fast_mode_for_account(
|
||||
&ProviderAccountId::new("acct_start").unwrap(),
|
||||
candidate.upstream_model().unwrap().as_str(),
|
||||
));
|
||||
let metadata = ProviderCallMetadata::new(
|
||||
candidate.provider().clone(),
|
||||
candidate.upstream_model().unwrap().clone(),
|
||||
@@ -4792,7 +4798,7 @@ fn start_snapshot_with_image_policy(
|
||||
account_scope(&provider, "acct_start")
|
||||
.as_ref()
|
||||
.clone()
|
||||
.with_fast_mode(fast_mode)
|
||||
.with_fast_mode_override(Some(fast_mode))
|
||||
.with_image_generation(allow_image_generation),
|
||||
),
|
||||
enabled,
|
||||
@@ -5526,7 +5532,7 @@ fn entry_settings_freeze_authentication_and_rebase_only_explicit_overrides() {
|
||||
.execution_values()
|
||||
.unwrap()
|
||||
.fast_mode,
|
||||
FastMode::Disabled
|
||||
Some(FastMode::Disabled)
|
||||
);
|
||||
assert_eq!(
|
||||
prepared
|
||||
@@ -5649,7 +5655,7 @@ fn child_settings_recompute_key_scope_without_inheriting_parent_defaults() {
|
||||
account_scope(&provider, "acct_start")
|
||||
.as_ref()
|
||||
.clone()
|
||||
.with_fast_mode(FastMode::Disabled)
|
||||
.with_fast_mode_override(Some(FastMode::Disabled))
|
||||
.with_request_profiles(profiles(name)),
|
||||
),
|
||||
true,
|
||||
@@ -5688,7 +5694,7 @@ fn child_settings_recompute_key_scope_without_inheriting_parent_defaults() {
|
||||
let configuration = RequestSettings::new(snapshots.acquire().unwrap())
|
||||
.with_execution(parent.client().policy(), previous.timeout_ms);
|
||||
let mut values = previous.clone();
|
||||
values.fast_mode = FastMode::Default;
|
||||
values.fast_mode = Some(FastMode::Default);
|
||||
values.client_limits = RateLimits::unlimited();
|
||||
values.timeout_ms = Some(90_000);
|
||||
let mut runtime = serde_json::to_value(&values.runtime).unwrap();
|
||||
@@ -5722,7 +5728,7 @@ fn child_settings_recompute_key_scope_without_inheriting_parent_defaults() {
|
||||
Some(actual.clone())
|
||||
);
|
||||
assert_eq!(actual.client_limits.max_concurrency, expected_limit);
|
||||
assert_eq!(actual.fast_mode, expected_fast);
|
||||
assert_eq!(actual.fast_mode, Some(expected_fast));
|
||||
assert_eq!(actual.timeout_ms, expected_timeout);
|
||||
let facts = serde_json::to_value(actual.runtime).unwrap();
|
||||
assert_eq!(facts["request_profiles"]["openai"]["identity"], profile);
|
||||
|
||||
@@ -186,7 +186,10 @@ fn gateway_error_should_keep_client_visible_upstream_fields_out_of_safe_diagnost
|
||||
));
|
||||
let gateway = GatewayError::from_provider(&error);
|
||||
|
||||
assert_eq!(gateway.safe_message(), "Account quota is exhausted.");
|
||||
assert_eq!(
|
||||
gateway.safe_message(),
|
||||
"Upstream account quota is exhausted."
|
||||
);
|
||||
assert_eq!(gateway.client_message(), message);
|
||||
assert_eq!(gateway.client_error_code(), Some("quota_exhausted"));
|
||||
assert_eq!(gateway.client_error_type(), Some("rate_limit_error"));
|
||||
|
||||
@@ -53,7 +53,7 @@ fn policy_with_profiles(
|
||||
Arc::new(
|
||||
FrozenAccountScope::new(Arc::default(), ClientRoutingScope::all_accounts())
|
||||
.with_request_profiles(overrides)
|
||||
.with_fast_mode(FastMode::Disabled),
|
||||
.with_fast_mode_override(Some(FastMode::Disabled)),
|
||||
),
|
||||
true,
|
||||
RateLimits {
|
||||
@@ -153,7 +153,7 @@ fn scope_changes_recompute_defaults_and_inherit_only_explicit_overrides() {
|
||||
values.runtime = values
|
||||
.runtime
|
||||
.with_model_mappings(BTreeMap::from([("alias".into(), "model".into())]));
|
||||
values.fast_mode = FastMode::Default;
|
||||
values.fast_mode = Some(FastMode::Default);
|
||||
values.client_limits = RateLimits::unlimited();
|
||||
values.timeout_ms = Some(90_000);
|
||||
let changed = original.replace_execution(&values, "plugin").unwrap();
|
||||
@@ -168,14 +168,14 @@ fn scope_changes_recompute_defaults_and_inherit_only_explicit_overrides() {
|
||||
parent_values.runtime.request_profiles(),
|
||||
&profiles(&[("openai", "parent"), ("xai", "second")])
|
||||
);
|
||||
assert_eq!(parent_values.fast_mode, FastMode::Default);
|
||||
assert_eq!(parent_values.fast_mode, Some(FastMode::Default));
|
||||
let child_settings = rebased.with_execution(&child, Some(60_000));
|
||||
let child_values = child_settings.execution_values().unwrap();
|
||||
assert_eq!(
|
||||
child_values.runtime.request_profiles(),
|
||||
&profiles(&[("openai", "child"), ("xai", "second")])
|
||||
);
|
||||
assert_eq!(child_values.fast_mode, FastMode::Disabled);
|
||||
assert_eq!(child_values.fast_mode, Some(FastMode::Disabled));
|
||||
assert_eq!(child_values.client_limits, child.limits());
|
||||
assert_eq!(child_values.timeout_ms, Some(60_000));
|
||||
assert_eq!(child_settings.snapshot().mapped_model("alias"), "model");
|
||||
@@ -186,6 +186,81 @@ fn scope_changes_recompute_defaults_and_inherit_only_explicit_overrides() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_fast_policy_survives_settings_resolution_until_explicitly_overridden() {
|
||||
use gateway_core::{
|
||||
account::ProviderAccountId,
|
||||
routing::{AccountGroupId, RoutingGroupSnapshot, RuntimeAccount, RuntimeAccountDirectory},
|
||||
};
|
||||
let group = AccountGroupId::new(format!("grp_{:032x}", 1)).unwrap();
|
||||
let account = ProviderAccountId::new("acct_group_fast").unwrap();
|
||||
let provider = ProviderKind::new("openai").unwrap();
|
||||
let scope = Arc::new(FrozenAccountScope::new(
|
||||
Arc::new(
|
||||
RuntimeAccountDirectory::new(BTreeMap::from([(
|
||||
account.clone(),
|
||||
RuntimeAccount::new(provider.clone(), [group.clone()].into()),
|
||||
)]))
|
||||
.with_group_fast_modes([(group.clone(), FastMode::Disabled)].into()),
|
||||
),
|
||||
ClientRoutingScope::restricted(
|
||||
vec![RoutingGroupSnapshot::new(group.clone(), "Standard".into())],
|
||||
[group].into(),
|
||||
[provider].into(),
|
||||
)
|
||||
.unwrap(),
|
||||
));
|
||||
let key = |name: &str| {
|
||||
ClientPolicy::new(
|
||||
ClientApiKeyId::new(name).unwrap(),
|
||||
PlaintextClientApiKey::new(format!("fixture-{name}")).unwrap(),
|
||||
scope.clone(),
|
||||
true,
|
||||
RateLimits::unlimited(),
|
||||
)
|
||||
};
|
||||
let parent = key("parent");
|
||||
let settings = RequestSettings::new(snapshot(1, "host")).with_execution(&parent, None);
|
||||
assert_eq!(settings.execution_values().unwrap().fast_mode, None);
|
||||
let resolved = |settings: &RequestSettings, key| {
|
||||
settings
|
||||
.apply_policy(key)
|
||||
.account_scope()
|
||||
.fast_mode_for_account(&account, "model")
|
||||
};
|
||||
assert_eq!(resolved(&settings, parent.clone()), FastMode::Disabled);
|
||||
let unchanged = settings
|
||||
.replace_execution(&settings.execution_values().unwrap(), "pass-through")
|
||||
.unwrap();
|
||||
assert_eq!(resolved(&unchanged, parent.clone()), FastMode::Disabled);
|
||||
|
||||
let mut values = settings.execution_values().unwrap();
|
||||
values.fast_mode = Some(FastMode::Default);
|
||||
let direct_default = settings
|
||||
.replace_execution(&values, "follow-client")
|
||||
.unwrap();
|
||||
assert_eq!(resolved(&direct_default, parent.clone()), FastMode::Default);
|
||||
values.fast_mode = Some(FastMode::Enabled);
|
||||
let enabled = settings.replace_execution(&values, "force-fast").unwrap();
|
||||
assert_eq!(resolved(&enabled, parent.clone()), FastMode::Enabled);
|
||||
values.fast_mode = Some(FastMode::Default);
|
||||
let default = enabled.replace_execution(&values, "follow-client").unwrap();
|
||||
assert_eq!(resolved(&default, parent.clone()), FastMode::Default);
|
||||
values.fast_mode = None;
|
||||
let cleared = default.replace_execution(&values, "group-policy").unwrap();
|
||||
assert_eq!(resolved(&cleared, parent.clone()), FastMode::Disabled);
|
||||
assert_eq!(
|
||||
cleared.inspect()["execution"]["fast_mode"]["value"],
|
||||
serde_json::Value::Null
|
||||
);
|
||||
let child = key("child");
|
||||
assert_eq!(
|
||||
resolved(&default.with_execution(&child, None), child),
|
||||
FastMode::Disabled
|
||||
);
|
||||
assert_eq!(resolved(&settings, parent), FastMode::Disabled);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicitly_selecting_the_host_profiles_overrides_keys_after_rebase() {
|
||||
let host = snapshot(1, "first");
|
||||
|
||||
@@ -2727,7 +2727,7 @@ fn decompression_setting_should_validate_and_remain_frozen_across_publication()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fast_mode_merges_only_bound_groups_without_changing_account_scope() {
|
||||
fn fast_mode_merges_only_enabled_bound_groups_of_the_selected_account() {
|
||||
use gateway_core::account::ProviderAccountId;
|
||||
use gateway_core::routing::AccountGroupId;
|
||||
for (mode, other_mode, expected) in [
|
||||
@@ -2758,6 +2758,8 @@ fn fast_mode_merges_only_bound_groups_without_changing_account_scope() {
|
||||
let open_group_id =
|
||||
AccountGroupId::new("grp_00000000000000000000000000000002").unwrap();
|
||||
let account_id = ProviderAccountId::new("acct_fast_policy").unwrap();
|
||||
let first_account = ProviderAccountId::new("acct_first_group").unwrap();
|
||||
let second_account = ProviderAccountId::new("acct_second_group").unwrap();
|
||||
let facts = SnapshotFacts::new(
|
||||
revision(1),
|
||||
revision(1),
|
||||
@@ -2786,11 +2788,19 @@ fn fast_mode_merges_only_bound_groups_without_changing_account_scope() {
|
||||
)
|
||||
.with_fast_mode(other_mode),
|
||||
],
|
||||
vec![SnapshotProviderAccountFacts::new(
|
||||
account_id.clone(),
|
||||
"alpha",
|
||||
)],
|
||||
[&account_id, &first_account, &second_account]
|
||||
.into_iter()
|
||||
.map(|id| SnapshotProviderAccountFacts::new(id.clone(), "alpha"))
|
||||
.collect(),
|
||||
vec![
|
||||
SnapshotAccountGroupMemberFacts::new(
|
||||
group_id.clone(),
|
||||
first_account.clone(),
|
||||
),
|
||||
SnapshotAccountGroupMemberFacts::new(
|
||||
open_group_id.clone(),
|
||||
second_account.clone(),
|
||||
),
|
||||
SnapshotAccountGroupMemberFacts::new(group_id, account_id.clone()),
|
||||
SnapshotAccountGroupMemberFacts::new(open_group_id, account_id.clone()),
|
||||
],
|
||||
@@ -2818,16 +2828,99 @@ fn fast_mode_merges_only_bound_groups_without_changing_account_scope() {
|
||||
&Default::default(),
|
||||
)
|
||||
.unwrap();
|
||||
for (account, effective) in [
|
||||
(
|
||||
&account_id,
|
||||
if group_enabled { expected } else { other_mode },
|
||||
),
|
||||
(
|
||||
&first_account,
|
||||
if group_enabled {
|
||||
mode
|
||||
} else {
|
||||
FastMode::Default
|
||||
},
|
||||
),
|
||||
(&second_account, other_mode),
|
||||
] {
|
||||
assert_eq!(
|
||||
plan.account_scope()
|
||||
.fast_mode_for_account(account, "public-model"),
|
||||
if bound { effective } else { FastMode::Default },
|
||||
"account={account}, mode={mode:?}, other={other_mode:?}, enabled={group_enabled}, bound={bound}"
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
plan.fast_mode(),
|
||||
if bound { expected } else { FastMode::Default },
|
||||
"mode={mode:?}, other={other_mode:?}, enabled={group_enabled}, bound={bound}"
|
||||
plan.account_scope().allows(&first_account),
|
||||
!bound || group_enabled
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fast_mode_ignores_unbound_groups_and_groups_that_deny_the_model() {
|
||||
use gateway_core::account::{AccountModelAccess, AccountModelAccessMode, ProviderAccountId};
|
||||
use gateway_core::routing::AccountGroupId;
|
||||
|
||||
let group = |id| AccountGroupId::new(format!("grp_{id:032x}")).unwrap();
|
||||
let account = ProviderAccountId::new("acct_model_fast").unwrap();
|
||||
let facts = SnapshotFacts::new(
|
||||
revision(1),
|
||||
revision(1),
|
||||
SettingsValues::new(3, "smart", BTreeMap::new(), None, None),
|
||||
vec![SnapshotClientPolicyFacts::new(
|
||||
ClientApiKeyId::new("key_model_fast").unwrap(),
|
||||
PlaintextClientApiKey::new("fixture-model-fast").unwrap(),
|
||||
vec![group(1), group(2)],
|
||||
RateLimits::unlimited(),
|
||||
)],
|
||||
vec![
|
||||
SnapshotAccountGroupFacts::new(group(1), "Fast".into(), true)
|
||||
.with_fast_mode(FastMode::Enabled)
|
||||
.with_model_access(
|
||||
AccountModelAccess::new(
|
||||
AccountModelAccessMode::Allowlist,
|
||||
vec!["fast-model".into()],
|
||||
)
|
||||
.unwrap(),
|
||||
),
|
||||
SnapshotAccountGroupFacts::new(group(2), "Standard".into(), true)
|
||||
.with_fast_mode(FastMode::Disabled)
|
||||
.with_model_access(
|
||||
AccountModelAccess::new(
|
||||
AccountModelAccessMode::Denylist,
|
||||
vec!["fast-model".into()],
|
||||
)
|
||||
.unwrap(),
|
||||
),
|
||||
SnapshotAccountGroupFacts::new(group(3), "Unbound".into(), true)
|
||||
.with_fast_mode(FastMode::Disabled),
|
||||
],
|
||||
vec![SnapshotProviderAccountFacts::new(account.clone(), "alpha")],
|
||||
(1..=3)
|
||||
.map(|id| SnapshotAccountGroupMemberFacts::new(group(id), account.clone()))
|
||||
.collect(),
|
||||
);
|
||||
let snapshot = block_on(
|
||||
RuntimeSnapshotCompiler::new(
|
||||
Arc::new(TestSnapshotStore::new(Ok(facts))),
|
||||
Arc::new(TestCatalog::Unavailable),
|
||||
)
|
||||
.compile(),
|
||||
)
|
||||
.unwrap();
|
||||
let scope = snapshot.client_policies().next().unwrap().account_scope();
|
||||
for (model, expected) in [
|
||||
("fast-model", FastMode::Enabled),
|
||||
("standard-model", FastMode::Disabled),
|
||||
] {
|
||||
assert!(scope.allows_model(&account, model));
|
||||
assert_eq!(scope.fast_mode_for_account(&account, model), expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_feature_permissions_merge_independently_with_deny_precedence() {
|
||||
use gateway_core::account::ProviderAccountId;
|
||||
|
||||
@@ -48,6 +48,7 @@ tracing = "0.1.44"
|
||||
tracing-appender = "0.2.5"
|
||||
tracing-subscriber = { version = "0.3.23", features = ["env-filter", "json"] }
|
||||
yaml-rust2 = "0.13.0"
|
||||
uuid = { version = "1.23.3", features = ["v4"] }
|
||||
|
||||
[dev-dependencies]
|
||||
hyper = { version = "=1.11.1", default-features = false, features = ["server"] }
|
||||
|
||||
@@ -117,6 +117,11 @@ pub async fn initialize_command_line(mut config: HostConfig) -> Result<HostBundl
|
||||
}
|
||||
|
||||
impl HostBundle {
|
||||
/// 宿主配置解析后的运行数据目录,供需要磁盘空间的内置服务使用。
|
||||
pub fn runtime_data_dir(&self) -> &std::path::Path {
|
||||
self.config.runtime_data_dir()
|
||||
}
|
||||
|
||||
/// 向启动控制台报告一个组装阶段已就绪
|
||||
pub fn report_startup_ready(&self, service: &'static str) {
|
||||
tracing::info!(target: "gateway_startup", service, "服务启动正常");
|
||||
|
||||
@@ -37,6 +37,7 @@ const MAX_OFFICIAL_PLUGIN_MANIFEST_SIZE: u64 = 256 * 1024;
|
||||
/// gateway-admin 消费的真实进程/文件系统操作实现
|
||||
#[derive(Clone)]
|
||||
pub struct ProcessSystemOperations {
|
||||
instance_id: String,
|
||||
cancellation: CancellationToken,
|
||||
events: Arc<UpdateEvents>,
|
||||
config: Arc<SystemUpdateConfig>,
|
||||
@@ -62,6 +63,7 @@ impl ProcessSystemOperations {
|
||||
ReleaseFiles::installed(&config)
|
||||
}));
|
||||
Self {
|
||||
instance_id: uuid::Uuid::new_v4().to_string(),
|
||||
cancellation,
|
||||
events: Arc::new(UpdateEvents::default()),
|
||||
config: Arc::new(config),
|
||||
@@ -350,6 +352,8 @@ impl SystemOperations for ProcessSystemOperations {
|
||||
.await;
|
||||
Ok(SystemVersion {
|
||||
version: self.config.version.clone(),
|
||||
instance_id: self.instance_id.clone(),
|
||||
restart_supported: self.config.self_restart_enabled,
|
||||
git_sha: self.config.git_sha.clone(),
|
||||
build_time: self.config.build_time.clone(),
|
||||
deployment_mode: self.config.deployment_mode.clone(),
|
||||
|
||||
@@ -122,11 +122,12 @@ impl WorkerSupervisor {
|
||||
health: &self.health,
|
||||
};
|
||||
let deadline = tokio::time::Instant::now() + timeout;
|
||||
for (_, handle) in &mut shutdown.handles {
|
||||
for (worker, handle) in &mut shutdown.handles {
|
||||
if tokio::time::timeout_at(deadline, &mut *handle)
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
tracing::warn!(target: "gateway_shutdown", %worker, "后台任务收尾超时,强制终止");
|
||||
handle.abort();
|
||||
let _ = handle.await;
|
||||
}
|
||||
@@ -459,6 +460,7 @@ async fn acquire_and_run(
|
||||
let acquisition = AssertUnwindSafe(leader_lease.try_acquire(request)).catch_unwind();
|
||||
tokio::pin!(acquisition);
|
||||
let acquisition = tokio::select! {
|
||||
biased;
|
||||
() = cancellation.cancelled() => return ScheduledOutcome::ShuttingDown,
|
||||
acquisition = &mut acquisition => acquisition,
|
||||
};
|
||||
@@ -490,12 +492,13 @@ async fn run_local_cycle(
|
||||
.catch_unwind();
|
||||
tokio::pin!(cycle);
|
||||
tokio::select! {
|
||||
outcome = &mut cycle => task_result(outcome),
|
||||
biased;
|
||||
() = cancellation.cancelled() => {
|
||||
cycle_cancel.cancel();
|
||||
let _ = cycle.await;
|
||||
ScheduledOutcome::ShuttingDown
|
||||
}
|
||||
outcome = &mut cycle => task_result(outcome),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -527,17 +530,21 @@ async fn run_leased_cycle(
|
||||
|
||||
let outcome = loop {
|
||||
tokio::select! {
|
||||
result = &mut cycle => break task_result(result),
|
||||
biased;
|
||||
() = cancellation.cancelled() => {
|
||||
cycle_cancel.cancel();
|
||||
let _ = cycle.await;
|
||||
break ScheduledOutcome::ShuttingDown;
|
||||
}
|
||||
result = &mut cycle => break task_result(result),
|
||||
() = &mut renewal => {
|
||||
let renewed = renew_guard(
|
||||
let Some(renewed) = cancellation.run_until_cancelled(renew_guard(
|
||||
guard.as_mut(),
|
||||
schedule.leader_lease_renewal_interval(),
|
||||
).await;
|
||||
)).await else {
|
||||
// 返回循环首个取消分支,统一等待正在执行的周期收尾
|
||||
continue;
|
||||
};
|
||||
if let Err(error) = renewed {
|
||||
cycle_cancel.cancel();
|
||||
let _ = cycle.await;
|
||||
|
||||
@@ -142,6 +142,8 @@ async fn restart_should_request_process_restart_inside_docker() {
|
||||
config.deployment_mode = "docker".to_owned();
|
||||
let shutdown = CancellationToken::new();
|
||||
let service = ProcessSystemOperations::new(shutdown.clone(), config);
|
||||
assert!(!service.update_status().await.expect("status").need_restart);
|
||||
assert!(service.version().await.expect("version").restart_supported);
|
||||
service
|
||||
.restart(Arc::new(AllowingUpdatePreflight))
|
||||
.await
|
||||
@@ -152,6 +154,48 @@ async fn restart_should_request_process_restart_inside_docker() {
|
||||
.expect("shutdown requested");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn version_should_distinguish_same_version_service_instances() {
|
||||
let fixture = Fixture::new();
|
||||
let config = fixture.config("http://127.0.0.1:1/repos");
|
||||
let service = ProcessSystemOperations::new(CancellationToken::new(), config.clone());
|
||||
let version = service.version().await.expect("version");
|
||||
assert!(!version.instance_id.is_empty());
|
||||
assert_eq!(
|
||||
service
|
||||
.clone()
|
||||
.version()
|
||||
.await
|
||||
.expect("same instance")
|
||||
.instance_id,
|
||||
version.instance_id
|
||||
);
|
||||
|
||||
let replacement = ProcessSystemOperations::new(CancellationToken::new(), config);
|
||||
let restarted = replacement.version().await.expect("new instance");
|
||||
assert_eq!(restarted.version, version.version);
|
||||
assert_ne!(restarted.instance_id, version.instance_id);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn version_should_report_restart_disabled_when_host_rejects_it() {
|
||||
let fixture = Fixture::new();
|
||||
let mut config = fixture.config("http://127.0.0.1:1/repos");
|
||||
config.self_restart_enabled = false;
|
||||
let shutdown = CancellationToken::new();
|
||||
let service = ProcessSystemOperations::new(shutdown.clone(), config);
|
||||
assert!(!service.version().await.expect("version").restart_supported);
|
||||
assert_eq!(
|
||||
service
|
||||
.restart(Arc::new(AllowingUpdatePreflight))
|
||||
.await
|
||||
.expect_err("restart disabled")
|
||||
.kind(),
|
||||
SystemOperationErrorKind::Conflict
|
||||
);
|
||||
assert!(!shutdown.is_cancelled());
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn accepted_restart_excludes_system_operations_until_service_release() {
|
||||
let fixture = Fixture::new();
|
||||
|
||||
@@ -219,6 +219,7 @@ enum LeaseStep {
|
||||
enum RenewStep {
|
||||
Success,
|
||||
Error,
|
||||
Pending,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
@@ -268,11 +269,12 @@ impl WorkerLeaderLeaseGuard for FakeLeaseGuard {
|
||||
fn renew(&mut self) -> BoxFuture<'_, Result<(), WorkerLeaseError>> {
|
||||
Box::pin(async move {
|
||||
lock_unpoisoned(&self.renewals).push(self.worker.clone());
|
||||
match lock_unpoisoned(&self.renew_scripts)
|
||||
let step = lock_unpoisoned(&self.renew_scripts)
|
||||
.get_mut(&self.worker)
|
||||
.and_then(VecDeque::pop_front)
|
||||
.unwrap_or(RenewStep::Success)
|
||||
{
|
||||
.unwrap_or(RenewStep::Success);
|
||||
match step {
|
||||
RenewStep::Pending => pending().await,
|
||||
RenewStep::Success => Ok(()),
|
||||
RenewStep::Error => Err(WorkerLeaseError::safe("expected renewal failure")),
|
||||
}
|
||||
@@ -510,6 +512,31 @@ async fn long_cycle_renews_leader_lease_before_ttl() {
|
||||
supervisor.shutdown(Duration::from_secs(1)).await;
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn shutdown_signals_the_cycle_while_lease_renewal_is_pending() {
|
||||
let leases = Arc::new(FakeLeasePort::default());
|
||||
leases.renew_script(target_worker(), [RenewStep::Pending]);
|
||||
let task = CancellationTask {
|
||||
entered: Arc::new(AtomicUsize::new(0)),
|
||||
observed: Arc::new(AtomicUsize::new(0)),
|
||||
};
|
||||
let supervisor = supervisor();
|
||||
supervisor
|
||||
.start(
|
||||
target_plan(task.clone(), renewal_schedule()),
|
||||
leases.clone(),
|
||||
Arc::new(RecordingDiagnostics::default()),
|
||||
)
|
||||
.unwrap();
|
||||
yield_until(|| task.entered.load(Ordering::SeqCst) != 0).await;
|
||||
tokio::time::advance(Duration::from_millis(10)).await;
|
||||
yield_until(|| leases.renewal_count(&target_worker()) == 1).await;
|
||||
// 关闭预算短于续租超时,协作取消仍应完成
|
||||
supervisor.shutdown(Duration::from_millis(1)).await;
|
||||
assert_eq!(task.observed.load(Ordering::SeqCst), 1);
|
||||
assert!(lock_unpoisoned(&leases.active_guards).is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn renewal_failure_cancels_old_cycle_before_another_leader_cycle_starts() {
|
||||
let task = ConcurrentCycleTask {
|
||||
|
||||
@@ -248,21 +248,21 @@ impl Execution {
|
||||
request_body_limit,
|
||||
)
|
||||
.map_err(|error| fault_error(error, UpstreamSendState::NotSent))?;
|
||||
let upstream_model = invocation.metadata.upstream_model().ok_or_else(invalid)?;
|
||||
let request = UpstreamAdapterRequest {
|
||||
adapter_id: declaration.id.clone(),
|
||||
provider: declaration.provider,
|
||||
upstream_model: invocation
|
||||
.metadata
|
||||
.upstream_model()
|
||||
.ok_or_else(invalid)?
|
||||
.as_str()
|
||||
.to_owned(),
|
||||
upstream_model: upstream_model.as_str().to_owned(),
|
||||
client_key_id: invocation.context.client_api_key_ref().as_str().to_owned(),
|
||||
account_id: invocation.account.account_id().as_str().to_owned(),
|
||||
credential_revision: invocation.account.credential_revision().get(),
|
||||
protocol: invocation.operation.protocol().to_owned(),
|
||||
client_transport: invocation.context.client_transport().as_str().to_owned(),
|
||||
fast_mode: invocation.context.fast_mode().as_str().to_owned(),
|
||||
fast_mode: invocation
|
||||
.context
|
||||
.fast_mode_for_account(invocation.account.account_id(), upstream_model.as_str())
|
||||
.as_str()
|
||||
.to_owned(),
|
||||
request_elapsed_ms: u64::try_from(
|
||||
invocation.context.timing_started_at().elapsed().as_millis(),
|
||||
)
|
||||
|
||||
@@ -7,13 +7,16 @@ use serde_json::{Value, json};
|
||||
#[tokio::test]
|
||||
async fn middleware_preserves_fast_modes_and_sources() {
|
||||
for (mode, expected) in [
|
||||
(FastMode::Default, FastMode::Default),
|
||||
(FastMode::Enabled, FastMode::Enabled),
|
||||
(FastMode::Disabled, FastMode::Disabled),
|
||||
(FastMode::Enabled, FastMode::Disabled),
|
||||
(FastMode::Ultrafast, FastMode::Ultrafast),
|
||||
(FastMode::Enabled, FastMode::Ultrafast),
|
||||
(FastMode::Disabled, FastMode::Default),
|
||||
(None, None),
|
||||
(None, Some(FastMode::Default)),
|
||||
(Some(FastMode::Default), Some(FastMode::Default)),
|
||||
(Some(FastMode::Enabled), Some(FastMode::Enabled)),
|
||||
(Some(FastMode::Disabled), Some(FastMode::Disabled)),
|
||||
(Some(FastMode::Enabled), Some(FastMode::Disabled)),
|
||||
(Some(FastMode::Ultrafast), Some(FastMode::Ultrafast)),
|
||||
(Some(FastMode::Enabled), Some(FastMode::Ultrafast)),
|
||||
(Some(FastMode::Disabled), Some(FastMode::Default)),
|
||||
(Some(FastMode::Enabled), None),
|
||||
] {
|
||||
let snapshot = gateway_core::routing::RuntimeSnapshot::new(
|
||||
ConfigRevision::new(1).unwrap(),
|
||||
@@ -43,8 +46,7 @@ async fn middleware_preserves_fast_modes_and_sources() {
|
||||
let settings = settings.replace_execution(&seed, "seed").unwrap();
|
||||
let wire = serde_json::to_value(&seed).unwrap();
|
||||
let mut updated = wire.clone();
|
||||
updated["fast_mode"] = json!(expected.as_str());
|
||||
updated["timeout_ms"] = json!(90_000);
|
||||
updated["fast_mode"] = json!(expected);
|
||||
let contribution = crate::support::contribution(
|
||||
Capability::Middleware,
|
||||
vec![Stage::Request],
|
||||
@@ -61,8 +63,8 @@ async fn middleware_preserves_fast_modes_and_sources() {
|
||||
id: "fast-settings",
|
||||
configuration: json!({
|
||||
"mode":"settings", "expected_settings":wire, "settings":updated,
|
||||
"expected_fast_source": if mode == FastMode::Default { Value::Null } else {
|
||||
json!({"instance_id":"seed", "order":1, "value":mode.as_str()})
|
||||
"expected_fast_source": if mode.is_none() { Value::Null } else {
|
||||
json!({"instance_id":"seed", "order":1, "value":mode})
|
||||
},
|
||||
}),
|
||||
bindings: vec![binding(
|
||||
@@ -102,11 +104,11 @@ async fn middleware_preserves_fast_modes_and_sources() {
|
||||
assert_eq!(settings.execution_values().unwrap().fast_mode, expected);
|
||||
assert_eq!(
|
||||
settings.execution_values().unwrap().timeout_ms,
|
||||
Some(90_000)
|
||||
Some(60_000)
|
||||
);
|
||||
let sources = settings.inspect();
|
||||
let fast_source = &sources["execution"]["fast_mode"];
|
||||
if mode == FastMode::Default && expected == FastMode::Default {
|
||||
if mode.is_none() && expected.is_none() {
|
||||
assert!(fast_source.is_null());
|
||||
} else {
|
||||
assert_eq!(
|
||||
@@ -117,12 +119,9 @@ async fn middleware_preserves_fast_modes_and_sources() {
|
||||
"fast-settings"
|
||||
}
|
||||
);
|
||||
assert_eq!(fast_source["value"], expected.as_str());
|
||||
assert_eq!(fast_source["value"], json!(expected));
|
||||
}
|
||||
assert_eq!(
|
||||
sources["execution"]["timeout_ms"]["instance_id"],
|
||||
"fast-settings"
|
||||
);
|
||||
assert!(sources["execution"]["timeout_ms"].is_null());
|
||||
next.run(request).await
|
||||
})
|
||||
}),
|
||||
|
||||
@@ -1277,7 +1277,7 @@ async fn real_request_plugins_rewrite_settings_in_onion_order() {
|
||||
let baseline = ExecutionSettings {
|
||||
runtime: SettingsValues::new(3, "smart", BTreeMap::new(), None, None)
|
||||
.with_request_profiles(profiles("key-default")),
|
||||
fast_mode: FastMode::Disabled,
|
||||
fast_mode: Some(FastMode::Disabled),
|
||||
client_limits: RateLimits {
|
||||
max_concurrency: 2,
|
||||
requests_per_minute: 10,
|
||||
@@ -1314,7 +1314,7 @@ async fn real_request_plugins_rewrite_settings_in_onion_order() {
|
||||
gateway_core::routing::ClientRoutingScope::all_accounts(),
|
||||
)
|
||||
.with_request_profiles(profiles("key-default"))
|
||||
.with_fast_mode(baseline.fast_mode),
|
||||
.with_fast_mode_override(baseline.fast_mode),
|
||||
),
|
||||
true,
|
||||
baseline.client_limits,
|
||||
|
||||
@@ -179,7 +179,6 @@ fn context_with_body_limit(
|
||||
ClientApiKeyId::new(key).unwrap(),
|
||||
)
|
||||
.with_upstream_adapters(runtime.execution_registry().upstream_adapters(generation))
|
||||
.with_fast_mode(mode)
|
||||
.with_request_body_limit(bytes),
|
||||
NonZeroU32::new(1).unwrap(),
|
||||
SystemTime::now() + Duration::from_secs(5),
|
||||
@@ -187,7 +186,13 @@ fn context_with_body_limit(
|
||||
gateway_core::account::RotationStrategy::RoundRobin,
|
||||
std::num::NonZeroU32::new(1).unwrap(),
|
||||
),
|
||||
AccountAttemptContext::new(Default::default(), None, None),
|
||||
AccountAttemptContext::new(Default::default(), None, None).with_account_scope(Arc::new(
|
||||
gateway_core::routing::FrozenAccountScope::new(
|
||||
Arc::default(),
|
||||
gateway_core::routing::ClientRoutingScope::all_accounts(),
|
||||
)
|
||||
.with_fast_mode_override(Some(mode)),
|
||||
)),
|
||||
None,
|
||||
CancellationToken::new(),
|
||||
)
|
||||
|
||||
@@ -588,7 +588,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
);
|
||||
if let Some(expected) = configuration.get("expected_fast_source") {
|
||||
let sources = &call.request.head.settings_sources["execution"];
|
||||
assert_eq!(sources["input"]["fast_mode"], "default");
|
||||
assert!(sources["input"]["fast_mode"].is_null());
|
||||
assert_eq!(&sources["fast_mode"], expected);
|
||||
}
|
||||
if let Some(settings) = configuration.get("settings") {
|
||||
|
||||
@@ -489,7 +489,7 @@ let plugin = PluginBuilder::from_json(manifest_json)?
|
||||
|
||||
#### 模型请求与 attempt
|
||||
|
||||
`RequestCall.request.head` 包含完整 Client Key 与分组归属。request 中间件改写正文后,OpenAI 在进入 attempt 前应用宿主 Fast 策略;
|
||||
`RequestCall.request.head` 包含完整 Client Key 与分组归属。request 中间件改写正文后,OpenAI 按选中账号和上游模型解析宿主 Fast 策略,在进入 attempt 前应用;
|
||||
attempt 中间件在此基线上继续改写,终端不再应用 Fast 策略。
|
||||
request 与 attempt 阶段通过 `append_header` 添加的请求头会进入上游请求,不适合存放插件内部标记或仅供下游读取的信息。
|
||||
OpenAI 与 xAI 的上游 headers 先由账号和画像生成,插件同名字段覆盖基线,同名多值按插件顺序保留;不存在按认证、Cookie 或会话名称划分的保护列表。
|
||||
@@ -498,7 +498,8 @@ CPR 中间件添加的 HTTP 扩展头在发往 Antigravity 时经过该 Provider
|
||||
实际账号租约、凭据版本与计费归属仍记录真实选中事实,不随插件修改 header 名称而伪造
|
||||
|
||||
request 阶段 `request.head.settings` 是本次调用的有效设置对象,包含 `runtime`、`fast_mode`、`client_limits` 和 `timeout_ms`。
|
||||
`fast_mode` 使用 `default`、`enabled`、`ultrafast`、`disabled` 四个值,具体档位语义见[账号分组](../../../../../docs/api.md#6-账号分组)。
|
||||
`fast_mode` 为 `null` 时按选中账号的有效分组解析;显式 `default` 表示跟随客户端,`enabled`、`ultrafast`、`disabled` 覆盖分组策略,具体档位语义见[账号分组](../../../../../docs/api.md#6-账号分组)。
|
||||
保留该字段不建立新覆盖,改写为 `null` 恢复按分组解析;其他改写形成当前 Key 的显式覆盖,优先于分组策略。attempt 中间件仍可直接改写正文档位
|
||||
`runtime` 使用宿主快照的设置字段,画像已合并 Client Key 设置;可以修改映射、画像、调度、位置及计价等执行参数。
|
||||
SDK 仅在对象改变时提交完整替换,`false`、`0`、空映射和合同允许的 `null` 不表示跳过;不做隐式深合并。
|
||||
线协议省略 `next.settings` 才表示保留;显式 `null` 仍按完整替换校验,因不符合设置对象合同而拒绝。
|
||||
|
||||
@@ -41,7 +41,7 @@ Provider、业务协议和传输名称不能写入宿主兼容清单的 capabili
|
||||
`TypedCall<UpstreamAdapterRequest>` 包含只读的 Key、账号、凭据版本、模型、协议、Header 和宿主续接投影;
|
||||
原始请求正文位于 `call.payload`,原始账号凭据不进入插件输入。宿主首次消费冷流才调用插件
|
||||
|
||||
`fast_mode` 是本次模型执行的有效设置,取值为 `default`、`enabled`、`ultrafast` 或 `disabled`。OpenAI 在 attempt 中间件之前将 Fast 设置应用到正文基线,
|
||||
`fast_mode` 是按选中账号及上游模型解析后的有效策略,取值为 `default`、`enabled`、`ultrafast` 或 `disabled`,请求设置的显式覆盖优先于分组策略。OpenAI 在 attempt 中间件之前将 Fast 设置应用到正文基线,
|
||||
适配器收到经过 attempt 中间件处理的正文;attempt 中间件显式改写档位后,宿主不会在发送前再次应用 Fast 策略。
|
||||
其他请求设置与 Key 作用域的覆盖规则见[模型请求与 attempt](capabilities.md#模型请求与-attempt)
|
||||
|
||||
|
||||
@@ -3,7 +3,10 @@
|
||||
use crate::chat_completions::{
|
||||
ChatError, custom_tool_schema,
|
||||
error::{invalid, unsupported},
|
||||
request::string,
|
||||
request::{
|
||||
block_text, empty_history_content, empty_history_part, function_parameters,
|
||||
reasoning_effort, response_format, stop_sequences, string,
|
||||
},
|
||||
validate_request,
|
||||
};
|
||||
use serde_json::{Map, Value, json};
|
||||
@@ -13,7 +16,7 @@ pub fn convert_request(chat: &Map<String, Value>) -> Result<Map<String, Value>,
|
||||
validate_request(chat)?;
|
||||
let mut system = Vec::new();
|
||||
if let Some(instructions) = chat.get("instructions").filter(|v| !v.is_null()) {
|
||||
system.extend(parts(instructions, "instructions", true)?);
|
||||
system.extend(parts(instructions, "instructions", "system")?);
|
||||
}
|
||||
let mut contents = Vec::new();
|
||||
let mut calls = BTreeMap::new();
|
||||
@@ -30,7 +33,7 @@ pub fn convert_request(chat: &Map<String, Value>) -> Result<Map<String, Value>,
|
||||
system.extend(parts(
|
||||
&message["content"],
|
||||
&format!("{path}.content"),
|
||||
true,
|
||||
role,
|
||||
)?);
|
||||
continue;
|
||||
}
|
||||
@@ -48,7 +51,7 @@ pub fn convert_request(chat: &Map<String, Value>) -> Result<Map<String, Value>,
|
||||
}
|
||||
let mut text = Vec::new();
|
||||
let mut media = Vec::new();
|
||||
for part in parts(&message["content"], &format!("{path}.content"), false)? {
|
||||
for part in parts(&message["content"], &format!("{path}.content"), role)? {
|
||||
if let Some(value) = part.get("text").and_then(Value::as_str) {
|
||||
text.push(value.to_owned());
|
||||
} else {
|
||||
@@ -61,12 +64,12 @@ pub fn convert_request(chat: &Map<String, Value>) -> Result<Map<String, Value>,
|
||||
}
|
||||
vec![response]
|
||||
} else {
|
||||
let mut content = if message["content"].is_null() {
|
||||
Vec::new()
|
||||
} else {
|
||||
parts(&message["content"], &format!("{path}.content"), false)?
|
||||
};
|
||||
if let Some(refusal) = message.get("refusal").and_then(Value::as_str) {
|
||||
let mut content = parts(&message["content"], &format!("{path}.content"), role)?;
|
||||
if let Some(refusal) = message
|
||||
.get("refusal")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|v| !v.is_empty())
|
||||
{
|
||||
content.push(json!({"text":refusal}));
|
||||
}
|
||||
for (call_index, call) in message
|
||||
@@ -105,6 +108,9 @@ pub fn convert_request(chat: &Map<String, Value>) -> Result<Map<String, Value>,
|
||||
}
|
||||
content
|
||||
};
|
||||
if role == "assistant" && content.is_empty() {
|
||||
continue;
|
||||
}
|
||||
append(
|
||||
&mut contents,
|
||||
if role == "assistant" { "model" } else { "user" },
|
||||
@@ -134,11 +140,10 @@ pub fn convert_request(chat: &Map<String, Value>) -> Result<Map<String, Value>,
|
||||
generation.insert(to.into(), value.clone());
|
||||
}
|
||||
}
|
||||
if let Some(effort) = chat
|
||||
.get("reasoning_effort")
|
||||
.or_else(|| chat.get("reasoning").and_then(|v| v.get("effort")))
|
||||
.filter(|v| !v.is_null())
|
||||
{
|
||||
if let Some(stops) = stop_sequences(chat)? {
|
||||
generation.insert("stopSequences".into(), stops);
|
||||
}
|
||||
if let Some(effort) = reasoning_effort(chat) {
|
||||
let budget: i64 = match effort.as_str() {
|
||||
Some("none") => 0,
|
||||
Some("minimal" | "low") => 1024,
|
||||
@@ -158,11 +163,7 @@ pub fn convert_request(chat: &Map<String, Value>) -> Result<Map<String, Value>,
|
||||
},
|
||||
);
|
||||
}
|
||||
if let Some(format) = chat
|
||||
.get("response_format")
|
||||
.or_else(|| chat.get("text").and_then(|v| v.get("format")))
|
||||
.filter(|v| !v.is_null())
|
||||
{
|
||||
if let Some(format) = response_format(chat) {
|
||||
match format["type"].as_str() {
|
||||
Some("json_schema") => {
|
||||
generation.insert("responseMimeType".into(), json!("application/json"));
|
||||
@@ -205,7 +206,11 @@ fn append(contents: &mut Vec<Value>, role: &str, parts: Vec<Value>) {
|
||||
}
|
||||
}
|
||||
|
||||
fn parts(value: &Value, path: &str, system: bool) -> Result<Vec<Value>, ChatError> {
|
||||
fn parts(value: &Value, path: &str, role: &str) -> Result<Vec<Value>, ChatError> {
|
||||
if empty_history_content(role, value) {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let system = matches!(role, "system" | "developer");
|
||||
if let Some(text) = value.as_str() {
|
||||
return Ok(vec![json!({"text":text})]);
|
||||
}
|
||||
@@ -214,12 +219,13 @@ fn parts(value: &Value, path: &str, system: bool) -> Result<Vec<Value>, ChatErro
|
||||
.ok_or_else(|| invalid(path))?
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, part)| !empty_history_part(role, part))
|
||||
.map(|(index, part)| {
|
||||
let path = format!("{path}[{index}]");
|
||||
let kind = string(part.get("type"), &format!("{path}.type"), false)?;
|
||||
match kind {
|
||||
"text" | "input_text" | "output_text" => {
|
||||
Ok(json!({"text":string(part.get("text"), &format!("{path}.text"), true)?}))
|
||||
Ok(json!({"text":block_text(part.get("text"), &path)?}))
|
||||
}
|
||||
"refusal" if !system => Ok(
|
||||
json!({"text":string(part.get("refusal"), &format!("{path}.refusal"), true)?}),
|
||||
@@ -314,16 +320,10 @@ fn tools(chat: &Map<String, Value>, result: &mut Map<String, Value>) -> Result<(
|
||||
let parameters = if kind == "custom" {
|
||||
custom_tool_schema(definition.get("format"), &format!("{path}.custom.format"))?
|
||||
} else {
|
||||
definition
|
||||
.get("parameters")
|
||||
.cloned()
|
||||
.unwrap_or_else(|| json!({"type":"object","properties":{}}))
|
||||
function_parameters(definition, &path)?
|
||||
};
|
||||
if !parameters.is_object() {
|
||||
return Err(invalid(&format!("{path}.function.parameters")));
|
||||
}
|
||||
let mut declaration = json!({"name":name,"parametersJsonSchema":parameters});
|
||||
if let Some(value) = definition.get("description") {
|
||||
if let Some(value) = definition.get("description").filter(|v| !v.is_null()) {
|
||||
declaration["description"] = value.clone();
|
||||
}
|
||||
declarations.push(declaration);
|
||||
|
||||
@@ -4,7 +4,10 @@ use crate::anthropic::MessagesModelCapabilities;
|
||||
use crate::chat_completions::{
|
||||
ChatError, custom_tool_schema,
|
||||
error::{invalid, unsupported},
|
||||
request::string,
|
||||
request::{
|
||||
block_text, empty_history_content, empty_history_part, function_parameters,
|
||||
reasoning_effort, response_format, stop_sequences, string,
|
||||
},
|
||||
validate_request,
|
||||
};
|
||||
use serde_json::{Map, Value, json};
|
||||
@@ -37,6 +40,9 @@ pub fn convert_request(
|
||||
result.insert(field.into(), value.clone());
|
||||
}
|
||||
}
|
||||
if let Some(stops) = stop_sequences(chat)? {
|
||||
result.insert("stop_sequences".into(), stops);
|
||||
}
|
||||
if let Some(tier) = chat.get("service_tier").and_then(Value::as_str) {
|
||||
match tier {
|
||||
"priority" => {
|
||||
@@ -53,7 +59,7 @@ pub fn convert_request(
|
||||
}
|
||||
let mut system = Vec::new();
|
||||
if let Some(instructions) = chat.get("instructions").filter(|v| !v.is_null()) {
|
||||
system.extend(content(instructions, "instructions", true)?);
|
||||
system.extend(content(instructions, "instructions", "system")?);
|
||||
}
|
||||
let mut messages = Vec::new();
|
||||
let mut calls = BTreeMap::new();
|
||||
@@ -70,7 +76,7 @@ pub fn convert_request(
|
||||
system.extend(content(
|
||||
&message["content"],
|
||||
&format!("{path}.content"),
|
||||
true,
|
||||
role,
|
||||
)?);
|
||||
continue;
|
||||
}
|
||||
@@ -84,15 +90,15 @@ pub fn convert_request(
|
||||
return Err(invalid(&format!("{path}.tool_call_id")));
|
||||
}
|
||||
vec![
|
||||
json!({"type":"tool_result","tool_use_id":id,"content":content(&message["content"], &format!("{path}.content"), false)?}),
|
||||
json!({"type":"tool_result","tool_use_id":id,"content":content(&message["content"], &format!("{path}.content"), role)?}),
|
||||
]
|
||||
} else {
|
||||
let mut blocks = if message["content"].is_null() {
|
||||
Vec::new()
|
||||
} else {
|
||||
content(&message["content"], &format!("{path}.content"), false)?
|
||||
};
|
||||
if let Some(refusal) = message.get("refusal").and_then(Value::as_str) {
|
||||
let mut blocks = content(&message["content"], &format!("{path}.content"), role)?;
|
||||
if let Some(refusal) = message
|
||||
.get("refusal")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|v| !v.is_empty())
|
||||
{
|
||||
blocks.push(json!({"type":"text","text":refusal}));
|
||||
}
|
||||
for (call_index, call) in message
|
||||
@@ -130,6 +136,9 @@ pub fn convert_request(
|
||||
}
|
||||
blocks
|
||||
};
|
||||
if role == "assistant" && blocks.is_empty() {
|
||||
continue;
|
||||
}
|
||||
append_message(
|
||||
&mut messages,
|
||||
if role == "assistant" {
|
||||
@@ -148,10 +157,7 @@ pub fn convert_request(
|
||||
}
|
||||
result.insert("messages".into(), messages.into());
|
||||
tools(chat, &mut result, capabilities)?;
|
||||
let format = chat
|
||||
.get("response_format")
|
||||
.or_else(|| chat.get("text").and_then(|v| v.get("format")));
|
||||
if let Some(format) = format.filter(|v| !v.is_null()) {
|
||||
if let Some(format) = response_format(chat) {
|
||||
match format["type"].as_str() {
|
||||
Some("json_schema") => {
|
||||
let schema = format
|
||||
@@ -190,7 +196,11 @@ fn append_message(messages: &mut Vec<Value>, role: &str, blocks: Vec<Value>) {
|
||||
}
|
||||
}
|
||||
|
||||
fn content(value: &Value, path: &str, system: bool) -> Result<Vec<Value>, ChatError> {
|
||||
fn content(value: &Value, path: &str, role: &str) -> Result<Vec<Value>, ChatError> {
|
||||
if empty_history_content(role, value) {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let system = matches!(role, "system" | "developer");
|
||||
if let Some(text) = value.as_str() {
|
||||
return Ok(vec![json!({"type":"text","text":text})]);
|
||||
}
|
||||
@@ -200,12 +210,13 @@ fn content(value: &Value, path: &str, system: bool) -> Result<Vec<Value>, ChatEr
|
||||
.ok_or_else(|| invalid(path))?
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, part)| !empty_history_part(role, part))
|
||||
{
|
||||
let path = format!("{path}[{index}]");
|
||||
let kind = string(part.get("type"), &format!("{path}.type"), false)?;
|
||||
let block = match kind {
|
||||
"text" | "input_text" | "output_text" => {
|
||||
json!({"type":"text","text":string(part.get("text"), &format!("{path}.text"), true)?})
|
||||
json!({"type":"text","text":block_text(part.get("text"), &path)?})
|
||||
}
|
||||
"refusal" if !system => {
|
||||
json!({"type":"text","text":string(part.get("refusal"), &format!("{path}.refusal"), true)?})
|
||||
@@ -295,17 +306,11 @@ fn tools(
|
||||
let schema = if kind == "custom" {
|
||||
custom_tool_schema(declaration.get("format"), &format!("{path}.custom.format"))?
|
||||
} else {
|
||||
declaration
|
||||
.get("parameters")
|
||||
.cloned()
|
||||
.unwrap_or_else(|| json!({"type":"object","properties":{}}))
|
||||
function_parameters(declaration, &path)?
|
||||
};
|
||||
if !schema.is_object() {
|
||||
return Err(invalid(&format!("{path}.function.parameters")));
|
||||
}
|
||||
let mut target = json!({"name":name,"input_schema":schema});
|
||||
for field in ["description", "strict", "cache_control"] {
|
||||
if let Some(value) = declaration.get(field) {
|
||||
if let Some(value) = declaration.get(field).filter(|v| !v.is_null()) {
|
||||
target[field] = value.clone();
|
||||
}
|
||||
}
|
||||
@@ -393,11 +398,7 @@ fn reasoning(
|
||||
capabilities: &MessagesModelCapabilities,
|
||||
max_tokens: u64,
|
||||
) -> Result<(), ChatError> {
|
||||
let Some(effort) = chat
|
||||
.get("reasoning_effort")
|
||||
.or_else(|| chat.get("reasoning").and_then(|v| v.get("effort")))
|
||||
.filter(|v| !v.is_null())
|
||||
else {
|
||||
let Some(effort) = reasoning_effort(chat) else {
|
||||
return Ok(());
|
||||
};
|
||||
let effort = effort.as_str().ok_or_else(|| invalid("reasoning_effort"))?;
|
||||
|
||||
@@ -30,11 +30,7 @@ pub fn validate_request(body: &Map<String, Value>) -> Result<(), ChatError> {
|
||||
field: "messages".into(),
|
||||
expected: "an array",
|
||||
})?;
|
||||
if messages.is_empty() {
|
||||
return Err(ChatError::EmptyField {
|
||||
field: "messages".into(),
|
||||
});
|
||||
}
|
||||
let mut has_message = false;
|
||||
for (index, message) in messages.iter().enumerate() {
|
||||
let path = format!("messages[{index}]");
|
||||
let message = message.as_object().ok_or_else(|| invalid(&path))?;
|
||||
@@ -42,43 +38,53 @@ pub fn validate_request(body: &Map<String, Value>) -> Result<(), ChatError> {
|
||||
if !matches!(role, "system" | "developer" | "user" | "assistant" | "tool") {
|
||||
return Err(unsupported(&format!("{path}.role")));
|
||||
}
|
||||
for (field, allowed) in [
|
||||
("tool_calls", "assistant"),
|
||||
("refusal", "assistant"),
|
||||
("tool_call_id", "tool"),
|
||||
] {
|
||||
if role != allowed && message.get(field).is_some_and(|v| !v.is_null()) {
|
||||
return Err(invalid(&format!("{path}.{field}")));
|
||||
let calls = match message.get("tool_calls") {
|
||||
None | Some(Value::Null) => &[][..],
|
||||
Some(Value::Array(calls)) => calls.as_slice(),
|
||||
_ => return Err(invalid(&format!("{path}.tool_calls"))),
|
||||
};
|
||||
if role != "assistant" && !calls.is_empty() {
|
||||
return Err(invalid(&format!("{path}.tool_calls")));
|
||||
}
|
||||
let refusal = message.get("refusal").filter(|v| !v.is_null() && *v != "");
|
||||
if let Some(value) = refusal {
|
||||
if role != "assistant" {
|
||||
return Err(invalid(&format!("{path}.refusal")));
|
||||
}
|
||||
string(Some(value), &format!("{path}.refusal"), true)?;
|
||||
}
|
||||
for field in ["function_call", "audio"] {
|
||||
if message.get(field).is_some_and(|v| !v.is_null()) {
|
||||
return Err(unsupported(&format!("{path}.{field}")));
|
||||
}
|
||||
}
|
||||
for field in ["name", "refusal"] {
|
||||
if let Some(value) = message.get(field).filter(|v| !v.is_null()) {
|
||||
string(Some(value), &format!("{path}.{field}"), true)?;
|
||||
}
|
||||
}
|
||||
if role == "tool" {
|
||||
string(
|
||||
message.get("tool_call_id"),
|
||||
&format!("{path}.tool_call_id"),
|
||||
false,
|
||||
)?;
|
||||
// Responses 的独立工具输出通过名称标识,不依赖前序调用
|
||||
let field = if message.get("tool_call_id").is_none_or(Value::is_null) {
|
||||
"name"
|
||||
} else {
|
||||
"tool_call_id"
|
||||
};
|
||||
string(message.get(field), &format!("{path}.{field}"), false)?;
|
||||
} else if message
|
||||
.get("tool_call_id")
|
||||
.is_some_and(|v| !v.is_null() && v != "")
|
||||
{
|
||||
return Err(invalid(&format!("{path}.tool_call_id")));
|
||||
}
|
||||
if let Some(content) = message.get("content").filter(|v| !v.is_null()) {
|
||||
let content = message.get("content").unwrap_or(&Value::Null);
|
||||
if !empty_history_content(role, content) {
|
||||
if !content.is_string() && !content.is_array() {
|
||||
return Err(invalid(&format!("{path}.content")));
|
||||
}
|
||||
has_message = true;
|
||||
if let Some(parts) = content.as_array() {
|
||||
for (part_index, part) in parts.iter().enumerate() {
|
||||
let part_path = format!("{path}.content[{part_index}]");
|
||||
let kind = string(part.get("type"), &format!("{part_path}.type"), false)?;
|
||||
match kind {
|
||||
"text" | "input_text" | "output_text" => {
|
||||
string(part.get("text"), &format!("{part_path}.text"), true)?;
|
||||
block_text(part.get("text"), &part_path)?;
|
||||
}
|
||||
"image_url" | "file" | "input_audio" | "input_image" | "input_file"
|
||||
if matches!(role, "user" | "tool") => {}
|
||||
@@ -89,45 +95,37 @@ pub fn validate_request(body: &Map<String, Value>) -> Result<(), ChatError> {
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if role != "assistant"
|
||||
|| (!message
|
||||
.get("tool_calls")
|
||||
.is_some_and(|v| v.as_array().is_some_and(|v| !v.is_empty()))
|
||||
&& !message.get("refusal").is_some_and(Value::is_string))
|
||||
{
|
||||
return Err(invalid(&format!("{path}.content")));
|
||||
}
|
||||
if let Some(calls) = message.get("tool_calls").filter(|v| !v.is_null()) {
|
||||
for (call_index, call) in calls
|
||||
.as_array()
|
||||
.ok_or_else(|| invalid(&format!("{path}.tool_calls")))?
|
||||
.iter()
|
||||
.enumerate()
|
||||
{
|
||||
let call_path = format!("{path}.tool_calls[{call_index}]");
|
||||
string(call.get("id"), &format!("{call_path}.id"), false)?;
|
||||
let kind = string(call.get("type"), &format!("{call_path}.type"), false)?;
|
||||
if !matches!(kind, "function" | "custom") {
|
||||
return Err(unsupported(&format!("{call_path}.type")));
|
||||
}
|
||||
string(
|
||||
call.get(kind).and_then(|v| v.get("name")),
|
||||
&format!("{call_path}.{kind}.name"),
|
||||
false,
|
||||
)?;
|
||||
let data_field = if kind == "function" {
|
||||
"arguments"
|
||||
} else {
|
||||
"input"
|
||||
};
|
||||
string(
|
||||
call.get(kind).and_then(|v| v.get(data_field)),
|
||||
&format!("{call_path}.{kind}.{data_field}"),
|
||||
true,
|
||||
)?;
|
||||
has_message |= refusal.is_some() || !calls.is_empty();
|
||||
for (call_index, call) in calls.iter().enumerate() {
|
||||
let call_path = format!("{path}.tool_calls[{call_index}]");
|
||||
string(call.get("id"), &format!("{call_path}.id"), false)?;
|
||||
let kind = string(call.get("type"), &format!("{call_path}.type"), false)?;
|
||||
if !matches!(kind, "function" | "custom") {
|
||||
return Err(unsupported(&format!("{call_path}.type")));
|
||||
}
|
||||
string(
|
||||
call.get(kind).and_then(|v| v.get("name")),
|
||||
&format!("{call_path}.{kind}.name"),
|
||||
false,
|
||||
)?;
|
||||
let data_field = if kind == "function" {
|
||||
"arguments"
|
||||
} else {
|
||||
"input"
|
||||
};
|
||||
string(
|
||||
call.get(kind).and_then(|v| v.get(data_field)),
|
||||
&format!("{call_path}.{kind}.{data_field}"),
|
||||
true,
|
||||
)?;
|
||||
}
|
||||
}
|
||||
if !has_message {
|
||||
return Err(ChatError::EmptyField {
|
||||
field: "messages".into(),
|
||||
});
|
||||
}
|
||||
for (field, value) in body.iter().filter(|(_, v)| !v.is_null()) {
|
||||
let valid = match field.as_str() {
|
||||
"n" => value.as_u64() == Some(1),
|
||||
@@ -150,7 +148,7 @@ pub fn validate_request(body: &Map<String, Value>) -> Result<(), ChatError> {
|
||||
}
|
||||
}
|
||||
if let Some(options) = body.get("stream_options").filter(|v| !v.is_null()) {
|
||||
if body.get("stream") != Some(&Value::Bool(true)) || !options.is_object() {
|
||||
if !options.is_object() {
|
||||
return Err(invalid("stream_options"));
|
||||
}
|
||||
for field in ["include_usage", "include_obfuscation"] {
|
||||
@@ -161,13 +159,99 @@ pub fn validate_request(body: &Map<String, Value>) -> Result<(), ChatError> {
|
||||
return Err(invalid(&format!("stream_options.{field}")));
|
||||
}
|
||||
}
|
||||
if options.get("include_obfuscation") == Some(&Value::Bool(true)) {
|
||||
if body.get("stream") == Some(&Value::Bool(true))
|
||||
&& options.get("include_obfuscation") == Some(&Value::Bool(true))
|
||||
{
|
||||
return Err(unsupported("stream_options.include_obfuscation"));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// 用户输入和工具结果保留原值,空指令或 assistant 正文不生成上游内容块
|
||||
pub(super) fn empty_history_content(role: &str, content: &Value) -> bool {
|
||||
can_omit_empty_text(role)
|
||||
&& (content.is_null()
|
||||
|| content == ""
|
||||
|| content
|
||||
.as_array()
|
||||
.is_some_and(|parts| parts.iter().all(plain_empty_text)))
|
||||
}
|
||||
|
||||
fn can_omit_empty_text(role: &str) -> bool {
|
||||
matches!(role, "system" | "developer" | "assistant")
|
||||
}
|
||||
|
||||
fn plain_empty_text(part: &Value) -> bool {
|
||||
// 只移除纯文本占位,带缓存断点等附加字段的块交给目标转换器
|
||||
part.get("text")
|
||||
.is_some_and(|text| text.is_null() || text == "")
|
||||
&& matches!(
|
||||
part.get("type").and_then(Value::as_str),
|
||||
Some("text" | "input_text" | "output_text")
|
||||
)
|
||||
&& part.as_object().is_some_and(|fields| {
|
||||
fields
|
||||
.iter()
|
||||
.all(|(key, value)| matches!(key.as_str(), "type" | "text") || value.is_null())
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn empty_history_part(role: &str, part: &Value) -> bool {
|
||||
can_omit_empty_text(role) && plain_empty_text(part)
|
||||
}
|
||||
|
||||
// 部分 Chat 客户端用显式 null 表示空文本,缺少 text 或其他类型仍按原字段报错
|
||||
pub(super) fn block_text<'a>(
|
||||
value: Option<&'a Value>,
|
||||
part_path: &str,
|
||||
) -> Result<&'a str, ChatError> {
|
||||
match value {
|
||||
Some(Value::Null) => Ok(""),
|
||||
value => string(value, &format!("{part_path}.text"), true),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn response_format(body: &Map<String, Value>) -> Option<&Value> {
|
||||
body.get("response_format")
|
||||
.filter(|v| !v.is_null())
|
||||
.or_else(|| body.get("text")?.get("format").filter(|v| !v.is_null()))
|
||||
}
|
||||
|
||||
pub(super) fn reasoning_effort(body: &Map<String, Value>) -> Option<&Value> {
|
||||
body.get("reasoning_effort")
|
||||
.filter(|v| !v.is_null())
|
||||
.or_else(|| {
|
||||
body.get("reasoning")?
|
||||
.get("effort")
|
||||
.filter(|v| !v.is_null())
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn stop_sequences(body: &Map<String, Value>) -> Result<Option<Value>, ChatError> {
|
||||
match body.get("stop") {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(Value::String(text)) => Ok(Some(json!([text]))),
|
||||
Some(Value::Array(values)) => {
|
||||
for (index, value) in values.iter().enumerate() {
|
||||
if !value.is_string() {
|
||||
return Err(invalid(&format!("stop[{index}]")));
|
||||
}
|
||||
}
|
||||
Ok((!values.is_empty()).then(|| Value::Array(values.clone())))
|
||||
}
|
||||
_ => Err(invalid("stop")),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn function_parameters(function: &Value, path: &str) -> Result<Value, ChatError> {
|
||||
match function.get("parameters") {
|
||||
None | Some(Value::Null) => Ok(json!({"type":"object","properties":{}})),
|
||||
Some(schema) if schema.is_object() => Ok(schema.clone()),
|
||||
_ => Err(invalid(&format!("{path}.function.parameters"))),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn string<'a>(
|
||||
value: Option<&'a Value>,
|
||||
path: &str,
|
||||
@@ -222,28 +306,16 @@ pub(crate) fn request_facts(body: &Map<String, Value>) -> RequestFacts {
|
||||
.any(|tool| tool.get("type").and_then(Value::as_str) == Some("image_generation")),
|
||||
reasoning: body.get("reasoning_effort").is_some_and(|v| !v.is_null())
|
||||
|| body.get("reasoning").is_some_and(Value::is_object),
|
||||
json_schema: body
|
||||
.get("response_format")
|
||||
json_schema: response_format(body)
|
||||
.and_then(|v| v.get("type"))
|
||||
.and_then(Value::as_str)
|
||||
== Some("json_schema")
|
||||
|| body
|
||||
.get("text")
|
||||
.and_then(|v| v.pointer("/format/type"))
|
||||
.and_then(Value::as_str)
|
||||
== Some("json_schema"),
|
||||
== Some("json_schema"),
|
||||
..RequestFacts::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn request_effort(body: &Map<String, Value>) -> Option<&str> {
|
||||
body.get("reasoning_effort")
|
||||
.and_then(Value::as_str)
|
||||
.or_else(|| {
|
||||
body.get("reasoning")
|
||||
.and_then(|value| value.get("effort"))
|
||||
.and_then(Value::as_str)
|
||||
})
|
||||
reasoning_effort(body).and_then(Value::as_str)
|
||||
}
|
||||
|
||||
/// 将无格式约束的 custom 工具表达为字符串参数,受约束格式必须由目标原生支持
|
||||
|
||||
@@ -4,7 +4,11 @@ use std::collections::HashSet;
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
use crate::chat_completions::{ChatError as RequestDecodeError, validate_request};
|
||||
use crate::chat_completions::{
|
||||
ChatError as RequestDecodeError,
|
||||
request::{block_text, empty_history_content, empty_history_part},
|
||||
validate_request,
|
||||
};
|
||||
|
||||
/// 将已验证的 Chat 正文直接转换为 Responses 请求
|
||||
pub fn convert_request(
|
||||
@@ -161,14 +165,8 @@ fn messages(value: Value) -> Result<Vec<Value>, RequestDecodeError> {
|
||||
let path = format!("messages[{index}]");
|
||||
let mut message = object(value, &path)?;
|
||||
let role = required_string(&mut message, "role", &format!("{path}.role"), false)?;
|
||||
let name = optional(&mut message, "name").filter(|name| name != "");
|
||||
if role == "tool" {
|
||||
let call_id = required_string(
|
||||
&mut message,
|
||||
"tool_call_id",
|
||||
&format!("{path}.tool_call_id"),
|
||||
false,
|
||||
)?;
|
||||
let call_id = optional(&mut message, "tool_call_id");
|
||||
let content_path = format!("{path}.content");
|
||||
let content = required(&mut message, "content", &content_path)?;
|
||||
let output = if content.is_string() {
|
||||
@@ -176,14 +174,24 @@ fn messages(value: Value) -> Result<Vec<Value>, RequestDecodeError> {
|
||||
} else {
|
||||
content_parts(content, &role, &content_path, false)?.into()
|
||||
};
|
||||
let kind = if custom_calls.contains(&call_id) {
|
||||
let kind = if call_id
|
||||
.as_ref()
|
||||
.and_then(Value::as_str)
|
||||
.is_some_and(|id| custom_calls.contains(id))
|
||||
{
|
||||
"custom_tool_call_output"
|
||||
} else {
|
||||
"function_call_output"
|
||||
};
|
||||
let mut item = json!({"type": kind, "call_id": call_id, "output": output});
|
||||
if let Some(name) = name {
|
||||
item["name"] = name;
|
||||
let mut item = json!({"type": kind, "output": output});
|
||||
if let Some(call_id) = call_id {
|
||||
item["call_id"] = call_id;
|
||||
}
|
||||
for field in ["name", "namespace"] {
|
||||
if let Some(value) = optional(&mut message, field).filter(|value| value != "") {
|
||||
string(&value, &format!("{path}.{field}"), true)?;
|
||||
item[field] = value;
|
||||
}
|
||||
}
|
||||
input.push(item);
|
||||
continue;
|
||||
@@ -193,8 +201,9 @@ fn messages(value: Value) -> Result<Vec<Value>, RequestDecodeError> {
|
||||
.map(|value| tool_calls(value, &format!("{path}.tool_calls")))
|
||||
.transpose()?
|
||||
.unwrap_or_default();
|
||||
let refusal = optional(&mut message, "refusal");
|
||||
let content = optional(&mut message, "content");
|
||||
let refusal = optional(&mut message, "refusal").filter(|v| v != "");
|
||||
let content =
|
||||
optional(&mut message, "content").filter(|v| !empty_history_content(&role, v));
|
||||
let is_assistant = role == "assistant";
|
||||
let mut parts = content
|
||||
.map(|value| content_parts(value, &role, &format!("{path}.content"), is_assistant))
|
||||
@@ -233,20 +242,23 @@ fn content_parts(
|
||||
is_assistant: bool,
|
||||
) -> Result<Vec<Value>, RequestDecodeError> {
|
||||
let parts = match value {
|
||||
Value::String(text) => return Ok(vec![text_part(text, is_assistant)]),
|
||||
Value::String(text) => return Ok(vec![text_part(&text, is_assistant)]),
|
||||
Value::Array(parts) => parts,
|
||||
_ => return Err(invalid_type(path, "a string or an array")),
|
||||
};
|
||||
let mut result = Vec::with_capacity(parts.len());
|
||||
for (index, value) in parts.into_iter().enumerate() {
|
||||
for (index, value) in parts
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.filter(|(_, part)| !empty_history_part(role, part))
|
||||
{
|
||||
let path = format!("{path}[{index}]");
|
||||
let mut part = object(value, &path)?;
|
||||
let kind = required_string(&mut part, "type", &format!("{path}.type"), false)?;
|
||||
let mut converted = match kind.as_str() {
|
||||
"text" | "input_text" | "output_text" => text_part(
|
||||
required_string(&mut part, "text", &format!("{path}.text"), true)?,
|
||||
is_assistant,
|
||||
),
|
||||
"text" | "input_text" | "output_text" => {
|
||||
text_part(block_text(part.get("text"), &path)?, is_assistant)
|
||||
}
|
||||
"image_url" if matches!(role, "user" | "tool") => image_part(
|
||||
required(&mut part, "image_url", &format!("{path}.image_url"))?,
|
||||
&format!("{path}.image_url"),
|
||||
@@ -278,7 +290,7 @@ fn content_parts(
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
fn text_part(text: String, is_assistant: bool) -> Value {
|
||||
fn text_part(text: &str, is_assistant: bool) -> Value {
|
||||
if is_assistant {
|
||||
json!({"type": "output_text", "text": text, "annotations": []})
|
||||
} else {
|
||||
@@ -369,16 +381,33 @@ fn tools(value: Value) -> Result<Vec<Value>, RequestDecodeError> {
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(index, value)| {
|
||||
let path = format!("tools[{index}]");
|
||||
let mut path = format!("tools[{index}]");
|
||||
let mut tool = object(value, &path)?;
|
||||
let kind = required_string(&mut tool, "type", &format!("{path}.type"), false)?;
|
||||
if matches!(kind.as_str(), "function" | "custom") {
|
||||
if let Some(nested) = optional(&mut tool, &kind) {
|
||||
tool = object(nested, &format!("{path}.{kind}"))?;
|
||||
path = format!("{path}.{kind}");
|
||||
tool = object(nested, &path)?;
|
||||
}
|
||||
if kind == "function" && tool.get("strict").is_none_or(Value::is_null) {
|
||||
// Chat 的缺省是宽松 schema,不能让 Responses 收紧参数合同
|
||||
tool.insert("strict".into(), false.into());
|
||||
if tool.get("description") == Some(&Value::Null) {
|
||||
tool.remove("description");
|
||||
}
|
||||
if kind == "function" {
|
||||
if tool.get("parameters") == Some(&Value::Null) {
|
||||
tool.remove("parameters");
|
||||
}
|
||||
if tool.get("strict").is_none_or(Value::is_null) {
|
||||
// Chat 的缺省是宽松 schema,不能让 Responses 收紧参数合同
|
||||
tool.insert("strict".into(), false.into());
|
||||
}
|
||||
} else if let Some(format) = tool.get_mut("format").and_then(Value::as_object_mut)
|
||||
&& format.get("type").and_then(Value::as_str) == Some("grammar")
|
||||
&& let Some(grammar) = optional(format, "grammar")
|
||||
{
|
||||
// Chat 将语法嵌套在 grammar,Responses 使用同层的 syntax 和 definition
|
||||
let grammar = object(grammar, &format!("{path}.format.grammar"))?;
|
||||
format.extend(grammar);
|
||||
format.insert("type".into(), "grammar".into());
|
||||
}
|
||||
}
|
||||
// hosted 工具采用原生 Responses 结构,支持范围由选中的 Provider 决定
|
||||
|
||||
@@ -1,4 +1,21 @@
|
||||
//! 跨协议 HTTP 传输、下游环境头分类与重试时间解析
|
||||
//! 跨协议 HTTP 头分类、响应关联与重试时间解析
|
||||
|
||||
/// 响应关联 ID 的头名与优先级沿用官方 Codex
|
||||
pub const RESPONSE_REQUEST_ID_HEADERS: [&str; 4] = [
|
||||
"x-request-id",
|
||||
"x-oai-request-id",
|
||||
"x-openai-request-id",
|
||||
"x-ms-request-id",
|
||||
];
|
||||
|
||||
/// 从各传输容器提供的可读 HTTP 头值中选取关联 ID,空值不阻止别名回退
|
||||
pub fn preferred_response_request_id<'a>(
|
||||
mut header: impl FnMut(&str) -> Option<&'a str>,
|
||||
) -> Option<&'a str> {
|
||||
RESPONSE_REQUEST_ID_HEADERS
|
||||
.iter()
|
||||
.find_map(|name| header(name).filter(|value| !value.trim().is_empty()))
|
||||
}
|
||||
|
||||
/// 上游可交给客户端的秒级与毫秒级重试等待头
|
||||
pub const RETRY_AFTER_HEADERS: [&str; 2] = ["retry-after", "retry-after-ms"];
|
||||
|
||||
@@ -4,7 +4,15 @@ use gateway_protocol::{
|
||||
chat_completions::{CHAT_PROTOCOL, ChatError, genai, messages, parse_request, responses},
|
||||
request::{request_facts, request_observation},
|
||||
};
|
||||
use serde_json::json;
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
fn target_requests(body: &Map<String, Value>) -> [Result<Map<String, Value>, ChatError>; 3] {
|
||||
[
|
||||
responses::convert_request(body),
|
||||
messages::convert_request(body, &Default::default()),
|
||||
genai::convert_request(body),
|
||||
]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parsing_retains_original_protocol_and_usage_preference() {
|
||||
@@ -42,7 +50,7 @@ fn invalid_envelopes_and_chat_controls_keep_safe_field_errors() {
|
||||
("n", json!(2)),
|
||||
("store", json!(true)),
|
||||
("previous_response_id", json!("resp_previous")),
|
||||
("stream_options", json!({"include_usage":true})),
|
||||
("stream_options", json!(true)),
|
||||
] {
|
||||
let mut request = super::request();
|
||||
request.insert(field.into(), value);
|
||||
@@ -55,14 +63,48 @@ fn invalid_envelopes_and_chat_controls_keep_safe_field_errors() {
|
||||
|
||||
#[test]
|
||||
fn invalid_tool_history_reports_source_path() {
|
||||
let request = json!({"model":"m","messages":[{"role":"tool","content":"ok"}]});
|
||||
assert_eq!(
|
||||
parse_request(&serde_json::to_vec(&request).unwrap())
|
||||
.err()
|
||||
for (identity, parameter) in [
|
||||
(json!({}), "messages[0].name"),
|
||||
(json!({"name":null}), "messages[0].name"),
|
||||
(json!({"name":" "}), "messages[0].name"),
|
||||
(json!({"name":17}), "messages[0].name"),
|
||||
(
|
||||
json!({"name":"notifications","tool_call_id":""}),
|
||||
"messages[0].tool_call_id",
|
||||
),
|
||||
(
|
||||
json!({"name":"notifications","tool_call_id":17}),
|
||||
"messages[0].tool_call_id",
|
||||
),
|
||||
] {
|
||||
let mut message = json!({"role":"tool","content":"ok"});
|
||||
message
|
||||
.as_object_mut()
|
||||
.unwrap()
|
||||
.parameter(),
|
||||
Some("messages[0].tool_call_id")
|
||||
);
|
||||
.extend(identity.as_object().unwrap().clone());
|
||||
let request = json!({"model":"m","messages":[message]});
|
||||
let error = parse_request(&serde_json::to_vec(&request).unwrap()).unwrap_err();
|
||||
assert_eq!(error.parameter(), Some(parameter));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn named_tool_outputs_preserve_the_original_request_and_target_requirements() {
|
||||
let request = json!({"model":"m","messages":[
|
||||
{"role":"tool","name":"notifications","namespace":"agent","content":"notice"}
|
||||
]});
|
||||
let parsed = parse_request(&serde_json::to_vec(&request).unwrap()).unwrap();
|
||||
assert_eq!(&parsed, request.as_object().unwrap());
|
||||
assert!(responses::convert_request(&parsed).is_ok());
|
||||
for result in [
|
||||
messages::convert_request(&parsed, &Default::default()),
|
||||
genai::convert_request(&parsed),
|
||||
] {
|
||||
assert_eq!(
|
||||
result.unwrap_err().parameter(),
|
||||
Some("messages[0].tool_call_id")
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -104,9 +146,320 @@ fn capability_facts_only_read_protocol_declarations() {
|
||||
assert!(!request_facts(CHAT_PROTOCOL, &body).tools);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_history_is_omitted_only_when_converting() {
|
||||
let mut baseline = super::request();
|
||||
baseline["messages"] = json!([
|
||||
{"role":"developer","content":"Keep replies short."},
|
||||
{"role":"user","content":"hello"}
|
||||
]);
|
||||
let expected = target_requests(&baseline).map(Result::unwrap);
|
||||
for role in ["system", "developer", "assistant"] {
|
||||
for content in [
|
||||
None,
|
||||
Some(Value::Null),
|
||||
Some(json!("")),
|
||||
Some(json!([])),
|
||||
Some(json!([{"type":"text","text":""},{"type":"output_text","text":""}])),
|
||||
Some(json!([{"type":"input_text","text":null}])),
|
||||
Some(json!([{"type":"text","text":"","prompt_cache_breakpoint":null}])),
|
||||
] {
|
||||
let mut placeholder =
|
||||
json!({"role":role,"tool_calls":[],"refusal":"","tool_call_id":""});
|
||||
if let Some(content) = content {
|
||||
placeholder["content"] = content;
|
||||
}
|
||||
let mut body = baseline.clone();
|
||||
body["messages"]
|
||||
.as_array_mut()
|
||||
.unwrap()
|
||||
.insert(1, placeholder.clone());
|
||||
let parsed = parse_request(&serde_json::to_vec(&body).unwrap()).unwrap();
|
||||
assert_eq!(parsed, body);
|
||||
assert_eq!(target_requests(&parsed).map(Result::unwrap), expected);
|
||||
|
||||
body["messages"] = json!([placeholder]);
|
||||
for error in target_requests(&body).map(Result::unwrap_err) {
|
||||
assert_eq!(error.parameter(), Some("messages"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_history_fields_preserve_tool_calls_results_and_refusals() {
|
||||
let mut body = super::request();
|
||||
body["messages"] = json!([
|
||||
{"role":"user","content":"hello"},
|
||||
{"role":"assistant","tool_calls":[{"id":"c","type":"function","function":{"name":"f","arguments":"{}"}}]},
|
||||
{"role":"tool","tool_call_id":"c","content":""},
|
||||
{"role":"assistant","refusal":"declined"}
|
||||
]);
|
||||
let expected = target_requests(&body).map(Result::unwrap);
|
||||
assert_eq!(expected[0]["input"][1]["call_id"], "c");
|
||||
assert_eq!(expected[0]["input"][2]["output"], "");
|
||||
assert_eq!(expected[1]["messages"][1]["content"][0]["type"], "tool_use");
|
||||
assert_eq!(expected[1]["messages"][3]["content"][0]["text"], "declined");
|
||||
assert_eq!(
|
||||
expected[2]["contents"][2]["parts"][0]["functionResponse"]["id"],
|
||||
"c"
|
||||
);
|
||||
assert_eq!(expected[2]["contents"][3]["parts"][0]["text"], "declined");
|
||||
body["messages"][0] = json!({"role":"user","content":"hello","name":17,"refusal":"","tool_calls":[],"tool_call_id":""});
|
||||
for content in [
|
||||
Value::Null,
|
||||
json!(""),
|
||||
json!([]),
|
||||
json!([{"type":"text","text":""}]),
|
||||
json!([{"type":"output_text","text":null}]),
|
||||
] {
|
||||
body["messages"][1]["content"] = content.clone();
|
||||
body["messages"][3]["content"] = content;
|
||||
assert_eq!(target_requests(&body).map(Result::unwrap), expected);
|
||||
}
|
||||
body["messages"][2]["content"] =
|
||||
json!([{"type":"text","text":""},{"type":"text","text":"x"},{"type":"text","text":""}]);
|
||||
let [responses, messages, genai] = target_requests(&body).map(Result::unwrap);
|
||||
assert_eq!(responses["input"][2]["output"].as_array().unwrap().len(), 3);
|
||||
assert_eq!(
|
||||
messages["messages"][2]["content"][0]["content"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.len(),
|
||||
3
|
||||
);
|
||||
assert_eq!(
|
||||
genai["contents"][2]["parts"][0]["functionResponse"]["response"]["output"],
|
||||
"\nx\n"
|
||||
);
|
||||
body["messages"][2]["content"][0]["text"] = Value::Null;
|
||||
assert_eq!(
|
||||
target_requests(&body).map(Result::unwrap),
|
||||
[responses, messages, genai]
|
||||
);
|
||||
body["messages"][2]["content"] = json!("");
|
||||
body["messages"][2]["name"] = json!(17);
|
||||
let parsed = parse_request(&serde_json::to_vec(&body).unwrap()).unwrap();
|
||||
let [responses, messages, genai] = target_requests(&parsed);
|
||||
assert_eq!(responses.unwrap_err().parameter(), Some("messages[2].name"));
|
||||
assert_eq!(messages.unwrap(), expected[1]);
|
||||
assert_eq!(genai.unwrap(), expected[2]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn filters_only_plain_empty_history_parts_and_keeps_source_indices() {
|
||||
let mut body = super::request();
|
||||
let blank = json!({"type":"input_text","text":""});
|
||||
let space = json!({"type":"text","text":" "});
|
||||
for role in ["system", "developer", "assistant", "user"] {
|
||||
body["messages"] = json!([{"role":role,"content":[space]}, {"role":"user","content":"hi"}]);
|
||||
let expected = target_requests(&body).map(Result::unwrap);
|
||||
body["messages"][0]["content"] = json!([blank, space, blank]);
|
||||
let actual = target_requests(&body).map(Result::unwrap);
|
||||
body["messages"][0]["content"][0]["text"] = Value::Null;
|
||||
assert_eq!(target_requests(&body).map(Result::unwrap), actual);
|
||||
if role == "user" {
|
||||
assert_eq!(
|
||||
actual[0]["input"][0]["content"].as_array().unwrap().len(),
|
||||
3
|
||||
);
|
||||
assert_eq!(actual[1]["messages"][0]["content"][1]["text"], " ");
|
||||
assert_eq!(actual[2]["contents"][0]["parts"][1]["text"], " ");
|
||||
} else {
|
||||
assert_eq!(actual, expected);
|
||||
}
|
||||
}
|
||||
let marked = json!({"type":"text","text":null,"prompt_cache_breakpoint":{"mode":"explicit"}});
|
||||
body["messages"][0] = json!({"role":"developer","content":[blank,marked]});
|
||||
let converted = responses::convert_request(&body).unwrap();
|
||||
assert_eq!(
|
||||
converted["input"][0]["content"],
|
||||
json!([{"type":"input_text","text":"","prompt_cache_breakpoint":{"mode":"explicit"}}])
|
||||
);
|
||||
body["messages"][0]["role"] = json!("assistant");
|
||||
assert_eq!(
|
||||
responses::convert_request(&body).unwrap_err().parameter(),
|
||||
Some("messages[0].content[1].prompt_cache_breakpoint")
|
||||
);
|
||||
for (part, code) in [
|
||||
(json!({"type":"text"}), "missing_required_parameter"),
|
||||
(json!({"type":"text","text":17}), "invalid_type"),
|
||||
(json!({"type":"text","text":{}}), "invalid_type"),
|
||||
] {
|
||||
body["messages"][0]["content"] = json!([{"type":"text","text":null},part]);
|
||||
for error in target_requests(&body).map(Result::unwrap_err) {
|
||||
assert_eq!(error.parameter(), Some("messages[0].content[1].text"));
|
||||
assert_eq!(error.code(), code);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn null_chat_controls_fall_back_to_native_format_and_effort() {
|
||||
let mut body = super::request();
|
||||
let schema = json!({"type":"object","properties":{"q":{"type":"string"}}});
|
||||
body.insert(
|
||||
"text".into(),
|
||||
json!({"format":{"type":"json_schema","name":"answer","schema":schema}}),
|
||||
);
|
||||
body.insert("reasoning".into(), json!({"effort":"low"}));
|
||||
let expected = target_requests(&body).map(Result::unwrap);
|
||||
assert_eq!(expected[1]["output_config"]["format"]["schema"], schema);
|
||||
assert_eq!(
|
||||
expected[2]["generationConfig"]["responseJsonSchema"],
|
||||
schema
|
||||
);
|
||||
assert_eq!(expected[1]["thinking"]["budget_tokens"], 1024);
|
||||
assert_eq!(
|
||||
expected[2]["generationConfig"]["thinkingConfig"]["thinkingBudget"],
|
||||
1024
|
||||
);
|
||||
body.insert("response_format".into(), Value::Null);
|
||||
body.insert("reasoning_effort".into(), Value::Null);
|
||||
assert_eq!(target_requests(&body).map(Result::unwrap), expected);
|
||||
assert!(request_facts(CHAT_PROTOCOL, &body).json_schema);
|
||||
|
||||
body["response_format"] = json!({"type":"text"});
|
||||
body["reasoning_effort"] = json!("none");
|
||||
let [responses, messages, genai] = target_requests(&body).map(Result::unwrap);
|
||||
assert!(!request_facts(CHAT_PROTOCOL, &body).json_schema);
|
||||
assert_eq!(responses["text"]["format"]["type"], "text");
|
||||
assert!(messages.get("output_config").is_none());
|
||||
assert!(
|
||||
genai["generationConfig"]
|
||||
.get("responseJsonSchema")
|
||||
.is_none()
|
||||
);
|
||||
assert_eq!(messages["thinking"]["type"], "disabled");
|
||||
assert_eq!(
|
||||
genai["generationConfig"]["thinkingConfig"]["thinkingBudget"],
|
||||
0
|
||||
);
|
||||
body["reasoning_effort"] = json!(5);
|
||||
for error in target_requests(&body).map(Result::unwrap_err) {
|
||||
assert_eq!(error.parameter(), Some("reasoning_effort"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn null_function_parameters_follow_each_targets_default() {
|
||||
let mut body = super::request();
|
||||
body.insert(
|
||||
"tools".into(),
|
||||
json!([{"type":"function","function":{"name":"clock"}}]),
|
||||
);
|
||||
let expected = target_requests(&body).map(Result::unwrap);
|
||||
assert!(expected[0]["tools"][0].get("parameters").is_none());
|
||||
let default_schema = json!({"type":"object","properties":{}});
|
||||
assert_eq!(expected[1]["tools"][0]["input_schema"], default_schema);
|
||||
assert_eq!(
|
||||
expected[2]["tools"][0]["functionDeclarations"][0]["parametersJsonSchema"],
|
||||
default_schema
|
||||
);
|
||||
body["tools"][0]["function"] =
|
||||
json!({"name":"clock","parameters":null,"description":null,"strict":null});
|
||||
assert_eq!(target_requests(&body).map(Result::unwrap), expected);
|
||||
|
||||
let schema =
|
||||
json!({"type":"object","properties":{"q":{"type":["string","null"],"default":null}}});
|
||||
body["tools"][0]["function"]["parameters"] = schema.clone();
|
||||
let [responses, messages, genai] = target_requests(&body).map(Result::unwrap);
|
||||
assert_eq!(responses["tools"][0]["parameters"], schema);
|
||||
assert_eq!(messages["tools"][0]["input_schema"], schema);
|
||||
assert_eq!(
|
||||
genai["tools"][0]["functionDeclarations"][0]["parametersJsonSchema"],
|
||||
schema
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stop_sequences_are_mapped_only_for_targets_that_support_them() {
|
||||
let mut body = super::request();
|
||||
let baseline = target_requests(&body).map(Result::unwrap);
|
||||
for stop in [Value::Null, json!([])] {
|
||||
body.insert("stop".into(), stop);
|
||||
assert_eq!(target_requests(&body).map(Result::unwrap), baseline);
|
||||
}
|
||||
for (stop, expected) in [
|
||||
(json!(" END"), json!([" END"])),
|
||||
(json!([" END", "\n"]), json!([" END", "\n"])),
|
||||
] {
|
||||
body["stop"] = stop;
|
||||
let [responses, messages, genai] = target_requests(&body).map(Result::unwrap);
|
||||
assert_eq!(responses, baseline[0]);
|
||||
assert_eq!(messages["stop_sequences"], expected);
|
||||
assert_eq!(genai["generationConfig"]["stopSequences"], expected);
|
||||
}
|
||||
for (stop, param) in [(json!(5), "stop"), (json!(["end", null]), "stop[1]")] {
|
||||
body["stop"] = stop;
|
||||
let [responses, messages, genai] = target_requests(&body);
|
||||
assert_eq!(responses.unwrap(), baseline[0]);
|
||||
for result in [messages, genai] {
|
||||
assert_eq!(result.unwrap_err().parameter(), Some(param));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stream_options_affect_only_streaming_delivery() {
|
||||
for stream in [None, Some(false), Some(true)] {
|
||||
let mut body = super::request();
|
||||
if let Some(stream) = stream {
|
||||
body.insert("stream".into(), json!(stream));
|
||||
}
|
||||
let expected = target_requests(&body).map(Result::unwrap);
|
||||
body.insert(
|
||||
"stream_options".into(),
|
||||
json!({"include_usage":true, "include_obfuscation":false}),
|
||||
);
|
||||
assert_eq!(target_requests(&body).map(Result::unwrap), expected);
|
||||
body["stream_options"]["include_obfuscation"] = json!(true);
|
||||
if stream == Some(true) {
|
||||
for error in target_requests(&body).map(Result::unwrap_err) {
|
||||
assert_eq!(
|
||||
error.parameter(),
|
||||
Some("stream_options.include_obfuscation")
|
||||
);
|
||||
}
|
||||
} else {
|
||||
assert_eq!(target_requests(&body).map(Result::unwrap), expected);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn all_targets_apply_the_same_common_request_validation() {
|
||||
for (field, value, parameter) in [
|
||||
(
|
||||
"messages",
|
||||
json!([{"role":"system","content":null},{"role":"developer","content":null}]),
|
||||
"messages",
|
||||
),
|
||||
(
|
||||
"messages",
|
||||
json!([{"role":"developer"},{"role":"assistant","audio":{"id":"audio"}}]),
|
||||
"messages[1].audio",
|
||||
),
|
||||
(
|
||||
"messages",
|
||||
json!([{"role":"system","content":42}]),
|
||||
"messages[0].content",
|
||||
),
|
||||
(
|
||||
"messages",
|
||||
json!([{"role":"system","content":null},{"role":"user","content":null}]),
|
||||
"messages[1].content",
|
||||
),
|
||||
(
|
||||
"messages",
|
||||
json!([{"role":"tool","tool_call_id":"c","content":null}]),
|
||||
"messages[0].content",
|
||||
),
|
||||
(
|
||||
"messages",
|
||||
json!([{"role":"system","content":null,"tool_calls":[{}]}]),
|
||||
"messages[0].tool_calls",
|
||||
),
|
||||
(
|
||||
"messages",
|
||||
json!([{"role":"assistant","content":"ok","refusal":17}]),
|
||||
@@ -114,13 +467,18 @@ fn all_targets_apply_the_same_common_request_validation() {
|
||||
),
|
||||
(
|
||||
"messages",
|
||||
json!([{"role":"user","content":"ok","name":17}]),
|
||||
"messages[0].name",
|
||||
json!([{"role":"assistant","tool_calls":{}}]),
|
||||
"messages[0].tool_calls",
|
||||
),
|
||||
(
|
||||
"messages",
|
||||
json!([{"role":"user","content":"ok","tool_calls":[]}]),
|
||||
"messages[0].tool_calls",
|
||||
json!([{"role":"developer","tool_call_id":"c"}]),
|
||||
"messages[0].tool_call_id",
|
||||
),
|
||||
(
|
||||
"messages",
|
||||
json!([{"role":"user","content":"ok","refusal":"declined"}]),
|
||||
"messages[0].refusal",
|
||||
),
|
||||
(
|
||||
"messages",
|
||||
@@ -130,8 +488,8 @@ fn all_targets_apply_the_same_common_request_validation() {
|
||||
("n", json!(2), "n"),
|
||||
(
|
||||
"stream_options",
|
||||
json!({"include_usage":true}),
|
||||
"stream_options",
|
||||
json!({"include_usage":1}),
|
||||
"stream_options.include_usage",
|
||||
),
|
||||
] {
|
||||
let mut body = super::request();
|
||||
@@ -140,11 +498,7 @@ fn all_targets_apply_the_same_common_request_validation() {
|
||||
.err()
|
||||
.unwrap();
|
||||
assert_eq!(expected.parameter(), Some(parameter));
|
||||
for result in [
|
||||
responses::convert_request(&body),
|
||||
messages::convert_request(&body, &Default::default()),
|
||||
genai::convert_request(&body),
|
||||
] {
|
||||
for result in target_requests(&body) {
|
||||
assert_eq!(result.unwrap_err(), expected);
|
||||
}
|
||||
}
|
||||
@@ -152,11 +506,14 @@ fn all_targets_apply_the_same_common_request_validation() {
|
||||
|
||||
#[test]
|
||||
fn custom_format_constraints_are_preserved_or_rejected_by_the_target() {
|
||||
for format in [
|
||||
json!(null),
|
||||
json!({"type":"text"}),
|
||||
json!({"type":"grammar","grammar":{"syntax":"lark","definition":"PRIVATE_GRAMMAR"}}),
|
||||
json!(17),
|
||||
for (format, expected) in [
|
||||
(json!(null), json!(null)),
|
||||
(json!({"type":"text"}), json!({"type":"text"})),
|
||||
(
|
||||
json!({"type":"grammar","grammar":{"syntax":"lark","definition":"PRIVATE_GRAMMAR"}}),
|
||||
json!({"type":"grammar","syntax":"lark","definition":"PRIVATE_GRAMMAR"}),
|
||||
),
|
||||
(json!(17), json!(17)),
|
||||
] {
|
||||
let mut body = super::request();
|
||||
body.insert(
|
||||
@@ -164,7 +521,7 @@ fn custom_format_constraints_are_preserved_or_rejected_by_the_target() {
|
||||
json!([{"type":"custom","custom":{"name":"run","format":format}}]),
|
||||
);
|
||||
let responses = responses::convert_request(&body).unwrap();
|
||||
assert_eq!(responses["tools"][0]["format"], format);
|
||||
assert_eq!(responses["tools"][0]["format"], expected);
|
||||
for result in [
|
||||
messages::convert_request(&body, &Default::default()),
|
||||
genai::convert_request(&body),
|
||||
|
||||
@@ -53,6 +53,31 @@ fn preserves_ordered_roles_images_and_modern_tool_round_trip() {
|
||||
assert!(converted.get("previous_response_id").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn named_tool_outputs_preserve_unpaired_identity_and_order() {
|
||||
for call_id in [None, Some(Value::Null)] {
|
||||
let mut notice = json!({"role":"tool","name":"lookup","namespace":"agent","content":[{"type":"text","text":"independent notice"}]});
|
||||
if let Some(call_id) = call_id {
|
||||
notice["tool_call_id"] = call_id;
|
||||
}
|
||||
let converted = convert(json!({"model":"model-a","messages":[
|
||||
{"role":"assistant","tool_calls":[{"id":"call_lookup","type":"custom","custom":{"name":"lookup","input":"query"}}]},
|
||||
notice,
|
||||
{"role":"tool","tool_call_id":"call_lookup","content":"matched result"},
|
||||
{"role":"tool","name":"notifications","content":"another notice"}
|
||||
]}));
|
||||
assert_eq!(
|
||||
converted["input"],
|
||||
json!([
|
||||
{"type":"custom_tool_call","call_id":"call_lookup","name":"lookup","input":"query"},
|
||||
{"type":"function_call_output","name":"lookup","namespace":"agent","output":[{"type":"input_text","text":"independent notice"}]},
|
||||
{"type":"custom_tool_call_output","call_id":"call_lookup","output":"matched result"},
|
||||
{"type":"function_call_output","name":"notifications","output":"another notice"}
|
||||
])
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn web_search_options_require_a_hosted_search_and_flatten_location() {
|
||||
for (options, expected) in [
|
||||
@@ -278,7 +303,7 @@ fn custom_tools_keep_native_input_and_mixed_call_families_through_history() {
|
||||
]}));
|
||||
assert_eq!(
|
||||
converted["tools"][0],
|
||||
json!({"type":"custom", "name":"patch", "format":schema})
|
||||
json!({"type":"custom", "name":"patch", "format":{"type":"grammar","syntax":"lark","definition":"start: /.+/"}})
|
||||
);
|
||||
assert_eq!(
|
||||
converted["tool_choice"],
|
||||
@@ -293,6 +318,40 @@ fn custom_tools_keep_native_input_and_mixed_call_families_through_history() {
|
||||
assert_eq!(converted["input"][5]["type"], "function_call_output");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_grammar_formats_keep_their_constraints_and_source_paths() {
|
||||
for nested in [false, true] {
|
||||
for syntax in ["lark", "regex"] {
|
||||
let format =
|
||||
json!({"type":"grammar","syntax":syntax,"definition":"OK","future_field":true});
|
||||
let definition = json!({"name":"probe","format":format});
|
||||
let tool = if nested {
|
||||
json!({"type":"custom","custom":definition})
|
||||
} else {
|
||||
json!({"type":"custom","name":"probe","format":format})
|
||||
};
|
||||
let mut body =
|
||||
json!({"model":"m","messages":[{"role":"user","content":"hello"}],"tools":[tool]});
|
||||
assert_eq!(convert(body.clone())["tools"][0]["format"], format);
|
||||
let declaration = if nested {
|
||||
&mut body["tools"][0]["custom"]
|
||||
} else {
|
||||
&mut body["tools"][0]
|
||||
};
|
||||
declaration["format"] = json!({"type":"grammar","grammar":false});
|
||||
let error = convert_request(body.as_object().unwrap()).unwrap_err();
|
||||
assert_eq!(
|
||||
error.parameter(),
|
||||
Some(if nested {
|
||||
"tools[0].custom.format.grammar"
|
||||
} else {
|
||||
"tools[0].format.grammar"
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn files_and_audio_are_preserved_as_inputs_instead_of_losing_the_user_turn() {
|
||||
for file in [
|
||||
|
||||
@@ -1,9 +1,61 @@
|
||||
//! 验证传输头部分类,以及响应中的连接级和身份字段过滤
|
||||
|
||||
use gateway_protocol::http::{
|
||||
is_transport_managed_request_header, parse_retry_after_seconds, response_header_is_forwardable,
|
||||
is_transport_managed_request_header, parse_retry_after_seconds, preferred_response_request_id,
|
||||
response_header_is_forwardable,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn response_request_ids_follow_official_header_priority() {
|
||||
let names = [
|
||||
"x-request-id",
|
||||
"x-oai-request-id",
|
||||
"x-openai-request-id",
|
||||
"x-ms-request-id",
|
||||
];
|
||||
let mut headers = http::HeaderMap::new();
|
||||
for name in names {
|
||||
headers.insert(name, http::HeaderValue::from_static(name));
|
||||
}
|
||||
headers.insert("cf-ray", http::HeaderValue::from_static("trace-only"));
|
||||
for name in names {
|
||||
assert_eq!(
|
||||
preferred_response_request_id(|name| headers.get(name)?.to_str().ok()),
|
||||
Some(name),
|
||||
);
|
||||
headers.remove(name);
|
||||
}
|
||||
assert_eq!(
|
||||
preferred_response_request_id(|name| headers.get(name)?.to_str().ok()),
|
||||
None,
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn response_request_ids_skip_unusable_first_values_without_rewriting_headers() {
|
||||
let mut headers = http::HeaderMap::new();
|
||||
headers.insert(
|
||||
"x-request-id",
|
||||
http::HeaderValue::from_bytes(b"\xff").unwrap(),
|
||||
);
|
||||
headers.append(
|
||||
"x-request-id",
|
||||
http::HeaderValue::from_static("second-value"),
|
||||
);
|
||||
headers.insert("x-oai-request-id", http::HeaderValue::from_static(" \t "));
|
||||
headers.insert("x-openai-request-id", http::HeaderValue::from_static(""));
|
||||
headers.insert(
|
||||
"x-ms-request-id",
|
||||
http::HeaderValue::from_static(" opaque-id "),
|
||||
);
|
||||
assert_eq!(
|
||||
preferred_response_request_id(|name| headers.get(name)?.to_str().ok()),
|
||||
Some(" opaque-id "),
|
||||
);
|
||||
assert_eq!(headers["x-request-id"].as_bytes(), b"\xff");
|
||||
assert_eq!(headers.get_all("x-request-id").iter().count(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retry_after_should_accept_nonnegative_seconds_and_http_dates() {
|
||||
for (header, expected) in [
|
||||
|
||||
@@ -69,7 +69,9 @@ impl ClientAdmissionRecoveryRepository for PgClientAdmissionRecoveryRepository {
|
||||
lease.lease_expires_at, request.outcome
|
||||
from model_requests request
|
||||
left join model_request_leases lease on lease.request_id = request.id
|
||||
where request.started_at >= $1 or request.outcome = 'running'
|
||||
where (request.started_at >= $1 or request.outcome = 'running')
|
||||
and (request.client_transport, request.request_kind)
|
||||
is distinct from ('internal_plugin', 'plugin_child_model')
|
||||
order by request.client_api_key_ref, request.started_at, request.id",
|
||||
)
|
||||
.bind(window_started_at)
|
||||
|
||||
@@ -325,19 +325,36 @@ impl AccountStore for PgAdminAccountStore {
|
||||
));
|
||||
}
|
||||
let now = Utc::now();
|
||||
let cooldown = runtime.cooldown;
|
||||
let now_system_time = std::time::SystemTime::from(now);
|
||||
let active_rate_limited_ids = cooldown
|
||||
let active_rate_limited_ids = runtime
|
||||
.cooldown
|
||||
.iter()
|
||||
.filter(|(_, cooldown)| cooldown.is_active(now_system_time))
|
||||
.map(|(account_id, _)| account_id.clone())
|
||||
.collect::<Vec<_>>();
|
||||
let active_model_revisions = runtime
|
||||
.model_cooldowns
|
||||
.iter()
|
||||
.flat_map(|(account, models)| {
|
||||
models
|
||||
.iter()
|
||||
.filter(|model| model.until() > now_system_time)
|
||||
.filter_map(|model| {
|
||||
i64::try_from(model.credential_revision().get())
|
||||
.ok()
|
||||
.map(|revision| (account.clone(), revision))
|
||||
})
|
||||
})
|
||||
.collect::<std::collections::BTreeSet<_>>()
|
||||
.into_iter()
|
||||
.collect();
|
||||
let page = load_admin_account_page(
|
||||
&self.pool,
|
||||
&self.query_budget,
|
||||
&query,
|
||||
now,
|
||||
active_rate_limited_ids,
|
||||
active_model_revisions,
|
||||
)
|
||||
.await?;
|
||||
let item_ids = page
|
||||
@@ -351,14 +368,12 @@ impl AccountStore for PgAdminAccountStore {
|
||||
.into_iter()
|
||||
.map(|(summary, platform_icon)| {
|
||||
let account_id = summary.id.clone();
|
||||
let projection = account_status_projection(
|
||||
&summary,
|
||||
now.into(),
|
||||
cooldown.get(&account_id).copied(),
|
||||
);
|
||||
let (projection, model_cooldowns) =
|
||||
super::runtime::account_directory_projection(&summary, now.into(), &runtime);
|
||||
let mut account = admin_account_record(summary)?;
|
||||
account.groups = groups_by_account.remove(&account_id).unwrap_or_default();
|
||||
Ok(AccountPageItem {
|
||||
model_cooldowns,
|
||||
platform_icon,
|
||||
protection_rules: runtime
|
||||
.protection_rules
|
||||
@@ -397,8 +412,8 @@ impl AccountStore for PgAdminAccountStore {
|
||||
return Ok(None);
|
||||
};
|
||||
let now = Utc::now();
|
||||
let cooldown = runtime.cooldown.get(account_id).copied();
|
||||
let projection = account_status_projection(&record.summary, now.into(), cooldown);
|
||||
let (projection, model_cooldowns) =
|
||||
super::runtime::account_directory_projection(&record.summary, now.into(), &runtime);
|
||||
let account_id = record.summary.id.clone();
|
||||
let mut groups = self
|
||||
.account_groups_by_account(std::slice::from_ref(&account_id))
|
||||
@@ -424,6 +439,7 @@ impl AccountStore for PgAdminAccountStore {
|
||||
)
|
||||
})?;
|
||||
Ok(Some(AccountPageItem {
|
||||
model_cooldowns,
|
||||
platform_icon,
|
||||
protection_rules: runtime
|
||||
.protection_rules
|
||||
|
||||
@@ -16,7 +16,10 @@ pub(crate) async fn load_admin_account_page(
|
||||
query: &AdminAccountListQuery,
|
||||
now: DateTime<Utc>,
|
||||
active_rate_limited_ids: Vec<String>,
|
||||
active_model_revisions: Vec<(String, i64)>,
|
||||
) -> AdminStoreResult<AdminAccountPageRows> {
|
||||
let (model_account_ids, model_revisions): (Vec<_>, Vec<_>) =
|
||||
active_model_revisions.into_iter().unzip();
|
||||
validate_group_filter(pool, query.group_filter.as_ref()).await?;
|
||||
|
||||
let provider_kind = query
|
||||
@@ -56,7 +59,10 @@ pub(crate) async fn load_admin_account_page(
|
||||
when a.credential_state <> 'ready'
|
||||
or a.access_token_expires_at <= $2 then 'error'
|
||||
when a.quota_access_state = 'exhausted' then 'quota_exhausted'
|
||||
when a.id = any($1::text[]) then 'rate_limited'
|
||||
when a.id = any($1::text[]) or exists (
|
||||
select 1 from unnest($13::text[], $14::bigint[]) as limits(account_id, revision)
|
||||
where limits.account_id = a.id and limits.revision = a.credential_revision
|
||||
) then 'rate_limited'
|
||||
when a.quota_paused then 'quota_paused'
|
||||
else 'normal'
|
||||
end as admin_status
|
||||
@@ -165,6 +171,8 @@ pub(crate) async fn load_admin_account_page(
|
||||
.bind(usage_ids)
|
||||
.bind(usage_tokens)
|
||||
.bind(usage_latest)
|
||||
.bind(model_account_ids)
|
||||
.bind(model_revisions)
|
||||
.fetch_all(&mut *snapshot.tx)
|
||||
.await
|
||||
.map_err(|source| postgres_unavailable("load admin account page", source))?;
|
||||
|
||||
@@ -12,6 +12,40 @@ use gateway_core::{
|
||||
|
||||
use super::ProviderAccountSummary;
|
||||
|
||||
pub(crate) fn account_directory_projection(
|
||||
account: &ProviderAccountSummary,
|
||||
now: SystemTime,
|
||||
runtime: &gateway_admin::model::accounts::AccountRuntimeSnapshot,
|
||||
) -> (
|
||||
AccountStatusProjection,
|
||||
Vec<gateway_core::provider_ports::ProviderScopedCooldown>,
|
||||
) {
|
||||
let models = runtime
|
||||
.model_cooldowns
|
||||
.get(&account.id)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter(|cooldown| {
|
||||
cooldown.credential_revision().get() == account.credential_revision.get()
|
||||
&& cooldown.until() > now
|
||||
})
|
||||
.cloned()
|
||||
.collect::<Vec<_>>();
|
||||
let mut projection =
|
||||
account_status_projection(account, now, runtime.cooldown.get(&account.id).copied());
|
||||
// 目录汇总展示部分模型受限,不将其写入整账号 cooldown 或用于其他模型的调度
|
||||
if !models.is_empty()
|
||||
&& matches!(
|
||||
projection.status,
|
||||
gateway_core::account::AccountStatus::Normal
|
||||
| gateway_core::account::AccountStatus::QuotaPaused
|
||||
)
|
||||
{
|
||||
projection.status = gateway_core::account::AccountStatus::RateLimited;
|
||||
}
|
||||
(projection, models)
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub(crate) fn account_status_projection(
|
||||
account: &ProviderAccountSummary,
|
||||
|
||||
@@ -155,8 +155,6 @@ impl ClientAdmissionRequest {
|
||||
return Err(invalid("lease TTL must be positive"));
|
||||
}
|
||||
redis_duration_millis(self.lease_ttl)?;
|
||||
redis_integer(self.limits.max_concurrency, "maximum concurrency")?;
|
||||
redis_integer(self.limits.requests_per_minute, "requests per minute")?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -287,6 +285,7 @@ impl ClientAdmissionRepository for RedisClientAdmissionRepository {
|
||||
.key(&keys[1])
|
||||
.arg(&request.model_request_id)
|
||||
.arg(lease_ttl_ms)
|
||||
// ZCARD 的取值都能精确表示,超过 Lua 精确范围的限额始终大于实际计数
|
||||
.arg(request.limits.max_concurrency)
|
||||
.arg(request.limits.requests_per_minute)
|
||||
.arg(MAX_REDIS_EXACT_INTEGER)
|
||||
|
||||
@@ -11,7 +11,7 @@ use gateway_core::{
|
||||
},
|
||||
};
|
||||
use redis::{Script, aio::ConnectionManager};
|
||||
use std::{collections::BTreeMap, sync::LazyLock};
|
||||
use std::{collections::BTreeMap, sync::LazyLock, time::SystemTime};
|
||||
|
||||
use crate::{Revision, StoreError, StoreResult, redis_unavailable, require_nonempty};
|
||||
|
||||
@@ -55,6 +55,42 @@ static WRITE_ACCOUNT: LazyLock<Script> = LazyLock::new(|| {
|
||||
)
|
||||
});
|
||||
|
||||
// 模型事实与目录索引同次写入;普通成功只清整账号冷却,不触碰这里的期限
|
||||
const WRITE_SCOPED: &str = r#"
|
||||
local current = tonumber(redis.call('HGET', KEYS[1], 'revision') or '0')
|
||||
local incoming = tonumber(ARGV[1])
|
||||
local until_ms = tonumber(ARGV[2])
|
||||
local limited_ms = tonumber(ARGV[4])
|
||||
local clock = redis.call('TIME')
|
||||
local now_ms = tonumber(clock[1]) * 1000 + math.floor(tonumber(clock[2]) / 1000)
|
||||
if current > incoming or until_ms <= now_ms then return 0 end
|
||||
if current == incoming then
|
||||
local previous = tonumber(redis.call('HGET', KEYS[1], 'until_ms') or '0')
|
||||
local limited = tonumber(redis.call('HGET', KEYS[1], 'rate_limited_until_ms') or '0')
|
||||
if previous >= until_ms and limited >= limited_ms then return 0 end
|
||||
until_ms = math.max(previous, until_ms)
|
||||
limited_ms = math.max(limited, limited_ms)
|
||||
end
|
||||
redis.call('HSET', KEYS[1], 'revision', incoming, 'until_ms', until_ms, 'rate_limited_until_ms', limited_ms)
|
||||
redis.call('PEXPIREAT', KEYS[1], until_ms + 60000)
|
||||
if limited_ms > now_ms then
|
||||
redis.call('ZADD', KEYS[2], limited_ms, ARGV[3])
|
||||
local latest = redis.call('ZRANGE', KEYS[2], -1, -1, 'WITHSCORES')
|
||||
redis.call('PEXPIREAT', KEYS[2], tonumber(latest[2]) + 60000)
|
||||
redis.call('ZADD', KEYS[3], 'GT', latest[2], ARGV[5])
|
||||
else
|
||||
redis.call('ZREM', KEYS[2], ARGV[3])
|
||||
end
|
||||
return 1
|
||||
"#;
|
||||
|
||||
const ACTIVE_SCOPES: &str = r#"
|
||||
local clock = redis.call('TIME')
|
||||
local now_ms = tonumber(clock[1]) * 1000 + math.floor(tonumber(clock[2]) / 1000)
|
||||
redis.call('ZREMRANGEBYSCORE', KEYS[1], '-inf', now_ms)
|
||||
return redis.call('ZRANGE', KEYS[1], 0, -1)
|
||||
"#;
|
||||
|
||||
const READ_SCOPED: &str = r#"
|
||||
local revision = redis.call('HGET', KEYS[1], 'revision')
|
||||
local until_ms = redis.call('HGET', KEYS[1], 'until_ms')
|
||||
@@ -62,9 +98,9 @@ local clock = redis.call('TIME')
|
||||
local now_ms = (tonumber(clock[1]) * 1000) + math.floor(tonumber(clock[2]) / 1000)
|
||||
if not revision or not until_ms or tonumber(until_ms) <= now_ms then
|
||||
redis.call('DEL', KEYS[1])
|
||||
return {0, '0', '0'}
|
||||
return {0, '0', '0', '0'}
|
||||
end
|
||||
return {1, revision, until_ms}
|
||||
return {1, revision, until_ms, redis.call('HGET', KEYS[1], 'rate_limited_until_ms') or '0'}
|
||||
"#;
|
||||
|
||||
const INVALIDATE_SCRIPT: &str = r#"
|
||||
@@ -132,6 +168,73 @@ impl RedisCredentialCooldownRepository {
|
||||
format!("{}:account:active-cooldowns", self.namespace)
|
||||
}
|
||||
|
||||
fn model_index_key(&self, account: &str) -> StoreResult<String> {
|
||||
Ok(format!("{}:models", self.key(account)?))
|
||||
}
|
||||
|
||||
fn active_model_index_key(&self) -> String {
|
||||
format!("{}:account:active-model-cooldowns", self.namespace)
|
||||
}
|
||||
|
||||
async fn read_model_cooldowns(
|
||||
&self,
|
||||
account: &str,
|
||||
) -> StoreResult<Vec<ProviderScopedCooldown>> {
|
||||
let models: Vec<String> = Script::new(ACTIVE_SCOPES)
|
||||
.key(self.model_index_key(account)?)
|
||||
.invoke_async(&mut self.connection.clone())
|
||||
.await
|
||||
.map_err(|source| redis_unavailable("list account model cooldowns", source))?;
|
||||
let account =
|
||||
ProviderAccountId::new(account).map_err(|_| invalid("invalid cooldown account"))?;
|
||||
let scopes = models
|
||||
.into_iter()
|
||||
.map(|model| {
|
||||
gateway_core::routing::UpstreamModelId::new(model)
|
||||
.map(ProviderCooldownScope::upstream_model)
|
||||
.map_err(|_| invalid("invalid cooldown model"))
|
||||
})
|
||||
.collect::<StoreResult<Vec<_>>>()?;
|
||||
let mut cooldowns = Vec::new();
|
||||
for scopes in scopes.chunks(COOLDOWN_READ_BATCH_SIZE) {
|
||||
let script = Script::new(READ_SCOPED);
|
||||
let commands = scopes
|
||||
.iter()
|
||||
.map(|scope| {
|
||||
let mut command = redis::cmd("EVALSHA");
|
||||
command
|
||||
.arg(script.get_hash())
|
||||
.arg(1)
|
||||
.arg(self.scoped_key(account.as_str(), scope)?);
|
||||
Ok(command)
|
||||
})
|
||||
.collect();
|
||||
for (scope, value) in scopes
|
||||
.iter()
|
||||
.zip(self.read_script_batch(&script, commands).await)
|
||||
{
|
||||
let value = redis::from_redis_value(value?)
|
||||
.map_err(|source| redis_unavailable("decode model cooldown", source))?;
|
||||
if let Some(cooldown) = parse_scoped_cooldown(value, &account, scope)?
|
||||
&& let Some(until) = cooldown
|
||||
.rate_limited_until()
|
||||
.filter(|until| *until > SystemTime::now())
|
||||
{
|
||||
cooldowns.push(
|
||||
ProviderScopedCooldown::new(
|
||||
account.clone(),
|
||||
cooldown.credential_revision(),
|
||||
scope.clone(),
|
||||
until,
|
||||
)
|
||||
.with_rate_limited_until(Some(until)),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(cooldowns)
|
||||
}
|
||||
|
||||
fn capacity_failures_key(&self, provider_account_id: &str) -> StoreResult<String> {
|
||||
let fingerprint = resource_fingerprint("credential cooldown", provider_account_id)?;
|
||||
Ok(format!(
|
||||
@@ -168,49 +271,27 @@ impl RedisCredentialCooldownRepository {
|
||||
credential_revision: Revision,
|
||||
cooldown_until: DateTime<Utc>,
|
||||
kind: ProviderCooldownKind,
|
||||
index_member: Option<&str>,
|
||||
index_member: &str,
|
||||
) -> StoreResult<bool> {
|
||||
let until_ms = cooldown_until.timestamp_millis();
|
||||
if until_ms <= 0 {
|
||||
return Err(invalid("cooldown expiry must be positive"));
|
||||
}
|
||||
let mut connection = self.connection.clone();
|
||||
let written = if let Some(index_member) = index_member {
|
||||
WRITE_ACCOUNT
|
||||
.key(key)
|
||||
.key(self.active_index_key())
|
||||
.key(self.protection_key(index_member)?)
|
||||
.key(self.protection_index_key())
|
||||
.arg(credential_revision.get())
|
||||
.arg(until_ms)
|
||||
.arg(index_member)
|
||||
.arg(kind.as_str())
|
||||
.arg(uuid::Uuid::new_v4().to_string())
|
||||
.invoke_async::<i64>(&mut connection)
|
||||
.await
|
||||
} else {
|
||||
Script::new(WRITE_SCRIPT)
|
||||
.key(key)
|
||||
.arg(credential_revision.get())
|
||||
.arg(until_ms)
|
||||
.arg("")
|
||||
.arg(kind.as_str())
|
||||
.arg(uuid::Uuid::new_v4().to_string())
|
||||
.invoke_async::<i64>(&mut connection)
|
||||
.await
|
||||
}
|
||||
.map_err(|source| redis_unavailable("cache credential cooldown", source))?;
|
||||
Ok(written == 1)
|
||||
}
|
||||
|
||||
async fn read_scoped_key(&self, key: String) -> StoreResult<Option<(Revision, DateTime<Utc>)>> {
|
||||
let result = Script::new(READ_SCOPED)
|
||||
let written = WRITE_ACCOUNT
|
||||
.key(key)
|
||||
.invoke_async(&mut self.connection.clone())
|
||||
.await;
|
||||
parse_scoped_cooldown(
|
||||
result.map_err(|source| redis_unavailable("read credential cooldown", source))?,
|
||||
)
|
||||
.key(self.active_index_key())
|
||||
.key(self.protection_key(index_member)?)
|
||||
.key(self.protection_index_key())
|
||||
.arg(credential_revision.get())
|
||||
.arg(until_ms)
|
||||
.arg(index_member)
|
||||
.arg(kind.as_str())
|
||||
.arg(uuid::Uuid::new_v4().to_string())
|
||||
.invoke_async::<i64>(&mut connection)
|
||||
.await
|
||||
.map_err(|source| redis_unavailable("cache credential cooldown", source))?;
|
||||
Ok(written == 1)
|
||||
}
|
||||
|
||||
/// 保留每条命令的错误,脚本失效时只补发尚未执行的 NOSCRIPT 项
|
||||
@@ -294,26 +375,18 @@ impl RedisCredentialCooldownRepository {
|
||||
&self,
|
||||
key: String,
|
||||
through_revision: Revision,
|
||||
index_member: Option<&str>,
|
||||
index_key: String,
|
||||
index_member: &str,
|
||||
) -> StoreResult<bool> {
|
||||
let mut connection = self.connection.clone();
|
||||
let removed = if let Some(index_member) = index_member {
|
||||
Script::new(INVALIDATE_SCRIPT)
|
||||
.key(key)
|
||||
.key(self.active_index_key())
|
||||
.arg(through_revision.get())
|
||||
.arg(index_member)
|
||||
.invoke_async::<i64>(&mut connection)
|
||||
.await
|
||||
} else {
|
||||
Script::new(INVALIDATE_SCRIPT)
|
||||
.key(key)
|
||||
.arg(through_revision.get())
|
||||
.arg("")
|
||||
.invoke_async::<i64>(&mut connection)
|
||||
.await
|
||||
}
|
||||
.map_err(|source| redis_unavailable("invalidate credential cooldown", source))?;
|
||||
let removed = Script::new(INVALIDATE_SCRIPT)
|
||||
.key(key)
|
||||
.key(index_key)
|
||||
.arg(through_revision.get())
|
||||
.arg(index_member)
|
||||
.invoke_async::<i64>(&mut connection)
|
||||
.await
|
||||
.map_err(|source| redis_unavailable("invalidate credential cooldown", source))?;
|
||||
Ok(removed == 1)
|
||||
}
|
||||
|
||||
@@ -337,8 +410,16 @@ impl RedisCredentialCooldownRepository {
|
||||
}
|
||||
|
||||
pub(crate) async fn active_cooldowns(&self) -> StoreResult<AccountRuntimeSnapshot> {
|
||||
self.read_cooldown_accounts(self.all_cooldown_accounts().await?)
|
||||
let mut accounts = self.all_cooldown_accounts().await?;
|
||||
let model_accounts: Vec<String> = Script::new(ACTIVE_SCOPES)
|
||||
.key(self.active_model_index_key())
|
||||
.invoke_async(&mut self.connection.clone())
|
||||
.await
|
||||
.map_err(|source| redis_unavailable("list model cooldown accounts", source))?;
|
||||
accounts.extend(model_accounts);
|
||||
accounts.sort_unstable();
|
||||
accounts.dedup();
|
||||
self.read_cooldown_accounts(accounts).await
|
||||
}
|
||||
|
||||
pub(crate) async fn account_cooldowns(
|
||||
@@ -349,13 +430,16 @@ impl RedisCredentialCooldownRepository {
|
||||
return Ok(AccountRuntimeSnapshot::default());
|
||||
}
|
||||
// 索引与冷却事实由 Lua 原子维护,只读取范围内实际有状态的账号
|
||||
let (cooldowns, protections): (Vec<Option<f64>>, Vec<Option<f64>>) = redis::pipe()
|
||||
let [cooldowns, protections, models]: [Vec<Option<f64>>; 3] = redis::pipe()
|
||||
.cmd("ZMSCORE")
|
||||
.arg(self.active_index_key())
|
||||
.arg(accounts)
|
||||
.cmd("ZMSCORE")
|
||||
.arg(self.protection_index_key())
|
||||
.arg(accounts)
|
||||
.cmd("ZMSCORE")
|
||||
.arg(self.active_model_index_key())
|
||||
.arg(accounts)
|
||||
.query_async(&mut self.connection.clone())
|
||||
.await
|
||||
.map_err(|error| redis_unavailable("read scoped account cooldown index", error))?;
|
||||
@@ -363,8 +447,11 @@ impl RedisCredentialCooldownRepository {
|
||||
.iter()
|
||||
.zip(cooldowns)
|
||||
.zip(protections)
|
||||
.filter(|((_, cooldown), protection)| cooldown.is_some() || protection.is_some())
|
||||
.map(|((account, _), _)| account.clone())
|
||||
.zip(models)
|
||||
.filter(|(((_, cooldown), protection), model)| {
|
||||
cooldown.is_some() || protection.is_some() || model.is_some()
|
||||
})
|
||||
.map(|(((account, _), _), _)| account.clone())
|
||||
.collect();
|
||||
self.read_cooldown_accounts(active).await
|
||||
}
|
||||
@@ -376,15 +463,20 @@ impl RedisCredentialCooldownRepository {
|
||||
use futures::{StreamExt as _, TryStreamExt as _};
|
||||
let reads = futures::stream::iter(accounts)
|
||||
.map(|account| async move {
|
||||
self.read_account_runtime(&account)
|
||||
.await
|
||||
.map(|runtime| (account, runtime))
|
||||
let (runtime, models) = tokio::try_join!(
|
||||
self.read_account_runtime(&account),
|
||||
self.read_model_cooldowns(&account),
|
||||
)?;
|
||||
Ok((account, runtime, models))
|
||||
})
|
||||
.buffer_unordered(32)
|
||||
.try_collect::<Vec<_>>()
|
||||
.await?;
|
||||
let mut snapshot = AccountRuntimeSnapshot::default();
|
||||
for (account, (cooldown, freeze)) in reads {
|
||||
for (account, (cooldown, freeze), models) in reads {
|
||||
if !models.is_empty() {
|
||||
snapshot.model_cooldowns.insert(account.clone(), models);
|
||||
}
|
||||
if let Some(cooldown) = cooldown {
|
||||
snapshot.cooldown.insert(
|
||||
account.clone(),
|
||||
@@ -446,7 +538,7 @@ impl CredentialCooldownRepository for RedisCredentialCooldownRepository {
|
||||
cooldown.credential_revision,
|
||||
cooldown.cooldown_until,
|
||||
cooldown.kind,
|
||||
Some(&cooldown.provider_account_id),
|
||||
&cooldown.provider_account_id,
|
||||
)
|
||||
.await
|
||||
}
|
||||
@@ -480,7 +572,8 @@ impl CredentialCooldownRepository for RedisCredentialCooldownRepository {
|
||||
.invalidate_at_key(
|
||||
self.key(provider_account_id)?,
|
||||
through_revision,
|
||||
Some(provider_account_id),
|
||||
self.active_index_key(),
|
||||
provider_account_id,
|
||||
)
|
||||
.await?;
|
||||
Ok(protection_cleared || cooldown_cleared)
|
||||
@@ -530,6 +623,7 @@ impl CredentialCooldownRepository for RedisCredentialCooldownRepository {
|
||||
local removed = 0
|
||||
for i = 2, #KEYS do removed = removed + redis.call('DEL', KEYS[i]) end
|
||||
redis.call('ZREM', ARGV[2], ARGV[1])
|
||||
redis.call('ZREM', ARGV[3], ARGV[1])
|
||||
return removed + redis.call('ZREM', KEYS[1], ARGV[1])
|
||||
"#,
|
||||
)
|
||||
@@ -537,6 +631,7 @@ impl CredentialCooldownRepository for RedisCredentialCooldownRepository {
|
||||
.key(keys)
|
||||
.arg(provider_account_id)
|
||||
.arg(self.protection_index_key())
|
||||
.arg(self.active_model_index_key())
|
||||
.invoke_async(&mut connection)
|
||||
.await
|
||||
.map_err(|source| redis_unavailable("delete account cooldowns and index", source))?;
|
||||
@@ -686,18 +781,37 @@ impl ProviderCooldownPort for RedisCredentialCooldownRepository {
|
||||
Box::pin(async move {
|
||||
let revision = Revision::new(cooldown.credential_revision().get())
|
||||
.map_err(|_| provider_invalid("encode scoped credential cooldown"))?;
|
||||
self.cache_at_key(
|
||||
self.scoped_key(cooldown.account_id().as_str(), cooldown.scope())
|
||||
.map_err(|_| provider_invalid("encode scoped credential cooldown"))?,
|
||||
revision,
|
||||
cooldown.until().into(),
|
||||
ProviderCooldownKind::RateLimit,
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.map_err(|source| {
|
||||
crate::provider_unavailable("cache scoped credential cooldown", source)
|
||||
})
|
||||
let account = cooldown.account_id().as_str();
|
||||
let key = self
|
||||
.scoped_key(account, cooldown.scope())
|
||||
.map_err(|_| provider_invalid("encode scoped credential cooldown"))?;
|
||||
let index = self
|
||||
.model_index_key(account)
|
||||
.map_err(|_| provider_invalid("encode model cooldown index"))?;
|
||||
let until: DateTime<Utc> = cooldown.until().into();
|
||||
let written: i64 = Script::new(WRITE_SCOPED)
|
||||
.key(key)
|
||||
.key(index)
|
||||
.key(self.active_model_index_key())
|
||||
.arg(revision.get())
|
||||
.arg(until.timestamp_millis())
|
||||
.arg(cooldown.scope().value())
|
||||
.arg(
|
||||
cooldown
|
||||
.rate_limited_until()
|
||||
.map(DateTime::<Utc>::from)
|
||||
.map_or(0, |time| time.timestamp_millis()),
|
||||
)
|
||||
.arg(account)
|
||||
.invoke_async(&mut self.connection.clone())
|
||||
.await
|
||||
.map_err(|source| {
|
||||
crate::provider_unavailable(
|
||||
"cache scoped credential cooldown",
|
||||
redis_unavailable("write model cooldown", source),
|
||||
)
|
||||
})?;
|
||||
Ok(written == 1)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -708,24 +822,18 @@ impl ProviderCooldownPort for RedisCredentialCooldownRepository {
|
||||
) -> futures::future::BoxFuture<'a, Result<Option<ProviderScopedCooldown>, ProviderStoreError>>
|
||||
{
|
||||
Box::pin(async move {
|
||||
self.read_scoped_key(
|
||||
self.scoped_key(account_id.as_str(), scope)
|
||||
.map_err(|_| provider_invalid("encode scoped credential cooldown"))?,
|
||||
)
|
||||
.await
|
||||
.map_err(|source| {
|
||||
let key = self
|
||||
.scoped_key(account_id.as_str(), scope)
|
||||
.map_err(|_| provider_invalid("encode scoped credential cooldown"))?;
|
||||
let value = Script::new(READ_SCOPED)
|
||||
.key(key)
|
||||
.invoke_async(&mut self.connection.clone())
|
||||
.await
|
||||
.map_err(|source| redis_unavailable("read scoped cooldown", source))
|
||||
.and_then(|value| parse_scoped_cooldown(value, account_id, scope));
|
||||
value.map_err(|source| {
|
||||
crate::provider_unavailable("read scoped credential cooldown", source)
|
||||
})?
|
||||
.map(|(revision, until)| {
|
||||
Ok(ProviderScopedCooldown::new(
|
||||
account_id.clone(),
|
||||
CredentialRevision::new(revision.get())
|
||||
.map_err(|_| provider_invalid("decode scoped credential cooldown"))?,
|
||||
scope.clone(),
|
||||
until.into(),
|
||||
))
|
||||
})
|
||||
.transpose()
|
||||
})
|
||||
}
|
||||
|
||||
@@ -754,28 +862,16 @@ impl ProviderCooldownPort for RedisCredentialCooldownRepository {
|
||||
.collect();
|
||||
let values = self.read_script_batch(&script, commands).await;
|
||||
results.extend(batch.iter().zip(values).map(|(account, value)| {
|
||||
let value = value
|
||||
value
|
||||
.and_then(|value| {
|
||||
redis::from_redis_value(value).map_err(|source| {
|
||||
redis_unavailable("decode scoped cooldown", source)
|
||||
})
|
||||
})
|
||||
.and_then(parse_scoped_cooldown)
|
||||
.and_then(|value| parse_scoped_cooldown(value, account, scope))
|
||||
.map_err(|source| {
|
||||
crate::provider_unavailable("read scoped credential cooldown", source)
|
||||
})?;
|
||||
value
|
||||
.map(|(revision, until)| {
|
||||
Ok(ProviderScopedCooldown::new(
|
||||
account.clone(),
|
||||
CredentialRevision::new(revision.get()).map_err(|_| {
|
||||
provider_invalid("decode scoped credential cooldown")
|
||||
})?,
|
||||
scope.clone(),
|
||||
until.into(),
|
||||
))
|
||||
})
|
||||
.transpose()
|
||||
}));
|
||||
}
|
||||
results
|
||||
@@ -795,7 +891,9 @@ impl ProviderCooldownPort for RedisCredentialCooldownRepository {
|
||||
self.scoped_key(account_id.as_str(), scope)
|
||||
.map_err(|_| provider_invalid("encode scoped credential cooldown"))?,
|
||||
revision,
|
||||
None,
|
||||
self.model_index_key(account_id.as_str())
|
||||
.map_err(|_| provider_invalid("encode model cooldown index"))?,
|
||||
scope.value(),
|
||||
)
|
||||
.await
|
||||
.map_err(|source| {
|
||||
@@ -858,21 +956,35 @@ pub(super) fn invalid(message: &str) -> StoreError {
|
||||
}
|
||||
}
|
||||
|
||||
type ScopedCooldownReply = (i64, String, i64, i64);
|
||||
|
||||
fn parse_scoped_cooldown(
|
||||
(present, revision, until_ms): (i64, String, String),
|
||||
) -> StoreResult<Option<(Revision, DateTime<Utc>)>> {
|
||||
(present, revision, until_ms, limited_ms): ScopedCooldownReply,
|
||||
account: &ProviderAccountId,
|
||||
scope: &ProviderCooldownScope,
|
||||
) -> StoreResult<Option<ProviderScopedCooldown>> {
|
||||
if present == 0 {
|
||||
return Ok(None);
|
||||
}
|
||||
let revision = revision
|
||||
.parse::<u64>()
|
||||
.map_err(|source| invalid("cached cooldown revision is invalid").with_source(source))?;
|
||||
let until_ms = until_ms
|
||||
.parse::<i64>()
|
||||
.map_err(|source| invalid("cached cooldown expiry is invalid").with_source(source))?;
|
||||
let cooldown_until = DateTime::from_timestamp_millis(until_ms)
|
||||
.ok_or_else(|| invalid("cached cooldown expiry is invalid"))?;
|
||||
Ok(Some((Revision::new(revision)?, cooldown_until)))
|
||||
let revision =
|
||||
CredentialRevision::new(revision).map_err(|_| invalid("invalid cooldown revision"))?;
|
||||
let deadline = |ms| {
|
||||
DateTime::from_timestamp_millis(ms)
|
||||
.map(SystemTime::from)
|
||||
.ok_or_else(|| invalid("cached cooldown expiry is invalid"))
|
||||
};
|
||||
Ok(Some(
|
||||
ProviderScopedCooldown::new(
|
||||
account.clone(),
|
||||
revision,
|
||||
scope.clone(),
|
||||
deadline(until_ms)?,
|
||||
)
|
||||
.with_rate_limited_until((limited_ms > 0).then(|| deadline(limited_ms)).transpose()?),
|
||||
))
|
||||
}
|
||||
|
||||
fn provider_cooldown(record: CredentialCooldown) -> Result<ProviderCooldown, ProviderStoreError> {
|
||||
|
||||
@@ -240,18 +240,21 @@ pub(crate) struct StaleModelRequestRecoveryTask {
|
||||
impl ScheduledTask for StaleModelRequestRecoveryTask {
|
||||
fn run_cycle(
|
||||
&self,
|
||||
_context: WorkerCycleContext,
|
||||
context: WorkerCycleContext,
|
||||
) -> futures::future::BoxFuture<'_, Result<(), WorkerTaskError>> {
|
||||
Box::pin(async move {
|
||||
gateway_core::engine::ExecutionStore::recover_expired(
|
||||
self.execution.as_ref(),
|
||||
SystemTime::now(),
|
||||
)
|
||||
.await
|
||||
.map(|_| ())
|
||||
.map_err(|source| {
|
||||
WorkerTaskError::safe("stale request recovery failed").with_source(source)
|
||||
})
|
||||
context
|
||||
.cancellation()
|
||||
.run_until_cancelled(gateway_core::engine::ExecutionStore::recover_expired(
|
||||
self.execution.as_ref(),
|
||||
SystemTime::now(),
|
||||
))
|
||||
.await
|
||||
.transpose()
|
||||
.map(|_| ())
|
||||
.map_err(|source| {
|
||||
WorkerTaskError::safe("stale request recovery failed").with_source(source)
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -62,6 +62,23 @@ async fn recovery_loads_precise_window_and_running_request_facts() {
|
||||
.await
|
||||
.expect("remove missing lease fixture");
|
||||
|
||||
seed_request(
|
||||
&database.pool,
|
||||
"nested-child",
|
||||
now - Duration::seconds(8),
|
||||
now + Duration::seconds(30),
|
||||
"running",
|
||||
)
|
||||
.await;
|
||||
sqlx::query(
|
||||
"update model_requests set client_transport = 'internal_plugin',
|
||||
request_kind = case id when 'recent-running' then 'plugin_bound_model' else 'plugin_child_model' end
|
||||
where id in ('nested-child', 'recent-running')",
|
||||
)
|
||||
.execute(&database.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let repository = PgClientAdmissionRecoveryRepository::new(database.pool.clone());
|
||||
let actual = repository
|
||||
.load_client_admission_recovery(window_started_at)
|
||||
|
||||
@@ -2,6 +2,76 @@
|
||||
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn model_cooldown_status_filter_and_details_share_revision_and_expiry_rules() {
|
||||
use gateway_core::provider_ports::{ProviderCooldownScope, ProviderScopedCooldown};
|
||||
let Some(database) = TestDatabase::create("account_model_cooldown").await else {
|
||||
return;
|
||||
};
|
||||
let repository = PgProviderAccountRepository::new(database.pool.clone());
|
||||
let ids = ["acct_active", "acct_stale", "acct_expired", "acct_disabled"];
|
||||
for id in ids {
|
||||
let mut record = account(id, id);
|
||||
record.enabled = id != "acct_disabled";
|
||||
repository.insert_provider_account(record).await.unwrap();
|
||||
}
|
||||
let mut runtime = AccountRuntimeSnapshot::default();
|
||||
for id in ids {
|
||||
let stored = repository.load_provider_account(id).await.unwrap().unwrap();
|
||||
let revision = stored.summary.credential_revision.get();
|
||||
let revision = if id == "acct_stale" {
|
||||
revision + 1
|
||||
} else {
|
||||
revision
|
||||
};
|
||||
let until = Utc::now() + TimeDelta::seconds(if id == "acct_expired" { -1 } else { 60 });
|
||||
runtime.model_cooldowns.insert(
|
||||
id.into(),
|
||||
vec![ProviderScopedCooldown::new(
|
||||
ProviderAccountId::new(id).unwrap(),
|
||||
gateway_core::account::CredentialRevision::new(revision).unwrap(),
|
||||
ProviderCooldownScope::upstream_model(
|
||||
gateway_core::routing::UpstreamModelId::new("gpt-5.4").unwrap(),
|
||||
),
|
||||
until.into(),
|
||||
)],
|
||||
);
|
||||
}
|
||||
let store = admin_account_store(&database.pool);
|
||||
let page = store
|
||||
.list_accounts(
|
||||
AccountListQuery {
|
||||
page: 1,
|
||||
page_size: PageSize::new(20).unwrap(),
|
||||
provider_kind: None,
|
||||
group_filter: None,
|
||||
search: None,
|
||||
status: Some(AccountStatus::RateLimited),
|
||||
sort: None,
|
||||
},
|
||||
runtime.clone(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(page.total, 1);
|
||||
assert_eq!(page.summary.rate_limited, 1);
|
||||
assert_eq!(page.summary.normal, 2);
|
||||
assert_eq!(page.summary.disabled, 1);
|
||||
let item = &page.items[0];
|
||||
assert_eq!(item.account.id, "acct_active");
|
||||
assert_eq!(item.projection.status, AccountStatus::RateLimited);
|
||||
assert!(item.projection.cooldown.is_none());
|
||||
assert_eq!(item.model_cooldowns.len(), 1);
|
||||
let detail = store
|
||||
.load_account("acct_active", runtime)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(detail.projection, item.projection);
|
||||
assert_eq!(detail.model_cooldowns, item.model_cooldowns);
|
||||
database.close().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn import_name_only_overrides_a_single_account_and_keeps_batch_names() {
|
||||
use gateway_admin::model::accounts::AccountImportSettings;
|
||||
|
||||
@@ -940,6 +940,7 @@ async fn terminal_admin_list_filters_and_sorts_before_pagination_with_retained_u
|
||||
sort: None,
|
||||
},
|
||||
AccountRuntimeSnapshot {
|
||||
model_cooldowns: BTreeMap::new(),
|
||||
protection_rules: std::collections::BTreeMap::new(),
|
||||
cooldown: BTreeMap::from([(
|
||||
"acct_alpha".to_owned(),
|
||||
|
||||
@@ -18,11 +18,19 @@ fn client_admission_rejects_zero_ttl() {
|
||||
assert!(request.validate().is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn client_admission_rejects_values_outside_redis_exact_integer_range() {
|
||||
let mut request = admission_request("request-1", "key-1", Duration::from_secs(30));
|
||||
#[tokio::test]
|
||||
async fn configured_limits_above_lua_integer_precision_allow_requests() {
|
||||
let Some((repository, mut connection, namespace)) = repository().await else {
|
||||
return;
|
||||
};
|
||||
let mut request = admission_request("req_large_limits", "key-1", Duration::from_secs(30));
|
||||
request.limits.max_concurrency = 1_u64 << 53;
|
||||
assert!(request.validate().is_err());
|
||||
request.limits.requests_per_minute = i64::MAX as u64;
|
||||
assert_eq!(
|
||||
repository.admit_client_request(&request).await.unwrap(),
|
||||
ClientAdmissionDecision::Granted
|
||||
);
|
||||
delete_namespace_keys(&mut connection, &namespace).await;
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -313,7 +313,12 @@ async fn scoped_cooldown_isolated_by_model_and_revision_fenced() {
|
||||
.is_some()
|
||||
);
|
||||
let keys = namespace_keys(&mut connection, &namespace).await;
|
||||
assert_eq!(keys.len(), 1);
|
||||
assert_eq!(
|
||||
keys.iter()
|
||||
.filter(|key| key.contains(":cooldown:model:"))
|
||||
.count(),
|
||||
1
|
||||
);
|
||||
assert!(!keys[0].contains(account_id.as_str()));
|
||||
assert!(!keys[0].contains(model_b.value()));
|
||||
}
|
||||
@@ -516,6 +521,142 @@ fn runtime_store(
|
||||
)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn model_cooldowns_are_visible_in_runtime_without_blocking_the_entire_account() {
|
||||
use gateway_admin::ports::store::AccountRuntimeStore as _;
|
||||
let Some((repository, connection, namespace)) = repository().await else {
|
||||
return;
|
||||
};
|
||||
let runtime = runtime_store(&repository, connection, &namespace);
|
||||
let id = ProviderAccountId::new("acct_model_limit").unwrap();
|
||||
let revision = CredentialRevision::new(1).unwrap();
|
||||
let models = ["gpt-5.4", "gpt-5.5"].map(|model| {
|
||||
ProviderCooldownScope::upstream_model(
|
||||
gateway_core::routing::UpstreamModelId::new(model).unwrap(),
|
||||
)
|
||||
});
|
||||
let until: SystemTime = millisecond_precision(Utc::now() + Duration::seconds(60)).into();
|
||||
// 不支持的模型仍影响选号,但不能让目录误报限流;两种期限可重叠
|
||||
let unsupported_until = until + std::time::Duration::from_secs(1800);
|
||||
repository
|
||||
.put_scoped_if_later(ProviderScopedCooldown::new(
|
||||
id.clone(),
|
||||
revision,
|
||||
models[0].clone(),
|
||||
unsupported_until,
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
runtime
|
||||
.active_rate_limits()
|
||||
.await
|
||||
.unwrap()
|
||||
.model_cooldowns
|
||||
.is_empty()
|
||||
);
|
||||
for scope in &models {
|
||||
repository
|
||||
.put_scoped_if_later(
|
||||
ProviderScopedCooldown::new(id.clone(), revision, scope.clone(), until)
|
||||
.with_rate_limited_until(Some(until)),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
repository.clear_after_success(&id, revision).await.unwrap();
|
||||
let snapshot = runtime.active_rate_limits().await.unwrap();
|
||||
assert!(snapshot.cooldown.is_empty());
|
||||
assert_eq!(snapshot.model_cooldowns[id.as_str()].len(), 2);
|
||||
assert!(
|
||||
snapshot.model_cooldowns[id.as_str()]
|
||||
.iter()
|
||||
.all(|model| model.until() == until)
|
||||
);
|
||||
assert_eq!(
|
||||
repository
|
||||
.read_scoped(&id, &models[0])
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.until(),
|
||||
unsupported_until
|
||||
);
|
||||
let scoped = runtime
|
||||
.account_rate_limits(&[id.to_string()])
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(scoped.model_cooldowns, snapshot.model_cooldowns);
|
||||
repository
|
||||
.clear_scoped(&id, &models[0], revision)
|
||||
.await
|
||||
.unwrap();
|
||||
let snapshot = runtime.active_rate_limits().await.unwrap();
|
||||
assert_eq!(snapshot.model_cooldowns[id.as_str()].len(), 1);
|
||||
assert_eq!(snapshot.model_cooldowns[id.as_str()][0].scope(), &models[1]);
|
||||
repository
|
||||
.delete_account_cooldowns(id.as_str())
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
runtime
|
||||
.active_rate_limits()
|
||||
.await
|
||||
.unwrap()
|
||||
.model_cooldowns
|
||||
.is_empty()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn expired_model_cooldown_disappears_from_the_directory_even_during_redis_grace() {
|
||||
use gateway_admin::ports::store::AccountRuntimeStore as _;
|
||||
let Some((repository, mut connection, namespace)) = repository().await else {
|
||||
return;
|
||||
};
|
||||
let runtime = runtime_store(&repository, connection.clone(), &namespace);
|
||||
let id = ProviderAccountId::new("acct_model_expired").unwrap();
|
||||
let until = (Utc::now() + Duration::minutes(1)).into();
|
||||
repository
|
||||
.put_scoped_if_later(
|
||||
ProviderScopedCooldown::new(
|
||||
id.clone(),
|
||||
CredentialRevision::new(1).unwrap(),
|
||||
ProviderCooldownScope::upstream_model(
|
||||
gateway_core::routing::UpstreamModelId::new("gpt-5.4").unwrap(),
|
||||
),
|
||||
until,
|
||||
)
|
||||
.with_rate_limited_until(Some(until)),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let key = namespace_keys(&mut connection, &namespace)
|
||||
.await
|
||||
.into_iter()
|
||||
.find(|key| key.contains(":cooldown:model:"))
|
||||
.unwrap();
|
||||
redis::cmd("HSET")
|
||||
.arg(key)
|
||||
.arg("until_ms")
|
||||
.arg(Utc::now().timestamp_millis() - 1000)
|
||||
.query_async::<i64>(&mut connection)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
runtime
|
||||
.active_rate_limits()
|
||||
.await
|
||||
.unwrap()
|
||||
.model_cooldowns
|
||||
.is_empty()
|
||||
);
|
||||
repository
|
||||
.delete_account_cooldowns(id.as_str())
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn capacity_freeze_survives_due_time_and_runtime_restart_until_probe_succeeds() {
|
||||
use gateway_admin::ports::store::AccountRuntimeStore as _;
|
||||
|
||||
@@ -27,6 +27,7 @@ http-body-util = "0.1.5"
|
||||
reqwest = { version = "=0.12.28", default-features = false, features = ["json", "rustls-tls-native-roots", "socks", "stream"] }
|
||||
serde = { version = "1.0.228", features = ["derive"] }
|
||||
serde_json = { version = "1.0.150", features = ["raw_value"] }
|
||||
sevenz-rust2 = { version = "0.27.0", default-features = false }
|
||||
sha2 = "0.11.0"
|
||||
tar = { version = "0.4.46", default-features = false }
|
||||
tempfile = "3.27.0"
|
||||
@@ -39,6 +40,7 @@ uuid = { version = "1.23.3", features = ["v7"] }
|
||||
zip = { version = "9.8.0", default-features = false, features = ["deflate-flate2"] }
|
||||
|
||||
[dev-dependencies]
|
||||
sevenz-rust2 = { version = "0.27.0", default-features = false, features = ["compress"] }
|
||||
wiremock = "0.6.5"
|
||||
tokio = { version = "=1.53.3", features = ["rt-multi-thread"] }
|
||||
|
||||
|
||||
@@ -308,6 +308,18 @@ impl CatalogService {
|
||||
}
|
||||
}
|
||||
}
|
||||
if !refresh
|
||||
&& matches!(
|
||||
current.account.credential_state(),
|
||||
gateway_core::account::CredentialState::Invalid
|
||||
| gateway_core::account::CredentialState::Banned
|
||||
)
|
||||
{
|
||||
return Ok(ProviderModels {
|
||||
models: Vec::new(),
|
||||
observed_at: None,
|
||||
});
|
||||
}
|
||||
if current.account.authentication_kind() == super::api_key::API_KEY {
|
||||
let material = super::api_key::ApiKeyMaterial::load(¤t)?;
|
||||
let client = crate::transport::GenAiClient::new(
|
||||
@@ -316,7 +328,12 @@ impl CatalogService {
|
||||
)
|
||||
.map_err(|e| error(AdminKind::Unavailable).with_source(e))?;
|
||||
let observed_at = SystemTime::now();
|
||||
let catalog = client.catalog(&material.api_key).await.map_err(|e| {
|
||||
let result = client.catalog(&material.api_key).await;
|
||||
if let Err(failure) = &result {
|
||||
super::record_account_failure(self.accounts.as_ref(), ¤t.account, failure)
|
||||
.await;
|
||||
}
|
||||
let catalog = result.map_err(|e| {
|
||||
error(AdminKind::Unavailable)
|
||||
.with_public_message("GenAI 模型目录查询失败")
|
||||
.with_source(e)
|
||||
@@ -333,15 +350,16 @@ impl CatalogService {
|
||||
let client = CloudCodeClient::new(&self.origin, current.account.outbound_proxy(), &profile)
|
||||
.map_err(|e| error(AdminKind::Unavailable).with_source(e))?;
|
||||
let observed_at = SystemTime::now();
|
||||
let catalog = client
|
||||
.catalog(&material.access_token)
|
||||
.await
|
||||
.map_err(|e| match e.kind() {
|
||||
Kind::Unauthorized => error(AdminKind::CredentialRefreshRequired).with_source(e),
|
||||
_ => error(AdminKind::Unavailable)
|
||||
.with_public_message("Antigravity 项目或模型目录查询失败")
|
||||
.with_source(e),
|
||||
})?;
|
||||
let result = client.catalog(&material.access_token).await;
|
||||
if let Err(error) = &result {
|
||||
super::record_account_failure(self.accounts.as_ref(), ¤t.account, error).await;
|
||||
}
|
||||
let catalog = result.map_err(|e| match e.kind() {
|
||||
Kind::Unauthorized => error(AdminKind::CredentialRefreshRequired).with_source(e),
|
||||
_ => error(AdminKind::Unavailable)
|
||||
.with_public_message("Antigravity 项目或模型目录查询失败")
|
||||
.with_source(e),
|
||||
})?;
|
||||
self.publish(
|
||||
¤t.account,
|
||||
current.account.plan_type().map(str::to_owned),
|
||||
@@ -452,6 +470,13 @@ impl CatalogService {
|
||||
&self,
|
||||
cancellation: &gateway_core::lifecycle::CancellationToken,
|
||||
) -> Result<(), gateway_core::task::WorkerTaskError> {
|
||||
cancellation
|
||||
.run_until_cancelled(self.refresh_due_accounts())
|
||||
.await
|
||||
.unwrap_or(Ok(()))
|
||||
}
|
||||
|
||||
async fn refresh_due_accounts(&self) -> Result<(), gateway_core::task::WorkerTaskError> {
|
||||
use futures::{StreamExt, stream};
|
||||
use gateway_core::task::WorkerTaskError;
|
||||
let catalogs = self
|
||||
@@ -469,7 +494,11 @@ impl CatalogService {
|
||||
.await
|
||||
.map_err(|e| WorkerTaskError::safe("读取 Antigravity 账号失败").with_source(e))?;
|
||||
due.retain(|account| {
|
||||
matches!(account.authentication_kind(), "oauth" | "api_key")
|
||||
!matches!(
|
||||
account.credential_state(),
|
||||
gateway_core::account::CredentialState::Invalid
|
||||
| gateway_core::account::CredentialState::Banned
|
||||
) && matches!(account.authentication_kind(), "oauth" | "api_key")
|
||||
&& observations.get(account.id()).is_none_or(|observation| {
|
||||
observation.revision != account.revision()
|
||||
|| observation.observed_at.elapsed().unwrap_or_default()
|
||||
@@ -484,9 +513,9 @@ impl CatalogService {
|
||||
let offset = self.refresh_cursor.fetch_add(32, Ordering::Relaxed) % due.len();
|
||||
due.rotate_left(offset);
|
||||
due.truncate(32);
|
||||
let mut updates=stream::iter(due).map(|account|async move {
|
||||
tokio::select! {biased;_=cancellation.cancelled()=>Ok(()),result=self.account_models(account.id(),true)=>result.map(|_|())}
|
||||
}).buffer_unordered(4);
|
||||
let mut updates = stream::iter(due)
|
||||
.map(|account| async move { self.account_models(account.id(), true).await })
|
||||
.buffer_unordered(4);
|
||||
let mut first_error = None;
|
||||
while let Some(result) = updates.next().await {
|
||||
if let Err(error) = result
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
//! 资源服务的明确拒绝更新账号访问状态,普通授权失败只触发 AT 续期
|
||||
|
||||
use crate::transport::{AccountRejection, account_rejection};
|
||||
use gateway_core::{
|
||||
account::{
|
||||
AccountErrorReason, AccountStateChange, CredentialState, ProviderAccount,
|
||||
ProviderAccountStore,
|
||||
},
|
||||
error::{ProviderError, ProviderErrorKind, StoreError},
|
||||
upstream::UpstreamSendState,
|
||||
};
|
||||
use std::time::{Duration, SystemTime};
|
||||
|
||||
pub(crate) async fn record_account_failure(
|
||||
accounts: &dyn ProviderAccountStore,
|
||||
account: &ProviderAccount,
|
||||
error: &ProviderError,
|
||||
) {
|
||||
if error.send_state() != UpstreamSendState::Sent {
|
||||
return;
|
||||
}
|
||||
let state = match account_rejection(error) {
|
||||
Some(AccountRejection::VerificationRequired) => Some((
|
||||
CredentialState::Invalid,
|
||||
AccountErrorReason::AccountUnverified,
|
||||
"Google 要求验证账号,完成验证后恢复账号状态",
|
||||
)),
|
||||
Some(AccountRejection::Banned) => Some((
|
||||
CredentialState::Banned,
|
||||
AccountErrorReason::AccountBanned,
|
||||
"Google 已停用账号",
|
||||
)),
|
||||
None if error.kind() == ProviderErrorKind::Unauthorized
|
||||
&& account.authentication_kind() == super::api_key::API_KEY =>
|
||||
{
|
||||
Some((
|
||||
CredentialState::Invalid,
|
||||
AccountErrorReason::CredentialInvalid,
|
||||
"上游拒绝 API Key",
|
||||
))
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let feedback = async {
|
||||
if let Some((credential_state, error_reason, message)) = state {
|
||||
accounts
|
||||
.apply_state_change(AccountStateChange {
|
||||
account_id: account.id().clone(),
|
||||
expected_revision: account.revision(),
|
||||
credential_state,
|
||||
observed_at: SystemTime::now(),
|
||||
error_reason: Some(error_reason),
|
||||
message: Some(message.into()),
|
||||
})
|
||||
.await?;
|
||||
} else if error.kind() == ProviderErrorKind::Unauthorized {
|
||||
// 资源服务拒绝 AT 不能证明 RT 失效,续期由 OAuth worker 负责
|
||||
accounts
|
||||
.expire_access_token(account, SystemTime::now())
|
||||
.await?;
|
||||
}
|
||||
Ok::<_, StoreError>(())
|
||||
};
|
||||
if !matches!(
|
||||
tokio::time::timeout(Duration::from_millis(100), feedback).await,
|
||||
Ok(Ok(()))
|
||||
) {
|
||||
tracing::warn!("Antigravity 账号失败反馈未能写入共享状态");
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,8 @@ pub(crate) mod api_key;
|
||||
mod authorization;
|
||||
pub(crate) mod catalog;
|
||||
mod documents;
|
||||
mod failure;
|
||||
pub(crate) use failure::record_account_failure;
|
||||
mod model_groups;
|
||||
pub(crate) mod oauth;
|
||||
pub(crate) mod quota;
|
||||
|
||||
@@ -175,15 +175,20 @@ impl QuotaService {
|
||||
.map_err(upstream)?;
|
||||
// 用查询开始时间隔离交错返回的旧结果,失败不覆盖已有快照
|
||||
let observed_at = SystemTime::now();
|
||||
let info = client
|
||||
.account_info(&material.access_token)
|
||||
.await
|
||||
.map_err(upstream)?;
|
||||
let (catalog, summary) = tokio::try_join!(
|
||||
client.catalog_for_project(&material.access_token, info.project.clone()),
|
||||
client.quota_summary(&material.access_token, &info.project),
|
||||
)
|
||||
.map_err(upstream)?;
|
||||
let result = async {
|
||||
let info = client.account_info(&material.access_token).await?;
|
||||
let (catalog, summary) = tokio::try_join!(
|
||||
client.catalog_for_project(&material.access_token, info.project.clone()),
|
||||
client.quota_summary(&material.access_token, &info.project),
|
||||
)?;
|
||||
Ok::<_, gateway_core::error::ProviderError>((info, catalog, summary))
|
||||
}
|
||||
.await;
|
||||
if let Err(error) = &result {
|
||||
super::super::record_account_failure(self.accounts.as_ref(), ¤t.account, error)
|
||||
.await;
|
||||
}
|
||||
let (info, catalog, summary) = result.map_err(upstream)?;
|
||||
let (tier, plan_description) = match info.paid_tier {
|
||||
Some(paid) => (Some(paid.tier), paid.description),
|
||||
None => (info.current_tier, None),
|
||||
@@ -298,6 +303,13 @@ impl QuotaService {
|
||||
&self,
|
||||
cancel: &CancellationToken,
|
||||
) -> Result<(), WorkerTaskError> {
|
||||
cancel
|
||||
.run_until_cancelled(self.refresh_due_accounts())
|
||||
.await
|
||||
.unwrap_or(Ok(()))
|
||||
}
|
||||
|
||||
async fn refresh_due_accounts(&self) -> Result<(), WorkerTaskError> {
|
||||
let accounts = self
|
||||
.accounts
|
||||
.list_for_provider(&self.kind, false)
|
||||
@@ -317,10 +329,15 @@ impl QuotaService {
|
||||
let stale_before = now - interval;
|
||||
let mut due = Vec::new();
|
||||
let mut stale = Vec::new();
|
||||
for account in accounts
|
||||
.iter()
|
||||
.filter(|a| a.enabled() && a.authentication_kind() == "oauth")
|
||||
{
|
||||
for account in accounts.iter().filter(|a| {
|
||||
a.enabled()
|
||||
&& a.authentication_kind() == "oauth"
|
||||
&& !matches!(
|
||||
a.credential_state(),
|
||||
gateway_core::account::CredentialState::Invalid
|
||||
| gateway_core::account::CredentialState::Banned
|
||||
)
|
||||
}) {
|
||||
let snapshot = observations
|
||||
.remove(account.id())
|
||||
.filter(|s| s.credential_revision == account.revision());
|
||||
@@ -355,13 +372,7 @@ impl QuotaService {
|
||||
due.rotate_left(offset);
|
||||
due.truncate(32);
|
||||
let mut results = stream::iter(due)
|
||||
.map(|id| async move {
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = cancel.cancelled() => Ok(()),
|
||||
result = self.refresh(&id) => result,
|
||||
}
|
||||
})
|
||||
.map(|id| async move { self.refresh(&id).await })
|
||||
.buffer_unordered(4);
|
||||
while let Some(result) = results.next().await {
|
||||
if let Err(e) = result
|
||||
|
||||
@@ -4,8 +4,8 @@ use super::{oauth::error, service::CredentialService};
|
||||
use gateway_admin::ports::provider::{ProviderAdminError, ProviderAdminErrorKind as Kind};
|
||||
use gateway_core::{
|
||||
account::{
|
||||
CredentialCasOutcome, CredentialCasUpdate, CredentialRevision, CredentialState,
|
||||
LoadedCredential, PlaintextCredential, ProviderAccountUpdate, ProviderRefreshQuery,
|
||||
CredentialCasOutcome, CredentialCasUpdate, CredentialRevision, LoadedCredential,
|
||||
PlaintextCredential, ProviderAccountUpdate, ProviderRefreshQuery,
|
||||
},
|
||||
provider_ports::provider_refresh_backoff_at,
|
||||
task::WorkerTaskError,
|
||||
@@ -79,8 +79,8 @@ impl CredentialService {
|
||||
material,
|
||||
facts.access_token_expires_at.map(Into::into),
|
||||
None,
|
||||
)?
|
||||
.with_account_state(CredentialState::Ready, SystemTime::now(), None, None);
|
||||
)?;
|
||||
// AT 续期不证明资源服务已解除验证或封禁,提交时保留当前账号访问状态
|
||||
match self
|
||||
.accounts
|
||||
.compare_and_swap_credential(record)
|
||||
|
||||
@@ -304,6 +304,7 @@ impl CredentialService {
|
||||
Ok(grant) => grant,
|
||||
};
|
||||
self.rotation(¤t.account, grant, guards)
|
||||
.map(PreparedCredentialRotation::preserving_credential_state)
|
||||
}
|
||||
|
||||
pub(super) fn rotation(
|
||||
|
||||
@@ -9,17 +9,24 @@ mod transport;
|
||||
|
||||
use gateway_admin::ports::provider::ProviderBundle;
|
||||
use gateway_core::{provider_ports::ProviderStorePorts, routing::ProviderKind};
|
||||
use std::sync::Arc;
|
||||
use std::{path::PathBuf, sync::Arc};
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
#[error("Antigravity Provider 初始化失败")]
|
||||
pub struct ConfigError;
|
||||
|
||||
pub fn initialize(ports: ProviderStorePorts) -> Result<ProviderBundle, ConfigError> {
|
||||
pub async fn initialize(
|
||||
ports: ProviderStorePorts,
|
||||
artifact_dir: PathBuf,
|
||||
) -> Result<ProviderBundle, ConfigError> {
|
||||
let kind = ProviderKind::new("antigravity").map_err(|_| ConfigError)?;
|
||||
let oauth = Arc::new(credential::GoogleOAuth::for_provider()?);
|
||||
let origin = oauth.resource_origin().clone();
|
||||
let release = Arc::new(profile::ReleaseService::new(ports.artifact_profiles())?);
|
||||
let release = Arc::new(profile::ReleaseService::new(
|
||||
ports.artifact_profiles(),
|
||||
artifact_dir,
|
||||
)?);
|
||||
release.restore().await;
|
||||
let credentials = Arc::new(credential::CredentialService::new(
|
||||
kind.clone(),
|
||||
&ports,
|
||||
|
||||
@@ -20,12 +20,12 @@ impl Drop for ParseGuard {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct CancellableFile {
|
||||
file: std::fs::File,
|
||||
pub(crate) struct CancellableFile<R = std::fs::File> {
|
||||
file: R,
|
||||
cancellation: CancellationToken,
|
||||
}
|
||||
impl CancellableFile {
|
||||
pub(crate) fn new(file: std::fs::File) -> (Self, ParseGuard) {
|
||||
impl<R> CancellableFile<R> {
|
||||
pub(crate) fn new(file: R) -> (Self, ParseGuard) {
|
||||
let cancellation = CancellationToken::new();
|
||||
(
|
||||
Self {
|
||||
@@ -36,7 +36,7 @@ impl CancellableFile {
|
||||
)
|
||||
}
|
||||
}
|
||||
impl Read for CancellableFile {
|
||||
impl<R: Read> Read for CancellableFile<R> {
|
||||
fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
|
||||
if self.cancellation.is_cancelled() {
|
||||
return Err(io::Error::other("制品解析已取消"));
|
||||
@@ -44,6 +44,14 @@ impl Read for CancellableFile {
|
||||
self.file.read(buffer)
|
||||
}
|
||||
}
|
||||
impl<R: Seek> Seek for CancellableFile<R> {
|
||||
fn seek(&mut self, from: SeekFrom) -> io::Result<u64> {
|
||||
if self.cancellation.is_cancelled() {
|
||||
return Err(io::Error::other("制品解析已取消"));
|
||||
}
|
||||
self.file.seek(from)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn invalid() -> WorkerTaskError {
|
||||
WorkerTaskError::safe("Antigravity 发布包核验失败")
|
||||
@@ -131,10 +139,6 @@ impl<'a> RemoteArtifact<'a> {
|
||||
}
|
||||
Ok(body.into())
|
||||
}
|
||||
|
||||
pub(crate) async fn prefix(&self, maximum: u64) -> Result<Bytes, WorkerTaskError> {
|
||||
self.read(0, self.size.min(maximum)).await
|
||||
}
|
||||
}
|
||||
|
||||
/// 只缓存目录和所需条目,未下载的区间不能被当作零填充数据读取
|
||||
@@ -189,7 +193,7 @@ impl<'a> RemoteZip<'a> {
|
||||
|
||||
fn archive(
|
||||
&self,
|
||||
member: Option<(u64, Bytes)>,
|
||||
member: Vec<(u64, Bytes)>,
|
||||
) -> Result<zip::ZipArchive<Segments>, WorkerTaskError> {
|
||||
let mut chunks = vec![(
|
||||
self.artifact.size - self.tail.len() as u64,
|
||||
@@ -209,12 +213,22 @@ impl<'a> RemoteZip<'a> {
|
||||
name: &str,
|
||||
maximum: usize,
|
||||
) -> Result<Vec<u8>, WorkerTaskError> {
|
||||
let archive = self.archive(None)?;
|
||||
self.inspect(name, maximum as u64, move |reader| bounded(reader, maximum))
|
||||
.await
|
||||
}
|
||||
|
||||
pub(crate) async fn inspect<T: Send + 'static>(
|
||||
&self,
|
||||
name: &str,
|
||||
maximum: u64,
|
||||
inspect: impl FnOnce(&mut dyn Read) -> Result<T, WorkerTaskError> + Send + 'static,
|
||||
) -> Result<T, WorkerTaskError> {
|
||||
let archive = self.archive(Vec::new())?;
|
||||
let index = archive.index_for_name(name).ok_or_else(invalid)?;
|
||||
let entry = archive
|
||||
.by_index_data(index)
|
||||
.map_err(|e| invalid().with_source(e))?;
|
||||
if entry.size() > maximum as u64 || entry.is_dir() || entry.is_symlink() {
|
||||
if entry.size() > maximum || entry.is_dir() || entry.is_symlink() {
|
||||
return Err(invalid());
|
||||
}
|
||||
let start = entry.header_start();
|
||||
@@ -224,12 +238,25 @@ impl<'a> RemoteZip<'a> {
|
||||
.checked_add(30 + 2 * u64::from(u16::MAX))
|
||||
.ok_or_else(invalid)?
|
||||
.min(self.artifact.size.checked_sub(start).ok_or_else(invalid)?);
|
||||
let member = self.artifact.read(start, length).await?;
|
||||
let mut archive = self.archive(Some((start, member)))?;
|
||||
let file = archive
|
||||
.by_name(name)
|
||||
.map_err(|e| invalid().with_source(e))?;
|
||||
bounded(file, maximum)
|
||||
let mut members = Vec::new();
|
||||
let mut offset = start;
|
||||
while offset < start + length {
|
||||
let length = (start + length - offset).min(MAX_RANGE_BYTES);
|
||||
members.push((offset, self.artifact.read(offset, length).await?));
|
||||
offset += length;
|
||||
}
|
||||
let archive = self.archive(members)?;
|
||||
let (reader, _guard) = CancellableFile::new(archive.into_inner());
|
||||
let name = name.to_owned();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let mut archive = zip::ZipArchive::new(reader).map_err(|e| invalid().with_source(e))?;
|
||||
let mut file = archive
|
||||
.by_name(&name)
|
||||
.map_err(|e| invalid().with_source(e))?;
|
||||
inspect(&mut file)
|
||||
})
|
||||
.await
|
||||
.map_err(|e| invalid().with_source(e))?
|
||||
}
|
||||
}
|
||||
|
||||
@@ -281,6 +308,7 @@ pub(crate) async fn download(
|
||||
client: &Client,
|
||||
url: &str,
|
||||
sha512: Option<&str>,
|
||||
artifact_dir: &std::path::Path,
|
||||
) -> Result<std::fs::File, WorkerTaskError> {
|
||||
let mut response = client
|
||||
.get(url)
|
||||
@@ -296,7 +324,11 @@ pub(crate) async fn download(
|
||||
{
|
||||
return Err(invalid());
|
||||
}
|
||||
let file = tempfile::tempfile().map_err(|e| invalid().with_source(e))?;
|
||||
// 官方包可能大于容器的 /tmp;匿名文件随句柄释放,失败和取消也不会留下半包。
|
||||
tokio::fs::create_dir_all(artifact_dir)
|
||||
.await
|
||||
.map_err(|e| invalid().with_source(e))?;
|
||||
let file = tempfile::tempfile_in(artifact_dir).map_err(|e| invalid().with_source(e))?;
|
||||
let mut file = tokio::fs::File::from_std(file);
|
||||
let mut count = 0u64;
|
||||
let mut digest = Sha512::new();
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! 从官方发布包核对版本和目标平台,不执行下载的程序或发起模型请求
|
||||
|
||||
use super::archive::{CancellableFile, RemoteArtifact, RemoteZip, bounded, download, invalid};
|
||||
use super::archive::{CancellableFile, RemoteZip, bounded, download, invalid};
|
||||
use super::selection::{Architecture, ClientKind, Platform, ReleaseTarget};
|
||||
use gateway_core::task::WorkerTaskError;
|
||||
use std::io::Read;
|
||||
@@ -14,8 +14,8 @@ pub(crate) struct Release {
|
||||
pub(crate) sha512: Option<String>,
|
||||
}
|
||||
|
||||
const MAX_ASAR_BYTES: usize = 16 * 1024 * 1024;
|
||||
const MAX_BINARY_BYTES: u64 = 512 * 1024 * 1024;
|
||||
pub(super) const MAX_ASAR_BYTES: usize = 16 * 1024 * 1024;
|
||||
pub(super) const MAX_BINARY_BYTES: u64 = 512 * 1024 * 1024;
|
||||
|
||||
pub(crate) async fn verify(
|
||||
client: &reqwest::Client,
|
||||
@@ -23,7 +23,8 @@ pub(crate) async fn verify(
|
||||
version: &str,
|
||||
url: &str,
|
||||
sha512: Option<&str>,
|
||||
) -> Result<(), WorkerTaskError> {
|
||||
artifact_dir: &std::path::Path,
|
||||
) -> Result<u64, WorkerTaskError> {
|
||||
match (target.client, target.platform) {
|
||||
(ClientKind::Desktop, Platform::Macos) => {
|
||||
let url = url.strip_suffix(".dmg").ok_or_else(invalid)?;
|
||||
@@ -40,23 +41,27 @@ pub(crate) async fn verify(
|
||||
let executable = archive
|
||||
.read("Antigravity.app/Contents/MacOS/Antigravity", 1024 * 1024)
|
||||
.await?;
|
||||
architecture(&executable, target)
|
||||
}
|
||||
(ClientKind::Desktop, Platform::Windows) => {
|
||||
let artifact = RemoteArtifact::open(client, url.to_owned()).await?;
|
||||
let header = artifact.prefix(1024 * 1024).await?;
|
||||
let (offset, size) = pe_resources(&header)?;
|
||||
let resources = artifact.read(offset, size).await?;
|
||||
windows_version(&resources, version)
|
||||
architecture(&executable, target)?;
|
||||
archive
|
||||
.inspect(
|
||||
"Antigravity.app/Contents/Resources/bin/language_server",
|
||||
MAX_BINARY_BYTES,
|
||||
move |reader| verify_binary(reader, target, None),
|
||||
)
|
||||
.await
|
||||
}
|
||||
_ => {
|
||||
let file = download(client, url, sha512).await?;
|
||||
let file = download(client, url, sha512, artifact_dir).await?;
|
||||
// 取消 worker 时同步中止阻塞解包,临时文件由解析任务退出时关闭
|
||||
let (file, _guard) = CancellableFile::new(file);
|
||||
let version = version.to_owned();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
if target.client == ClientKind::Cli && target.platform == Platform::Windows {
|
||||
verify_binary(file, target, &version)
|
||||
if target.platform == Platform::Windows {
|
||||
if target.client == ClientKind::Cli {
|
||||
verify_binary(file, target, Some(&version))
|
||||
} else {
|
||||
super::installer::verify(file, target, &version)
|
||||
}
|
||||
} else {
|
||||
verify_tar(file, target, &version)
|
||||
}
|
||||
@@ -124,11 +129,12 @@ pub(crate) fn verify_tar(
|
||||
file: impl Read,
|
||||
target: ReleaseTarget,
|
||||
version: &str,
|
||||
) -> Result<(), WorkerTaskError> {
|
||||
) -> Result<u64, WorkerTaskError> {
|
||||
let decoder = flate2::read::GzDecoder::new(file);
|
||||
let mut archive = tar::Archive::new(decoder.take(2 * 1024 * 1024 * 1024));
|
||||
let mut found_version = false;
|
||||
let mut found_executable = false;
|
||||
let mut changelist = None;
|
||||
for (index, entry) in archive
|
||||
.entries()
|
||||
.map_err(|e| invalid().with_source(e))?
|
||||
@@ -153,7 +159,7 @@ pub(crate) fn verify_tar(
|
||||
if found_executable || entry.size() > MAX_BINARY_BYTES {
|
||||
return Err(invalid());
|
||||
}
|
||||
verify_binary(&mut entry, target, version)?;
|
||||
changelist = Some(verify_binary(&mut entry, target, Some(version))?);
|
||||
found_version = true;
|
||||
found_executable = true;
|
||||
} else if target.client == ClientKind::Desktop {
|
||||
@@ -163,6 +169,11 @@ pub(crate) fn verify_tar(
|
||||
return Err(invalid());
|
||||
}
|
||||
found_version = true;
|
||||
} else if path.ends_with("resources/bin/language_server") {
|
||||
if changelist.is_some() || entry.size() > MAX_BINARY_BYTES {
|
||||
return Err(invalid());
|
||||
}
|
||||
changelist = Some(verify_binary(&mut entry, target, None)?);
|
||||
} else if name == "antigravity" {
|
||||
if found_executable {
|
||||
return Err(invalid());
|
||||
@@ -177,7 +188,7 @@ pub(crate) fn verify_tar(
|
||||
}
|
||||
}
|
||||
if found_version && found_executable {
|
||||
Ok(())
|
||||
changelist.ok_or_else(invalid)
|
||||
} else {
|
||||
Err(invalid())
|
||||
}
|
||||
@@ -186,24 +197,54 @@ pub(crate) fn verify_tar(
|
||||
pub(crate) fn verify_binary(
|
||||
mut reader: impl Read,
|
||||
target: ReleaseTarget,
|
||||
version: &str,
|
||||
) -> Result<(), WorkerTaskError> {
|
||||
version: Option<&str>,
|
||||
) -> Result<u64, WorkerTaskError> {
|
||||
let mut header = [0; 1024];
|
||||
reader
|
||||
.read_exact(&mut header)
|
||||
.map_err(|e| invalid().with_source(e))?;
|
||||
architecture(&header, target)?;
|
||||
// 官方 CLI 把版本文件嵌入 Go 制品,保留其换行与终止字节避免匹配依赖版本
|
||||
let marker = format!("\0{version}\n\0").into_bytes();
|
||||
let marker = version.map(|version| format!("\0{version}\n\0").into_bytes());
|
||||
// Go 制品的源码根目录携带实际 CL;发布目录编号、依赖版本不能代替这个值
|
||||
const PREFIX: &[u8] = b"googlefile:/google_src/files/";
|
||||
const SUFFIX: &[u8] = b"/depot/";
|
||||
let overlap = marker
|
||||
.as_ref()
|
||||
.map_or(0, Vec::len)
|
||||
.max(PREFIX.len() + 20 + SUFFIX.len());
|
||||
let mut tail = header.to_vec();
|
||||
let mut chunk = [0; 64 * 1024];
|
||||
let mut count = 1024u64;
|
||||
let mut found = false;
|
||||
let mut found = marker.is_none();
|
||||
let mut changelist = None;
|
||||
loop {
|
||||
if tail.windows(marker.len()).any(|v| v == marker) {
|
||||
if marker
|
||||
.as_ref()
|
||||
.is_some_and(|marker| tail.windows(marker.len()).any(|v| v == marker))
|
||||
{
|
||||
found = true;
|
||||
}
|
||||
let keep = tail.len().saturating_sub(marker.len());
|
||||
for (offset, candidate) in tail.windows(PREFIX.len()).enumerate() {
|
||||
if candidate != PREFIX {
|
||||
continue;
|
||||
}
|
||||
let rest = &tail[offset + PREFIX.len()..];
|
||||
let digits = rest.iter().take_while(|c| c.is_ascii_digit()).count();
|
||||
if !rest[digits..].starts_with(SUFFIX) {
|
||||
continue;
|
||||
}
|
||||
let value = std::str::from_utf8(&rest[..digits])
|
||||
.ok()
|
||||
.and_then(|s| s.parse::<u64>().ok())
|
||||
.filter(|value| *value > 0)
|
||||
.ok_or_else(invalid)?;
|
||||
if changelist.is_some_and(|previous| previous != value) {
|
||||
return Err(invalid());
|
||||
}
|
||||
changelist = Some(value);
|
||||
}
|
||||
let keep = tail.len().saturating_sub(overlap);
|
||||
tail.drain(..keep);
|
||||
let size = reader
|
||||
.read(&mut chunk)
|
||||
@@ -217,7 +258,11 @@ pub(crate) fn verify_binary(
|
||||
}
|
||||
tail.extend_from_slice(&chunk[..size]);
|
||||
}
|
||||
if found { Ok(()) } else { Err(invalid()) }
|
||||
if found {
|
||||
changelist.ok_or_else(invalid)
|
||||
} else {
|
||||
Err(invalid())
|
||||
}
|
||||
}
|
||||
|
||||
fn pe_offset(body: &[u8]) -> Result<usize, WorkerTaskError> {
|
||||
@@ -231,52 +276,6 @@ fn pe_offset(body: &[u8]) -> Result<usize, WorkerTaskError> {
|
||||
Ok(offset)
|
||||
}
|
||||
|
||||
pub(crate) fn pe_resources(body: &[u8]) -> Result<(u64, u64), WorkerTaskError> {
|
||||
let pe = pe_offset(body)?;
|
||||
let count = u16_at(body, pe + 6)? as usize;
|
||||
let start = pe + 24 + u16_at(body, pe + 20)? as usize;
|
||||
for i in 0..count.min(96) {
|
||||
let section = start + i * 40;
|
||||
if body.get(section..section + 8) == Some(b".rsrc\0\0\0") {
|
||||
return Ok((
|
||||
u64::from(u32_at(body, section + 20)?),
|
||||
u64::from(u32_at(body, section + 16)?),
|
||||
));
|
||||
}
|
||||
}
|
||||
Err(invalid())
|
||||
}
|
||||
|
||||
pub(crate) fn windows_version(body: &[u8], version: &str) -> Result<(), WorkerTaskError> {
|
||||
let parts: Vec<u16> = version
|
||||
.split('.')
|
||||
.map(str::parse)
|
||||
.collect::<Result<_, _>>()
|
||||
.map_err(|_| invalid())?;
|
||||
if parts.len() != 3 {
|
||||
return Err(invalid());
|
||||
}
|
||||
let high = u32::from(parts[0]) << 16 | u32::from(parts[1]);
|
||||
let low = u32::from(parts[2]) << 16;
|
||||
let mut found = false;
|
||||
for (offset, bytes) in body.windows(8).enumerate() {
|
||||
// 官方 Windows 安装器的 dwStrucVersion 为零,也接受标准的 0x00010000
|
||||
if bytes.starts_with(b"\xbd\x04\xef\xfe")
|
||||
&& matches!(u32_at(body, offset + 4)?, 0 | 0x0001_0000)
|
||||
{
|
||||
if u32_at(body, offset + 8)? != high
|
||||
|| u32_at(body, offset + 12)? != low
|
||||
|| u32_at(body, offset + 16)? != high
|
||||
|| u32_at(body, offset + 20)? != low
|
||||
{
|
||||
return Err(invalid());
|
||||
}
|
||||
found = true;
|
||||
}
|
||||
}
|
||||
if found { Ok(()) } else { Err(invalid()) }
|
||||
}
|
||||
|
||||
fn u16_at(body: &[u8], offset: usize) -> Result<u16, WorkerTaskError> {
|
||||
Ok(u16::from_le_bytes(
|
||||
body.get(offset..offset + 2)
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
//! 读取 Windows 安装器内的 7z 应用包,将版本与 language server 的 CL 绑定核验
|
||||
|
||||
use super::archive::{bounded, invalid};
|
||||
use super::artifact::{MAX_ASAR_BYTES, MAX_BINARY_BYTES, asar_version, verify_binary};
|
||||
use super::selection::ReleaseTarget;
|
||||
use gateway_core::task::WorkerTaskError;
|
||||
use std::io::{self, Read, Seek, SeekFrom};
|
||||
|
||||
pub(crate) fn verify(
|
||||
mut file: impl Read + Seek,
|
||||
target: ReleaseTarget,
|
||||
version: &str,
|
||||
) -> Result<u64, WorkerTaskError> {
|
||||
let mut prefix = Vec::new();
|
||||
file.by_ref()
|
||||
.take(2 * 1024 * 1024)
|
||||
.read_to_end(&mut prefix)
|
||||
.map_err(|e| invalid().with_source(e))?;
|
||||
let start = prefix
|
||||
.windows(8)
|
||||
.position(|bytes| bytes == b"7z\xbc\xaf\x27\x1c\0\x04")
|
||||
.ok_or_else(invalid)? as u64;
|
||||
file.seek(SeekFrom::Start(start))
|
||||
.map_err(|e| invalid().with_source(e))?;
|
||||
let source = Payload { file, start };
|
||||
let mut archive = sevenz_rust2::ArchiveReader::new_with_memory_limit(
|
||||
source,
|
||||
sevenz_rust2::Password::empty(),
|
||||
// 官方 NSIS 应用包使用 256 MiB 字典,另预留 1 MiB 解码状态,线程限制为一个
|
||||
257 * 1024,
|
||||
)
|
||||
.map_err(|e| invalid().with_source(e))?;
|
||||
archive.set_thread_count(1);
|
||||
let files = &archive.archive().files;
|
||||
if files.len() > 16_384
|
||||
|| files
|
||||
.iter()
|
||||
.try_fold(0u64, |sum, file| sum.checked_add(file.size))
|
||||
.is_none_or(|size| size > 2 * 1024 * 1024 * 1024)
|
||||
{
|
||||
return Err(invalid());
|
||||
}
|
||||
let mut found_version = false;
|
||||
let mut changelist = None;
|
||||
archive
|
||||
.for_each_entries(|entry, reader| {
|
||||
let result = (|| {
|
||||
if entry.is_directory || entry.is_anti_item {
|
||||
return Ok(());
|
||||
}
|
||||
match entry.name.as_str() {
|
||||
"resources/app.asar" => {
|
||||
if found_version
|
||||
|| entry.size > MAX_ASAR_BYTES as u64
|
||||
|| asar_version(&bounded(reader, MAX_ASAR_BYTES)?)? != version
|
||||
{
|
||||
return Err(invalid());
|
||||
}
|
||||
found_version = true;
|
||||
}
|
||||
"resources/bin/language_server.exe" => {
|
||||
if changelist.is_some() || entry.size > MAX_BINARY_BYTES {
|
||||
return Err(invalid());
|
||||
}
|
||||
changelist = Some(verify_binary(reader, target, None)?);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Ok(())
|
||||
})();
|
||||
result.map_err(|_| {
|
||||
sevenz_rust2::Error::Other("Antigravity Windows 制品内容无效".into())
|
||||
})?;
|
||||
Ok(true)
|
||||
})
|
||||
.map_err(|e| invalid().with_source(e))?;
|
||||
if found_version {
|
||||
changelist.ok_or_else(invalid)
|
||||
} else {
|
||||
Err(invalid())
|
||||
}
|
||||
}
|
||||
|
||||
/// 安装器前缀不属于 7z,解码器的偏移必须以实际签名为零点
|
||||
struct Payload<R> {
|
||||
file: R,
|
||||
start: u64,
|
||||
}
|
||||
impl<R: Read> Read for Payload<R> {
|
||||
fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
|
||||
self.file.read(buffer)
|
||||
}
|
||||
}
|
||||
impl<R: Seek> Seek for Payload<R> {
|
||||
fn seek(&mut self, from: SeekFrom) -> io::Result<u64> {
|
||||
let from = match from {
|
||||
SeekFrom::Start(offset) => SeekFrom::Start(
|
||||
self.start
|
||||
.checked_add(offset)
|
||||
.ok_or(io::ErrorKind::InvalidInput)?,
|
||||
),
|
||||
other => other,
|
||||
};
|
||||
self.file
|
||||
.seek(from)?
|
||||
.checked_sub(self.start)
|
||||
.ok_or_else(|| io::ErrorKind::InvalidInput.into())
|
||||
}
|
||||
}
|
||||
Loaded 100 of 248 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user