Compare commits

..
64 Commits
Author SHA1 Message Date
ZyyandCodex 99c5864914 chore: bump version to 3.61.1-rc.3
Co-authored-by: Codex <noreply@openai.com>
2026-12-03 18:18:19 +08:00
Zyy 060b275ce6 chore(antigravity): integrate account verification feedback (#837)
Preserve koeria’s contribution for #836. Main already includes the account validation fix in dd234c361.
2026-12-03 18:16:11 +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
koeria 3eefb8d156 style: cargo fmt provider-antigravity failure.rs 2026-12-03 17:34:00 +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
koeria df5d50bbf5 fix(antigravity): mark account unverified on upstream VALIDATION_REQUIRED 2026-12-03 16:02:29 +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
ZyyandCodex cad1a9245e chore: bump version to 3.61.0
Co-authored-by: Codex <noreply@openai.com>
2026-12-01 21:10:22 +08:00
ZyyandCodex d4d1114e73 fix(scheduling): score recent model load alongside concurrency
Include recent request pressure in Smart load scores before near-best
selection, keeping the concurrency penalty independent. Remove the
separate recent-count filter and share the score with diagnostics and
queue selection.

Co-authored-by: Codex <noreply@openai.com>
2026-12-01 19:20:04 +08:00
9e8a5a9b61 feat(scheduling): balance accounts using recent model load (#820)
Prefer accounts with fewer recent requests among near-best Smart candidates
while preserving affinity and existing eligibility constraints. Save recent
load snapshots asynchronously to Redis and restore live buckets on startup.

Co-authored-by: Zyy <zyycn@users.noreply.github.com>
Co-authored-by: Codex <noreply@openai.com>
2026-12-01 18:40:09 +08:00
ZyyandCodex 9a5bf55bdf fix(release): validate release branches and recover latest promotion
Co-authored-by: Codex <noreply@openai.com>
2026-12-01 17:17:35 +08:00
ZyyandCodex f57a375407 feat(frontend): show compact release channel badges in the sidebar
Co-authored-by: Codex <noreply@openai.com>
2026-12-01 17:17:35 +08:00
ZyyandCodex 82cb91e1af fix(updater): report the published version for the selected channel
Return an unknown version when discovery fails and preserve local update capability during rate limits. Keep release notes tied to the selected channel and require a higher version for installation.

Co-authored-by: Codex <noreply@openai.com>
2026-12-01 16:22:13 +08:00
ZyyandCodex 441c012613 fix(accounts): show token usage for the displayed quota window
Co-authored-by: Codex <noreply@openai.com>
2026-12-01 16:21:43 +08:00
ZyyandCodex 983eca5fe7 fix(frontend): stabilize select text and hide empty token values
Hide empty token values while preserving their labels and layout. Align the UI dependency, lockfile, and submodule with the select font-weight fix.

Co-authored-by: Codex <noreply@openai.com>
2026-12-01 16:05:44 +08:00
ZyyandCodex e0b0ab14da fix(openai): preserve quota observation timestamps
Keep header and stream quota facts tied to their collection time so delayed responses cannot replace a newer refresh. Filter stale observations again on merge conflicts and retain timestamps through failure and warmup paths.

Co-authored-by: Codex <noreply@openai.com>
2026-12-01 15:27:03 +08:00
b4bb97d1dc feat(accounts): add xAI and Antigravity API key upstreams (#816)
* feat(accounts): add xAI and Antigravity API key upstreams

Support native Responses and GenAI API key accounts with custom upstream URLs.
Reuse account management and isolate credentials, catalogs, and runtime connections by revision.

Refs #814

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

* refactor(antigravity): simplify API key account names

Use name consistently in API key account documents and verify the exported contract before reimport.

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-01 15:07:11 +08:00
ZyyandCodex 9f979110d2 fix(gateway): forward upstream retry headers regardless of error kind
Co-authored-by: Codex <noreply@openai.com>
2026-12-01 13:33:10 +08:00
github-actions[bot] a5cddfe4a5 chore(release): update release channels to 3.60.5 2026-12-01 05:12:39 +00:00
ZyyandCodex 914c4c24d3 chore: bump version to 3.60.5
Co-authored-by: Codex <noreply@openai.com>
2026-12-01 12:52:44 +08:00
ZyyandCodex 7251546c75 fix(gateway): preserve upstream retry headers across capacity rotation
Co-authored-by: Codex <noreply@openai.com>
2026-12-01 12:52:24 +08:00
ZyyandCodex 3c38925716 docs(skills): clarify frontend tooltip and list loading guidance
Co-authored-by: Codex <noreply@openai.com>
2026-12-01 12:33:02 +08:00
ZyyandCodex 43ca35b027 fix(antigravity): explain Google account connection test failures
Refs #805

Co-authored-by: Codex <noreply@openai.com>
2026-12-01 12:18:47 +08:00
ZyyandCodex 95d545a7d8 perf(admin): show request error popovers without fetching details
Co-authored-by: Codex <noreply@openai.com>
2026-12-01 12:17:35 +08:00
ZyyandCodex db3324f90a fix(admin): show upstream errors and retry waits in request popovers
Localize interrupted requests, align quota badges, and update the icon picker to the responsive UI revision.

Co-authored-by: Codex <noreply@openai.com>
2026-12-01 11:56:13 +08:00
ZyyandCodex 30bcff3419 test(store): verify display names for accounts sharing an email
Co-authored-by: Codex <noreply@openai.com>
2026-12-01 11:56:13 +08:00
329503d967 fix(admin): use account display names in sorting and usage (#815)
* fix(admin): use account display names in sorting and usage

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

* fix(ui): remove native tooltips from usage identity cells

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-01 11:10:24 +08:00
eae19e211e fix(openai): start weekly bucket warmup after reset-credit consume (#813)
* fix(openai): start weekly bucket warmup after reset-credit consume

After a successful reset or already_redeemed consume, refresh quota and
advance an already-enabled bucket warmup to the actual reset time. Pull
an early reset's registered future boundary back so due() is not blocked
until the original window ends. Keep the five-minute recheck and skip
warmup when the new round already has usage.

* fix(openai): make credit-triggered weekly warmup idempotent

Register confirmed redemptions with bucket progress and recheck usage in the warmup worker. Preserve precise usage evidence and keep rolling quota deadlines separate from confirmed resets.

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

* refactor(openai): keep only the latest warmup redemption

Reuse account warmup progress to recognize retries of the latest credit. Remove the receipt table and keep the existing storage contract.

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-01 10:56:06 +08:00
github-actions[bot] 294e9c8bd8 chore(release): update release channels to 3.60.4 2026-11-30 16:44:00 +00:00
ZyyandCodex 1b92c552b9 chore: bump version to 3.60.4
Co-authored-by: Codex <noreply@openai.com>
2026-11-30 23:53:30 +08:00
ZyyandCodex c9fb2ac465 test(openai): align request fixtures with empty defaults
Use the empty country default in content preservation assertions and configure residency explicitly in routing header coverage.

Co-authored-by: Codex <noreply@openai.com>
2026-11-30 23:48:12 +08:00
ZyyandCodex 6bf109e784 test(store): initialize configuration revision baseline
Initialize configuration and settings revisions after test migrations so functional assertions remain independent of migration revision increments.

Co-authored-by: Codex <noreply@openai.com>
2026-11-30 23:25:46 +08:00
ZyyandCodex fa187c5031 fix(settings): keep help controls transparent and consistent
Use a shared 24px square help trigger for request settings and automatic
approval details. Align the UI dependency and submodule with the disabled
link background fix.

Co-authored-by: Codex <noreply@openai.com>
2026-11-30 23:17:02 +08:00
ZyyandCodex 5f7e1723f3 fix(openai): default request country and residency to empty
Use the empty country policy and leave residency and account routing unset.
Migrate existing follow-location policies and us residency values while
preserving custom settings and advancing the settings revision.
Update the settings UI, existing contract tests, and deployment guidance.

Co-authored-by: Codex <noreply@openai.com>
2026-11-30 23:02:45 +08:00
ZyyandCodex 7d34be5d02 fix(antigravity): preserve native signatures across model switches
Recognize known Claude and Gemini signature envelopes without wrapping
response signatures. Remove foreign thinking history while preserving
compatible or unknown signatures, ordinary text, and tool history.

Integrate cleanup into request field editing and reuse unchanged history.
Keep counting and unknown model families untouched, without session caches.
Cover native JSON/SSE, escaped fields, malformed envelopes, and model
switches; document recognition and account compatibility boundaries.

Co-authored-by: Codex <noreply@openai.com>
2026-11-30 23:02:44 +08:00
github-actions[bot] ebb3c4b1fa chore(release): update release channels to 3.60.3 2026-11-30 12:57:31 +00:00
ZyyandCodex 2bf0ca146d chore: bump version to 3.60.3
Co-authored-by: Codex <noreply@openai.com>
2026-11-30 20:34:41 +08:00
ZyyandCodex 5c1e27fc47 fix(plugins): account for peer queues when awaiting cancellation
Use the existing queue timeout for cancellation confirmations so normal peer backpressure does not terminate healthy sessions. Cover delayed acknowledgements and bounded cleanup of unresponsive peers.

Co-authored-by: Codex <noreply@openai.com>
2026-11-30 20:33:31 +08:00
dependabot[bot] 03f21c26eb chore(deps): bump @lucide/vue in /frontend in the minor-and-patch group (#810)
Bumps the minor-and-patch group in /frontend with 1 update: [@lucide/vue](https://github.com/lucide-icons/lucide/tree/HEAD/packages/vue).


Updates `@lucide/vue` from 1.83.0 to 1.84.0
- [Release notes](https://github.com/lucide-icons/lucide/releases)
- [Commits](https://github.com/lucide-icons/lucide/commits/1.84.0/packages/vue)

---
updated-dependencies:
- dependency-name: "@lucide/vue"
  dependency-version: 1.84.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-and-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-11-30 20:33:31 +08:00
ZyyandCodex 280ded5707 chore(deps): pin h2 to the Codex baseline and hold Rust image updates
Co-authored-by: Codex <noreply@openai.com>
2026-11-30 18:44:09 +08:00
8fb07f993c fix(antigravity): repair missing native Claude tool IDs (#808)
Pair uniquely named calls and results in adjacent model/user turns before
sending native Claude requests. Preserve existing IDs and raw business
fields, avoid ID collisions, and leave ambiguous history unchanged.
Cover JSON/SSE transport, partial IDs, replay stability, and scope limits.

Co-authored-by: Zyy <zyycn@users.noreply.github.com>
Co-authored-by: Codex <noreply@openai.com>
2026-11-30 17:56:45 +08:00
ZyyandCodex ee691246c7 fix(build): retain sha2 optimization across dependency updates
Match the sha2 package without pinning its patch version so dev and test builds retain the intended optimization after lockfile updates. Keep multipart concurrency assertions and timeouts unchanged.

Co-authored-by: Codex <noreply@openai.com>
2026-11-30 15:36:23 +08:00
ZyyandCodex e406a6bcd8 fix(plugins): separate cancellation send and confirmation deadlines
Start the confirmation deadline after the cancellation frame is written. Arbitrate acknowledgements and expiry in the reader and commit failures under the call table lock. Cover queued cancellation under backpressure and recovery at the default in-flight limit.

Co-authored-by: Codex <noreply@openai.com>
2026-11-30 15:13:22 +08:00
ZyyandCodex 4ffaeb3051 fix(xai): align Grok passthrough and client-owned history
Align the Grok 1.0.92 transport profile, retain only continuation routing metadata, and filter downstream environment headers at provider boundaries.

Co-authored-by: Codex <noreply@openai.com>
2026-11-30 14:37:32 +08:00
github-actions[bot] a126c194f5 chore(release): update release channels to 3.60.2 2026-11-30 04:00:31 +00:00
378 changed files with 14780 additions and 3395 deletions
@@ -4,7 +4,9 @@
## 领域必读
确定页面方案或审查结论前,读取[前端职责](../../../../docs/architecture.md#34-前端模块职责)、[文案与信息层级](../../../../docs/theme.md#界面文案与信息层级)和[界面验证](../../../../CONTRIBUTING.md#界面验证)的完整章节,局部修改同样读取。明确本次用户操作、原页面、最接近的同类实现及可复用基础组件,沿用既有设计与请求层,按本轮验收分工留存所需截图
确定页面方案或审查结论前,读取[前端职责](../../../../docs/architecture.md#34-前端模块职责)、[文案与信息层级](../../../../docs/theme.md#界面文案与信息层级)和[界面验证](../../../../CONTRIBUTING.md#界面验证)的完整章节,局部修改同样读取。新增或移动文件时,页面与布局按同一套目录规则,根据调用范围和导出内容区分组件私有实现、共享常量和共享纯函数
明确本次用户操作、原页面、最接近的同类实现及可复用基础组件,沿用既有设计与请求层,按本轮验收分工留存所需截图
## 按改动补齐规范
@@ -21,10 +23,15 @@
普通维护和新增业务页面沿用现有设计;设计技能中的配色、字体、布局探索不覆盖项目规范,主题算法只在涉及时读取
- 页面和组件不添加浏览器原生提示的 `title` 属性。确需补充说明时,按内容复用已有的 Tooltip 或 Popover
- 列表行需要快速展示少量字段时,先核对列表接口已返回的字段和后端查询已读取的数据。能随当前页低成本返回的字段直接用于展示,完整详情在用户打开详情时加载
## 验收范围与收尾
验证前按[界面验证](../../../../CONTRIBUTING.md#界面验证)明确本次受影响的用户路径、状态和通过条件。局部修改围绕受影响区域及相关操作验收;主题、窗口尺寸和空/加载/错误状态仅在受影响时补充,共用主题或基础组件变更按主题规范扩大范围
沿实际操作验证待确认、执行中、完成、失败与取消等受影响阶段,同时检查当前弹层和背景区域,核对应该出现的反馈与不应出现的状态。必要时延迟模拟响应以观察过渡状态,不能仅凭请求成功或截图齐全判定交互通过
通过后按[验证停止条件](../../../../CONTRIBUTING.md#验证)收尾;只有新改动、失败或未解疑点时补验相关部分。补交截图或 PR 材料时复用仍有效的运行证据
## 交付前
@@ -37,7 +44,7 @@
- **样式与状态**:是否使用对应 Token 与 utility,局部样式是否符合适用边界,受影响的主题、窄屏及交互状态是否正确
- **模块归属**从调用方核对公开入口。页面或多文件组件通过 `index.vue` 提供界面,其他页面复用整页时引用所属模块的布局入口,独立复用的业务组件按领域放置
- **Provider 边界**涉及账号操作、身份配置或定价时,沿接口响应、控件和提交载荷追踪同一条规则。服务端决定的能力使用接口字段,Provider 专属表单解释自己的字段,多个页面共用的编辑流程只维护一份。按[前端职责](../../../../docs/architecture.md#34-前端模块职责)核对归属
- **查询与动作**:区分首次加载、刷新、分页、单行与批量操作,核对 loading、禁用状态的影响范围;沿用请求层错误处理,不在页面叠加同一错误的提示
- **查询与动作**:区分首次加载、刷新、分页、单行与批量操作,明确当前动作的反馈归属及其他控件的禁用范围,避免同一动作在前后景重复显示执行反馈。待确认不等于已提交,复用交互时重新核对 loading、进度与结果的显示条件是否适用于当前动作;沿用请求层错误处理,不在页面叠加同一错误的提示
- **运行证据**:按界面验证核对截图与实际交互,证据对应当前实现;页面 PR 的可访问图片和 Draft 条件按该节执行
交付简述所复用的页面或组件、实际验证范围及缺口;环境不足时如实说明,不能仅凭构建、源码或截图推断未验证的行为
@@ -46,7 +46,9 @@ release/publish "$release_version"
- 尚未推送:补齐缺失的步骤,按入口原子推送分支和 tag
- 已推送但未触发:使用入口提示的 dispatch 命令
- 已有 run:跟踪对应提交的任务,失败时重跑失败任务。构建产物保留 7 天,过期后从原 tag 重跑完整工作流
- Release 尚未公开时,跟踪原 run 并重跑失败任务。构建产物保留 7 天,过期后从原 tag 重跑工作流
- 正式版已公开,GitHub Latest 或镜像 `latest` 提升中断时,在已有恢复授权下执行 `gh workflow run release.yml --ref main -f tag="v$release_version" -f recover_latest=true`。任务核对公开附件、版本镜像与 tag 提交对应的镜像摘要,补齐稳定入口后同步通道表。若任一稳定入口已经指向更新版本,则保留现有入口
- 仅通道表写入失败时,确认工作流能写入 `main`,按已有授权执行 `gh workflow run release.yml --ref main -f tag="v$release_version" -f index_only=true`。各通道均可用此入口重新核对公开附件并合并通道表
### 修复源码后同版本重发
@@ -60,7 +62,7 @@ release/publish "$release_version"
- 发布完成后核对 GitHub Release 的版本、正式版/预发行状态和中文变更正文;对照平台清单与工作流确认归档、校验和及镜像产物。
工作流附加的安装说明和自动提交列表按其当前配置处理,不用它们替代手写的中文变更说明。
- 回读 `main:release/version.yaml` 的 `published`。正式版参与同一大版本四个普通通道的比较;RC 参与 RC、Beta、Alpha,Beta 参与 Beta、Alpha,Alpha 只参与自身。实验版只推进 `exp["X.Y.Z"]`。有通道推进时应有 `chore(release): update release channels to <version>` 提交;重复执行或较旧版本未推进任何通道时无提交
- 通道表写入失败时,确认该版本已公开、工作流能写入 `main`,再按已有授权执行 `gh workflow run release.yml --ref main -f tag="v$release_version" -f index_only=true`。恢复任务重新校验公开附件、读取并合并当前清单,不重新打包或改 tag
- 正式版提升或恢复后,回读 GitHub Latest 的 tag 与镜像 `latest` 的摘要,核对两者均指向预期正式版
- 保留 v3.42.0 在线升级使用的 `update-index` 页面和 v3.42.1 的 `version.yaml` 附件
- 返回版本、tag 对应提交、Release/工作流链接及实际结果。失败、仍在构建或缺失产物时明确说明,不能称为发布成功;
Release 和镜像已生成也不表示用户的运行实例已经升级。
+3
View File
@@ -27,6 +27,7 @@ updates:
# 按官方 Codex 锁文件、协议指纹或已审计 fork 固定;完成对应核对与实测后再手动升级。
ignore:
- dependency-name: aws-lc-rs
- dependency-name: h2
- dependency-name: hyper
- dependency-name: hyper-rustls
- dependency-name: hyper-tls
@@ -71,6 +72,8 @@ updates:
directories:
- /deploy
labels: []
ignore:
- dependency-name: rust
schedule:
interval: weekly
day: monday
+40 -15
View File
@@ -1,4 +1,4 @@
require_relative 'release-metadata'
require_relative 'published-channels'
# 构建和验证可以并行;调用方必须在仓库级发布锁内执行本脚本
module ReleasePublication
@@ -39,44 +39,69 @@ module ReleasePublication
end
end
def self.image_digest(ref)
digest = run('docker', 'buildx', 'imagetools', 'inspect', ref, '--format', '{{.Manifest.Digest}}')
raise "Invalid image digest for #{ref}" unless digest.match?(/\Asha256:[a-f0-9]{64}\z/)
digest
end
def self.tag(image, digest, name)
ref = "#{image}:#{name}"
run('docker', 'buildx', 'imagetools', 'create', '-t', ref, "#{image}@#{digest}")
actual = run('docker', 'buildx', 'imagetools', 'inspect', ref, '--format', '{{.Manifest.Digest}}')
raise "Promoted image digest changed: #{ref}" unless actual == digest
raise "Promoted image digest changed: #{ref}" unless image_digest(ref) == digest
end
def self.publish(version:, image:, digest:, repository:, release_id:)
version = ReleaseMetadata.version(version)
version = ReleaseMetadata.release_version(version)
raise 'Invalid image digest' unless digest.match?(/\Asha256:[a-f0-9]{64}\z/)
raise 'Invalid GitHub release ID' unless release_id.match?(/\A\d+\z/)
endpoint = "repos/#{repository}/releases/#{release_id}"
# 附件上传及镜像证明、签名已完成,再公开版本入口;失败可从本 job 重跑
tag(image, digest, version.tr('+', '-'))
# 附件、签名和证明就绪后才公开版本入口
tag(image, digest, version)
run('gh', 'api', '--method', 'PATCH', endpoint, '-F', 'draft=false', '-f', 'make_latest=false')
return if ReleaseMetadata.prerelease?(version)
promote_latest(version, image, digest, repository, endpoint) unless ReleaseMetadata.prerelease?(version)
end
current_versions = [latest_release(repository), latest_image(image)]
def self.recover_latest(tag:, image:, repository:, ref:)
version = ReleaseMetadata.release_version(tag)
raise 'Latest recovery requires a stable release' if ReleaseMetadata.prerelease?(version)
commit = ReleaseMetadata.tag_commit(tag, ref)
release = PublishedChannels::Publisher.new(repository).verify_assets(version)
digest = image_digest("#{image}:#{version}")
raise "Version image differs from the image built for #{commit}" unless image_digest("#{image}:sha-#{commit}") == digest
promote_latest(version, image, digest, repository, "repos/#{repository}/releases/#{release.fetch('id')}")
end
def self.promote_latest(version, image, digest, repository, endpoint)
github_latest = latest_release(repository)
docker_latest = latest_image(image)
current_versions = [github_latest, docker_latest]
unless can_promote?(version, current_versions)
puts "Published #{version}; latest remains at #{current_versions.compact.join(', ')}"
return
end
# 两个服务不能原子更新;同时检查两侧版本,让失败重试可以补齐而旧版不能回退
tag(image, digest, 'latest')
run('gh', 'api', '--method', 'PATCH', endpoint, '-f', 'make_latest=true')
tag(image, digest, 'latest') unless docker_latest == version && image_digest("#{image}:latest") == digest
run('gh', 'api', '--method', 'PATCH', endpoint, '-f', 'make_latest=true') unless github_latest == "v#{version}"
puts "Published #{version} and promoted latest"
end
end
if $PROGRAM_NAME == __FILE__
begin
ReleasePublication.publish(
version: ENV.fetch('VERSION'), image: "#{ENV.fetch('REGISTRY')}/#{ENV.fetch('IMAGE_NAME')}",
digest: ENV.fetch('DIGEST'), repository: ENV.fetch('GITHUB_REPOSITORY'),
release_id: ENV.fetch('RELEASE_ID')
)
image = "#{ENV.fetch('REGISTRY')}/#{ENV.fetch('IMAGE_NAME')}"
repository = ENV.fetch('GITHUB_REPOSITORY')
case ARGV
when []
ReleasePublication.publish(version: ENV.fetch('VERSION'), image: image, digest: ENV.fetch('DIGEST'),
repository: repository, release_id: ENV.fetch('RELEASE_ID'))
when ['recover-latest']
ReleasePublication.recover_latest(tag: ENV.fetch('TAG'), image: image, repository: repository, ref: ENV.fetch('GITHUB_REF'))
else
raise 'usage: publish-release.rb [recover-latest]'
end
rescue StandardError => error
warn "error: #{error.message}"
exit 1
+2 -1
View File
@@ -67,11 +67,12 @@ module PublishedChannels
end
missing = expected - uploaded
raise "Incomplete release #{tag}: #{missing.join(', ')}" unless missing.empty?
release
end
def check_unpublished(version)
existing = find_release(version)
raise "Release v#{version} already public; use index-only recovery" if existing && !existing.fetch('draft')
raise "Release v#{version} already public; use recover_latest or index_only" if existing && !existing.fetch('draft')
end
def publish(version)
+32 -5
View File
@@ -20,6 +20,31 @@ module ReleaseMetadata
version(value).split('+', 2).first.include?('-')
end
def self.release_version(raw)
value = version(raw)
raise "Release versions cannot contain build metadata: #{raw}" if value.include?('+')
value
end
def self.validate_branch(raw, ref)
value = release_version(raw)
if value.include?('-exp.')
raise "Experimental releases require an experimental/<purpose> branch" unless ref.match?(%r{\Arefs/heads/experimental/.+\z})
elsif ref != 'refs/heads/main'
raise "Release #{value} requires the main branch"
end
value
end
# 从触发工作流的提交核对 tag,允许分支前进后重试同一发行
def self.tag_commit(tag, ref)
value = validate_branch(tag, ref)
raise "Expected release tag v#{value}" unless tag == "v#{value}"
commit = git('rev-parse', '--verify', "refs/tags/#{tag}^{commit}")
raise "#{tag} is outside #{ref}" unless git('merge-base', commit, 'HEAD') == commit
commit
end
def self.sort_key(value)
Gem::Version.new(version(value).split('+', 2).first)
end
@@ -67,7 +92,7 @@ module ReleaseMetadata
end
def self.outputs(tag)
value = version(YAML.load_file('release/version.yaml').fetch('version'))
value = release_version(YAML.load_file('release/version.yaml').fetch('version'))
raise "Release tag #{tag} does not match v#{value}" unless tag == "v#{value}"
validate_notes(value)
entries = platforms
@@ -80,7 +105,6 @@ module ReleaseMetadata
{
'tag' => tag,
'version' => value,
'docker_version' => value.tr('+', '-'),
'build_time' => Time.now.utc.iso8601,
'git_sha' => git('rev-parse', 'HEAD'),
'platform_matrix' => JSON.generate('include' => entries),
@@ -113,13 +137,16 @@ end
if $PROGRAM_NAME == __FILE__
begin
command, value = ARGV
raise 'usage: release-metadata.rb validate VERSION | outputs TAG' unless ARGV.length == 2
command, value, ref = ARGV
arity = command == 'outputs' ? 2 : 3
raise 'usage: release-metadata.rb validate VERSION REF | tag-commit TAG REF | outputs TAG' unless ARGV.length == arity
case command
when 'validate'
value = ReleaseMetadata.version(value)
value = ReleaseMetadata.validate_branch(value, ref)
ReleaseMetadata.validate_notes(value)
puts value
when 'tag-commit'
puts ReleaseMetadata.tag_commit(value, ref)
when 'outputs'
metadata = ReleaseMetadata.outputs(value)
ReleaseMetadata.seal_manifest(metadata)
+50 -14
View File
@@ -11,6 +11,10 @@ on:
description: 'Recover the index for an already public release without rebuilding'
type: boolean
default: false
recover_latest:
description: 'Recover latest and the channel index for an already public stable release'
type: boolean
default: false
permissions:
contents: read
@@ -25,7 +29,7 @@ env:
jobs:
release-info:
if: ${{ !inputs.index_only }}
if: ${{ !inputs.index_only && !inputs.recover_latest }}
runs-on: ubuntu-26.04
timeout-minutes: 10
permissions:
@@ -34,7 +38,6 @@ jobs:
outputs:
tag: ${{ steps.version.outputs.tag }}
version: ${{ steps.version.outputs.version }}
docker_version: ${{ steps.version.outputs.docker_version }}
build_time: ${{ steps.version.outputs.build_time }}
git_sha: ${{ steps.version.outputs.git_sha }}
platform_matrix: ${{ steps.version.outputs.platform_matrix }}
@@ -53,9 +56,15 @@ jobs:
- name: Checkout
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
ref: ${{ inputs.tag }}
fetch-depth: 0
- name: Verify release branch and check out the tagged commit
env:
RELEASE_TAG: ${{ inputs.tag }}
run: |
commit="$(ruby .github/scripts/release-metadata.rb tag-commit "$RELEASE_TAG" "$GITHUB_REF")"
git checkout --detach "$commit"
- name: Read release metadata and seal plugin manifest
id: version
env:
@@ -273,7 +282,7 @@ jobs:
shell: bash
env:
VERSION: ${{ needs.release-info.outputs.version }}
DOCKER_VERSION: ${{ needs.release-info.outputs.docker_version }}
DOCKER_VERSION: ${{ needs.release-info.outputs.version }}
PLATFORM_MATRIX: ${{ needs.release-info.outputs.platform_matrix }}
run: ruby .github/scripts/package-release.rb archives
@@ -443,6 +452,12 @@ jobs:
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Check that the release is unpublished
env:
GH_TOKEN: ${{ github.token }}
VERSION: ${{ needs.release-info.outputs.version }}
run: ruby .github/scripts/published-channels.rb check "$VERSION"
- name: Assemble candidate image manifest
id: manifest
shell: bash
@@ -507,6 +522,7 @@ jobs:
- name: Prepare release notes
shell: bash
env:
BUILD_TYPE: ${{ needs.release-info.outputs.build_type }}
INSTALLATION_NOTES: |
## Linux 一键安装(Docker Compose)
@@ -521,17 +537,11 @@ jobs:
run: |
ruby <<'RUBY'
notes = File.readlines('release/notes.md').drop(1).join.strip
installation = ENV.fetch('INSTALLATION_NOTES').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\n#{installation}\n")
File.write(output, "#{notes}\n")
RUBY
- name: Check that the release is unpublished
env:
GH_TOKEN: ${{ github.token }}
VERSION: ${{ needs.release-info.outputs.version }}
run: ruby .github/scripts/published-channels.rb check "$VERSION"
- name: Generate release asset provenance
uses: actions/attest@1e69f48acb82d1966a394da916b4c1698aa569d6 # v4.2.2
with:
@@ -542,7 +552,7 @@ jobs:
uses: softprops/action-gh-release@8a0cd651e5b2365bd640854a3fa5dfc70e4875f3 # v3.0.4
with:
tag_name: ${{ needs.release-info.outputs.tag }}
generate_release_notes: true
generate_release_notes: ${{ needs.release-info.outputs.build_type != 'experimental' }}
previous_tag: ${{ needs.release-info.outputs.previous_tag }}
prerelease: ${{ needs.release-info.outputs.prerelease == 'true' }}
# action 保留已公开 Release 的状态,新 Release 上传完成后仍保持草稿
@@ -567,8 +577,34 @@ jobs:
VERSION: ${{ needs.release-info.outputs.version }}
run: ruby .github/scripts/published-channels.rb publish "$VERSION"
recover-latest:
if: inputs.recover_latest
runs-on: ubuntu-26.04
concurrency:
group: release-publication
queue: max
permissions:
contents: write
packages: write
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
fetch-depth: 0
- uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1
- uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ github.token }}
- name: Restore latest from the verified version image
env:
GH_TOKEN: ${{ github.token }}
TAG: ${{ inputs.tag }}
run: ruby .github/scripts/publish-release.rb recover-latest
recover-index:
if: inputs.index_only
needs: recover-latest
if: ${{ !cancelled() && (needs.recover-latest.result == 'success' || (inputs.index_only && !inputs.recover_latest)) }}
runs-on: ubuntu-26.04
concurrency:
group: release-publication
+24 -2
View File
@@ -1887,6 +1887,7 @@ dependencies = [
"tracing",
"tracing-appender",
"tracing-subscriber",
"uuid",
"wiremock",
"yaml-rust2 0.13.2",
]
@@ -2073,9 +2074,9 @@ dependencies = [
[[package]]
name = "h2"
version = "0.4.21"
version = "0.4.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b634322c4924093fe6a6e05ecbe5717cd3c6014934455f4ae8e5cf14ba3264a8"
checksum = "ef8e5e5a340588f4452631496976cf8636d4a7ecf600239fdc27615d2530bc16"
dependencies = [
"atomic-waker",
"bytes",
@@ -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",
@@ -3499,6 +3507,8 @@ dependencies = [
"jsonwebtoken",
"p256",
"reqwest",
"rustls",
"rustls-native-certs",
"semver",
"serde",
"serde_json",
@@ -4183,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"
+1 -1
View File
@@ -45,7 +45,7 @@ opt-level = 2
[profile.dev.package.blake2]
opt-level = 2
[profile.dev.package."sha2@0.11.1"]
[profile.dev.package.sha2]
opt-level = 2
[profile.dev.package."miniz_oxide@0.9.1"]
@@ -79,7 +79,7 @@ impl Providers {
)
.await?;
environment.host.report_startup_ready("OpenAI Provider");
let antigravity = provider_antigravity::initialize(ports.clone())?;
let antigravity = provider_antigravity::initialize(ports.clone()).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(())
})
}
@@ -55,7 +55,7 @@ pub struct AccountImportSettings {
/// 账号列表排序字段
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AccountSortField {
Email,
Name,
Status,
PlanType,
Usage,
@@ -889,12 +889,14 @@ impl UsageErrorOrigin {
}
/// 使用记录表格的窄读模型
#[derive(Debug, Clone, PartialEq)]
#[derive(Clone, PartialEq)]
pub struct UsageListRecord {
pub platform_icon: Option<String>,
pub outcome: RequestOutcome,
/// 已保存的上游错误对象含非空字符串 code、type 或 message
pub has_upstream_error: bool,
pub upstream_error_message: Option<String>,
pub retry_after_ms: Option<u64>,
pub error_code: Option<String>,
pub error_message: Option<String>,
pub error_kind: Option<String>,
@@ -961,6 +963,17 @@ pub struct UsageListRecord {
pub started_at: DateTime<Utc>,
}
// 上游错误原文只交付给管理端,避免整行调试输出带出正文
impl std::fmt::Debug for UsageListRecord {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("UsageListRecord")
.field("id", &self.id)
.field("outcome", &self.outcome)
.finish_non_exhaustive()
}
}
/// 受控请求详情中的上游错误字段,不参与错误分类或普通日志输出
#[derive(Clone, PartialEq)]
pub struct UsageUpstreamError {
@@ -1169,6 +1182,7 @@ pub struct DiagnosticsObservation {
pub struct DiagnosticObservation {
pub key: String,
pub name: String,
pub account_email: Option<String>,
pub providers: Vec<String>,
pub platform_icon: Option<String>,
pub account_authentication_kind: Option<String>,
@@ -1647,6 +1661,7 @@ pub struct DiagnosticsItem {
pub platform_icon: Option<String>,
pub key: String,
pub name: String,
pub account_email: Option<String>,
pub account_authentication_kind: Option<String>,
pub account_plan_type: Option<String>,
/// 仅账号维度补充当前互联识别结果
@@ -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;
@@ -50,11 +50,13 @@ 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,
pub update_channel: String,
pub latest_version: String,
pub latest_version: Option<String>,
pub has_update: bool,
pub update_cached: bool,
pub update_warning: Option<String>,
@@ -67,7 +69,7 @@ pub struct SystemVersion {
pub struct SystemUpdateDetail {
pub policy: SystemUpdatePolicy,
pub current_version: String,
pub latest_version: String,
pub latest_version: Option<String>,
pub has_update: bool,
pub deployment_mode: String,
pub build_type: 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(())
}
}
@@ -1342,7 +1342,8 @@ impl AccountsService for DefaultAccountsService {
.map(ToOwned::to_owned);
let upstream_body = error
.upstream_response()
.map(|response| String::from_utf8_lossy(response.body()).into_owned());
.and_then(gateway_core::engine::probe::AccountProbeUpstreamResponse::body)
.map(|body| String::from_utf8_lossy(body).into_owned());
let message = error.client_message().to_owned();
vec![AccountConnectionTestEvent::Failed {
source: error.source(),
@@ -4,7 +4,7 @@ mod flow;
use std::sync::Arc;
use gateway_core::{routing::ProviderKind, runtime::SnapshotControl};
use gateway_core::{account::ProviderAccountId, routing::ProviderKind, runtime::SnapshotControl};
use crate::{
model::AdminError,
@@ -40,6 +40,20 @@ impl CredentialsService {
}
}
/// 已有账号的凭据操作按已保存的归属选择 Provider
pub async fn for_account(
&self,
account_id: &ProviderAccountId,
) -> Result<ProviderCredentials, AdminError> {
let account = self
.accounts
.load_account_record(account_id)
.await
.map_err(|error| super::map_store_error(error, "provider credentials"))?
.ok_or_else(|| AdminError::not_found("账号不存在"))?;
self.for_provider(&account.provider_kind)
}
pub fn for_provider(&self, kind: &ProviderKind) -> Result<ProviderCredentials, AdminError> {
let provider = self
.providers
@@ -379,6 +379,7 @@ impl ObservabilityService for DefaultObservabilityService {
account_upstream_peer: peers.get(&item.key).copied(),
key: item.key,
name: item.name,
account_email: item.account_email,
account_authentication_kind: item.account_authentication_kind,
account_plan_type_display: self.historical_plan_display(
item.account_plan_type_display,
@@ -1,5 +1,108 @@
//! 按 Provider 组织凭据导入、授权与提交边界测试
//! 验证账号归属分派,并组织凭据导入、授权与提交边界测试
mod openai;
mod peer;
mod xai;
use gateway_admin::model::{
AdminErrorKind,
provider_credentials::{CredentialMutation, RotateCredential},
};
use gateway_core::account::ProviderAccountId;
use super::{
AdminHarness,
accounts::{
FakeAccountStore, FakeProviderAdmin, account_record, context, document, events, recorded,
revision,
},
};
#[tokio::test]
async fn account_rotation_should_dispatch_by_saved_provider_for_each_authentication_kind() {
for kind in ["openai", "xai", "antigravity"] {
for authentication in ["oauth", "api_key"] {
let store_events = events();
let mut account = account_record(kind);
account.authentication_kind = authentication.to_owned();
if authentication == "api_key" {
account.upstream_user_id = None;
account.has_refresh_token = false;
account.access_token_expires_at = None;
account.next_refresh_at = None;
}
let account_id = ProviderAccountId::new(account.id.clone()).unwrap();
let store = FakeAccountStore::with_account(account, store_events.clone());
let mut harness = AdminHarness::new().accounts(store.clone());
let mut provider_events = Vec::new();
for registered_kind in ["openai", "xai", "antigravity"] {
let calls = events();
harness = harness.provider(FakeProviderAdmin::new(registered_kind, calls.clone()));
provider_events.push((registered_kind, calls));
}
let services = harness.build().await;
let result = services
.credentials()
.for_account(&account_id)
.await
.expect("select saved provider")
.rotate(RotateCredential {
mutation: CredentialMutation {
context: context("rotate-account-connection"),
account_id: account_id.clone(),
},
settings: None,
provider_material: document(),
})
.await
.expect("rotate selected account");
assert_eq!(result.account_id, account_id);
assert_eq!(result.credential_revision, Some(revision(2)));
assert_eq!(store.audit_requests(), ["rotate-account-connection"]);
assert_eq!(
recorded(&store_events),
[
"store.load_account_record",
"store.credential_details",
"store.commit_rotation",
]
);
for (registered_kind, calls) in provider_events {
let expected: &[&str] = if registered_kind == kind {
&[
"provider.prepare_rotation",
"guard.finish",
"provider.account_facts_changed",
]
} else {
&[]
};
assert_eq!(recorded(&calls), expected, "{kind}/{authentication}");
}
}
}
}
#[tokio::test]
async fn missing_account_should_stop_credential_dispatch_before_provider_or_store_mutation() {
let store_events = events();
let provider_events = events();
let store = FakeAccountStore::new("openai", store_events.clone());
let mut harness = AdminHarness::new().accounts(store.clone());
for kind in ["openai", "xai", "antigravity"] {
harness = harness.provider(FakeProviderAdmin::new(kind, provider_events.clone()));
}
let services = harness.build().await;
let error = services
.credentials()
.for_account(&ProviderAccountId::new("acct_missing").unwrap())
.await
.err()
.expect("missing account must fail before selecting a provider");
assert_eq!(error.kind(), AdminErrorKind::NotFound);
assert_eq!(recorded(&store_events), ["store.load_account_record"]);
assert!(recorded(&provider_events).is_empty());
assert!(store.audit_requests().is_empty());
}
@@ -454,6 +454,8 @@ fn total_record(
platform_icon: None,
provider_account_upstream_peer: None,
has_upstream_error: false,
upstream_error_message: None,
retry_after_ms: None,
error_code: None,
error_message: None,
error_kind: None,
@@ -550,6 +552,7 @@ fn diagnostic(name: &str, request_count: u64) -> DiagnosticObservation {
account_plan_type_display: None,
key: name.to_owned(),
name: name.to_owned(),
account_email: None,
request_count,
success_count: request_count,
failure_count: 0,
@@ -27,12 +27,14 @@ 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(),
update_channel: "stable".to_owned(),
latest_version: "1.0.0".to_owned(),
latest_version: None,
has_update: false,
update_cached: false,
update_warning: None,
@@ -50,7 +52,7 @@ impl SystemOperations for RecordingSystemOperations {
available_channels: vec![gateway_admin::model::system::SystemUpdateChannel::Stable],
},
current_version: "1.0.0".to_owned(),
latest_version: "1.0.0".to_owned(),
latest_version: None,
has_update: false,
deployment_mode: "source".to_owned(),
build_type: "source".to_owned(),
@@ -288,13 +288,13 @@ impl UpdateAccountRequest {
}
}
/// 编辑 OpenAI 账号的连接设置;OAuth 仅接受传输方式
/// 连接字段由 Provider 按账号类型校验,未提供的选项不注入凭据文档
#[derive(Clone, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct AccountConnectionUpdateRequest {
pub protocol: Option<String>,
pub base_url: Option<String>,
pub transport: String,
pub transport: Option<String>,
pub api_key: Option<String>,
}
@@ -310,7 +310,11 @@ impl AccountConnectionUpdateRequest {
if let Some(base_url) = &self.base_url {
require_text(base_url, 2048, "connection.baseUrl")?;
}
if !matches!(self.transport.as_str(), "http" | "prefer_websocket") {
if self
.transport
.as_deref()
.is_some_and(|transport| !matches!(transport, "http" | "prefer_websocket"))
{
return Err(WireValidationError::new("connection.transport"));
}
if self.api_key.as_ref().is_some_and(|key| {
@@ -324,8 +328,10 @@ impl AccountConnectionUpdateRequest {
}
fn into_document(self) -> ProviderDocument {
let mut material =
Map::from_iter([("transport".to_owned(), Value::String(self.transport))]);
let mut material = Map::new();
if let Some(transport) = self.transport {
material.insert("transport".to_owned(), Value::String(transport));
}
if let Some(protocol) = self.protocol {
material.insert("protocol".to_owned(), Value::String(protocol));
}
@@ -281,13 +281,13 @@ where
let (command, connection) = request.into_command().map_err(map_wire_error)?;
let context = auth.context().mutation_context();
let result = if let Some(provider_material) = connection {
let provider = ProviderKind::new("openai").map_err(|_| AdminError::internal())?;
let account_id = ProviderAccountId::new(command.account_id.clone())
.map_err(|_| AdminError::internal())?;
let result = state
.admin_services()
.credentials()
.for_provider(&provider)
.for_account(&account_id)
.await
.map_err(map_service_error)?
.rotate(RotateCredential {
mutation: CredentialMutation {
@@ -203,7 +203,7 @@ fn parse_provider(value: &str) -> Result<Option<ProviderKind>, WireValidationErr
fn parse_sort_field(value: &str) -> Option<AccountSortField> {
match value.trim() {
"email" => Some(AccountSortField::Email),
"name" => Some(AccountSortField::Name),
"status" => Some(AccountSortField::Status),
"planType" => Some(AccountSortField::PlanType),
"usage" => Some(AccountSortField::Usage),
@@ -263,6 +263,8 @@ pub(crate) fn usage_list_record_view(
upstream_status_code: record.upstream_status_code,
error_code: record.error_code,
error_message: record.error_message,
upstream_error_message: record.upstream_error_message,
retry_after_ms: record.retry_after_ms,
error_kind: record.error_kind,
websocket_close_code: record.websocket_close_code,
continuation_unavailable_reason: record.continuation_unavailable_reason,
@@ -1354,13 +1356,14 @@ pub(crate) fn diagnostics_view(
.map(|item| DiagnosticItemView {
providers: item.providers,
platform_icon: item.platform_icon,
key: item.key,
account_email: item.account_email,
authentication_kind: item.account_authentication_kind,
name: if item.name == "__none__" {
name: if item.key == "__none__" {
"未知".to_owned()
} else {
item.name
},
key: item.key,
request_count: item.request_count,
account_plan_type: item.account_plan_type,
account_plan_type_display: item.account_plan_type_display,
@@ -92,6 +92,8 @@ pub struct UsageListRecordView {
pub upstream_status_code: Option<u16>,
pub error_code: Option<String>,
pub error_message: Option<String>,
pub upstream_error_message: Option<String>,
pub retry_after_ms: Option<u64>,
pub error_kind: Option<String>,
pub websocket_close_code: Option<u16>,
pub continuation_unavailable_reason: Option<String>,
@@ -878,6 +880,7 @@ pub struct DiagnosticItemView {
pub platform_icon: Option<String>,
pub key: String,
pub name: String,
pub account_email: Option<String>,
pub authentication_kind: Option<String>,
pub account_plan_type: Option<String>,
pub account_plan_type_display: Option<String>,
@@ -81,12 +81,14 @@ 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,
deployment_mode_label: String,
update_channel: String,
latest_version: String,
latest_version: Option<String>,
has_update: bool,
update_cached: bool,
update_warning: Option<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,
@@ -114,7 +118,7 @@ impl From<SystemVersion> for SystemVersionView {
struct SystemUpdateDetailView {
policy: SystemUpdatePolicy,
current_version: String,
latest_version: String,
latest_version: Option<String>,
has_update: bool,
deployment_mode: String,
deployment_mode_label: String,
@@ -72,10 +72,6 @@ pub(crate) fn client_error_code(code: &str) -> &str {
}
}
pub(crate) fn is_retry_after_header(name: &str) -> bool {
name.eq_ignore_ascii_case("retry-after") || name.eq_ignore_ascii_case("retry-after-ms")
}
/// 为 HTTP 错误或流内失败保留原有字段,仅投影客户端需要的重试信号
pub(crate) fn capacity_error_for_client(data: &Value) -> Option<Value> {
const CODE_PATHS: [&str; 2] = ["/error/code", "/response/error/code"];
@@ -91,12 +87,6 @@ pub(crate) fn capacity_error_for_client(data: &Value) -> Option<Value> {
return None;
}
let mut projected = data.clone();
// 容量等待与换号已由网关执行;旧账号的等待提示不能再次阻塞客户端的新一轮路由
for path in ["/headers", "/error/headers", "/response/error/headers"] {
if let Some(Value::Object(headers)) = projected.pointer_mut(path) {
headers.retain(|name, _| !is_retry_after_header(name));
}
}
for path in CODE_PATHS {
if let Some(code) = projected.pointer_mut(path)
&& capacity_code(code)
@@ -11,11 +11,12 @@ 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;
use crate::client_error::{ProtocolErrorBody, capacity_error_for_client, is_retry_after_header};
use crate::client_error::{ProtocolErrorBody, capacity_error_for_client};
pub use crate::client_error::{
gateway_error_contract, gateway_error_response, openai_error_response,
@@ -109,6 +110,24 @@ pub fn model_not_found_response() -> (StatusCode, Json<Value>) {
)
}
/// 将上游实际给出的等待头交给客户端错误事件
pub(crate) fn upstream_retry_headers(error: &EngineError) -> serde_json::Map<String, Value> {
let mut headers = Vec::new();
if let EngineError::Provider(provider) = error {
provider.extend_client_retry_headers(&mut headers, &[]);
}
headers
.into_iter()
.filter_map(|header| {
let value = HeaderValue::from_bytes(header.value()).ok()?;
Some((
header.name().to_ascii_lowercase(),
Value::String(value.to_str().ok()?.to_owned()),
))
})
.collect()
}
/// 在下游尚未提交时交付 Provider 的 HTTP 失败响应,并应用客户端容量恢复合同
pub fn engine_error_response(error: &EngineError) -> Response {
let capacity_unavailable = matches!(error, EngineError::Provider(error)
@@ -122,7 +141,6 @@ pub fn engine_error_response(error: &EngineError) -> Response {
let projected = serde_json::from_slice::<Value>(upstream.body())
.ok()
.and_then(|body| capacity_error_for_client(&body));
let suppress_retry_after = capacity_unavailable || projected.is_some();
let mut response = match projected {
Some(body) => {
let mut response = Response::new(Body::from(body.to_string()));
@@ -145,9 +163,6 @@ pub fn engine_error_response(error: &EngineError) -> Response {
response.headers_mut().insert(CONTENT_TYPE, content_type);
}
for header in upstream.headers() {
if suppress_retry_after && is_retry_after_header(header.name()) {
continue;
}
let Ok(name) = HeaderName::from_bytes(header.name().as_bytes()) else {
continue;
};
@@ -156,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);
}
@@ -830,7 +831,10 @@ impl StreamingExecutionBody {
}
Ok(None) => return Err(invalid_execution_stream()),
Err(error) if self.committed => {
self.push_stream_error(gateway_error_from_engine(&error));
self.push_stream_error(
gateway_error_from_engine(&error),
crate::data_plane::error::upstream_retry_headers(&error),
);
continue;
}
Err(error) => return Err(MiddlewareError::Engine(error)),
@@ -893,9 +897,13 @@ impl StreamingExecutionBody {
}
}
fn push_stream_error(&mut self, error: GatewayError) {
fn push_stream_error(
&mut self,
error: GatewayError,
headers: serde_json::Map<String, serde_json::Value>,
) {
self.pending.push_back(MiddlewareFrame::new(
self.encoder.error_frame(&error),
self.encoder.error_frame(&error, headers),
MiddlewareFraming::SseEvent,
false,
));
@@ -935,7 +943,7 @@ impl MiddlewareBody for StreamingExecutionBody {
"Gateway response stream could not be delivered.",
),
};
self.push_stream_error(error);
self.push_stream_error(error, Default::default());
}
Ok(self.pending.pop_front())
})
@@ -972,7 +980,7 @@ impl MiddlewareBody for StreamingExecutionBody {
"The Chat response could not be finalized.",
),
};
self.push_stream_error(error);
self.push_stream_error(error, Default::default());
}
}
}
@@ -113,15 +113,9 @@ async fn stream_failure(
error_encoder: Option<fn(&Value) -> Bytes>,
append_done: bool,
) -> Body {
let status = response.status();
let retry_after = response
.headers()
.get(header::RETRY_AFTER)
.and_then(|value| value.to_str().ok())
.map(ToOwned::to_owned);
let bytes = to_bytes(response.into_body(), usize::MAX)
.await
.unwrap_or_default();
let (parts, body) = response.into_parts();
let status = parts.status;
let bytes = to_bytes(body, usize::MAX).await.unwrap_or_default();
let json = serde_json::from_slice::<Value>(&bytes).ok();
let raw_message = std::str::from_utf8(&bytes)
.ok()
@@ -144,16 +138,20 @@ async fn stream_failure(
)
});
// HTTP 头已提交,按官方 SSE 错误合同保留允许下发的重试建议
if let Some(retry_after) = retry_after
&& let Some(error) = data["response"]["error"].as_object_mut()
&& let Some(headers) = error
.entry("headers")
.or_insert_with(|| serde_json::json!({}))
.as_object_mut()
{
headers
.entry("retry-after")
.or_insert(Value::String(retry_after));
for name in gateway_protocol::http::RETRY_AFTER_HEADERS {
if let Some(value) = parts
.headers
.get(name)
.and_then(|value| value.to_str().ok())
&& let Some(error) = data["response"]["error"].as_object_mut()
&& let Some(headers) = error
.entry("headers")
.or_insert_with(|| serde_json::json!({}))
.as_object_mut()
&& !headers.keys().any(|key| key.eq_ignore_ascii_case(name))
{
headers.insert(name.to_owned(), Value::String(value.to_owned()));
}
}
let mut event = match error_encoder {
Some(encode) => encode(&data).to_vec(),
@@ -6,7 +6,8 @@ use gateway_protocol::anthropic::ANTHROPIC_PROTOCOL;
use gateway_protocol::{
anthropic::MessagesAccumulator,
openai::sse::{
DONE_SSE_FRAME, encode_sse_event_with_metadata, response_failed_sse_event_with_id,
DONE_SSE_FRAME, encode_sse_event, encode_sse_event_with_metadata,
response_failed_sse_data_with_id,
},
};
use serde_json::{Value, json};
@@ -159,7 +160,11 @@ impl GenerationEncoder {
}
}
pub(super) fn error_frame(&self, error: &GatewayError) -> Bytes {
pub(super) fn error_frame(
&self,
error: &GatewayError,
headers: serde_json::Map<String, Value>,
) -> Bytes {
let (status, error_type, code) = gateway_error_contract(error.kind());
match self {
Self::Chat(_) => {
@@ -169,12 +174,21 @@ impl GenerationEncoder {
"message": error.client_message(),
}}))
}
Self::Responses(encoder) => Bytes::from(response_failed_sse_event_with_id(
encoder.response_id(),
error.client_error_type().unwrap_or(error_type),
crate::client_error::client_error_code(error.client_error_code().unwrap_or(code)),
error.client_message(),
)),
Self::Responses(encoder) => {
let mut data = response_failed_sse_data_with_id(
encoder.response_id(),
error.client_error_type().unwrap_or(error_type),
crate::client_error::client_error_code(
error.client_error_code().unwrap_or(code),
),
error.client_message(),
);
if !headers.is_empty() {
data["response"]["error"]["headers"] = json!(headers);
data["error"]["headers"] = Value::Object(headers);
}
Bytes::from(encode_sse_event("response.failed", &data.to_string()))
}
Self::GenAi { .. } => {
crate::data_plane::genai::error_frame(status, error.client_message())
}
@@ -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(
@@ -575,7 +575,10 @@ impl WebSocketExecutionBody {
Ok(Some(delivery)) => delivery,
Ok(None) => return Err(MiddlewareError::InvalidState),
Err(error) if self.committed => {
self.push_gateway_error(gateway_error_from_engine(&error));
self.push_gateway_error(
gateway_error_from_engine(&error),
crate::data_plane::error::upstream_retry_headers(&error),
);
continue;
}
Err(error) => return Err(MiddlewareError::Engine(error)),
@@ -635,7 +638,11 @@ impl WebSocketExecutionBody {
Ok(())
}
fn push_gateway_error(&mut self, error: GatewayError) {
fn push_gateway_error(
&mut self,
error: GatewayError,
headers: serde_json::Map<String, serde_json::Value>,
) {
let (status, default_type, default_code) = gateway_error_contract(error.kind());
self.pending.push_back(MiddlewareFrame::new(
Bytes::from(
@@ -646,7 +653,7 @@ impl WebSocketExecutionBody {
error.client_message(),
None,
Some(&self.request_id),
serde_json::Map::new(),
headers,
)
.to_string(),
),
@@ -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;
@@ -173,12 +177,18 @@ pub(super) fn initial_engine_error_event(
};
let upstream = provider.and_then(|error| error.client_visible_upstream_response());
// 最终失败响应优先于会话快照,避免混入先前 attempt 或 opening 的关联头
let mut headers =
response_event_headers(upstream.map_or(response_headers, |response| response.headers()));
let mut headers = if let Some((provider, response)) = provider.zip(upstream) {
let mut headers = response.headers().to_vec();
provider.extend_client_retry_headers(&mut headers, &[]);
response_event_headers(&headers)
} else {
response_event_headers(response_headers)
};
if upstream.is_none() {
// 会话 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)
@@ -216,7 +226,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>()
@@ -639,14 +639,22 @@ async fn connection_update_requires_admin_and_validates_before_calling_the_servi
"connection":{"baseUrl":"https://api.example.invalid/v1", "transport":"http"}
});
for (authenticated, transport, oauth, expected) in [
(false, "http", false, StatusCode::UNAUTHORIZED),
(true, "invalid", false, StatusCode::BAD_REQUEST),
(false, Some("http"), false, StatusCode::UNAUTHORIZED),
(true, Some("invalid"), false, StatusCode::BAD_REQUEST),
// 夹具没有凭据 Store,合法输入必须进入服务,不能按普通设置静默保存
(true, "http", false, StatusCode::SERVICE_UNAVAILABLE),
(true, "http", true, StatusCode::SERVICE_UNAVAILABLE),
(true, Some("http"), false, StatusCode::SERVICE_UNAVAILABLE),
(true, Some("http"), true, StatusCode::SERVICE_UNAVAILABLE),
(true, None, false, StatusCode::SERVICE_UNAVAILABLE),
] {
let mut input = input.clone();
input["connection"]["transport"] = serde_json::json!(transport);
if let Some(transport) = transport {
input["connection"]["transport"] = serde_json::json!(transport);
} else {
input["connection"]
.as_object_mut()
.unwrap()
.remove("transport");
}
if oauth {
input["connection"]
.as_object_mut()
@@ -126,7 +126,7 @@ mod query {
"provider": "xai",
"search": " operator ",
"status": "normal",
"sortBy": "lastUsedAt",
"sortBy": "name",
"sortDirection": "desc"
}))
.expect("deserialize account query");
@@ -139,10 +139,7 @@ mod query {
));
assert_eq!(query.search.as_deref(), Some("operator"));
assert_eq!(query.status, Some(AccountStatus::Normal));
assert_eq!(
query.sort.expect("sort").field,
AccountSortField::LastUsedAt
);
assert_eq!(query.sort.expect("sort").field, AccountSortField::Name);
assert_eq!(
query.sort.expect("copy sort").direction,
SortDirection::Desc
@@ -727,6 +724,20 @@ mod actions {
);
}
#[test]
fn native_api_key_connection_accepts_address_and_key_without_transport() {
let request: UpdateAccountRequest = serde_json::from_value(json!({
"accountId":"acct_api", "enabled":true, "concurrencyLimit":null,
"weight":1, "groupIds":[],
"connection":{"baseUrl":"https://relay.example/antigravity/v1beta","apiKey":"fixture-key"}
})).unwrap();
request.validate().unwrap();
let connection = request.connection.unwrap();
assert!(connection.protocol.is_none());
assert!(connection.transport.is_none());
assert_eq!(connection.api_key.as_deref(), Some("fixture-key"));
}
#[test]
fn account_connection_update_rejects_invalid_fields_and_generic_credentials() {
let request = json!({
@@ -753,7 +753,8 @@ async fn diagnostics_should_keep_stable_key_and_display_name_contract() {
account_authentication_kind: authentication_kind.map(str::to_owned),
account_plan_type: plan_type.map(str::to_owned),
account_plan_type_display: None,
name: "diag@example.invalid".to_owned(),
account_email: Some("diag@example.invalid".to_owned()),
name: "__none__".to_owned(),
request_count: 2,
success_count: 2,
failure_count: 0,
@@ -813,11 +814,13 @@ async fn diagnostics_should_keep_stable_key_and_display_name_contract() {
(
&value["data"]["items"][0]["key"],
&value["data"]["items"][0]["name"],
&value["data"]["items"][0]["accountEmail"],
&value["data"]["items"][0]["latencyP95Ms"],
&value["data"]["dimension"],
),
(
&serde_json::json!("acct_diag"),
&serde_json::json!("__none__"),
&serde_json::json!("diag@example.invalid"),
&serde_json::json!(3800),
&serde_json::json!("account"),
@@ -987,6 +990,8 @@ async fn usage_route_projects_request_facts_and_billing() {
platform_icon: None,
provider_account_upstream_peer: None,
has_upstream_error: false,
upstream_error_message: None,
retry_after_ms: None,
error_code: None,
error_message: None,
error_kind: None,
@@ -1089,6 +1094,8 @@ async fn usage_route_projects_request_facts_and_billing() {
failed.upstream_status_code = Some(429);
failed.error_code = Some("server_error".to_owned());
failed.error_message = Some("The upstream service is temporarily unavailable.".to_owned());
failed.upstream_error_message = Some("Retry once capacity is available.".to_owned());
failed.retry_after_ms = Some(30_000);
records.push(failed);
let mut closed = records[0].clone();
closed.id = "request_ws_closed".to_owned();
@@ -1131,6 +1138,11 @@ async fn usage_route_projects_request_facts_and_billing() {
assert!(value["data"]["items"][0]["errorCode"].is_null());
assert!(value["data"]["items"][0]["errorMessage"].is_null());
assert_eq!(value["data"]["items"][3]["errorCode"], "server_error");
assert_eq!(
value["data"]["items"][3]["upstreamErrorMessage"],
"Retry once capacity is available."
);
assert_eq!(value["data"]["items"][3]["retryAfterMs"], 30_000);
assert_eq!(value["data"]["items"][3]["clientStatusCode"], 503);
assert_eq!(value["data"]["items"][3]["upstreamStatusCode"], 429);
assert_eq!(value["data"]["items"][3]["errorOrigin"], "upstream");
@@ -1540,7 +1540,7 @@ async fn runtime_settings_reject_incomplete_and_stale_replacements() {
);
assert_eq!(
initial["openaiRequestSettings"]["requestCountry"],
json!({"mode":"follow_location"})
json!({"mode":"default"})
);
let mut body = update_body();
body["configRevision"] = initial["configRevision"].clone();
@@ -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");
@@ -216,7 +237,7 @@ impl SystemOperations for ProgressSystem {
available_channels: vec![SystemUpdateChannel::Stable, SystemUpdateChannel::Beta],
},
current_version: "0.1.0".into(),
latest_version: "0.2.0".into(),
latest_version: Some("0.2.0".into()),
has_update: true,
deployment_mode: "docker".into(),
build_type: "release".into(),
@@ -256,12 +256,20 @@ 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"}]}
]);
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]
@@ -101,8 +101,8 @@ async fn capacity_errors_offer_client_retry_without_changing_upstream_facts() {
assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
if raw_response {
assert_eq!(response.headers()["x-request-id"], "req_capacity");
assert!(!response.headers().contains_key("retry-after"));
assert!(!response.headers().contains_key("retry-after-ms"));
assert_eq!(response.headers()["retry-after"], "7");
assert_eq!(response.headers()["retry-after-ms"], "7000");
}
let body: Value = serde_json::from_slice(
&to_bytes(response.into_body(), 4096)
@@ -116,7 +116,6 @@ async fn capacity_errors_offer_client_retry_without_changing_upstream_facts() {
if raw_response {
let mut expected = original.clone();
expected["error"]["code"] = json!("server_error");
expected["error"]["headers"] = json!({"x-request-id":"req_capacity"});
assert_eq!(body, expected);
}
let EngineError::Provider(provider) = error else {
@@ -397,16 +396,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(
@@ -420,17 +419,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]
@@ -509,6 +515,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,
@@ -517,11 +524,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]
@@ -578,19 +593,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)
);
}
}
@@ -1416,7 +1416,7 @@ async fn streaming_bad_request_preserves_extended_error_fields_before_and_after_
Some(b"application/json".to_vec()),
Bytes::from(json!({"error": error}).to_string()),
)
.with_headers(headers(&[("retry-after", "7")])),
.with_headers(headers(&[("retry-after", "7"), ("retry-after-ms", "7012")])),
)
};
let immediate = FakeSession::streaming(
@@ -1447,7 +1447,7 @@ async fn streaming_bad_request_preserves_extended_error_fields_before_and_after_
.find(|event| event.event.as_deref() == Some("response.failed"))
.unwrap();
let payload: Value = serde_json::from_str(&failed.data).unwrap();
error["headers"] = json!({"retry-after": "7"});
error["headers"] = json!({"retry-after": "7", "retry-after-ms":"7012"});
assert_eq!(payload["response"]["error"], error);
assert!(bytes.ends_with(b"data: [DONE]\n\n"));
}
@@ -2214,14 +2214,13 @@ async fn streaming_upstream_wire_failure_should_not_be_rewritten_as_a_gateway_er
#[tokio::test]
async fn streaming_upstream_error_event_should_be_translated_to_response_failed_for_sse() {
for (error_type, code, client_code, kind, client_status, keeps_retry_after) in [
for (error_type, code, client_code, kind, client_status) in [
(
"service_unavailable_error",
"server_is_overloaded",
"server_error",
ProviderErrorKind::UpstreamCapacityUnavailable,
503,
false,
),
(
"rate_limit_error",
@@ -2229,7 +2228,6 @@ async fn streaming_upstream_error_event_should_be_translated_to_response_failed_
"turn_rate_limit_exceeded",
ProviderErrorKind::RateLimited,
429,
true,
),
] {
let trace = Arc::new(Trace::default());
@@ -2306,16 +2304,17 @@ async fn streaming_upstream_error_event_should_be_translated_to_response_failed_
.find(|event| event.event.as_deref() == Some("response.failed"))
.expect("translated response.failed event");
let failed: Value = serde_json::from_str(&failed.data).expect("response.failed JSON");
let mut expected = json!({
let expected = json!({
"type": "response.failed",
"status": client_status,
"headers": {"x-request-id": "req_test"},
"headers": {"Retry-After": "24", "retry-after-ms": "24000", "x-request-id": "req_test"},
"response": {
"id": "resp_test",
"model": "public-model",
"status": "failed",
"error": {
"type": error_type,
"headers": {"retry-after": "24", "retry-after-ms": "24000"},
"code": client_code,
"message": "Our servers are currently overloaded. Please try again later.",
"param": null,
@@ -2326,11 +2325,6 @@ async fn streaming_upstream_error_event_should_be_translated_to_response_failed_
"sequence_number": 2,
"future_event_field": {"keep": true}
});
if keeps_retry_after {
expected["headers"]["Retry-After"] = json!("24");
expected["headers"]["retry-after-ms"] = json!("24000");
expected["response"]["error"]["headers"] = json!({"retry-after": "24"});
}
assert_eq!(
(
@@ -2346,18 +2340,38 @@ async fn streaming_upstream_error_event_should_be_translated_to_response_failed_
}
#[tokio::test]
async fn streaming_capacity_error_after_commit_offers_client_retry() {
for code in ["server_is_overloaded", "slow_down"] {
let trace = Arc::new(Trace::default());
let error = ProviderError::new(
async fn streaming_errors_after_commit_preserve_upstream_retry_headers() {
for (kind, code, expected) in [
(
ProviderErrorKind::UpstreamCapacityUnavailable,
UpstreamSendState::Sent,
)
.with_client_visible_upstream_error(ClientVisibleUpstreamError::new(
"busy",
Some(code.to_owned()),
Some("service_unavailable_error".to_owned()),
));
"server_is_overloaded",
"server_error",
),
(
ProviderErrorKind::UpstreamCapacityUnavailable,
"slow_down",
"server_error",
),
(
ProviderErrorKind::QuotaExhausted,
"previous_response_not_found",
"previous_response_not_found",
),
] {
let trace = Arc::new(Trace::default());
let error = ProviderError::new(kind, UpstreamSendState::Sent)
.with_client_visible_upstream_response(
ClientVisibleUpstreamResponse::new(400, None, Bytes::new()).with_headers(vec![
ProviderResponseHeader::new("Retry-After", Bytes::from_static(b"309")),
ProviderResponseHeader::new("retry-after-ms", Bytes::from_static(b"309001")),
ProviderResponseHeader::new("x-unrelated", Bytes::from_static(b"omit")),
]),
)
.with_client_visible_upstream_error(ClientVisibleUpstreamError::new(
"busy",
Some(code.to_owned()),
Some("service_unavailable_error".to_owned()),
));
let session = FakeSession::streaming(
Arc::clone(&trace),
vec![
@@ -2377,7 +2391,11 @@ async fn streaming_capacity_error_after_commit_offers_client_retry() {
.find(|event| event.event.as_deref() == Some("response.failed"))
.expect("failed event");
let failed: Value = serde_json::from_str(&failed.data).expect("JSON");
assert_eq!(failed["response"]["error"]["code"], "server_error");
assert_eq!(failed["response"]["error"]["code"], expected);
assert_eq!(
failed["response"]["error"]["headers"],
json!({"retry-after": "309", "retry-after-ms": "309001"})
);
assert_eq!(failed["response"]["error"]["message"], "busy");
assert_eq!(text.matches("event: response.failed").count(), 1);
assert!(text.ends_with("data: [DONE]\n\n"));
@@ -3282,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"),
@@ -3297,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] {
@@ -3325,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
@@ -3341,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 {
@@ -3349,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(
@@ -3359,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);
}
@@ -3376,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);
}
}
@@ -3396,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"
@@ -1256,16 +1256,12 @@ fn capacity_failure_projection_preserves_wire_metadata_and_original_events() {
assert_eq!(sse_data["response"]["error"]["code"], "server_error");
assert_eq!(sse_data["response"]["error"]["message"], "busy");
assert_eq!(sse_data["response"]["error"]["future"], 42);
assert_eq!(
sse_data["response"]["error"]["headers"],
json!({"x-request-id":"req_capacity"})
);
assert_eq!(sse_data["response"]["error"]["headers"], error["headers"]);
let messages = ws.push_websocket(&event);
let ws_data: Value = serde_json::from_str(&messages[0]).expect("JSON");
if event_type == "error" && status.is_some() {
let mut expected = original.clone();
expected["error"]["code"] = json!("server_error");
expected["error"]["headers"] = json!({"x-request-id":"req_capacity"});
expected["status_code"] = json!(503);
assert_eq!(ws_data, expected);
} else {
@@ -340,8 +340,8 @@ async fn initial_capacity_failure_offers_client_retry_with_upstream_correlation(
assert_eq!(error["error"]["code"], "server_error");
assert_eq!(error["error"]["message"], "busy");
assert_eq!(error["headers"]["x-request-id"], "req_capacity");
assert!(error["headers"].get("retry-after").is_none());
assert!(error["headers"].get("retry-after-ms").is_none());
assert_eq!(error["headers"]["retry-after"], "7");
assert_eq!(error["headers"]["retry-after-ms"], "7000");
}
}
}
@@ -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 {
@@ -720,7 +770,9 @@ async fn initial_quota_recovery_delivers_client_projection_instead_of_upstream_s
ClientVisibleUpstreamResponse::new(
400,
Some(b"application/json".to_vec()),
Bytes::from(json!({"error":detail}).to_string()),
Bytes::from(
json!({"error":detail, "headers":{"Retry-After-Ms":"777"}}).to_string(),
),
)
.with_headers(vec![header("x-request-id", b"req-quota-rejected")]),
);
@@ -729,6 +781,7 @@ async fn initial_quota_recovery_delivers_client_projection_instead_of_upstream_s
assert_eq!(error["error"], detail);
assert_eq!(error["headers"]["x-request-id"], "req-quota-rejected");
assert!(error["headers"].get("retry-after").is_none());
assert_eq!(error["headers"]["retry-after-ms"], "777");
}
#[tokio::test]
@@ -743,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")
}));
}
@@ -104,6 +104,8 @@ fn usage_record() -> UsageListRecord {
platform_icon: None,
provider_account_upstream_peer: None,
has_upstream_error: false,
upstream_error_message: Some("private-sentinel-upstream".into()),
retry_after_ms: Some(30_000),
error_code: None,
error_message: None,
error_kind: None,
@@ -91,12 +91,14 @@ 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(),
update_channel: "release".to_owned(),
latest_version: "3.8.0".to_owned(),
latest_version: Some("3.8.0".to_owned()),
has_update: true,
update_cached: true,
update_warning: Some("internal-update-warning".to_owned()),
@@ -21,6 +21,8 @@ pub use quota_settings::{
};
mod proxy;
pub use proxy::{InvalidOutboundProxy, OutboundProxy};
mod recent_requests;
pub use recent_requests::{InvalidRecentRequestSnapshot, RecentRequestSnapshot};
mod scheduling;
pub mod scope;
mod selection;
@@ -36,6 +38,6 @@ pub(crate) use selection::smart_score;
pub use selection::*;
pub use store::{
AccountCatalogObservation, AccountCatalogOmissions, ProviderAccountStore, QuotaWarmupState,
QuotaWarmupStateUpdate, StoredAccountCatalog,
QuotaWarmupStateUpdate, RecentRequestStore, StoredAccountCatalog,
};
pub use upstream::*;
@@ -0,0 +1,230 @@
//! 账号与模型的近期请求计数,按秒滚动并在进程内回收过期记录
use std::collections::HashMap;
use std::time::{Duration, Instant, SystemTime};
use crate::identity::ProviderKind;
use super::ProviderAccountId;
const WINDOW_SECONDS: u64 = 60;
/// 快照内容不满足账号标识、秒桶或计数约束
#[derive(Debug, Clone, Copy, thiserror::Error)]
#[error("recent request snapshot is invalid")]
pub struct InvalidRecentRequestSnapshot;
/// 可丢失的近期请求快照,保留观测时间与每个秒桶的年龄
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct RecentRequestSnapshot {
captured_at: SystemTime,
windows: Vec<PersistedWindow>,
}
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
struct PersistedWindow {
provider: ProviderKind,
account: String,
model: String,
buckets: Vec<(Duration, u64)>,
}
#[derive(Debug)]
pub(super) struct RecentRequests {
epoch: Instant,
last_cleanup: u64,
windows: HashMap<(ProviderKind, ProviderAccountId, String), RequestWindow>,
}
#[derive(Debug)]
struct RequestWindow {
buckets: [u64; WINDOW_SECONDS as usize],
second: u64,
total: u64,
}
impl RequestWindow {
fn advance(&mut self, second: u64) {
let elapsed = second.saturating_sub(self.second);
if elapsed >= WINDOW_SECONDS {
self.buckets.fill(0);
self.total = 0;
} else {
for offset in 1..=elapsed {
let index = ((self.second + offset) % WINDOW_SECONDS) as usize;
self.total -= self.buckets[index];
self.buckets[index] = 0;
}
}
self.second = self.second.max(second);
}
}
impl Default for RecentRequests {
fn default() -> Self {
Self {
epoch: Instant::now(),
last_cleanup: 0,
windows: HashMap::new(),
}
}
}
impl RecentRequests {
pub(super) fn snapshot(&mut self, now: Instant, wall_now: SystemTime) -> RecentRequestSnapshot {
let second = self.second(now);
let mut windows = Vec::with_capacity(self.windows.len());
for ((provider, account, model), window) in &mut self.windows {
window.advance(second);
if window.total == 0 {
continue;
}
let buckets = (0..WINDOW_SECONDS.min(second + 1))
.filter_map(|age| {
let index = ((second - age) % WINDOW_SECONDS) as usize;
let count = window.buckets[index];
(count > 0).then(|| {
let started = self.epoch + Duration::from_secs(second - age);
(now.saturating_duration_since(started), count)
})
})
.collect();
windows.push(PersistedWindow {
provider: provider.clone(),
account: account.as_str().to_owned(),
model: model.clone(),
buckets,
});
}
RecentRequestSnapshot {
captured_at: wall_now,
windows,
}
}
pub(super) fn restore(
snapshot: RecentRequestSnapshot,
now: Instant,
wall_now: SystemTime,
) -> Result<Self, InvalidRecentRequestSnapshot> {
let mut restored = Self {
epoch: now,
last_cleanup: 0,
windows: HashMap::new(),
};
// 墙钟只用于跨进程计算停机时长,回拨或过期快照从空窗口重新积累
let Ok(downtime) = wall_now.duration_since(snapshot.captured_at) else {
return Ok(restored);
};
if downtime.as_secs() >= WINDOW_SECONDS {
return Ok(restored);
}
// 单调时钟无法容纳完整窗口时重新积累,避免延长历史计数寿命
let Some(epoch) = now.checked_sub(Duration::from_secs(WINDOW_SECONDS)) else {
return Ok(restored);
};
restored.epoch = epoch;
let second = restored.second(now);
for entry in snapshot.windows {
let account =
ProviderAccountId::new(entry.account).map_err(|_| InvalidRecentRequestSnapshot)?;
if entry.buckets.len() > WINDOW_SECONDS as usize {
return Err(InvalidRecentRequestSnapshot);
}
let mut window = RequestWindow {
buckets: [0; WINDOW_SECONDS as usize],
second,
total: 0,
};
for (age, count) in entry.buckets {
let age = age.saturating_add(downtime);
if age.as_secs() >= WINDOW_SECONDS || count == 0 {
continue;
}
let Some(started) = now.checked_sub(age) else {
continue;
};
let offset = started.saturating_duration_since(restored.epoch).as_secs();
let index = (offset % WINDOW_SECONDS) as usize;
window.buckets[index] = window.buckets[index]
.checked_add(count)
.ok_or(InvalidRecentRequestSnapshot)?;
window.total = window
.total
.checked_add(count)
.ok_or(InvalidRecentRequestSnapshot)?;
}
if window.total > 0 {
restored
.windows
.insert((entry.provider, account, entry.model), window);
}
}
Ok(restored)
}
fn second(&mut self, now: Instant) -> u64 {
let second = now
.checked_duration_since(self.epoch)
.unwrap_or_default()
.as_secs();
if second.saturating_sub(self.last_cleanup) >= WINDOW_SECONDS {
self.windows.retain(|_, window| {
window.advance(second);
window.total > 0
});
self.last_cleanup = second;
}
second
}
pub(super) fn record(
&mut self,
provider: &ProviderKind,
account: &ProviderAccountId,
model: &str,
started_at: Instant,
now: Instant,
) {
// 首个响应确认请求已发送,使用 attempt 开始时间,避免慢响应挤到完成时刻
if now.saturating_duration_since(started_at).as_secs() >= WINDOW_SECONDS {
return;
}
let second = self.second(now);
let started = started_at
.checked_duration_since(self.epoch)
.unwrap_or_default()
.as_secs();
let window = self
.windows
.entry((provider.clone(), account.clone(), model.to_owned()))
.or_insert(RequestWindow {
buckets: [0; WINDOW_SECONDS as usize],
second,
total: 0,
});
window.advance(second);
if window.second.saturating_sub(started) < WINDOW_SECONDS {
window.buckets[(started % WINDOW_SECONDS) as usize] += 1;
window.total += 1;
}
}
pub(super) fn count(
&mut self,
provider: &ProviderKind,
account: &ProviderAccountId,
model: &str,
now: Instant,
) -> u64 {
let second = self.second(now);
let Some(window) =
self.windows
.get_mut(&(provider.clone(), account.clone(), model.to_owned()))
else {
return 0;
};
window.advance(second);
window.total
}
}
@@ -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]
@@ -257,6 +257,8 @@ impl AccountSelectionPolicy {
pub struct AccountRuntimeSignals {
/// 本次调度容量池的在途数,不合并其他独立池
pub in_flight: u32,
/// 同模型最近一分钟已确认发送的请求数,按秒滚动
pub recent_requests: u64,
pub last_started_at: Option<SystemTime>,
pub quota_reset_at: Option<SystemTime>,
pub quota_reset_windows: Option<Arc<[AccountQuotaResetWindow]>>,
@@ -368,9 +370,82 @@ impl AccountFeedback {
#[derive(Debug, Default)]
pub struct AccountFeedbackStats {
accounts: RwLock<HashMap<AccountFeedbackKey, AccountFeedback>>,
requests: Mutex<super::recent_requests::RecentRequests>,
}
impl AccountFeedbackStats {
/// 后台导出当前窗口,序列化与存储在释放锁后执行
#[must_use]
pub fn snapshot_recent_requests_at(
&self,
now: Instant,
wall_now: SystemTime,
) -> super::RecentRequestSnapshot {
self.requests
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.snapshot(now, wall_now)
}
/// 仅在数据面启动前恢复窗口,按实际停机时长淘汰过期请求
pub fn restore_recent_requests_at(
&self,
snapshot: super::RecentRequestSnapshot,
now: Instant,
wall_now: SystemTime,
) -> Result<(), super::InvalidRecentRequestSnapshot> {
let restored = super::recent_requests::RecentRequests::restore(snapshot, now, wall_now)?;
*self
.requests
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner) = restored;
Ok(())
}
/// 记录已确认发送的请求;同一 attempt 由 stream 边界保证只记录一次
pub fn record_request_at(
&self,
provider: &ProviderKind,
account: &ProviderAccountId,
model: &str,
started_at: Instant,
now: Instant,
) {
self.requests
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.record(provider, account, model, started_at, now);
}
/// 读取指定模型的近期负载,未知模型不参与比较
#[must_use]
pub fn recent_requests(
&self,
provider: &ProviderKind,
account: &ProviderAccountId,
model: Option<&str>,
) -> u64 {
self.recent_requests_at(provider, account, model, Instant::now())
}
/// 在指定单调时刻读取秒级滚动窗口
#[doc(hidden)]
#[must_use]
pub fn recent_requests_at(
&self,
provider: &ProviderKind,
account: &ProviderAccountId,
model: Option<&str>,
now: Instant,
) -> u64 {
model.map_or(0, |model| {
self.requests
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.count(provider, account, model, now)
})
}
/// 读取账号当前的错误率与首个有效输出延迟 EWMA
#[must_use]
pub fn scheduling_signals(
@@ -978,6 +1053,8 @@ impl AccountSelector {
// 首输出 10 秒时延迟得分减半;固定尺度不随其他候选账号变化
const SMART_LATENCY_HALF_SCORE_MS: f64 = 10_000.0;
// 最近一分钟 10 次请求对应 0.5 的近期负载压力,固定尺度不代表上游 RPM 限额
const SMART_RECENT_REQUEST_HALF_LOAD: f64 = 10.0;
fn capacity_utilization(candidate: &AccountCandidate, context: &AccountSelectionContext) -> f64 {
context
@@ -1012,7 +1089,10 @@ fn select_smart_candidate<'a>(
pub(crate) fn smart_score(candidate: &AccountCandidate, context: &AccountSelectionContext) -> f64 {
let config = context.policy.smart_scheduling();
let now = context.now;
let load = 1.0 - capacity_utilization(candidate, context).clamp(0.0, 1.0);
// 两类压力独立扣分,近期热度不能稀释当前并发占用的代价
let recent_requests = candidate.signals.recent_requests as f64;
let recent_load = recent_requests / (SMART_RECENT_REQUEST_HALF_LOAD + recent_requests);
let load = 1.0 - capacity_utilization(candidate, context).clamp(0.0, 1.0) - recent_load;
let quota = candidate
.signals
.quota_remaining_rank
@@ -1,6 +1,7 @@
//! Provider 账号持久化端口
use async_trait::async_trait;
use futures::future::BoxFuture;
use crate::error::StoreError;
use crate::identity::ProviderKind;
@@ -9,9 +10,19 @@ use super::{
AccountStateChange, CredentialCasOutcome, CredentialCasUpdate, CredentialRevision,
LoadedCredential, NewProviderAccount, ProviderAccount, ProviderAccountId,
ProviderAccountUpdate, ProviderRefreshQuery, QuotaAccessChange, QuotaObservation,
QuotaObservationTouch, QuotaObservationVersion, QuotaWriteOutcome,
QuotaObservationTouch, QuotaObservationVersion, QuotaWriteOutcome, RecentRequestSnapshot,
};
/// 快照存储只供启动与后台任务使用,数据面不依赖此端口
pub trait RecentRequestStore: Send + Sync {
fn load(&self) -> BoxFuture<'_, Result<Option<RecentRequestSnapshot>, StoreError>>;
fn save<'a>(
&'a self,
snapshot: &'a RecentRequestSnapshot,
ttl: std::time::Duration,
) -> BoxFuture<'a, Result<(), StoreError>>;
}
/// 一个账号最后成功的目录观测;正文由 Provider 解释,归属不能按相同正文合并
#[derive(Clone)]
pub struct AccountCatalogObservation {
@@ -41,6 +41,7 @@ impl TraceContext {
"blocker": AccountSelector.scheduling_blocker(candidate, context)
.map(|blocker| format!("{blocker:?}")),
"inFlight": signals.in_flight,
"recentRequests": signals.recent_requests,
"concurrencyLimit": context.concurrency_limit(candidate).get(),
"quotaRemainingBasisPoints": signals.quota_remaining_rank,
"quotaResetAtUnixMs": signals.quota_reset_at.and_then(|reset|
@@ -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())
@@ -1480,7 +1479,7 @@ where
&& let Some(original) = self.last_retryable_failure.take()
{
// 迁移只改变客户端恢复指令;失败分类、发送事实与运维正文仍属于原请求
error = original.with_client_recovery_from(error);
error = original.with_client_recovery_from(error, &self.last_retryable_failure_events);
self.last_retryable_failure_events.clear();
}
let kind = error.kind();
@@ -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,
@@ -1547,11 +1547,8 @@ impl DefaultExecutionService {
) -> AccountProbeError {
let (source, send_state, upstream_response) = match error {
EngineError::Provider(provider_error) => {
let upstream_response = provider_error
.client_visible_upstream_response()
.map(AccountProbeUpstreamResponse::from_client_response);
let upstream_response = AccountProbeUpstreamResponse::from_provider(provider_error);
let has_upstream_facts = provider_error.send_state() != UpstreamSendState::NotSent
|| provider_error.upstream_status().is_some()
|| provider_error.upstream_code().is_some()
|| provider_error.client_visible_upstream_error().is_some()
|| upstream_response.is_some();
+10 -10
View File
@@ -18,12 +18,14 @@ pub mod policy;
pub mod probe;
mod prompt_rewrite;
pub mod provider;
mod recent_request_persistence;
pub mod response_control;
pub mod upstream_adapter;
use crate::lifecycle::{Deadline, LeaseGuard};
pub use coordinator::{AttemptCoordinator, ResponseExecutionSession};
pub use recent_request_persistence::RecentRequestPersistence;
use std::collections::BTreeSet;
use std::fmt;
@@ -328,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>,
@@ -422,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,
@@ -476,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,
@@ -741,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]
+13 -13
View File
@@ -5,9 +5,7 @@ use std::fmt;
use bytes::Bytes;
use futures::future::BoxFuture;
use crate::error::{
ClientVisibleUpstreamResponse, GatewayError, GatewayErrorKind, ProxyConnectionHint,
};
use crate::error::{GatewayError, GatewayErrorKind, ProviderError, ProxyConnectionHint};
use crate::identity::ProviderKind;
use crate::routing::UpstreamModelId;
use crate::{
@@ -60,16 +58,18 @@ pub struct AccountProbeResult {
pub struct AccountProbeUpstreamResponse {
status: u16,
content_type: Option<Vec<u8>>,
body: Bytes,
body: Option<Bytes>,
}
impl AccountProbeUpstreamResponse {
pub(crate) fn from_client_response(response: &ClientVisibleUpstreamResponse) -> Self {
Self {
status: response.status(),
content_type: response.content_type().map(<[u8]>::to_vec),
body: response.body().clone(),
}
pub(crate) fn from_provider(error: &ProviderError) -> Option<Self> {
let response = error.client_visible_upstream_response();
// 即使没有可展示的响应正文,Provider 收到的状态码仍可用于诊断
Some(Self {
status: response.map(|r| r.status()).or(error.upstream_status())?,
content_type: response.and_then(|r| r.content_type()).map(<[u8]>::to_vec),
body: response.map(|r| r.body().clone()),
})
}
#[must_use]
@@ -83,8 +83,8 @@ impl AccountProbeUpstreamResponse {
}
#[must_use]
pub const fn body(&self) -> &Bytes {
&self.body
pub const fn body(&self) -> Option<&Bytes> {
self.body.as_ref()
}
}
@@ -97,7 +97,7 @@ impl fmt::Debug for AccountProbeUpstreamResponse {
"content_type",
&self.content_type.as_ref().map(|_| "<present>"),
)
.field("body", &"<redacted>")
.field("body", &self.body.as_ref().map(|_| "<redacted>"))
.finish()
}
}
@@ -283,6 +283,8 @@ struct ProviderStreamAccountFeedback {
provider_kind: ProviderKind,
account_id: ProviderAccountId,
failure_filter: fn(&ProviderError) -> bool,
upstream_model: Option<UpstreamModelId>,
request_recorded: bool,
started_at: Option<Instant>,
first_output_ms: Option<u64>,
reported: bool,
@@ -297,7 +299,27 @@ impl ProviderStreamAccountFeedback {
self.started_at.get_or_insert_with(Instant::now);
}
fn record_request(&mut self) {
if self.request_recorded {
return;
}
if let (Some(model), Some(started_at)) = (&self.upstream_model, self.started_at) {
self.stats.record_request_at(
&self.provider_kind,
&self.account_id,
model.as_str(),
started_at,
Instant::now(),
);
}
self.request_recorded = true;
}
fn observe(&mut self, event: &ProviderEvent) {
// 纯连接观测可能出现在未发送失败之前,不能单独证明请求已送达
if event.has_client_event() {
self.record_request();
}
if self.first_output_ms.is_some()
|| !event.canonical_facts().iter().any(|event| {
matches!(
@@ -332,6 +354,9 @@ impl ProviderStreamAccountFeedback {
}
fn report_failure(&mut self, error: &ProviderError) {
if error.send_state() == UpstreamSendState::Sent {
self.record_request();
}
if self.reported
// `Ambiguous` 仍须关闭重放边界,但不能证明失败由账号造成;将它计入
// 账号评分会把传输不确定性错误归因给账号
@@ -523,6 +548,8 @@ impl ProviderStream {
provider_kind: self.metadata.provider().clone(),
account_id: self.metadata.provider_account_id().clone(),
failure_filter,
upstream_model: self.metadata.upstream_model().cloned(),
request_recorded: false,
started_at: None,
first_output_ms: None,
reported: false,
@@ -0,0 +1,77 @@
//! 近期请求统计的启动恢复、周期快照与有界关闭刷写
use std::sync::Arc;
use std::time::{Duration, Instant, SystemTime};
use futures::{FutureExt, future::BoxFuture};
use futures_timer::Delay;
use crate::account::{AccountFeedbackStats, RecentRequestStore};
use crate::error::{StoreError, StoreErrorKind};
use crate::task::{DaemonTask, WorkerDaemonContext, WorkerTaskError};
const FLUSH_INTERVAL: Duration = Duration::from_secs(1);
const IO_TIMEOUT: Duration = Duration::from_secs(2);
const SNAPSHOT_TTL: Duration = Duration::from_secs(120);
/// 由 Host 监督的单进程快照任务,不重放单次请求或恢复旧健康分
pub struct RecentRequestPersistence {
stats: Arc<AccountFeedbackStats>,
store: Arc<dyn RecentRequestStore>,
}
impl RecentRequestPersistence {
#[must_use]
pub fn new(stats: Arc<AccountFeedbackStats>, store: Arc<dyn RecentRequestStore>) -> Self {
Self { stats, store }
}
/// 在 Provider 接收请求前恢复一次,后台任务重启不再次覆盖内存
pub async fn restore(&self) -> Result<(), StoreError> {
if let Some(snapshot) = bounded(self.store.load()).await? {
self.stats
.restore_recent_requests_at(snapshot, Instant::now(), SystemTime::now())
.map_err(|error| StoreError::caused_by(StoreErrorKind::InvalidData, error))?;
}
Ok(())
}
async fn flush(&self) -> Result<(), StoreError> {
let snapshot = self
.stats
.snapshot_recent_requests_at(Instant::now(), SystemTime::now());
// 快照离开内存锁后才序列化和等待存储,慢 Redis 不占用选号锁
bounded(self.store.save(&snapshot, SNAPSHOT_TTL)).await
}
}
impl DaemonTask for RecentRequestPersistence {
fn run(&self, context: WorkerDaemonContext) -> BoxFuture<'_, Result<(), WorkerTaskError>> {
Box::pin(async move {
loop {
let stopping = futures::select_biased! {
() = context.cancellation().cancelled().fuse() => true,
() = Delay::new(FLUSH_INTERVAL).fuse() => false,
};
self.flush().await.map_err(|error| {
WorkerTaskError::safe("近期请求统计保存失败").with_source(error)
})?;
if stopping {
return Ok(());
}
context.succeeded();
}
})
}
}
async fn bounded<T>(
operation: impl std::future::Future<Output = Result<T, StoreError>>,
) -> Result<T, StoreError> {
let operation = operation.fuse();
futures::pin_mut!(operation);
futures::select_biased! {
result = operation => result,
() = Delay::new(IO_TIMEOUT).fuse() => Err(StoreError::new(StoreErrorKind::Unavailable)),
}
}
+84 -15
View File
@@ -1093,8 +1093,60 @@ impl ProviderError {
self.client_visible_upstream_response.as_deref()
}
/// 将原失败携带的等待头补入客户端响应,保留响应中已有的值
pub fn extend_client_retry_headers(
&self,
headers: &mut Vec<ProviderResponseHeader>,
events: &[ProviderEvent],
) {
let original = self.client_visible_upstream_response();
let body = std::cell::LazyCell::new(|| {
original.and_then(|response| serde_json::from_slice(response.body()).ok())
});
let event = events
.iter()
.rev()
.find_map(ProviderEvent::wire_event)
.map(|wire| wire.data());
for name in gateway_protocol::http::RETRY_AFTER_HEADERS {
if headers
.iter()
.any(|header| header.name().eq_ignore_ascii_case(name))
{
continue;
}
if let Some(header) = original.and_then(|response| {
response
.headers()
.iter()
.rev()
.find(|header| header.name().eq_ignore_ascii_case(name))
}) {
headers.push(header.clone());
continue;
}
let read = |value| gateway_protocol::openai::events::error_event_header(value, name);
if let Some(value) = event
.and_then(read)
.or_else(|| body.as_ref().and_then(read))
{
headers.push(ProviderResponseHeader::new(
name,
Bytes::copy_from_slice(value.as_bytes()),
));
}
}
}
/// 绑定迁移完成后仅替换客户端恢复投影,保留原始失败的诊断与计费事实
pub(crate) fn with_client_recovery_from(mut self, recovery: Self) -> Self {
pub(crate) fn with_client_recovery_from(
mut self,
mut recovery: Self,
events: &[ProviderEvent],
) -> Self {
if let Some(response) = recovery.client_visible_upstream_response.as_deref_mut() {
self.extend_client_retry_headers(&mut response.headers, events);
}
if let Some(reason) = recovery.continuation_unavailable_reason() {
self = self.with_continuation_unavailable_reason(reason);
}
@@ -1384,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.",
)
}
@@ -1464,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,
@@ -1487,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,
@@ -1507,11 +1564,23 @@ 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.",
),
@@ -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,
@@ -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,
}
@@ -40,7 +40,7 @@ impl Default for OpenAiRequestSettings {
Self {
request_country: Default::default(),
oauth_guardian_review_model: true,
residency: Some("us".to_owned()),
residency: None,
account_routing_override: None,
}
}
@@ -58,7 +58,7 @@ pub enum OpenAiRequestCountry {
impl Default for OpenAiRequestCountry {
fn default() -> Self {
Self::FollowLocation {}
Self::Default {}
}
}
@@ -5,6 +5,7 @@ mod model_access;
mod proxy;
mod quota_reset_priority;
mod quota_settings;
mod recent_requests;
mod scope;
mod selection;
mod selection_diagnostics;
@@ -56,6 +57,7 @@ fn candidate(id: &str, in_flight: u32, remaining: Option<u64>) -> AccountCandida
account: account(id),
signals: AccountRuntimeSignals {
in_flight,
recent_requests: 0,
last_started_at: None,
quota_reset_at: None,
quota_reset_windows: None,
@@ -229,6 +231,7 @@ fn diagnostic_selection_bypasses_all_local_account_eligibility() {
),
signals: AccountRuntimeSignals {
in_flight: 0,
recent_requests: 0,
last_started_at: None,
quota_reset_at: None,
quota_reset_windows: None,
@@ -249,6 +252,7 @@ fn diagnostic_selection_bypasses_all_local_account_eligibility() {
),
signals: AccountRuntimeSignals {
in_flight: 0,
recent_requests: 0,
last_started_at: None,
quota_reset_at: None,
quota_reset_windows: None,
@@ -644,6 +648,7 @@ fn provider_quota_overlay_should_preserve_store_concurrency_facts() {
let last_started_at = SystemTime::now();
let signals = AccountRuntimeSignals {
in_flight: 2,
recent_requests: 0,
last_started_at: Some(last_started_at),
quota_reset_at: None,
quota_reset_windows: None,
@@ -0,0 +1,182 @@
//! 验证近期负载的模型隔离、滑动过期、延迟确认与并发计数
use std::time::{Duration, Instant};
use gateway_core::account::{AccountFeedbackStats, ProviderAccountId};
use gateway_core::identity::ProviderKind;
#[test]
fn recent_requests_expire_by_start_time_and_isolate_accounts_models_and_providers() {
let stats = AccountFeedbackStats::default();
let provider = ProviderKind::new("openai").unwrap();
let other_provider = ProviderKind::new("xai").unwrap();
let account = ProviderAccountId::new("acct_recent").unwrap();
let other_account = ProviderAccountId::new("acct_other").unwrap();
let start = Instant::now();
for offset in [0, 30, 59] {
let now = start + Duration::from_secs(offset);
stats.record_request_at(&provider, &account, "model-a", now, now);
}
let now = start + Duration::from_secs(59);
assert_eq!(
stats.recent_requests_at(&provider, &account, Some("model-a"), now),
3
);
for (provider, account, model) in [
(&provider, &other_account, Some("model-a")),
(&other_provider, &account, Some("model-a")),
(&provider, &account, Some("model-b")),
(&provider, &account, None),
] {
assert_eq!(stats.recent_requests_at(provider, account, model, now), 0);
}
let now = start + Duration::from_secs(60);
assert_eq!(
stats.recent_requests_at(&provider, &account, Some("model-a"), now),
2
);
// 响应晚到时仍落在开始时的桶,已经过期的请求不重新进入窗口
stats.record_request_at(&provider, &account, "model-a", start, now);
stats.record_request_at(
&provider,
&account,
"model-a",
start + Duration::from_secs(30),
now,
);
assert_eq!(
stats.recent_requests_at(&provider, &account, Some("model-a"), now),
3
);
let now = start + Duration::from_secs(90);
assert_eq!(
stats.recent_requests_at(&provider, &account, Some("model-a"), now),
1
);
let now = start + Duration::from_secs(120);
assert_eq!(
stats.recent_requests_at(&provider, &account, Some("model-a"), now),
0
);
stats.record_request_at(&provider, &account, "model-a", now, now);
assert_eq!(
stats.recent_requests_at(&provider, &account, Some("model-a"), now),
1
);
assert_eq!(
AccountFeedbackStats::default().recent_requests(&provider, &account, Some("model-a")),
0
);
}
#[test]
fn concurrent_requests_are_counted_once_per_record() {
let stats = AccountFeedbackStats::default();
let provider = ProviderKind::new("openai").unwrap();
let account = ProviderAccountId::new("acct_recent").unwrap();
std::thread::scope(|scope| {
for _ in 0..8 {
scope.spawn(|| {
for _ in 0..1000 {
let now = Instant::now();
stats.record_request_at(&provider, &account, "model", now, now);
}
});
}
});
assert_eq!(
stats.recent_requests(&provider, &account, Some("model")),
8000
);
}
#[test]
fn snapshot_restores_only_live_buckets_and_preserves_expiration_after_downtime() {
let stats = AccountFeedbackStats::default();
let provider = ProviderKind::new("openai").unwrap();
let account = ProviderAccountId::new("acct_restart").unwrap();
let start = Instant::now();
let wall_start = std::time::SystemTime::now();
for offset in [0, 30, 59] {
let now = start + Duration::from_secs(offset);
stats.record_request_at(&provider, &account, "model", now, now);
}
let snapshot = stats.snapshot_recent_requests_at(
start + Duration::from_secs(59),
wall_start + Duration::from_secs(59),
);
let bytes = serde_json::to_vec(&snapshot).unwrap();
let snapshot = serde_json::from_slice(&bytes).unwrap();
let restored = AccountFeedbackStats::default();
restored
.restore_recent_requests_at(
snapshot,
start + Duration::from_secs(79),
wall_start + Duration::from_secs(79),
)
.unwrap();
for (offset, expected) in [(79, 2), (91, 1), (120, 0)] {
assert_eq!(
restored.recent_requests_at(
&provider,
&account,
Some("model"),
start + Duration::from_secs(offset)
),
expected,
);
}
}
#[test]
fn stale_snapshots_and_backward_wall_clock_start_with_an_empty_window() {
let stats = AccountFeedbackStats::default();
let provider = ProviderKind::new("openai").unwrap();
let account = ProviderAccountId::new("acct_restart").unwrap();
let now = Instant::now();
let wall_now = std::time::SystemTime::now();
stats.record_request_at(&provider, &account, "model", now, now);
let snapshot = stats.snapshot_recent_requests_at(now, wall_now);
for wall_restart in [
wall_now + Duration::from_secs(60),
wall_now - Duration::from_secs(1),
] {
let restored = AccountFeedbackStats::default();
restored
.restore_recent_requests_at(snapshot.clone(), now, wall_restart)
.unwrap();
assert_eq!(
restored.recent_requests_at(&provider, &account, Some("model"), now),
0
);
}
}
#[test]
fn invalid_snapshot_does_not_partially_replace_live_counts() {
let source = AccountFeedbackStats::default();
let live = AccountFeedbackStats::default();
let provider = ProviderKind::new("openai").unwrap();
let account = ProviderAccountId::new("acct_restart").unwrap();
let now = Instant::now();
let wall_now = std::time::SystemTime::now();
for _ in 0..2 {
source.record_request_at(&provider, &account, "model", now, now);
}
live.record_request_at(&provider, &account, "model", now, now);
let mut value =
serde_json::to_value(source.snapshot_recent_requests_at(now, wall_now)).unwrap();
let windows = value["windows"].as_array_mut().unwrap();
let mut invalid = windows[0].clone();
invalid["account"] = serde_json::json!("");
windows.push(invalid);
let snapshot = serde_json::from_value(value).unwrap();
assert!(
live.restore_recent_requests_at(snapshot, now, wall_now)
.is_err()
);
assert_eq!(
live.recent_requests_at(&provider, &account, Some("model"), now),
1,
);
}
@@ -36,6 +36,7 @@ fn reserved_pool_scoring_and_trace_use_its_capacity_instead_of_the_normal_limit(
let selected = &snapshot["events"][0]["data"]["candidates"][0];
assert_eq!(selected["concurrencyLimit"], 5);
assert_eq!(selected["inFlight"], 1);
assert_eq!(selected["recentRequests"], 0);
assert_eq!(selected["smartScore"], 0.8);
}
@@ -429,3 +430,189 @@ fn missing_expired_and_duplicate_periods_do_not_inflate_reset_score() {
);
}
}
#[test]
fn smart_prefers_recently_idle_accounts_and_disables_recent_load_with_zero_weight() {
let candidates = (0..130)
.map(|index| {
let mut candidate = candidate_with_concurrency(&format!("acct_{index:03}"), 0, 8);
candidate.signals.recent_requests = index / 2;
candidate
})
.collect::<Vec<_>>();
let mut context = context(RotationStrategy::Smart);
for cursor in 0..260 {
context.round_robin_cursor = cursor;
let selected = AccountSelector.select(&candidates, &context).unwrap();
assert_eq!(
selected.candidate().account.id(),
candidates[(cursor % 2) as usize].account.id()
);
}
// 系数归零时由其余维度和轮换决定,近期负载退出比较
context.policy = context
.policy
.with_smart_scheduling(SmartSchedulingConfig::new([0.0, 0.8, 1.0, 0.5, 0.0, 0.0]).unwrap());
for cursor in 0..130 {
context.round_robin_cursor = cursor;
let selected = AccountSelector.select(&candidates, &context).unwrap();
assert_eq!(
selected.candidate().account.id(),
candidates[cursor as usize].account.id()
);
}
}
#[test]
fn recent_load_respects_affinity_weight_capacity_and_configured_quota_weight() {
let mut candidates = [
candidate_with_concurrency("acct_busy", 0, 8),
candidate_with_concurrency("acct_idle", 0, 8),
];
candidates[0].signals.recent_requests = 20;
let mut context = context(RotationStrategy::Smart);
context.preferred_account = Some(candidates[0].account.id().clone());
assert_eq!(
AccountSelector
.select(&candidates, &context)
.unwrap()
.candidate()
.account
.id()
.as_str(),
"acct_busy"
);
context.preferred_account = None;
candidates[1].signals.in_flight = 8;
assert_eq!(
AccountSelector
.select(&candidates, &context)
.unwrap()
.candidate()
.account
.id()
.as_str(),
"acct_busy"
);
candidates[1].signals.in_flight = 0;
candidates[1].signals.quota_remaining_rank = Some(0);
candidates[0].signals.quota_remaining_rank = Some(10_000);
assert_eq!(
AccountSelector
.select(&candidates, &context)
.unwrap()
.candidate()
.account
.id()
.as_str(),
"acct_busy"
);
candidates[1].signals.quota_remaining_rank = Some(10_000);
candidates[0].account = candidates[0]
.account
.clone()
.with_scheduling(None, gateway_core::account::AccountWeight::new(2).unwrap());
candidates[1].account = candidates[1]
.account
.clone()
.with_scheduling(None, gateway_core::account::AccountWeight::new(1).unwrap());
assert_eq!(
AccountSelector
.select(&candidates, &context)
.unwrap()
.candidate()
.account
.id()
.as_str(),
"acct_busy"
);
}
#[test]
fn recent_model_load_competes_with_quota_and_cross_model_concurrency_before_score_filtering() {
for weights in [
[1.0, 0.1, 1.0, 0.0, 0.0, 0.0],
[1.0, 0.8, 1.0, 0.5, 0.0, 0.0],
] {
for limit in [6, 8] {
for (hot_requests, cool_requests, cool_in_flight, cool_quota) in [
(18, 0, 0, 9_000),
(18, 0, 0, 7_000),
(18, 0, 1, 10_000),
(16, 4, 1, 9_000),
(27, 3, 1, 7_000),
] {
let mut candidates = [
candidate_with_concurrency("acct_hot", 0, limit),
candidate_with_concurrency("acct_cool", cool_in_flight, limit),
];
candidates[0].signals.quota_remaining_rank = Some(10_000);
candidates[0].signals.recent_requests = hot_requests;
candidates[1].signals.quota_remaining_rank = Some(cool_quota);
candidates[1].signals.recent_requests = cool_requests;
let mut context = context(RotationStrategy::Smart);
context.policy = context
.policy
.with_smart_scheduling(SmartSchedulingConfig::new(weights).unwrap());
let selected = AccountSelector.select(&candidates, &context).unwrap();
assert_eq!(selected.candidate().account.id().as_str(), "acct_cool");
let trace = gateway_core::diagnostics::TraceContext::new("req_recent_score");
trace.account_selection(&candidates, &context, Some(&selected));
let snapshot = trace.snapshot().unwrap();
let scores = &snapshot["events"][0]["data"]["candidates"];
assert!(
scores[0]["smartScore"].as_f64().unwrap()
> scores[1]["smartScore"].as_f64().unwrap()
);
}
}
}
}
#[test]
fn recent_heat_does_not_dilute_concurrency_pressure_or_require_nonnegative_load_scores() {
let mut candidates = [
candidate_with_concurrency("acct_busy", 5, 6),
candidate_with_concurrency("acct_idle", 4, 6),
];
candidates[0].signals.quota_remaining_rank = Some(10_000);
candidates[1].signals.quota_remaining_rank = Some(9_000);
for candidate in &mut candidates {
candidate.signals.recent_requests = 30;
}
let mut context = context(RotationStrategy::Smart);
for quota_weight in [0.0, 0.8] {
context.policy = context.policy.with_smart_scheduling(
SmartSchedulingConfig::new([1.0, quota_weight, 0.0, 0.0, 0.0, 0.0]).unwrap(),
);
let selected = AccountSelector.select(&candidates, &context).unwrap();
assert_eq!(selected.candidate().account.id().as_str(), "acct_idle");
if quota_weight == 0.0 {
let trace = gateway_core::diagnostics::TraceContext::new("req_negative_load");
trace.account_selection(&candidates, &context, Some(&selected));
assert!(
trace.snapshot().unwrap()["events"][0]["data"]["candidates"][0]["smartScore"]
.as_f64()
.unwrap()
< 0.0
);
}
}
}
#[test]
fn recent_load_remains_effective_without_a_concurrency_limit() {
let mut candidates = [
super::candidate("acct_hot", 0, None),
super::candidate("acct_cool", 1, None),
];
candidates[0].signals.recent_requests = u64::MAX;
let mut context = context(RotationStrategy::Smart);
context.policy = gateway_core::account::AccountSelectionPolicy::new(
RotationStrategy::Smart,
gateway_core::account::AccountConcurrency::new(0),
);
let selected = AccountSelector.select(&candidates, &context).unwrap();
assert_eq!(selected.candidate().account.id().as_str(), "acct_cool");
}
@@ -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 {
@@ -2525,11 +2511,33 @@ fn native_capacity_above_wait_limit_rotates_before_requesting_client_replay() {
.with_continuation_recovery_disposition(
ContinuationRecoveryDisposition::ClientReplayRequired,
);
let original = if committed_prelude {
let event = json!({"type":"response.failed", "response":{"error":{
"headers":{"Retry-After":seconds.to_string(), "Retry-After-Ms":"317001", "x-private":"omit"}
}}});
original.with_atomic_client_events(vec![ProviderEvent::wire(
ProtocolWireEvent::json("openai", Some("response.failed".to_owned()), event)
.unwrap(),
)])
} else {
original.with_client_visible_upstream_response(
ClientVisibleUpstreamResponse::new(503, None, Bytes::from(original_body.clone()))
.with_headers(vec![gateway_core::event::ProviderResponseHeader::new(
"Retry-After-Ms",
Bytes::from_static(b"309001"),
)]),
)
};
let recovery = if replacement {
ProviderError::new(
ProviderErrorKind::ContinuationRecoveryRequired,
UpstreamSendState::NotSent,
)
.with_client_visible_upstream_response(ClientVisibleUpstreamResponse::new(
400,
None,
Bytes::from_static(b"{}"),
))
.with_continuation_unavailable_reason("account_rotated")
.with_continuation_recovery_disposition(
ContinuationRecoveryDisposition::ClientReplayRequired,
@@ -2602,6 +2610,29 @@ fn native_capacity_above_wait_limit_rotates_before_requesting_client_replay() {
error.continuation_unavailable_reason(),
(replacement && expected_attempts == 2).then_some("account_rotated")
);
if replacement && expected_attempts == 2 {
let response = error.client_visible_upstream_response().unwrap();
assert_eq!(response.status(), 400);
let headers: Vec<_> = response
.headers()
.iter()
.map(|header| (header.name().to_ascii_lowercase(), header.value().as_ref()))
.collect();
assert_eq!(
headers,
vec![
("retry-after".to_owned(), seconds.to_string().as_bytes()),
(
"retry-after-ms".to_owned(),
if committed_prelude {
b"317001"
} else {
b"309001"
}
),
]
);
}
let contexts = provider.contexts.lock().unwrap();
assert_eq!(contexts.len(), expected_attempts);
if contexts.len() == 2 {
@@ -6369,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,
@@ -6380,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",
@@ -6414,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,
);
}
}
}
@@ -2470,6 +2470,7 @@ impl Provider for PolicySelectingProvider {
account,
signals: AccountRuntimeSignals {
in_flight: 0,
recent_requests: 0,
last_started_at: None,
quota_reset_at: None,
quota_reset_windows: None,
@@ -3067,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(),
@@ -3509,8 +3516,10 @@ fn account_probe_should_not_write_to_the_persistent_execution_store() {
#[test]
fn probe_failures_should_be_observable_without_a_model_request_row() {
let store = Arc::new(TrackingExecutionStore::default());
let providers = ProviderRegistry::new([Arc::new(FailingProvider) as Arc<dyn Provider>])
.expect("provider registry");
let providers = ProviderRegistry::new([
Arc::new(FailingProvider { include_body: true }) as Arc<dyn Provider>
])
.expect("provider registry");
let service = DefaultExecutionService::new(
RuntimeSnapshotHandle::new(probe_snapshot()),
store.clone(),
@@ -3547,7 +3556,9 @@ fn probe_failures_should_be_observable_without_a_model_request_row() {
);
assert_eq!(
upstream.body(),
&Bytes::from_static(br#"{"error":{"message":"source upstream failure"}}"#),
Some(&Bytes::from_static(
br#"{"error":{"message":"source upstream failure"}}"#
)),
);
assert!(!format!("{error:?}").contains("source upstream failure"));
assert!(!store.touched.load(Ordering::SeqCst));
@@ -3687,8 +3698,10 @@ fn probe_observation_store_failure_preserves_the_provider_error() {
fail_probe_observation: AtomicBool::new(true),
..TrackingExecutionStore::default()
});
let providers = ProviderRegistry::new([Arc::new(FailingProvider) as Arc<dyn Provider>])
.expect("provider registry");
let providers = ProviderRegistry::new([Arc::new(FailingProvider {
include_body: false,
}) as Arc<dyn Provider>])
.expect("provider registry");
let service = DefaultExecutionService::new(
RuntimeSnapshotHandle::new(probe_snapshot()),
store.clone(),
@@ -3715,9 +3728,15 @@ fn probe_observation_store_failure_preserves_the_provider_error() {
assert_eq!(error.kind(), GatewayErrorKind::UpstreamUnavailable);
assert!(!store.touched.load(Ordering::SeqCst));
assert!(store.probe_failures().is_empty());
let upstream = error.upstream_response().unwrap();
assert_eq!(upstream.status(), 403);
assert!(upstream.body().is_none());
assert!(upstream.content_type().is_none());
}
struct FailingProvider;
struct FailingProvider {
include_body: bool,
}
#[derive(Clone, Copy)]
enum CatalogProvider {
@@ -4055,6 +4074,13 @@ impl Provider for FailingProvider {
_request: ProviderRequest,
_context: AttemptContext,
) -> Result<ProviderStream, ProviderError> {
if !self.include_body {
return Err(ProviderError::new(
ProviderErrorKind::PermissionDenied,
UpstreamSendState::Sent,
)
.with_status(403));
}
Err(
ProviderError::new(ProviderErrorKind::Transport, UpstreamSendState::NotSent)
.with_client_visible_upstream_response(ClientVisibleUpstreamResponse::new(
@@ -4772,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,
@@ -5506,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
@@ -5629,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,
@@ -5668,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();
@@ -5702,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);
@@ -10,6 +10,7 @@ mod extensions;
mod middleware;
mod policy;
mod provider;
mod recent_request_persistence;
mod response_control;
use gateway_core::engine::AttemptTrigger;
@@ -75,6 +75,7 @@ fn candidate(id: &str) -> AccountCandidate {
.with_scheduling(None, AccountWeight::new(100).unwrap()),
signals: AccountRuntimeSignals {
in_flight: 0,
recent_requests: 0,
last_started_at: None,
quota_reset_at: None,
quota_reset_windows: None,
@@ -242,6 +242,10 @@ fn provider_stream_should_report_common_account_success_and_first_output() {
let (failure_rate, first_output_ms) = feedback.scheduling_signals(&provider, &account);
assert_eq!(failure_rate, Some(0));
assert!(first_output_ms.is_some_and(|value| value >= 2));
assert_eq!(
feedback.recent_requests(&provider, &account, Some("gpt-5")),
1
);
}
#[test]
@@ -367,16 +371,25 @@ fn provider_stream_should_report_confirmed_sent_failure_but_ignore_unconfirmed_f
let metadata = ProviderCallMetadata::new(
provider.clone(),
UpstreamModelId::new("grok-4.5").expect("valid model"),
account,
account.clone(),
UpstreamTransport::new("http_sse").expect("valid transport"),
);
let events: EventStream = Box::pin(stream::iter([Err(ProviderError::new(
ProviderErrorKind::Transport,
send_state,
))]));
let events: EventStream = Box::pin(stream::iter([
Ok(gateway_core::event::ProviderEvent::observation(
gateway_core::event::ProviderResponseObservation::new(
UpstreamTransport::new("http_sse").unwrap(),
),
)),
Err(ProviderError::new(ProviderErrorKind::Transport, send_state)),
]));
let mut provider_stream =
ProviderStream::new(metadata, events, ()).with_account_feedback(Arc::clone(&feedback));
futures::executor::block_on(async {
provider_stream.next().await.unwrap().unwrap();
assert_eq!(
feedback.recent_requests(&provider, &account, Some("grok-4.5")),
0
);
assert!(
provider_stream
.next()
@@ -386,6 +399,17 @@ fn provider_stream_should_report_confirmed_sent_failure_but_ignore_unconfirmed_f
});
}
for (account, count) in [
(&sent_account, 1),
(&ambiguous_account, 0),
(&not_sent_account, 0),
] {
assert_eq!(
feedback.recent_requests(&provider, account, Some("grok-4.5")),
count
);
}
assert_eq!(
feedback.scheduling_signals(&provider, &sent_account).0,
Some(2_000)
@@ -434,6 +458,10 @@ fn provider_stream_should_ignore_repeated_failures_rejected_by_the_filter() {
feedback.scheduling_signals(&provider, &account),
(None, None)
);
assert_eq!(
feedback.recent_requests(&provider, &account, Some("gpt-5")),
100
);
}
#[test]
@@ -0,0 +1,162 @@
//! 验证近期请求快照异步合并、慢存储隔离、关闭刷写及失败预算
use std::sync::{
Arc, Mutex,
atomic::{AtomicUsize, Ordering},
};
use std::time::{Duration, Instant};
use futures::{channel::oneshot, future::BoxFuture};
use gateway_core::{
account::{AccountFeedbackStats, ProviderAccountId, RecentRequestSnapshot, RecentRequestStore},
engine::RecentRequestPersistence,
error::{StoreError, StoreErrorKind},
identity::ProviderKind,
lifecycle::CancellationToken,
task::{DaemonTask, WorkerDaemonContext},
};
#[derive(Default)]
struct MemoryStore {
snapshot: Mutex<Option<RecentRequestSnapshot>>,
saves: AtomicUsize,
loads: AtomicUsize,
started: Mutex<Option<oneshot::Sender<()>>>,
gate: Mutex<Option<oneshot::Receiver<()>>>,
fail: bool,
stalled: bool,
}
impl RecentRequestStore for MemoryStore {
fn load(&self) -> BoxFuture<'_, Result<Option<RecentRequestSnapshot>, StoreError>> {
Box::pin(async move {
self.loads.fetch_add(1, Ordering::SeqCst);
if self.stalled {
return std::future::pending().await;
}
Ok(self.snapshot.lock().unwrap().clone())
})
}
fn save<'a>(
&'a self,
snapshot: &'a RecentRequestSnapshot,
ttl: Duration,
) -> BoxFuture<'a, Result<(), StoreError>> {
Box::pin(async move {
assert_eq!(ttl, Duration::from_secs(120));
self.saves.fetch_add(1, Ordering::SeqCst);
if let Some(started) = self.started.lock().unwrap().take() {
started.send(()).unwrap();
}
let gate = self.gate.lock().unwrap().take();
if let Some(gate) = gate {
gate.await.unwrap();
}
if self.stalled {
return std::future::pending().await;
}
if self.fail {
return Err(StoreError::new(StoreErrorKind::Unavailable));
}
*self.snapshot.lock().unwrap() = Some(snapshot.clone());
Ok(())
})
}
}
#[test]
fn periodic_snapshot_keeps_traffic_live_during_slow_save_and_flushes_latest_on_shutdown() {
futures::executor::block_on(async {
let stats = Arc::new(AccountFeedbackStats::default());
let provider = ProviderKind::new("openai").unwrap();
let account = ProviderAccountId::new("acct_async").unwrap();
let (entered, entering) = oneshot::channel();
let (release, released) = oneshot::channel();
let store = Arc::new(MemoryStore {
started: Mutex::new(Some(entered)),
gate: Mutex::new(Some(released)),
..Default::default()
});
let persistence = RecentRequestPersistence::new(stats.clone(), store.clone());
for _ in 0..100 {
let now = Instant::now();
stats.record_request_at(&provider, &account, "model", now, now);
}
assert_eq!(store.saves.load(Ordering::SeqCst), 0);
let cancellation = CancellationToken::new();
let context = WorkerDaemonContext::new(cancellation.clone());
let driver = async {
entering.await.unwrap();
let now = Instant::now();
stats.record_request_at(&provider, &account, "model", now, now);
assert_eq!(
stats.recent_requests(&provider, &account, Some("model")),
101
);
assert_eq!(store.loads.load(Ordering::SeqCst), 0);
cancellation.cancel();
release.send(()).unwrap();
};
let (result, ()) = futures::join!(persistence.run(context), driver);
result.unwrap();
assert_eq!(store.saves.load(Ordering::SeqCst), 2);
let restarted = Arc::new(AccountFeedbackStats::default());
RecentRequestPersistence::new(restarted.clone(), store)
.restore()
.await
.unwrap();
assert_eq!(
restarted.recent_requests(&provider, &account, Some("model")),
101
);
});
}
#[test]
fn failed_save_preserves_memory_and_reports_failure_to_supervision() {
futures::executor::block_on(async {
let stats = Arc::new(AccountFeedbackStats::default());
let provider = ProviderKind::new("openai").unwrap();
let account = ProviderAccountId::new("acct_failed").unwrap();
let now = Instant::now();
stats.record_request_at(&provider, &account, "model", now, now);
let store = Arc::new(MemoryStore {
fail: true,
..Default::default()
});
let persistence = RecentRequestPersistence::new(stats.clone(), store.clone());
let stopping = CancellationToken::new();
stopping.cancel();
assert!(
persistence
.run(WorkerDaemonContext::new(stopping))
.await
.is_err()
);
assert_eq!(store.saves.load(Ordering::SeqCst), 1);
assert_eq!(stats.recent_requests(&provider, &account, Some("model")), 1);
});
}
#[test]
fn stalled_restore_and_shutdown_have_bounded_waits() {
futures::executor::block_on(async {
let stats = Arc::new(AccountFeedbackStats::default());
let store = Arc::new(MemoryStore {
stalled: true,
..Default::default()
});
let persistence = RecentRequestPersistence::new(stats, store);
let stopping = CancellationToken::new();
stopping.cancel();
let began = Instant::now();
let (restore, save) = futures::join!(
persistence.restore(),
persistence.run(WorkerDaemonContext::new(stopping)),
);
assert!(restore.is_err());
assert!(save.is_err());
assert!(began.elapsed() < Duration::from_secs(4));
});
}
@@ -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"));
@@ -9,6 +9,7 @@ fn scheduling_state_preserves_provider_neutral_signals() {
account.clone(),
AccountRuntimeSignals {
in_flight: 2,
recent_requests: 0,
last_started_at: None,
quota_reset_at: None,
quota_reset_windows: None,
@@ -37,6 +37,7 @@ fn candidate(id: &str, busy: bool) -> AccountCandidate {
inherited_concurrency: None,
signals: AccountRuntimeSignals {
in_flight: u32::from(busy),
recent_requests: 0,
last_started_at: None,
quota_reset_at: None,
quota_reset_windows: None,
@@ -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");
@@ -2617,7 +2617,7 @@ fn global_request_location_should_be_frozen_when_snapshot_is_published() {
assert_eq!(
plan(&handle.acquire().unwrap()).openai_request_settings(),
&gateway_core::settings::OpenAiRequestSettings {
residency: None,
request_country: OpenAiRequestCountry::FollowLocation {},
..Default::default()
}
);
@@ -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"] }
@@ -13,9 +13,7 @@ use yaml_rust2::Yaml;
use super::diagnostics::Diagnostics;
use super::metadata::{Metadata, published_version};
use super::release::{
GitHubRelease, base_update_detail, detail_from_release, update_target_allowed,
};
use super::release::{GitHubRelease, base_update_detail, update_target_allowed};
use super::{OperationError, SystemUpdateConfig, conflict, upstream};
const NORMAL: Duration = Duration::from_secs(1200);
@@ -155,11 +153,14 @@ impl ReleaseCache {
let (mut detail, target) = candidate(config, channel, &index)?;
detail.cached = cached;
if check != Check::Summary || detail.has_update {
let (release, reused) = self.exact(config, &target, age, diagnostics).await?;
let (release, reused) = self
.exact(config, &target, detail.has_update, age, diagnostics)
.await?;
if let Some(release) = release
&& check != Check::Summary
{
detail = detail_from_release(config, &release, channel);
detail.release_url.clone_from(&release.html_url);
detail.notes = release.body.clone().or_else(|| release.name.clone());
}
detail.cached = cached && reused;
}
@@ -173,6 +174,7 @@ impl ReleaseCache {
&self,
config: &SystemUpdateConfig,
target: &Version,
has_update: bool,
age: Duration,
diagnostics: &Diagnostics,
) -> Result<(Option<Arc<GitHubRelease>>, bool), OperationError> {
@@ -191,8 +193,12 @@ impl ReleaseCache {
entries.push_back((target.clone(), Arc::clone(&slot)));
slot
};
slot.get(age, self.metadata.release(config, target), diagnostics)
.await
slot.get(
age,
self.metadata.release(config, target, has_update),
diagnostics,
)
.await
}
pub(super) async fn install(
@@ -209,10 +215,10 @@ impl ReleaseCache {
.get(Duration::ZERO, self.metadata.index(config), diagnostics)
.await?;
let (detail, target) = candidate(config, channel, &index)?;
if !detail.has_update || detail.latest_version != confirmed {
if !detail.has_update || detail.latest_version.as_deref() != Some(confirmed) {
return Err(conflict("远端最新版本已变化,请重新检查并确认"));
}
self.exact(config, &target, Duration::ZERO, diagnostics)
self.exact(config, &target, true, Duration::ZERO, diagnostics)
.await?
.0
.ok_or_else(|| upstream("发布索引指向的 Release 不存在"))
@@ -231,11 +237,7 @@ fn candidate(
.map_err(|_| conflict("当前版本号无效"))?;
let target = published_version(index, &current, channel)?;
let mut detail = base_update_detail(config, channel, None, None);
if update_target_allowed(&current, &target, channel) {
detail.latest_version = target.to_string();
detail.has_update = true;
Ok((detail, target))
} else {
Ok((detail, current))
}
detail.latest_version = Some(target.to_string());
detail.has_update = update_target_allowed(&current, &target, channel);
Ok((detail, target))
}
@@ -83,6 +83,7 @@ impl Metadata {
&self,
config: &SystemUpdateConfig,
version: &Version,
has_update: bool,
) -> Result<Option<Arc<GitHubRelease>>, OperationError> {
let mut url =
Url::parse(&config.github_api_base).map_err(|_| invalid("发行查询地址无效"))?;
@@ -109,7 +110,7 @@ impl Metadata {
if release.tag_name != tag || release.draft || release.prerelease != prerelease {
return Err(upstream("GitHub 发行身份与发布索引不符"));
}
if config.version.trim_start_matches('v') != version {
if has_update {
release.install_assets(&version, &config.github_api_base)?;
}
Ok(Some(Arc::new(release)))
@@ -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(),
@@ -72,36 +72,6 @@ impl GitHubRelease {
}
}
pub(crate) fn detail_from_release(
config: &SystemUpdateConfig,
release: &GitHubRelease,
channel: UpdateChannel,
) -> SystemUpdateDetail {
let unsupported_reason = config.update_support_error();
let latest_version = normalize_version(&release.tag_name);
let has_update = validate_update_target(&config.version, &latest_version, channel).is_ok();
if unsupported_reason.is_some()
|| (!has_update && latest_version != normalize_version(&config.version))
{
return base_update_detail(config, channel, unsupported_reason, None);
}
SystemUpdateDetail {
policy: update_policy(config, channel),
current_version: config.version.clone(),
latest_version,
has_update,
deployment_mode: config.deployment_mode.clone(),
build_type: config.build_type.clone(),
release_url: release.html_url.clone(),
notes: release.body.clone().or_else(|| release.name.clone()),
cached: false,
update_supported: true,
unsupported_reason: None,
warning: None,
retry_at: None,
}
}
pub(crate) fn confirmed_target(target: Option<String>) -> Result<String, OperationError> {
let target = target.ok_or_else(|| conflict("请先确认目标版本"))?;
let target = normalize_version(&target);
@@ -364,14 +334,14 @@ pub(super) fn base_update_detail(
SystemUpdateDetail {
policy: update_policy(config, channel),
current_version: config.version.clone(),
latest_version: config.version.clone(),
latest_version: None,
has_update: false,
deployment_mode: config.deployment_mode.clone(),
build_type: config.build_type.clone(),
release_url: None,
notes: None,
cached: false,
update_supported: unsupported_reason.is_none() && warning.is_none(),
update_supported: unsupported_reason.is_none(),
unsupported_reason,
warning: warning.map(|error| error.message().to_owned()),
retry_at: warning.and_then(OperationError::retry_at),
+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;
@@ -30,7 +30,7 @@ async fn temporary_channel_should_filter_future_releases_without_changing_runnin
.update_detail(SystemUpdateCheck::Detail, Some(channel))
.await
.expect("detail");
assert_eq!(detail.latest_version, target);
assert_eq!(detail.latest_version.as_deref(), Some(target));
assert_eq!(detail.policy.channel, channel);
assert_eq!(
detail.policy.available_channels,
@@ -42,11 +42,11 @@ async fn temporary_channel_should_filter_future_releases_without_changing_runnin
.await
.expect("cached");
assert!(cached.cached);
assert_eq!(cached.latest_version, target);
assert_eq!(cached.latest_version.as_deref(), Some(target));
}
let version = service.version().await.expect("default check");
assert_eq!(version.update_channel, "stable");
assert_eq!(version.latest_version, "1.1.0");
assert_eq!(version.latest_version.as_deref(), Some("1.1.0"));
assert!(!fixture.state().exists(), "检查通道不能写入实例偏好");
let requests = server.received_requests().await.expect("requests");
assert_eq!(requests.len(), 5);
@@ -56,17 +56,27 @@ async fn temporary_channel_should_filter_future_releases_without_changing_runnin
async fn reopening_should_infer_running_channel_and_switching_to_stable_should_not_downgrade() {
let server = MockServer::start().await;
let fixture = Fixture::new();
fixture.mount_release_once(&server, "1.0.0").await;
mount_index(&server, fixture_index("1.0.0")).await;
Mock::given(path("/repos/owner/repository/releases/tags/v1.0.0"))
.respond_with(release_response("1.0.0", Vec::new()))
.mount(&server)
.await;
let mut config = fixture.config(&format!("{}/repos", server.uri()));
config.version = "1.1.0-beta.1".into();
let service = ProcessSystemOperations::new(CancellationToken::new(), config.clone());
let temporary = service
.update_detail(SystemUpdateCheck::Refresh, Some(Stable))
.await
.expect("view stable");
assert_eq!(temporary.policy.channel, Stable);
assert!(!temporary.has_update);
assert_eq!(temporary.latest_version, "1.1.0-beta.1");
for check in [SystemUpdateCheck::Summary, SystemUpdateCheck::Refresh] {
let temporary = service
.update_detail(check, Some(Stable))
.await
.expect("view stable");
assert_eq!(temporary.policy.channel, Stable);
assert!(!temporary.has_update);
assert_eq!(temporary.latest_version.as_deref(), Some("1.0.0"));
assert_eq!(
temporary.notes.is_some(),
check != SystemUpdateCheck::Summary
);
}
assert_eq!(
service
.update_detail(SystemUpdateCheck::Detail, None)
@@ -231,7 +241,7 @@ async fn inferred_prerelease_policy_should_follow_future_minor_and_patch_release
.await
.expect("check");
assert!(detail.has_update);
assert_eq!(detail.latest_version, target);
assert_eq!(detail.latest_version.as_deref(), Some(target));
assert_eq!(
complete_update(&service, target).await.operation.status,
SystemOperationStatus::Succeeded
@@ -78,7 +78,7 @@ async fn discovery_request_budget_is_constant_under_load() {
.update_detail(SystemUpdateCheck::Summary, None)
.await
.unwrap();
assert_eq!(summary.latest_version, target);
assert_eq!(summary.latest_version.as_deref(), Some(target.as_str()));
assert!(summary.notes.is_none());
assert_eq!(server.received_requests().await.unwrap().len(), 2);
@@ -96,7 +96,7 @@ async fn discovery_request_budget_is_constant_under_load() {
}
while let Some(detail) = callers.join_next().await {
let detail = detail.unwrap();
assert_eq!(detail.latest_version, target);
assert_eq!(detail.latest_version.as_deref(), Some(target.as_str()));
assert_eq!(detail.notes.as_deref(), Some("notes"));
}
for _ in 0..64 {
@@ -199,6 +199,10 @@ async fn api_cooldown_is_shared_and_summary_does_not_advertise_an_unverified_rel
.await
.unwrap();
assert!(first.warning.is_some());
assert!(first.update_supported);
assert!(first.unsupported_reason.is_none());
assert!(!first.has_update);
assert!(first.latest_version.is_none());
let retry_at = first.retry_at.expect("限流应提供重试时间");
assert!((298..=300).contains(&(retry_at - chrono::Utc::now()).num_seconds()));
for _ in 0..32 {
@@ -306,7 +310,11 @@ async fn install_rechecks_even_a_warm_candidate_and_never_downloads_a_changed_ta
.await
.unwrap();
assert!(detail.has_update);
let status = complete_update(&service, &detail.latest_version).await;
let status = complete_update(
&service,
detail.latest_version.as_deref().expect("confirmed target"),
)
.await;
assert_eq!(status.operation.status, SystemOperationStatus::Failed);
assert!(status.operation.error.unwrap().contains("重新检查并确认"));
assert_eq!(server.received_requests().await.unwrap().len(), 3);
@@ -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();
@@ -59,7 +59,7 @@ async fn update_detail_should_withhold_updates_for_source_builds() {
.update_detail(SystemUpdateCheck::Refresh, None)
.await
.expect("detail");
assert_eq!(detail.latest_version, "1.0.0");
assert!(detail.latest_version.is_none());
assert!(!detail.update_supported);
assert!(detail.unsupported_reason.is_some());
assert!(!detail.has_update);
@@ -107,10 +107,7 @@ async fn update_checks_should_follow_stage_promotion_and_experimental_isolation(
.await
.expect("detail");
assert_eq!(detail.has_update, allowed, "{current} -> {target}");
assert_eq!(
detail.latest_version,
if allowed { target } else { current }
);
assert_eq!(detail.latest_version.as_deref(), allowed.then_some(target));
assert_eq!(detail.notes.is_some(), allowed);
assert_eq!(detail.release_url.is_some(), allowed);
assert_eq!(detail.warning.is_none(), allowed);
@@ -161,7 +158,7 @@ async fn update_detail_should_keep_current_release_notes_without_allowing_reinst
.update_detail(SystemUpdateCheck::Refresh, None)
.await
.expect("current release");
assert_eq!(detail.latest_version, current);
assert_eq!(detail.latest_version.as_deref(), Some(current));
assert!(!detail.has_update);
assert!(detail.update_supported);
assert_eq!(
@@ -193,15 +190,15 @@ async fn update_detail_should_keep_current_release_notes_without_allowing_reinst
#[tokio::test]
async fn update_checks_should_ignore_downgrades_unknown_stages_and_build_metadata() {
for (current, target) in [
("3.12.0-beta.2", "3.12.0-beta.1"),
("3.12.0", "3.12.0+new-build"),
("3.12.0-beta.1+aaa", "3.12.0-beta.1+zzz"),
("3.12.0", "3.11.0"),
("3.12.0-alpha.1", "3.12.0-preview.2"),
("3.12.0-alpha.1", "3.12.0-beta"),
("3.12.0-alpha.1", "3.12.0-beta.0"),
("3.12.0-alpha.1", "3.12.0-beta.2.extra"),
for (current, target, published) in [
("3.12.0-beta.2", "3.12.0-beta.1", true),
("3.12.0", "3.12.0+new-build", true),
("3.12.0-beta.1+aaa", "3.12.0-beta.1+zzz", true),
("3.12.0", "3.11.0", true),
("3.12.0-alpha.1", "3.12.0-preview.2", false),
("3.12.0-alpha.1", "3.12.0-beta", false),
("3.12.0-alpha.1", "3.12.0-beta.0", false),
("3.12.0-alpha.1", "3.12.0-beta.2.extra", false),
] {
let server = MockServer::start().await;
let fixture = Fixture::new();
@@ -214,9 +211,12 @@ async fn update_checks_should_ignore_downgrades_unknown_stages_and_build_metadat
.await
.expect("detail");
assert!(!detail.has_update, "{current} -> {target}");
assert_eq!(detail.latest_version, current);
assert!(detail.notes.is_none());
assert!(detail.release_url.is_none());
assert_eq!(
detail.latest_version.as_deref(),
published.then_some(target)
);
assert_eq!(detail.notes.is_some(), published);
assert_eq!(detail.release_url.is_some(), published);
}
}

Some files were not shown because too many files have changed in this diff Show More