Compare commits

..
56 Commits
Author SHA1 Message Date
ZyyandCodex 0ebf6739e2 chore: bump version to 3.62.1-rc.1
Co-authored-by: Codex <noreply@openai.com>
2026-12-05 15:37:36 +08:00
ZyyandCodex b987cca4aa docs(release): base stable version bumps on changes since the last stable release
Co-authored-by: Codex <noreply@openai.com>
2026-12-05 15:36:01 +08:00
ZyyandCodex 72e82c565e fix(openai): clear only recovery feedback observed before success
Confirm the request still uses the current access token before resetting transient feedback across credential revisions. Track the latest 401 independently from Cloudflare streaks so an overlapping failure cannot suppress or be erased by a successful request.

Co-authored-by: Codex <noreply@openai.com>
2026-12-05 15:30:10 +08:00
47ccdeb737 fix(openai): preserve OAuth recovery and token rotation (#853)
* fix(openai): refresh OAuth tokens rejected before expiry

A 401 on a model request marked a refreshable OAuth account Expired when
its access token had not reached its expiry. Expired accounts are left out
of both selection and scheduled refresh, so the account stayed out of
rotation until it was refreshed by hand, even though the refresh token was
still valid.

Expire the rejected access token instead and let the OAuth worker renew
it, as quota refresh already does for token_revoked. A renewed token that
is rejected again before any successful request still marks the account
Expired.

Constraint: Accounts without a refresh token or a known expiry keep the existing Expired outcome
Rejected: Match the "status=503" text inside the 401 body | free-text matching, and other 401s on unexpired tokens would still strand the account
Rejected: Refresh on every 401 without a bound | an account whose renewed tokens keep failing would refresh in a loop
Confidence: high
Scope-risk: narrow
Tested: Rust 1.99.1 fmt --check; clippy -p provider-openai --all-targets --all-features -D warnings; provider-openai tests (1264 passed); the new selector case and the adapter case fail without the selector change
Not-tested: A live upstream 401 against this build; workspace-wide clippy and tests are left to CI

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* fix(openai): preserve OAuth recovery across concurrent feedback

Report success from native endpoints and upstream adapters, and keep stale
responses from clearing the current OAuth recovery bound. Serialize model
401 and Cookie feedback with token refresh through the account lease.
Recheck credential revisions after acquiring scheduled and manual refresh
leases so a queued snapshot cannot resend an already rotated refresh token.

Cookie feedback skips writes while refresh owns the lease; a later response
can capture cookies without discarding successfully exchanged tokens.

Validated: workspace fmt and strict Clippy; 1265 provider-openai tests;
48 gateway architecture and bootstrap tests. Real upstream and store service
integration remain for live verification and CI.

Co-authored-by: Codex <noreply@openai.com>

* fix(openai): retain token recovery across cookie revisions

Use the access token and revision that were sent upstream to recognize a successful OAuth request after a concurrent cookie write. Keep account and quota recovery fenced by revision, and preserve newer rejection records and replies from superseded tokens.

Co-authored-by: Codex <noreply@openai.com>

* fix(openai): preserve account feedback across cookie writes

Reset consecutive Cloudflare failures on a successful request using the current access token. Keep quota and account state fenced by the response revision. A model 401 can shorten expiry while the cookie writer holds the refresh lease; a conflicting write is retried only for the same token.

Co-authored-by: Codex <noreply@openai.com>

* test(openai): separate risk counters from OAuth rejection

Verify that a successful request using the rejected token breaks a path-block streak without allowing a refreshed token to be rejected indefinitely.

Co-authored-by: Codex <noreply@openai.com>

---------

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
Co-authored-by: Zyy <zyycn@users.noreply.github.com>
Co-authored-by: Codex <noreply@openai.com>
2026-12-05 14:00:11 +08:00
ZyyandCodex b20b0e2013 fix(release): freeze complete notes and expose backend validation
Co-authored-by: Codex <noreply@openai.com>
2026-12-05 02:09:06 +08:00
github-actions[bot] 16fc302d46 chore(release): update release channels to 3.62.0 2026-12-04 17:37:26 +00:00
ZyyandCodex 95c35d0a67 chore: bump version to 3.62.0
Co-authored-by: Codex <noreply@openai.com>
2026-12-05 01:07:04 +08:00
ZyyandCodex 259a2e1ba0 fix(backend): enforce body limits and simplify contracts
Reject subsequent reads after outbound bodies exceed capacity, reuse Client Key cursor wire types, and simplify protocol fixtures.

Clarify current API contracts, module ownership, and local test setup.

Co-authored-by: Codex <noreply@openai.com>
2026-12-05 00:45:03 +08:00
ZyyandCodex 2f51412625 fix(openai): align continuation history with Codex wire items
Project known response items and nested content for history matching without changing forwarded payloads. Preserve client tool-result metadata and compare unknown variants verbatim.

Add version-pinned replay fixtures and multi-turn outbound regression coverage.

Co-authored-by: Codex <noreply@openai.com>
2026-12-05 00:21:17 +08:00
PINGBOZHOUandClaude Opus 5.5 32f3b11ddf fix(openai): price gpt-image-2.6 models (#850)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 00:19:59 +08:00
github-actions[bot] c2891e14ce chore(release): update release channels to 3.61.1-rc.6 2026-12-04 13:53:03 +00:00
ZyyandCodex b28eee6e18 chore: bump version to 3.61.1-rc.6
Co-authored-by: Codex <noreply@openai.com>
2026-12-04 21:29:59 +08:00
6bf182677a fix(antigravity): repair IDs for same-name parallel tools (#849)
Pair ID-less calls and results by tool name and GenAI ordering when
counts match. Preserve ambiguous groups and existing raw JSON fields.

Co-authored-by: Zyy <zyycn@users.noreply.github.com>
Co-authored-by: Codex <noreply@openai.com>
2026-12-04 21:21:02 +08:00
ZyyandCodex 8d4b0496e2 fix(openai): map unsupported none reasoning effort to low when available
Co-authored-by: Codex <noreply@openai.com>
2026-12-04 20:40:14 +08:00
github-actions[bot] 9b08c3a50d chore(release): update release channels to 3.61.1-rc.5 2026-12-04 10:14:06 +00:00
ZyyandCodex f43e1f95c3 chore: bump version to 3.61.1-rc.5
Co-authored-by: Codex <noreply@openai.com>
2026-12-04 17:57:14 +08:00
21cf139c96 fix(openai): keep slow model catalog refreshes alive (#846)
Use a 30-second idle timeout for account retries and manual refreshes while keeping ordinary discovery bounded. Let the admin UI wait for these refreshes until completion or cancellation.

Co-authored-by: Zyy <zyycn@users.noreply.github.com>
Co-authored-by: Codex <noreply@openai.com>
2026-12-04 17:49:30 +08:00
ZyyandCodex 7d6e4cc4e7 fix(openai): limit model retry hints to scoped rate limits
Keep ordinary account cooldowns on their existing selection path, including peer accounts after quota synchronization.

Co-authored-by: Codex <noreply@openai.com>
2026-12-04 17:40:15 +08:00
ZyyandCodex 2ddcd7c936 feat(openai): track turn rate limits per account and model
Preserve session scheduling and retry hints while a model cools down. Show active model limits and their recovery times in the account list.

Co-authored-by: Codex <noreply@openai.com>
2026-12-04 17:17:10 +08:00
ZyyandCodex c71e6176c5 fix(web): add a subtle surface to client import options
Give the tool row a persistent muted background and light shadow, and
increase the inset around the GitHub link.

Co-authored-by: Codex <noreply@openai.com>
2026-12-04 14:54:47 +08:00
ZyyandCodex 28d3e3c2cb fix(web): centralize page sizing and preserve PWA bottom spacing
Keep long pages naturally sized and share the available page height across
viewport-bound panels. Let list cards fill the remaining space while
preserving internal scrolling and pagination in short windows.

Co-authored-by: Codex <noreply@openai.com>
2026-12-04 14:54:46 +08:00
dd793a84ab fix(protocol): preserve tool semantics across Chat and Codex (#844)
Support named independent tool outputs and flatten custom grammar formats.
Adapt Codex search aliases, long call IDs and tool names while preserving
history pairing and restoring client-visible names in JSON and SSE.

Refs #843

Co-authored-by: Zyy <zyycn@users.noreply.github.com>
Co-authored-by: Codex <noreply@openai.com>
2026-12-04 14:13:31 +08:00
ZyyandCodex 5ed8b626d7 docs(skills): ground safeguards in expected behavior
Co-authored-by: Codex <noreply@openai.com>
2026-12-04 13:33:50 +08:00
ZyyandCodex 96d8b25d0b fix(store): skip nested requests in key recovery and accept large limits
Co-authored-by: Codex <noreply@openai.com>
2026-12-04 13:25:44 +08:00
Zyy a193de4eba fix(providers): align SSE history reuse with Codex and use disk for Antigravity artifacts 2026-12-04 13:07:26 +08:00
github-actions[bot] e296bef65e chore(release): update release channels to 3.61.1-rc.4 2026-12-04 04:09:54 +00:00
ZyyandCodex 89092272a1 docs(readme): add the Telegram community invite
Co-authored-by: Codex <noreply@openai.com>
2026-12-04 11:49:02 +08:00
ZyyandCodex 09f3b39bbc chore: bump version to 3.61.1-rc.4
Co-authored-by: Codex <noreply@openai.com>
2026-12-04 11:37:01 +08:00
7591845f74 fix(openai): honor chat session affinity during account selection (#842)
Co-authored-by: Zyy <zyycn@users.noreply.github.com>
Co-authored-by: Codex <noreply@openai.com>
2026-12-04 11:27:41 +08:00
ZyyandCodex 67ac8fd067 fix(deps): update DOMPurify to 3.5.1
Co-authored-by: Codex <noreply@openai.com>
2026-12-04 11:14:27 +08:00
b232e367fc fix(openai): defer failed account catalog refresh with per-scope backoff (#839)
* fix(openai): defer failed account catalog refresh with per-scope backoff

* style: cargo fmt refresh.rs

* fix(openai): keep stale-catalog accounts probeable during refresh backoff

* fix(openai): schedule account catalog retries independently

Co-authored-by: Codex <noreply@openai.com>

---------

Co-authored-by: Zyy <zyycn@users.noreply.github.com>
Co-authored-by: Codex <noreply@openai.com>
2026-12-04 11:02:02 +08:00
ZyyandCodex 0bdaa29907 fix(ui): clarify update actions and align dashboard empty state
Co-authored-by: Codex <noreply@openai.com>
2026-12-03 21:13:07 +08:00
github-actions[bot] cc798e33a1 chore(release): update release channels to 3.61.1-rc.3 2026-12-03 18:48:31 +08:00
ZyyandCodex 6eabda047c chore: bump version to 3.61.1-rc.3
Co-authored-by: Codex <noreply@openai.com>
2026-12-03 18:48:31 +08:00
ZyyandCodex 3c560b9276 fix(ui): unify account subscription badges
Use compact badges in the dashboard and switch account rows to a stacked layout when the card is narrow.

Co-authored-by: Codex <noreply@openai.com>
2026-12-03 17:59:10 +08:00
ZyyandCodex 77c42cea98 fix(antigravity): publish verified client profiles
Derive changelists from official client artifacts and publish them with the
matching version only after verification. Restore profiles from the shared
cache at startup and check release metadata hourly.

Filter gateway fingerprint status from OAuth requests and recognize structured
workspace policy denials without changing unrelated request data.

Co-authored-by: Codex <noreply@openai.com>
2026-12-03 17:44:09 +08:00
ZyyandCodex dd234c3619 fix(antigravity): preserve structured Google denials
Preserve RPC status, ErrorInfo reasons and retry hints across generation,
token counting and resource queries. Isolate confirmed account denials,
keep verification links in diagnostics, and preserve access state during
token refresh.

Cover in-band and streaming failures, background query suppression and
stale credential feedback with regression tests.

Refs #836

Co-authored-by: Codex <noreply@openai.com>
2026-12-03 16:07:12 +08:00
ZyyandCodex b5e691c63d fix(dashboard): animate incremental data updates
Preserve chart state across updates and animate capacity, status distribution, and account reordering. Keep metric transition values synchronized when reduced motion is enabled.

Co-authored-by: Codex <noreply@openai.com>
2026-12-03 14:50:05 +08:00
Zyy 2d0a52096a fix(workers): prioritize shutdown during background tasks 2026-12-03 13:56:18 +08:00
github-actions[bot] 47620e217a chore(release): update release channels to 3.61.1-rc.2 2026-12-03 05:16:01 +00:00
ZyyandCodex 48aeccd0e0 chore: bump version to 3.61.1-rc.2
Co-authored-by: Codex <noreply@openai.com>
2026-12-03 12:54:43 +08:00
bdc618701b feat(system): add confirmed manual service restart (#832)
* feat(system): add confirmed manual service restart

Co-authored-by: Codex <noreply@openai.com>

* fix(system): preserve restart for legacy update responses

Co-authored-by: Codex <noreply@openai.com>

* fix(system): require explicit restart support

Co-authored-by: Codex <noreply@openai.com>

* docs(deploy): drop legacy restart notes

Co-authored-by: Codex <noreply@openai.com>

---------

Co-authored-by: Zyy <zyycn@users.noreply.github.com>
Co-authored-by: Codex <noreply@openai.com>
2026-12-03 12:48:52 +08:00
ZyyandCodex acd76a09dc fix(ui): keep loading feedback with the active action
Co-authored-by: Codex <noreply@openai.com>
2026-12-03 12:35:57 +08:00
ZyyandCodex 808387442b docs: strengthen frontend interaction verification
Co-authored-by: Codex <noreply@openai.com>
2026-12-03 12:35:57 +08:00
5bc4e3e5c8 fix(routing): scope Fast policy to the selected account (#829)
* fix(gateway): resolve fast policy from the account's hit group

Bound-group fast policies were merged once per API key at snapshot
compile time, so a disabled or forced group on the same key leaked its
policy onto accounts that only belong to other enabled groups. Keep the
per-group policies frozen on the account scope, skip disabled groups
when merging, and resolve the effective fast mode from the account the
request actually hit, falling back to the key-level merged value only
when the account matches no enabled bound group.

* ci: retrigger checks

* style(gateway): rustfmt the account-scoped fast mode helper

* fix(routing): scope Fast policy to selected eligible groups

Co-authored-by: Codex <noreply@openai.com>

* fix(routing): preserve explicit default Fast overrides

Co-authored-by: Codex <noreply@openai.com>

---------

Co-authored-by: Zyy <zyycn@users.noreply.github.com>
Co-authored-by: Codex <noreply@openai.com>
2026-12-03 11:39:33 +08:00
7e98130cac fix(openai): re-anchor bucket warmup after early quota reset (#830)
* fix(openai): re-anchor bucket warmup after upstream early quota reset

* fix(openai): record initial usage for early reset warmup

Co-authored-by: Codex <noreply@openai.com>

* fix(openai): preserve precise bucket reset boundaries

Co-authored-by: Codex <noreply@openai.com>

---------

Co-authored-by: Zyy <zyycn@users.noreply.github.com>
Co-authored-by: Codex <noreply@openai.com>
2026-12-03 11:36:44 +08:00
2821a5e3bd fix(protocol): handle empty Chat history and nullable fields (#831)
* fix(protocol): accept null-content system/developer chat messages

Codex 客户端偶尔会发送 content 为 null 的 system 消息,公共校验按空内容拒绝并报
Parameter messages[N].content has an invalid value。允许 system/developer 消息
内容为空,genai 与 messages 转换跳过空内容,responses 目标已自然忽略。

fixes #824

* fix(protocol): normalize empty Chat history and nullable fields

Co-authored-by: Codex <noreply@openai.com>

---------

Co-authored-by: Zyy <zyycn@users.noreply.github.com>
Co-authored-by: Codex <noreply@openai.com>
2026-12-03 11:36:44 +08:00
ZyyandCodex 6a6a167d41 perf(openai): trim SSE history after privacy processing
Match privacy-processed SSE requests against the existing WebSocket history prefix. Keep full input on a mismatch and resume trimming after a matching completed turn.

Record body receipt, authentication, decompression, decoding and execution preparation timings to distinguish ingress delays from upstream latency.

Cover metadata, body and header privacy across reuse, mismatch and resumed reuse.

Co-authored-by: Codex <noreply@openai.com>
2026-12-03 11:36:44 +08:00
ZyyandCodex cffb6b35d2 fix(protocol): handle empty Chat history and nullable request fields
Treat explicit null text as empty in Chat content blocks and preserve user input, tool results, and cache breakpoints during conversion. Resolve nullable format and reasoning controls consistently with routing, and forward stop sequences to Messages and GenAI.

Co-authored-by: Codex <noreply@openai.com>
2026-12-03 10:28:00 +08:00
ZyyandCodex 17e50df06f fix(accounts): hide zero token usage in the account list
Co-authored-by: Codex <noreply@openai.com>
2026-12-03 10:28:00 +08:00
ZyyandCodex f2d95cc3fa fix(errors): clarify account selection and upstream failures
Report WebSocket transport constraints separately from exhausted account quota, including mixed account pools. Clarify routing, concurrency, authentication, permission, transport and protocol failure messages while preserving upstream error details.

Update HTTP and WebSocket regression coverage and document the client error contract. Validate 2,620 tests, workspace Clippy, formatting and architecture checks.

Co-authored-by: Codex <noreply@openai.com>
2026-12-03 10:28:00 +08:00
ZyyandCodex e4f6e1d4e3 fix(protocol): align response request IDs with Codex
Share the four Codex request ID headers across HTTP, WebSocket, diagnostics, and continuation failures. Preserve current-failure IDs and the model execution ID fallback, and remove unsupported aliases.

Update regression coverage and the public API contract.

Co-authored-by: Codex <noreply@openai.com>
2026-12-03 10:28:00 +08:00
github-actions[bot] 66f650f097 chore(release): update release channels to 3.61.1-rc.1 2026-12-02 13:47:28 +00:00
ZyyandCodex ca4d02068a chore: bump version to 3.61.1-rc.1
Co-authored-by: Codex <noreply@openai.com>
2026-12-02 21:33:34 +08:00
Zyy d185a639a9 perf(openai): send incremental SSE history over pooled WebSockets 2026-12-02 21:09:28 +08:00
github-actions[bot] 3078dd9993 chore(release): update release channels to 3.61.0 2026-12-01 13:39:52 +00:00
283 changed files with 11301 additions and 2537 deletions

No files matched your search

+3 -1
View File
@@ -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 条件按该节执行
交付简述所复用的页面或组件、实际验证范围及缺口;环境不足时如实说明,不能仅凭构建、源码或截图推断未验证的行为
@@ -20,7 +20,7 @@
调用入口前重新核对当前脚本的副作用、目标版本和待推送提交,保留无关工作区内容,不自动清理或暂存用户文件。
先编辑 `release/notes.md`,保留为未提交改动(已暂存或未暂存均可);其他已跟踪文件的改动应先单独提交。
脚本只改 `release/version.yaml` 的顶层 `version`,按[接口弃用规则](../../../../backend/crates/gateway-plugin/sdk/docs/manifest.md#接口弃用)校验并维护 `plugin-api-deprecations.json`,将这些差异与最终工作区中的发布说明一起提交为 `chore: bump version to <version>`。
脚本更新 `release/version.yaml` 的顶层 `version`,按[接口弃用规则](../../../../backend/crates/gateway-plugin/sdk/docs/manifest.md#接口弃用)校验并维护 `plugin-api-deprecations.json`,生成发布说明的自动区块,将这些差异与手写正文一起提交为 `chore: bump version to <version>`。
不要提前单独提交说明或把版本文件改成目标版本;脚本要求说明相对 HEAD 有改动,并自行更新版本号。
本任务需要的提交按[项目约定](../../../../CONTRIBUTING.md#项目约定)保留英文 Conventional Commits 与相应署名。
@@ -31,7 +31,7 @@ release/publish "$release_version"
```
该命令会创建上述版本提交与 annotated tag,原子推送分支和 tag,再从长期分支手动触发 `release.yml`。
只读预检使用 `release/publish --check "$release_version"`。发布工作流读取 tag 中的说明,修改 tag 之后的本地文件不会改变该次构建。
只读预检使用 `release/publish --check "$release_version"`。发布工作流读取 tag 中已经生成的完整说明,不再查询 PR 或附加另一份自动日志;修改 tag 之后的本地文件不会改变该次构建。
只调整已发布页面的标题或正文时,编辑对应 GitHub Release 的 `name` 或 `body` 并回读核对;
保持已有 tag、源码提交、附件和预发行状态,不重新执行发布入口。
@@ -60,7 +60,8 @@ release/publish "$release_version"
### 验收
- 发布完成后核对 GitHub Release 的版本、正式版/预发行状态和中文变更正文;对照平台清单与工作流确认归档、校验和及镜像产物。
工作流附加的安装说明和自动提交列表按其当前配置处理,不用它们替代手写的中文变更说明。
正文应与 tag 内的说明一致,正式版的 `Full Changelog` 从上一正式版开始,PR 和直接提交覆盖本次范围;自动列表不替代手写的中文变更说明
- 核对 `backend-validation` 的结果。复用时检查摘要中的源码提交和成功 CI 链接,确认发行提交仅修改版本与说明;未满足复用条件时检查本次完整后端任务,不能把 `quality / backend` 的跳过单独记为测试通过
- 回读 `main:release/version.yaml` 的 `published`。正式版参与同一大版本四个普通通道的比较;RC 参与 RC、Beta、Alpha,Beta 参与 Beta、Alpha,Alpha 只参与自身。实验版只推进 `exp["X.Y.Z"]`。有通道推进时应有 `chore(release): update release channels to <version>` 提交;重复执行或较旧版本未推进任何通道时无提交
- 正式版提升或恢复后,回读 GitHub Latest 的 tag 与镜像 `latest` 的摘要,核对两者均指向预期正式版
- 保留 v3.42.0 在线升级使用的 `update-index` 页面和 v3.42.1 的 `version.yaml` 附件
@@ -9,12 +9,21 @@
3. 使用用户确定的目标版本,建议版本时说明兼容性、能力或修复依据;同名 tag 先区分重试与新发行,不递增版本掩盖冲突
4. 命名与晋级按[版本命名与升级规则](../../../../deploy/README.md#版本命名与升级规则),实验版另读[实验流程](experimental.md#分支与版本)
对比基线选自已公开且 tag 位于目标提交历史内的 GitHub Release
- 推荐正式版号和编写发布说明时,都核对上一正式版到目标提交的最终差异,覆盖期间全部预发行。对于向后兼容的变更,只要有用户可用的新功能,就从上一正式版递增 minor 并将 patch 归零,仅含修复则递增 patch
- alpha、beta、rc 优先对比同一 `X.Y.Z` 的上一常规预发行,没有时对比上一正式版
- exp 对比同一 `X.Y.Z` 的上一实验版,首次实验对比同号正式版
- 没有前序发行的首次发布从仓库起点核对
## 发布说明
读取当前 [notes.md](../../../../release/notes.md)与[项目约定](../../../../CONTRIBUTING.md#项目约定)中的发布说明条目
- 只在发布说明任务中修改 `release/notes.md`,替换为本次版本内容,首行为目标 tag,正文使用中文
- 常规版本按「新增功能」「优化改进」「问题修复」「升级须知」归类,省略空章节;单一改动可直接写一句。安装命令和文档入口由工作流附加
- 常规版本的手写正文按「新增功能」「优化改进」「问题修复」「升级须知」归类,省略空章节;单一改动可直接写一句
- `release/publish` 生成安装入口、文档链接和变更列表,保存到说明末尾的 `cpr-release:generated` 标记区块;重新准备说明时整块保留或移除,不在区块中手写内容
- 自动列表按实际提交中的 PR 编号补齐 GitHub 遗漏的合并记录,并列出直接提交;仍需对照完整 diff 核实中文正文,剔除回退或重复的用户影响
- 每条用一句短语讲清一个用户可感知的结果,不加句号,例如「系统更新:确认当前平台有安装包后才提示升级」
- 同一变化只写一次,保留会影响使用或升级的默认值和限制,不展开实现过程、逐条翻译提交或写未经验证的承诺
- 剔除回退、重复及未进入发行范围的内容,升级事项须能追溯到实际迁移、配置或兼容变化
@@ -31,7 +40,8 @@
在上一发行基线到 HEAD 的提交中检查是否已有目标版本的备版提交(`chore: bump version to <version>`;查历史时也匹配 `chore(release): prepare v<version>` 和 `chore(release): v<version>`),即使同名 tag 已不存在也要查。命中时先核对该提交对应的发行状态,按[失败恢复](operations.md#恢复与验收)处理,不在旧提交上再叠一个同名提交
发布说明准备好、其他代码已提交后,执行 `release/publish --check <version>`,检查版本、说明、工作区、远端分支与 tag、工具链和插件兼容窗口。
预检不修改文件、Git 引用或远端状态;远端存在本地未知提交时先同步再检查。它不替代 CI、发行物验证或实际发布授权
预检输出基线、目标提交和完整正文,核对 `Full Changelog` 范围、PR 列表及直接提交;正式执行也使用相同生成入口,将最终正文随版本提交保存
预检不修改文件、Git 引用或远端状态;远端存在本地未知提交或缺少已发布的基线 tag 时,先同步再检查。它不替代 CI、发行物验证或实际发布授权
按[验证要求](../../../../CONTRIBUTING.md#验证)核对目标提交的证据,区分通过、失败、跳过与未执行
数据库变更同时读取[迁移冻结规则](../../../../backend/migrations/README.md#冻结规则):
-6
View File
@@ -97,11 +97,6 @@ module ReleaseMetadata
validate_notes(value)
entries = platforms
docker, native = entries.partition { |entry| entry['docker'] == true }
previous = git('tag', '--list', 'v*', '--merged', 'HEAD').lines.map(&:strip).filter_map do |candidate|
next unless candidate.delete_prefix('v').match?(SEMVER)
key = sort_key(candidate)
[key, candidate] if key < sort_key(value)
end.max_by(&:first)&.last
{
'tag' => tag,
'version' => value,
@@ -112,7 +107,6 @@ module ReleaseMetadata
'non_docker_matrix' => JSON.generate('include' => native),
'windows_matrix' => JSON.generate('include' => entries.select { |entry| entry['os'] == 'windows' }),
'docker_platforms' => docker.map { |entry| entry['dockerPlatform'] }.join(','),
'previous_tag' => previous,
'prerelease' => prerelease?(value),
'build_type' => value.split('+', 2).first.include?('-exp.') ? 'experimental' : 'release'
}
+179
View File
@@ -0,0 +1,179 @@
require_relative 'release-metadata'
# 预检与发布共用日志范围;生成结果随版本提交保存,构建时不再查询可变的 PR 信息
module ReleaseNotes
START = '<!-- cpr-release:generated -->'
FINISH = '<!-- /cpr-release:generated -->'
def self.manual_body(document)
body = document.lines.drop(1).join.strip
return body unless body.include?(START) || body.include?(FINISH)
unless body.scan(START).length == 1 && body.scan(FINISH).length == 1 && body.end_with?(FINISH) &&
body.index(START) < body.index(FINISH)
raise 'Invalid generated release notes block; keep the complete block at the end or remove it'
end
body.split(START, 2).first.rstrip
end
def self.body(value)
ReleaseMetadata.validate_notes(value)
document = File.read('release/notes.md')
manual_body(document)
unless value.include?('-exp.') || document.include?(START)
raise 'Release notes are not prepared; use release/publish to generate and commit the final body'
end
document.lines.drop(1).join.strip + "\n"
end
# 只选已公开且属于目标历史的发行;首次实验版可以以同号正式版为基线
def self.previous_tag(value, releases, reachable)
core, stage = value.split('-', 2)
candidates = releases.select do |release|
tag = release.fetch('tag_name')
raw = tag.delete_prefix('v')
tag == "v#{raw}" && raw.match?(ReleaseMetadata::SEMVER) && !raw.include?('+') &&
!release.fetch('draft') && release.fetch('prerelease') == ReleaseMetadata.prerelease?(raw) &&
reachable.include?(tag)
end.map { |release| release.fetch('tag_name') }
lower = candidates.select { |tag| ReleaseMetadata.sort_key(tag) < ReleaseMetadata.sort_key(value) }
if stage
same_line = lower.select do |tag|
previous_core, previous_stage = tag.delete_prefix('v').split('-', 2)
previous_core == core && previous_stage &&
previous_stage.start_with?('exp.') == stage.start_with?('exp.')
end
return same_line.max_by { |tag| ReleaseMetadata.sort_key(tag) } unless same_line.empty?
return candidates.find { |tag| tag == "v#{core}" } if stage.start_with?('exp.')
end
lower.reject { |tag| ReleaseMetadata.prerelease?(tag) }.max_by { |tag| ReleaseMetadata.sort_key(tag) }
end
class Generator
def initialize(repository)
raise 'Invalid GitHub repository' unless repository.match?(%r{\A[\w.-]+/[\w.-]+\z})
@repository = repository
@endpoint = "repos/#{repository}"
@url = "https://github.com/#{repository}"
end
def api(path, data: nil, paginate: false)
args = ['gh', 'api', "#{@endpoint}/#{path}"]
args.concat(['--method', 'POST', '--input', '-']) if data
args.concat(['--paginate', '--jq', '.[] | @json']) if paginate
output, error, status = Open3.capture3(*args, stdin_data: data ? JSON.generate(data) : '')
raise "Cannot read release information: #{error.strip}" unless status.success?
paginate ? output.lines.map { |line| JSON.parse(line) } : JSON.parse(output)
end
def commits(base, head)
range = base ? "#{base}..#{head}" : head
ReleaseMetadata.git('log', '--first-parent', '--reverse', '--format=%H %s', range, '--').lines.map do |line|
sha, subject = line.strip.split(' ', 2)
[sha, subject]
end.reject do |sha, _|
paths = ReleaseMetadata.git('diff-tree', '--root', '--no-commit-id', '--name-only', '-r', sha).lines.map(&:strip)
!paths.empty? && (paths - %w[release/version.yaml release/notes.md]).empty?
end
end
def markdown(text)
text.gsub(/[\\`*_\[\]<>]/) { |character| "\\#{character}" }
end
def changelog(base, head, value, github_head)
# 没有前序发行时从仓库起点列举,不让 GitHub 自动猜测另一条发行线
# 未推送的提交由本地历史补齐,避免要求预检先写远端
github_range = base && ReleaseMetadata.git('merge-base', base, github_head) == ReleaseMetadata.git('rev-parse', "#{base}^{commit}")
generated = if github_range
api('releases/generate-notes', data: {
tag_name: "v#{value}", target_commitish: github_head, previous_tag_name: base
}).fetch('body').gsub("\r\n", "\n").strip
else
''
end
listed = generated.scan(%r{#{Regexp.escape(@url)}/pull/(\d+)\b}).flatten.map(&:to_i).uniq
missing = []
direct = []
commits(base, head).each do |sha, subject|
# 只识别合并提交格式,不把正文中的 Issue 引用猜成 PR
number = subject[/\(#(\d+)\)\z/, 1] || subject[/\AMerge pull request #(\d+)\b/, 1]
unless number
direct << "* #{markdown(subject)} ([#{sha[0, 9]}](#{@url}/commit/#{sha}))"
next
end
number = number.to_i
next if listed.include?(number)
pull = api("pulls/#{number}")
raise "Referenced PR ##{number} is not merged" unless pull.fetch('merged')
missing << "* #{markdown(pull.fetch('title'))} by @#{pull.fetch('user').fetch('login')} in #{@url}/pull/#{number}"
listed << number
end
unless missing.empty?
heading = "## What's Changed"
generated = if generated.include?(heading)
generated.sub(heading, "#{heading}\n#{missing.join("\n")}")
else
["#{heading}\n#{missing.join("\n")}", generated].reject(&:empty?).join("\n\n")
end
end
# 直接提交也有明确链接,不能把 PR 列表当成完整变更范围
generated += "\n\n## 其他提交\n#{direct.join("\n")}" unless direct.empty?
link = base ? "#{@url}/compare/#{base}...v#{value}" : "#{@url}/commits/#{head}"
generated += "\n\n**Full Changelog**: #{link}" unless generated.include?(link)
warn "日志范围:#{base || '仓库起点'} → #{head};#{listed.length} 个 PR,#{direct.length} 个直接提交"
warn "已补齐自动列表遗漏:#{missing.join("\n")}" unless missing.empty?
generated.strip
end
def prepare(value, head: 'HEAD', github_head: head)
value = ReleaseMetadata.release_version(value)
ReleaseMetadata.validate_notes(value)
head = ReleaseMetadata.git('rev-parse', '--verify', "#{head}^{commit}")
github_head = ReleaseMetadata.git('rev-parse', '--verify', "#{github_head}^{commit}")
unless ReleaseMetadata.git('merge-base', head, github_head) == github_head
raise 'GitHub source commit must be an ancestor of the release source'
end
reachable = ReleaseMetadata.git('tag', '--list', 'v*', '--merged', head).lines.map(&:strip)
releases = api('releases?per_page=100', paginate: true)
unknown = releases.map { |release| release.fetch('tag_name') } - ReleaseMetadata.git('tag', '--list', 'v*').lines.map(&:strip)
base = ReleaseNotes.previous_tag(value, releases, reachable + unknown)
raise "Published baseline tag #{base} is missing locally; fetch remote tags before preparing notes" if unknown.include?(base)
manual = ReleaseNotes.manual_body(File.read('release/notes.md'))
raise 'Release notes must contain a handwritten description' if manual.empty?
warn "发布基线:#{base || '仓库起点'};目标:v#{value};源码:#{head}"
return "# v#{value}\n\n#{manual}\n" if value.include?('-exp.')
installation = <<~MARKDOWN.strip
## Linux 一键安装(Docker Compose)
```bash
curl -fsSLO #{@url.sub('github.com', 'raw.githubusercontent.com')}/v#{value}/deploy/install.sh && CPR_RELEASE_TAG=v#{value} bash install.sh
```
## 📚 文档
- [GitHub 仓库](#{@url})
- [部署指南](#{@url}/blob/v#{value}/deploy/README.md)
MARKDOWN
"# v#{value}\n\n#{manual}\n\n#{START}\n#{installation}\n\n#{changelog(base, head, value, github_head)}\n#{FINISH}\n"
end
end
end
if $PROGRAM_NAME == __FILE__
begin
command, value, repository, github_head = ARGV
case command
when 'prepare'
raise 'prepare requires VERSION REPOSITORY GITHUB_HEAD' unless ARGV.length == 4
puts ReleaseNotes::Generator.new(repository).prepare(value, github_head: github_head)
when 'body'
raise 'body requires VERSION' unless ARGV.length == 2
puts ReleaseNotes.body(value)
else
raise 'usage: release-notes.rb prepare VERSION REPOSITORY GITHUB_HEAD | body VERSION'
end
rescue StandardError => error
warn "error: #{error.message}"
exit 1
end
end
+4 -2
View File
@@ -25,7 +25,7 @@ module ReleaseQuality
rows = capture('gh', 'api', '--paginate', "repos/#{repository}/actions/runs/#{run.fetch('id')}/jobs?per_page=100", '--jq', '.jobs[] | @json')
job = rows.lines.map { |line| JSON.parse(line) }.find { |entry| entry.fetch('name') == 'quality / backend' }
return nil unless job && job.fetch('conclusion') == 'success'
job.fetch('html_url')
{ 'sha' => parent, 'url' => job.fetch('html_url') }
end
end
@@ -37,8 +37,10 @@ if $PROGRAM_NAME == __FILE__
evidence = nil
end
puts "run_backend=#{evidence.nil?}"
puts "backend_source_sha=#{evidence ? evidence.fetch('sha') : ReleaseQuality.capture('git', 'rev-parse', 'HEAD').strip}"
puts "backend_evidence_url=#{evidence ? evidence.fetch('url') : ''}"
if ENV['GITHUB_STEP_SUMMARY']
message = evidence ? "后端质量检查复用版本提交父提交的 [CI 结果](#{evidence});仅版本与发布说明不同" : '未找到可复用的后端 CI 结果,完整检查发行提交'
message = evidence ? "后端质量检查复用 `#{evidence.fetch('sha')}` 的[成功 CI](#{evidence.fetch('url')});仅版本与发布说明不同" : '未找到可复用的后端 CI 结果,完整检查发行提交'
File.open(ENV.fetch('GITHUB_STEP_SUMMARY'), 'a') { |file| file.puts(message) }
end
end
+36 -23
View File
@@ -45,12 +45,13 @@ jobs:
non_docker_matrix: ${{ steps.version.outputs.non_docker_matrix }}
windows_matrix: ${{ steps.version.outputs.windows_matrix }}
docker_platforms: ${{ steps.version.outputs.docker_platforms }}
previous_tag: ${{ steps.version.outputs.previous_tag }}
prerelease: ${{ steps.version.outputs.prerelease }}
build_type: ${{ steps.version.outputs.build_type }}
rust: ${{ steps.toolchains.outputs.rust }}
rust_image: ${{ steps.toolchains.outputs.rust_image }}
run_backend: ${{ steps.quality.outputs.run_backend }}
backend_source_sha: ${{ steps.quality.outputs.backend_source_sha }}
backend_evidence_url: ${{ steps.quality.outputs.backend_evidence_url }}
steps:
- name: Checkout
@@ -75,6 +76,11 @@ jobs:
id: toolchains
run: ruby .github/scripts/toolchains.rb >> "$GITHUB_OUTPUT"
- name: Verify committed release notes
env:
VERSION: ${{ steps.version.outputs.version }}
run: ruby .github/scripts/release-notes.rb body "$VERSION" >> "$GITHUB_STEP_SUMMARY"
- name: Check reusable backend CI evidence
id: quality
env:
@@ -97,6 +103,31 @@ jobs:
run_backend: ${{ needs.release-info.outputs.run_backend == 'true' }}
run_frontend: false
backend-validation:
name: backend-validation (${{ needs.release-info.outputs.run_backend == 'true' && 'current release' || 'reused CI' }})
needs: [release-info, quality]
if: ${{ !cancelled() && needs.release-info.result == 'success' }}
runs-on: ubuntu-26.04
timeout-minutes: 5
steps:
- name: Report backend validation evidence
env:
QUALITY_RESULT: ${{ needs.quality.result }}
RUN_BACKEND: ${{ needs.release-info.outputs.run_backend }}
SOURCE_SHA: ${{ needs.release-info.outputs.backend_source_sha }}
EVIDENCE_URL: ${{ needs.release-info.outputs.backend_evidence_url }}
run: |
if [ "$QUALITY_RESULT" != success ]; then
echo "后端质量检查未通过:$QUALITY_RESULT" | tee -a "$GITHUB_STEP_SUMMARY"
exit 1
fi
if [ "$RUN_BACKEND" = true ]; then
echo "后端质量检查已执行并通过,提交:\`$SOURCE_SHA\`" | tee -a "$GITHUB_STEP_SUMMARY"
else
test -n "$EVIDENCE_URL"
echo "后端质量检查复用 \`$SOURCE_SHA\` 的[成功 CI]($EVIDENCE_URL);发行提交仅版本与发布说明不同" | tee -a "$GITHUB_STEP_SUMMARY"
fi
windows:
needs: release-info
name: windows-tests (${{ matrix.arch }})
@@ -411,7 +442,7 @@ jobs:
group: release-publication
queue: max
# 产物准备可与测试重叠,版本标签和 GitHub Release 必须等全部质量与镜像验证通过
needs: [release-info, quality, windows, security, package-assets, build-docker-image]
needs: [release-info, backend-validation, windows, security, package-assets, build-docker-image]
runs-on: ubuntu-26.04
timeout-minutes: 20
permissions:
@@ -522,25 +553,8 @@ jobs:
- name: Prepare release notes
shell: bash
env:
BUILD_TYPE: ${{ needs.release-info.outputs.build_type }}
INSTALLATION_NOTES: |
## Linux 一键安装(Docker Compose)
```bash
curl -fsSLO https://raw.githubusercontent.com/${{ github.repository }}/${{ needs.release-info.outputs.tag }}/deploy/install.sh && CPR_RELEASE_TAG=${{ needs.release-info.outputs.tag }} bash install.sh
```
## 📚 文档
- [GitHub 仓库](https://github.com/${{ github.repository }})
- [部署指南](https://github.com/${{ github.repository }}/blob/${{ needs.release-info.outputs.tag }}/deploy/README.md)
run: |
ruby <<'RUBY'
notes = File.readlines('release/notes.md').drop(1).join.strip
notes += "\n\n#{ENV.fetch('INSTALLATION_NOTES').strip}" unless ENV.fetch('BUILD_TYPE') == 'experimental'
output = File.join(ENV.fetch('RUNNER_TEMP'), 'release-notes.md')
File.write(output, "#{notes}\n")
RUBY
VERSION: ${{ needs.release-info.outputs.version }}
run: ruby .github/scripts/release-notes.rb body "$VERSION" > "$RUNNER_TEMP/release-notes.md"
- name: Generate release asset provenance
uses: actions/attest@1e69f48acb82d1966a394da916b4c1698aa569d6 # v4.2.2
@@ -552,8 +566,7 @@ jobs:
uses: softprops/action-gh-release@8a0cd651e5b2365bd640854a3fa5dfc70e4875f3 # v3.0.4
with:
tag_name: ${{ needs.release-info.outputs.tag }}
generate_release_notes: ${{ needs.release-info.outputs.build_type != 'experimental' }}
previous_tag: ${{ needs.release-info.outputs.previous_tag }}
generate_release_notes: false
prerelease: ${{ needs.release-info.outputs.prerelease == 'true' }}
# action 保留已公开 Release 的状态,新 Release 上传完成后仍保持草稿
draft: true
+2 -2
View File
@@ -122,7 +122,7 @@ PR 不接受以下协作规则文件的新增、修改、删除或重命名:
- 业务数据的解析、校验和展示优先复用已有逻辑。新增抽象放在拥有该职责的模块,避免重复事实源或无实际需求的通用层
- 新增代码注释使用中文。提交信息使用英文 Conventional Commits,参考近期历史,按完整功能归并
- AI 参与的提交按实际助手添加 `Co-authored-by: 名称 <邮箱>`,名称与邮箱采用该助手已知的署名身份,并保留其他实际共同作者署名;PR 的 AI 使用披露不替代提交署名
- 发布说明写入 `release/notes.md`,标题首行为目标版本的 `# vX.Y.Z`,章节标题和正文使用中文;命令、配置键、协议名等保留原文。只说明本次版本的实际变化,按影响交代升级事项
- 发布说明写入 `release/notes.md`,标题首行为目标版本的 `# vX.Y.Z`,手写章节标题和正文使用中文;命令、配置键、协议名等保留原文。只说明本次版本的实际变化,按影响交代升级事项。发行入口将自动变更列表和安装入口保存到末尾的生成区块,工作流按提交中的完整正文发布,基线与预检要求见[版本与说明准备](.agents/skills/cpr-release/references/preparation.md)
- PR 聚焦目标;无关格式化、重构和依赖升级单独处理
## 文档职责与更新条件
@@ -229,7 +229,7 @@ git diff --check
常规容器检查与发行构建共用二进制构建入口,并复用已检查的前端产物;Dockerfile、工具链、依赖或构建配置变化时执行完整源码镜像构建,定期安全检查也覆盖源码构建。两条路径均验证容器运行、安全扫描与关闭行为
发行构建与质量检查并行,Windows 两种架构的插件与系统更新测试独立运行。仅当发行提交只修改版本与发布说明,且其父提交有本仓库主分支成功的后端 CI 时复用该结果;缺少证据则完整重跑。对外发布等待质量、Windows 测试、依赖审计和镜像验证全部成功,构建耗时与测试报告保留 7 天
发行构建与质量检查并行,Windows 两种架构的插件与系统更新测试独立运行。仅当发行提交只修改版本与发布说明,且其父提交有本仓库主分支成功的后端 CI 时复用该结果;缺少证据则完整重跑。`backend-validation` 明确报告本次执行或复用结果,复用时列出被验证的源码提交和 CI 链接。对外发布等待质量、Windows 测试、依赖审计和镜像验证全部成功,构建耗时与测试报告保留 7 天
新增自动规则优先使用现有工具,要求依据明确、结果稳定、误报可控;无法可靠判定的设计与视觉问题保留审查判断,避免把具体源码写法锁成测试
+13 -7
View File
@@ -12,7 +12,7 @@
[![GHCR](https://img.shields.io/badge/GHCR-codex--proxy--rs-2496ED?logo=docker&logoColor=white&style=flat-square)](https://github.com/zyycn/codex-proxy-rs/pkgs/container/codex-proxy-rs)
[![License: Apache 2.0](https://img.shields.io/badge/License-Apache%202.0-blue.svg?style=flat-square)](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&amp;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 帮助到你了,欢迎请我喝杯咖啡 ☕
+20
View File
@@ -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")]
@@ -484,7 +484,6 @@ impl TryFrom<(ClientKeyPage, crate::time::TimePresenter)> for ClientKeyListData
let next_cursor = page
.next_cursor
.map(wire_cursor)
.transpose()?
.as_ref()
.map(encode_client_key_cursor)
.transpose()?;
@@ -597,7 +596,8 @@ impl From<ClientKeyMutation> for MutatedClientKeyData {
}
/// 解码后的 Client Key 游标字段
#[derive(Debug, Clone, PartialEq, Eq)]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ClientKeyCursorData {
pub sort: ClientKeySort,
pub value: ClientKeyCursorValue,
@@ -614,25 +614,12 @@ pub enum ClientKeyCursorValue {
LastUsedAt(Option<DateTime<Utc>>),
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct CursorWire {
sort: ClientKeySort,
value: ClientKeyCursorValue,
id: String,
}
/// 把 owner 游标编码为不透明 wire 值
pub fn encode_client_key_cursor(
cursor: &ClientKeyCursorData,
) -> Result<String, WireValidationError> {
validate_client_key_cursor(cursor)?;
let bytes = serde_json::to_vec(&CursorWire {
sort: cursor.sort,
value: cursor.value.clone(),
id: cursor.id.clone(),
})
.map_err(|_| WireValidationError::new("cursor"))?;
let bytes = serde_json::to_vec(cursor).map_err(|_| WireValidationError::new("cursor"))?;
Ok(URL_SAFE_NO_PAD.encode(bytes))
}
@@ -644,13 +631,8 @@ pub fn decode_client_key_cursor(encoded: &str) -> Result<ClientKeyCursorData, Wi
let bytes = URL_SAFE_NO_PAD
.decode(encoded)
.map_err(|_| WireValidationError::new("cursor"))?;
let cursor: CursorWire =
let cursor: ClientKeyCursorData =
serde_json::from_slice(&bytes).map_err(|_| WireValidationError::new("cursor"))?;
let cursor = ClientKeyCursorData {
sort: cursor.sort,
value: cursor.value,
id: cursor.id,
};
validate_client_key_cursor(&cursor)?;
Ok(cursor)
}
@@ -724,20 +706,18 @@ fn domain_cursor(cursor: ClientKeyCursorData) -> Result<ClientKeyCursor, WireVal
})
}
fn wire_cursor(cursor: ClientKeyCursor) -> Result<ClientKeyCursorData, WireValidationError> {
fn wire_cursor(cursor: ClientKeyCursor) -> ClientKeyCursorData {
let value = match cursor.value {
DomainCursorValue::Name(value) => ClientKeyCursorValue::Name(value),
DomainCursorValue::Enabled(value) => ClientKeyCursorValue::Enabled(value),
DomainCursorValue::CreatedAt(value) => ClientKeyCursorValue::CreatedAt(value),
DomainCursorValue::LastUsedAt(value) => ClientKeyCursorValue::LastUsedAt(value),
};
let cursor = ClientKeyCursorData {
ClientKeyCursorData {
sort: wire_sort(cursor.sort),
value,
id: cursor.id.to_string(),
};
validate_client_key_cursor(&cursor)?;
Ok(cursor)
}
}
fn client_key_id(
@@ -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,
+12 -10
View File
@@ -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 {
@@ -1,5 +1,6 @@
//! 验证 Client Key 管理接口的预算、密钥输入与查询合同
use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
use chrono::{DateTime, TimeZone as _, Utc};
use gateway_api::admin::client_keys::{
self, ClientKeyCursorData, ClientKeyCursorValue, ClientKeyListData, ClientKeyMutationRequest,
@@ -475,12 +476,41 @@ fn client_key_cursor_should_round_trip_and_reject_noncanonical_input() {
};
let encoded = encode_client_key_cursor(&cursor).expect("encode cursor");
let decoded = decode_client_key_cursor(&encoded).expect("decode cursor");
let wire = json!({
"sort": { "field": "createdAt", "direction": "desc" },
"value": { "kind": "createdAt", "value": "2026-07-18T08:00:00Z" },
"id": "key_cursor"
});
assert_eq!(decoded, cursor);
assert_eq!(
serde_json::from_slice::<serde_json::Value>(&URL_SAFE_NO_PAD.decode(&encoded).unwrap())
.unwrap(),
wire
);
assert!(!encoded.contains("key_cursor"));
for invalid in ["", "not-base64!", "e30"] {
assert!(decode_client_key_cursor(invalid).is_err());
}
for (field, value) in [
("unknownField", json!(true)),
("id", json!(" ")),
("value", json!({ "kind": "enabled", "value": true })),
(
"sort",
json!({ "field": "createdAt", "direction": "desc", "unknownField": true }),
),
] {
let mut invalid = wire.clone();
invalid[field] = value;
let encoded = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&invalid).unwrap());
assert_eq!(
decode_client_key_cursor(&encoded)
.expect_err("reject invalid cursor fields")
.field(),
"cursor"
);
}
}
#[test]
@@ -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,
+8 -10
View File
@@ -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]
+36 -14
View File
@@ -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;
+1
View File
@@ -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"] }
+5
View File
@@ -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, "服务启动正常");
@@ -416,6 +416,11 @@ impl HttpBody {
return Err(HttpError::sent("read size"));
}
loop {
if self.received > 32 * 1024 * 1024 {
// 累计量封存超限结果,后续读取不能交付已拒绝的缓冲
self.pending = Bytes::new();
return Err(HttpError::sent("response size"));
}
// 已缓冲的数据和就绪帧也受本次期限约束,不能绕过 owner 的读取预算
if Instant::now() >= deadline {
return Err(HttpError::sent("response deadline").with_kind(HttpErrorKind::Timeout));
@@ -445,9 +450,6 @@ impl HttpBody {
}
};
self.received = self.received.saturating_add(self.pending.len());
if self.received > 32 * 1024 * 1024 {
return Err(HttpError::sent("response size"));
}
}
}
}
@@ -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(),
+12 -5
View File
@@ -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;
@@ -158,6 +158,60 @@ async fn managed_http_caps_chunks_and_recovers_capacity_after_body_drop() {
);
}
#[tokio::test]
async fn managed_http_body_limit_rejects_all_reads_after_exceeding_capacity() {
let limit = 32 * 1024 * 1024;
let server = MockServer::start().await;
let client = HttpClient::new().unwrap();
for size in [limit, limit + 1] {
server.reset().await;
Mock::given(any())
.respond_with(ResponseTemplate::new(200).set_body_bytes(vec![42; size]))
.expect(1)
.mount(&server)
.await;
let mut response = client
.open(
request(server.uri()),
None,
&local_network(),
Duration::from_secs(10),
)
.await
.unwrap();
let mut received = 0;
let result = loop {
match response.body.read(64 * 1024).await {
Ok(Some(chunk)) => received += chunk.len(),
result => break result,
}
};
if size == limit {
assert!(result.unwrap().is_none());
assert_eq!(received, limit);
} else {
assert!(received <= limit);
let error = result.unwrap_err();
assert_eq!(error.kind(), HttpErrorKind::Response);
assert_eq!(error.send_state, UpstreamSendState::Sent);
assert_eq!(error.reason(), "response size");
assert_eq!(
response.body.read(1).await.unwrap_err().reason(),
"response size"
);
assert_eq!(
response
.body
.read_with_timeout(1, Duration::from_secs(1))
.await
.unwrap_err()
.reason(),
"response size"
);
}
}
}
#[tokio::test]
async fn managed_http_deadline_and_invalid_headers_preserve_send_facts() {
let server = MockServer::start().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();
+30 -3
View File
@@ -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 决定
+18 -1
View File
@@ -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),
@@ -1,4 +1,4 @@
//! Chat 到 Responses 的字段、媒体和工具映射回归
//! Chat 到 Responses 的字段、媒体和工具映射
use gateway_protocol::chat_completions::responses::convert_request;
use serde_json::{Value, json};
@@ -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,4 +1,4 @@
//! Responses 到 Chat 的完整响应、SSE增量及历史字段回归
//! Responses 到 Chat 的完整响应、流式增量、用量与错误投影
use gateway_protocol::chat_completions::{
ChatAccumulator, ChatError, ChatIdentity,
@@ -7,86 +7,67 @@ use gateway_protocol::chat_completions::{
use serde_json::{Value, json};
use std::collections::BTreeMap;
struct Session(Vec<Value>);
impl Session {
fn new(events: Vec<Value>) -> Self {
Self(events)
}
fn with_batch(mut self, events: Vec<Value>) -> Self {
self.0.extend(events);
self
}
}
struct Fixture(Session);
struct Projection {
json: Option<Value>,
chunks: Vec<Value>,
error: Option<ChatError>,
}
impl Fixture {
fn new(events: Session) -> Self {
Self(events)
}
fn post(&self, request: Value) -> Projection {
let identity = chat_identity();
let mut result = Projection {
json: None,
chunks: Vec::new(),
error: None,
};
if request["stream"] == true {
let mut encoder = ChatStreamEncoder::new(
identity,
request["stream_options"]["include_usage"] == true,
);
for event in &self.0.0 {
match encoder.push_event(event["type"].as_str(), event) {
Ok(chunks) => result.chunks.extend(chunks),
Err(error) => {
result.error = Some(error);
return result;
}
fn project_events(events: &[Value], streaming: bool, include_usage: bool) -> Projection {
let identity = chat_identity();
let mut result = Projection {
json: None,
chunks: Vec::new(),
error: None,
};
if streaming {
let mut encoder = ChatStreamEncoder::new(identity, include_usage);
for event in events {
match encoder.push_event(event["type"].as_str(), event) {
Ok(chunks) => result.chunks.extend(chunks),
Err(error) => {
result.error = Some(error);
return result;
}
}
match encoder.finish() {
Ok(chunks) => result.chunks.extend(chunks),
Err(error) => result.error = Some(error),
}
}
match encoder.finish() {
Ok(chunks) => result.chunks.extend(chunks),
Err(error) => result.error = Some(error),
}
} else {
let projected = if events.len() == 1 {
events[0]
.get("response")
.ok_or(ChatError::IncompleteStream)
.and_then(|value| project_response(value, &identity))
} else {
let projected = if self.0.0.len() == 1 {
self.0.0[0]
.get("response")
.ok_or(ChatError::IncompleteStream)
.and_then(|value| project_response(value, &identity))
} else {
let mut encoder = ChatStreamEncoder::new(identity, true);
let mut accumulator = ChatAccumulator::default();
let mut collect = || {
for event in &self.0.0 {
for chunk in encoder.push_event(event["type"].as_str(), event)? {
accumulator.push(&chunk)?;
}
}
for chunk in encoder.finish()? {
let mut encoder = ChatStreamEncoder::new(identity, true);
let mut accumulator = ChatAccumulator::default();
let mut collect = || {
for event in events {
for chunk in encoder.push_event(event["type"].as_str(), event)? {
accumulator.push(&chunk)?;
}
Ok::<_, ChatError>(())
};
collect().and_then(|()| accumulator.finish())
}
for chunk in encoder.finish()? {
accumulator.push(&chunk)?;
}
Ok::<_, ChatError>(())
};
match projected {
Ok(value) => result.json = Some(value),
Err(error) => result.error = Some(error),
}
collect().and_then(|()| accumulator.finish())
};
match projected {
Ok(value) => result.json = Some(value),
Err(error) => result.error = Some(error),
}
result
}
result
}
fn json_body(response: Projection) -> Value {
assert!(response.error.is_none(), "{:?}", response.error);
response.json.unwrap()
}
fn sse_body(response: Projection) -> (String, Vec<Value>) {
fn stream_chunks(response: Projection) -> (String, Vec<Value>) {
assert!(response.error.is_none(), "{:?}", response.error);
(
serde_json::to_string(&response.chunks).unwrap(),
@@ -100,9 +81,6 @@ fn chat_identity() -> ChatIdentity {
model: "model-a".to_owned(),
}
}
fn chat_request(stream: bool) -> Value {
json!({"model":"model-a","messages":[{"role":"user","content":"hello"}],"stream":stream})
}
fn wire(kind: &str, mut value: Value) -> Value {
value["type"] = json!(kind);
value
@@ -135,8 +113,8 @@ fn tool(id: &str, call_id: &str, name: &str, arguments: &str) -> Value {
#[test]
fn json_projects_public_identity_text_and_actual_usage() {
let fixture = Fixture::new(Session::new(vec![completed(json!([message("你好 🌍")]))]));
let response = fixture.post(chat_request(false));
let events = vec![completed(json!([message("你好 🌍")]))];
let response = project_events(&events, false, false);
let body = json_body(response);
assert_eq!(body["object"], "chat.completion");
assert!(body["id"].as_str().unwrap().starts_with("chatcmpl-"));
@@ -164,7 +142,7 @@ fn web_search_projects_citations_in_json_and_streams_the_original_links() {
let mut answer = message(&text);
answer["content"][0]["annotations"] = json!([citation]);
for stream in [false, true] {
let fixture = Fixture::new(Session::new(vec![
let events = vec![
created(),
wire(
"response.output_item.done",
@@ -189,13 +167,11 @@ fn web_search_projects_citations_in_json_and_streams_the_original_links() {
json!({"output_index":2,"item":answer}),
),
completed(json!([])),
]));
let mut request = chat_request(stream);
request["web_search_options"] = json!({});
let response = fixture.post(request);
];
let response = project_events(&events, stream, false);
let expected = format!("🌍 {text}");
if stream {
let (_, chunks) = sse_body(response);
let (_, chunks) = stream_chunks(response);
assert_eq!(combined(&chunks, "content"), expected);
assert_eq!(
chunks.last().unwrap()["choices"][0]["finish_reason"],
@@ -223,8 +199,8 @@ fn json_tool_arguments_and_refusal_do_not_become_assistant_text() {
{"type":"message","id":"refusal1","role":"assistant","status":"completed",
"content":[{"type":"refusal","refusal":"cannot help"}]}]),
] {
let fixture = Fixture::new(Session::new(vec![completed(output.clone())]));
let response = fixture.post(chat_request(false));
let events = vec![completed(output.clone())];
let response = project_events(&events, false, false);
let body = json_body(response);
let choice = &body["choices"][0];
assert_eq!(choice["message"]["content"], Value::Null);
@@ -245,7 +221,7 @@ fn json_tool_arguments_and_refusal_do_not_become_assistant_text() {
}
#[test]
fn sse_deduplicates_text_snapshots_and_emits_usage_only_when_requested() {
fn stream_deduplicates_text_snapshots_and_emits_usage_only_when_requested() {
for include_usage in [false, true] {
let terminal = completed(json!([message("你好 🌍")]));
let events = [
@@ -316,7 +292,7 @@ fn sse_deduplicates_text_snapshots_and_emits_usage_only_when_requested() {
}
#[test]
fn sse_preserves_interleaved_tools_and_reordered_terminal_snapshots() {
fn stream_preserves_interleaved_tools_and_reordered_terminal_snapshots() {
let first = tool(
"fc_first",
"call_first",
@@ -324,7 +300,7 @@ fn sse_preserves_interleaved_tools_and_reordered_terminal_snapshots() {
"{ \"city\": \"北京\" }",
);
let second = tool("fc_second", "call_second", "search", "{\"query\":\"Rust\"}");
let fixture = Fixture::new(Session::new(vec![
let events = vec![
created(),
wire(
"response.output_item.added",
@@ -355,8 +331,8 @@ fn sse_preserves_interleaved_tools_and_reordered_terminal_snapshots() {
json!({"output_index":2,"item":first}),
),
completed(json!([second, first])),
]));
let (_, chunks) = sse_body(fixture.post(chat_request(true)));
];
let (_, chunks) = stream_chunks(project_events(&events, true, false));
let mut tools = BTreeMap::<u64, (String, String, String)>::new();
for chunk in &chunks {
if let Some(calls) = chunk["choices"][0]["delta"]["tool_calls"].as_array() {
@@ -406,7 +382,7 @@ fn extra_attributes_and_auxiliary_events_preserve_existing_chat_results() {
let mut text = message("preserved");
text["future_optional"] = json!({"opaque":true});
text["content"][0]["future_attribute"] = json!([1, 2, 3]);
let fixture = Fixture::new(Session::new(vec![
let events = vec![
wire("response.future_auxiliary", json!({"future":true})),
wire(
"response.future_reasoning.delta",
@@ -414,8 +390,8 @@ fn extra_attributes_and_auxiliary_events_preserve_existing_chat_results() {
),
created(),
completed(json!([text])),
]));
let (_, chunks) = sse_body(fixture.post(chat_request(true)));
];
let (_, chunks) = stream_chunks(project_events(&events, true, false));
assert_eq!(combined(&chunks, "content"), "preserved");
assert!(
!chunks
@@ -430,7 +406,7 @@ fn compaction_state_preserves_chat_answer_without_exposing_ciphertext() {
for streaming in [false, true] {
let state =
json!({"type":kind,"id":"ctx_1","encrypted_content":"opaque-private-state"});
let fixture = Fixture::new(Session::new(vec![
let events = vec![
created(),
wire(
"response.output_item.added",
@@ -441,10 +417,10 @@ fn compaction_state_preserves_chat_answer_without_exposing_ciphertext() {
json!({"output_index":0,"item":state}),
),
completed(json!([state, message("preserved")])),
]));
let response = fixture.post(chat_request(streaming));
];
let response = project_events(&events, streaming, false);
if streaming {
let (text, chunks) = sse_body(response);
let (text, chunks) = stream_chunks(response);
assert_eq!(combined(&chunks, "content"), "preserved");
assert!(!text.contains("opaque-private-state"));
assert_eq!(
@@ -474,10 +450,10 @@ fn incomplete_projects_only_supported_finish_reasons() {
"id":"resp_chat_test","status":"incomplete","output":[message("partial")],
"incomplete_details":{"reason":reason}}}),
);
let fixture = Fixture::new(Session::new(vec![created(), event]));
let response = fixture.post(chat_request(streaming));
let events = vec![created(), event];
let response = project_events(&events, streaming, false);
if streaming {
let (_, chunks) = sse_body(response);
let (_, chunks) = stream_chunks(response);
assert_eq!(
chunks.last().unwrap()["choices"][0]["finish_reason"],
expected
@@ -497,7 +473,7 @@ fn encrypted_reasoning_stays_private_while_public_text_and_usage_are_projected()
"encrypted_content":"OPAQUE_ENCRYPTED_REASONING_MARKER"
});
for streaming in [false, true] {
let fixture = Fixture::new(Session::new(vec![
let events = vec![
created(),
wire(
"response.output_item.added",
@@ -525,14 +501,10 @@ fn encrypted_reasoning_stays_private_while_public_text_and_usage_are_projected()
"output_tokens_details":{"reasoning_tokens":2,"accepted_prediction_tokens":1}}
}}),
),
]));
let mut request = chat_request(streaming);
if streaming {
request["stream_options"] = json!({"include_usage":true});
}
let response = fixture.post(request);
];
let response = project_events(&events, streaming, true);
let (body, content, usage) = if streaming {
let (body, chunks) = sse_body(response);
let (body, chunks) = stream_chunks(response);
let usage = chunks
.iter()
.find(|chunk| chunk["choices"] == json!([]))
@@ -572,12 +544,8 @@ fn unrepresentable_business_output_fails_without_successful_chat_completion() {
json!({"id":"action_native","type":"computer_call","status":"completed","call_id":"call_action","action":{"type":"click","x":1,"y":2}}),
] {
for streaming in [false, true] {
let fixture = Fixture::new(Session::new(vec![created(), completed(json!([output]))]));
let mut request = chat_request(streaming);
if streaming {
request["stream_options"] = json!({"include_usage":true});
}
let response = fixture.post(request);
let events = vec![created(), completed(json!([output]))];
let response = project_events(&events, streaming, true);
assert_eq!(response.error, Some(ChatError::InvalidResponse));
assert!(
!response
@@ -592,16 +560,15 @@ fn unrepresentable_business_output_fails_without_successful_chat_completion() {
#[test]
fn stream_without_terminal_does_not_emit_a_successful_finish_or_usage() {
let fixture = Fixture::new(Session::new(vec![
let events = vec![
created(),
wire(
"response.output_text.delta",
json!({"item_id":"msg_chat_test","output_index":0,"content_index":0,"delta":"partial"}),
),
]));
let mut body = chat_request(true);
body["stream_options"] = json!({"include_usage":true});
let response = fixture.post(body);
];
let response = project_events(&events, true, true);
assert_eq!(response.error, Some(ChatError::IncompleteStream));
assert!(
!response
@@ -618,16 +585,15 @@ fn stream_without_terminal_does_not_emit_a_successful_finish_or_usage() {
}
#[test]
fn first_batch_terminal_can_finish_without_creating_usage_facts() {
let fixture = Fixture::new(Session::new(vec![wire(
fn completed_event_without_usage_does_not_invent_usage() {
let events = vec![wire(
"response.completed",
json!({"response":{
"id":"resp_chat_test","status":"completed","output":[message("done only")]
}}),
)]));
let mut body = chat_request(true);
body["stream_options"] = json!({"include_usage":true});
let (_, chunks) = sse_body(fixture.post(body));
)];
let (_, chunks) = stream_chunks(project_events(&events, true, true));
assert_eq!(combined(&chunks, "content"), "done only");
assert_eq!(
chunks
@@ -643,7 +609,7 @@ fn first_batch_terminal_can_finish_without_creating_usage_facts() {
fn refusal_deltas_and_done_snapshots_produce_only_standard_refusal() {
let output = json!({"id":"msg_refusal","type":"message","role":"assistant","status":"completed",
"content":[{"type":"refusal","refusal":"cannot help"}]});
let fixture = Fixture::new(Session::new(vec![
let events = vec![
created(),
wire(
"response.refusal.delta",
@@ -654,8 +620,8 @@ fn refusal_deltas_and_done_snapshots_produce_only_standard_refusal() {
json!({"item_id":"msg_refusal","output_index":0,"content_index":0,"refusal":"cannot help"}),
),
completed(json!([output])),
]));
let (_, chunks) = sse_body(fixture.post(chat_request(true)));
];
let (_, chunks) = stream_chunks(project_events(&events, true, false));
assert_eq!(combined(&chunks, "refusal"), "cannot help");
assert_eq!(combined(&chunks, "content"), "");
assert_eq!(
@@ -667,23 +633,20 @@ fn refusal_deltas_and_done_snapshots_produce_only_standard_refusal() {
#[test]
fn auxiliary_events_after_completed_preserve_exactly_one_finish_and_usage() {
for with_created in [false, true] {
// 终态与辅助事件同属一批 Core 交付 不构造已终结会话继续产出事件的另一种异常
let session = Session::new(if with_created {
let mut events = if with_created {
vec![created()]
} else {
Vec::new()
})
.with_batch(vec![
};
events.extend([
completed(json!([message("completed text")])),
wire(
"response.future_metadata",
json!({"response_id":"resp_chat_test","future":{"kept":true}}),
),
]);
let fixture = Fixture::new(session);
let mut body = chat_request(true);
body["stream_options"] = json!({"include_usage":true});
let (_, chunks) = sse_body(fixture.post(body));
let (_, chunks) = stream_chunks(project_events(&events, true, true));
assert_eq!(combined(&chunks, "content"), "completed text");
assert_eq!(
chunks
@@ -727,10 +690,9 @@ fn wire_failures_preserve_existing_recovery_fields_without_success_chunks() {
failure
}
};
let fixture = Fixture::new(Session::new(vec![created(), failure]));
let mut body = chat_request(true);
body["stream_options"] = json!({"include_usage":true});
let (_, chunks) = sse_body(fixture.post(body));
let events = vec![created(), failure];
let (_, chunks) = stream_chunks(project_events(&events, true, true));
let errors = chunks
.iter()
.filter_map(|chunk| chunk.get("error"))
@@ -749,15 +711,15 @@ fn wire_failures_preserve_existing_recovery_fields_without_success_chunks() {
#[test]
fn conflicting_text_snapshot_fails_instead_of_appending_replacement_content() {
let fixture = Fixture::new(Session::new(vec![
let events = vec![
created(),
wire(
"response.output_text.delta",
json!({"item_id":"msg_chat_test","output_index":0,"content_index":0,"delta":"already sent"}),
),
completed(json!([message("different result")])),
]));
let response = fixture.post(chat_request(true));
];
let response = project_events(&events, true, false);
assert_eq!(response.error, Some(ChatError::InvalidResponse));
assert_eq!(combined(&response.chunks, "content"), "already sent");
assert!(
@@ -795,7 +757,7 @@ fn custom_and_function_calls_keep_distinct_shapes_in_json_and_interleaved_stream
initial_custom["input"] = json!("");
let mut initial_function = function.clone();
initial_function["arguments"] = json!("");
let fixture = Fixture::new(Session::new(vec![
let events = vec![
created(),
wire(
"response.output_item.added",
@@ -818,10 +780,10 @@ fn custom_and_function_calls_keep_distinct_shapes_in_json_and_interleaved_stream
json!({"output_index":0,"item_id":"ct_1","input":"first\nsecond"}),
),
completed(output.clone()),
]));
let response = fixture.post(chat_request(streaming));
];
let response = project_events(&events, streaming, false);
if streaming {
let (body, chunks) = sse_body(response);
let (body, chunks) = stream_chunks(response);
assert_eq!(combined(&chunks, "refusal"), "no");
assert_eq!(combined(&chunks, "reasoning_content"), "thought");
assert!(!body.contains("PRIVATE_REASONING"));
@@ -870,7 +832,7 @@ fn custom_and_function_calls_keep_distinct_shapes_in_json_and_interleaved_stream
fn image_previews_and_final_images_are_projected_once_per_distinct_snapshot() {
let image = json!({"id":"ig_one","type":"image_generation_call","status":"completed","result":"ZmluYWw=","output_format":"webp"});
for streaming in [false, true] {
let fixture = Fixture::new(Session::new(vec![
let events = vec![
created(),
wire(
"response.image_generation_call.partial_image",
@@ -881,10 +843,10 @@ fn image_previews_and_final_images_are_projected_once_per_distinct_snapshot() {
json!({"output_index":0,"item":image}),
),
completed(json!([image, message("created")])),
]));
let response = fixture.post(chat_request(streaming));
];
let response = project_events(&events, streaming, false);
if streaming {
let (_, chunks) = sse_body(response);
let (_, chunks) = stream_chunks(response);
let images = chunks
.iter()
.filter_map(|chunk| chunk["choices"][0]["delta"]["images"].as_array())
@@ -913,7 +875,7 @@ fn output_logprobs_survive_json_projection_and_stream_snapshot_deduplication() {
let mut output = message("hello");
output["content"][0]["logprobs"] = probabilities.clone();
for streaming in [false, true] {
let fixture = Fixture::new(Session::new(vec![
let events = vec![
created(),
wire(
"response.output_text.delta",
@@ -924,10 +886,10 @@ fn output_logprobs_survive_json_projection_and_stream_snapshot_deduplication() {
json!({"output_index":0,"content_index":0,"item_id":"msg_chat_test","text":"hello","logprobs":probabilities}),
),
completed(json!([output])),
]));
let response = fixture.post(chat_request(streaming));
];
let response = project_events(&events, streaming, false);
if streaming {
let (_, chunks) = sse_body(response);
let (_, chunks) = stream_chunks(response);
let values = chunks
.iter()
.filter_map(|chunk| chunk["choices"][0]["logprobs"]["content"].as_array())
@@ -951,7 +913,7 @@ fn streaming_citation_offsets_follow_delivered_text_when_messages_interleave() {
first["content"][0]["annotations"] = json!([citation]);
let mut second = message("xy");
second["id"] = json!("msg_second");
let fixture = Fixture::new(Session::new(vec![
let events = vec![
created(),
wire(
"response.output_text.delta",
@@ -970,8 +932,8 @@ fn streaming_citation_offsets_follow_delivered_text_when_messages_interleave() {
json!({"output_index":0,"content_index":0,"item_id":"msg_chat_test","annotation_index":0,"annotation":citation}),
),
completed(json!([first, second])),
]));
let (_, chunks) = sse_body(fixture.post(chat_request(true)));
];
let (_, chunks) = stream_chunks(project_events(&events, true, false));
assert_eq!(combined(&chunks, "content"), "abxycd");
let annotations = chunks
.iter()
+53 -1
View File
@@ -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> {
+13 -10
View File
@@ -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]
Loaded 100 of 283 files, more files were not shown because too many files have changed in this diff. Show more