mirror of
https://github.com/Wei-Shaw/sub2api.git
synced 2026-12-04 23:51:08 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b0fa9f3e6e | ||
|
|
8b13851ac8 | ||
|
|
926d3cd86d | ||
|
|
ad9eeedebb | ||
|
|
9cd1a1eb21 | ||
|
|
ef29203002 | ||
|
|
7e4c614bcf | ||
|
|
3e8e3254d1 | ||
|
|
f8d891d6fb | ||
|
|
7a19bbef73 | ||
|
|
4328510f28 | ||
|
|
03c17491b3 | ||
|
|
03a489e43e | ||
|
|
589166e320 | ||
|
|
6613ced573 | ||
|
|
a2dfcc259f | ||
|
|
bf3951a59e | ||
|
|
a535a921f1 | ||
|
|
121a4cca17 | ||
|
|
42efee245e | ||
|
|
8ed701382c | ||
|
|
b140d5db8c | ||
|
|
04503e001e | ||
|
|
f242a6ea23 | ||
|
|
1cf7eb48c4 | ||
|
|
32e70f3d40 | ||
|
|
326ae1ffc9 | ||
|
|
c4ff9b90a9 | ||
|
|
7f3fe5bfde | ||
|
|
2164ea4878 | ||
|
|
2286c26d1b | ||
|
|
8d57f461ca | ||
|
|
e391d5fa38 | ||
|
|
b46b3cbabc | ||
|
|
fb07aaee23 | ||
|
|
70ad8365d9 | ||
|
|
d70676756f | ||
|
|
6b7cbc63be | ||
|
|
46b8792658 | ||
|
|
4f3f916317 | ||
|
|
f2eaed31c3 | ||
|
|
992ac63308 | ||
|
|
101c2462dd | ||
|
|
1ca302abf3 | ||
|
|
9750f8e039 | ||
|
|
568db32f22 | ||
|
|
119b04f945 | ||
|
|
857ab95081 | ||
|
|
470c02b399 | ||
|
|
97957edd9e | ||
|
|
63751ea4de | ||
|
|
1d585c94fd | ||
|
|
4cebc098c3 | ||
|
|
c7df3b693f | ||
|
|
d31a87a4e2 | ||
|
|
56848016c5 | ||
|
|
4763569af2 | ||
|
|
202740441d | ||
|
|
3b5310c5d5 | ||
|
|
e16a349ebb | ||
|
|
8a585c9141 | ||
|
|
6247d33eb6 | ||
|
|
6fd905f30d | ||
|
|
e54a186548 | ||
|
|
0563176a5d | ||
|
|
c782537eef | ||
|
|
d7ae0544e8 | ||
|
|
5146728d2f | ||
|
|
472ea57525 | ||
|
|
eb25511c71 | ||
|
|
c6d9d48f9a | ||
|
|
a38ffc3050 | ||
|
|
32e4283894 | ||
|
|
51e76a46c1 | ||
|
|
90eb1744d4 | ||
|
|
0b473ad60b | ||
|
|
2df3dbcfbb | ||
|
|
fde504e343 | ||
|
|
910d4d86b2 | ||
|
|
89fce5446d | ||
|
|
bd3a878ef4 | ||
|
|
0ebc8b2fd6 | ||
|
|
8da0388542 | ||
|
|
41c567b38f | ||
|
|
a6e02a37aa | ||
|
|
980ddd9425 | ||
|
|
0c641e5ed7 | ||
|
|
83a1f5dbe8 | ||
|
|
314de5d0c0 | ||
|
|
d7d45924e8 | ||
|
|
a81a345a17 | ||
|
|
e3151c5201 | ||
|
|
5c96ee4d29 | ||
|
|
cca745e8be | ||
|
|
9c32800986 | ||
|
|
ce026a2cbf | ||
|
|
ddb7eac633 | ||
|
|
27a61be4c9 | ||
|
|
b0d60a8c86 | ||
|
|
68071ddde1 | ||
|
|
b32ad6dfe1 | ||
|
|
5cbcb1b591 | ||
|
|
d3716a1730 | ||
|
|
b7878328b6 | ||
|
|
b6c21cd5e7 | ||
|
|
e257b78117 | ||
|
|
ade20f4e47 | ||
|
|
2101f4f940 | ||
|
|
f1013f177f | ||
|
|
975b2807d1 | ||
|
|
330198321f | ||
|
|
c1c9d195b3 | ||
|
|
94e56dd192 | ||
|
|
7349750c01 | ||
|
|
38eb97bd7a | ||
|
|
82cd13d1ec | ||
|
|
d05e8ef033 | ||
|
|
aee71b85b9 | ||
|
|
1f22424362 | ||
|
|
5854a1db43 | ||
|
|
2b86d2f6a0 | ||
|
|
c45ef4116f | ||
|
|
a0340d4dde | ||
|
|
4114fedd18 | ||
|
|
af187f9a50 | ||
|
|
f1394a1ab4 | ||
|
|
e0cf4984f0 | ||
|
|
dd6329b983 | ||
|
|
694d09379b | ||
|
|
a293214977 | ||
|
|
a0a03be96d | ||
|
|
c54ebd4f12 | ||
|
|
d085bb1a37 | ||
|
|
8dcdfff22a | ||
|
|
8480cb0cd9 | ||
|
|
fd64877581 | ||
|
|
734b922bd8 | ||
|
|
9d5fb150b9 | ||
|
|
e677462549 | ||
|
|
90f1151324 | ||
|
|
c487b215fa | ||
|
|
de34f50c1a | ||
|
|
b9d02c31a5 | ||
|
|
fc8af440ed | ||
|
|
bd89d3d943 | ||
|
|
6d7e6b9d84 | ||
|
|
1772430165 | ||
|
|
d850b8e3a2 | ||
|
|
e95e9eb748 | ||
|
|
849aa593d4 | ||
|
|
4f8e9ae2f1 | ||
|
|
b0f6f83911 | ||
|
|
7e75ee4b65 | ||
|
|
346a7dac02 | ||
|
|
24d77b3306 | ||
|
|
97705d147e | ||
|
|
203de719c3 | ||
|
|
39bac35a37 | ||
|
|
636981b28b | ||
|
|
ac981240cc | ||
|
|
d30179f4b5 | ||
|
|
733722f8c7 | ||
|
|
1280006a1f | ||
|
|
c829317fc5 | ||
|
|
6c79fdfc7a | ||
|
|
fa910c1c38 | ||
|
|
829bf2cdb9 | ||
|
|
197109ebce | ||
|
|
4584dcb392 | ||
|
|
fe40612b80 | ||
|
|
23ac69a021 | ||
|
|
796455c1c9 | ||
|
|
43c1ca0148 | ||
|
|
e055d7bafc | ||
|
|
c8f4264f8f | ||
|
|
a8481f0dec | ||
|
|
71ef577054 | ||
|
|
74ba91aa6b | ||
|
|
530c5e3a4f | ||
|
|
6dd5a045b6 | ||
|
|
5846bfbbfa | ||
|
|
d70a23f84b | ||
|
|
98a44ba3f3 | ||
|
|
1546c0c18e | ||
|
|
37a0f3870b | ||
|
|
43511b40e9 | ||
|
|
c115dc27ab |
No files matched your search
@@ -35,7 +35,7 @@ jobs:
|
||||
cache-dependency-path: backend/go.sum
|
||||
- name: Verify Go version
|
||||
run: |
|
||||
go version | grep -q 'go1.27.3'
|
||||
go version | grep -q 'go1.27.4'
|
||||
- name: Unit tests
|
||||
working-directory: backend
|
||||
run: make test-unit
|
||||
@@ -75,7 +75,7 @@ jobs:
|
||||
cache-dependency-path: backend/go.sum
|
||||
- name: Verify Go version
|
||||
run: |
|
||||
go version | grep -q 'go1.27.3'
|
||||
go version | grep -q 'go1.27.4'
|
||||
- name: golangci-lint
|
||||
uses: golangci/golangci-lint-action@v9
|
||||
with:
|
||||
|
||||
@@ -137,7 +137,7 @@ jobs:
|
||||
check-latest: false
|
||||
cache: false
|
||||
- name: Verify Go version
|
||||
run: go version | grep -q 'go1.27.3'
|
||||
run: go version | grep -q 'go1.27.4'
|
||||
- name: Restore target-specific Go cache
|
||||
id: go-cache
|
||||
uses: actions/cache/restore@v6
|
||||
|
||||
@@ -23,7 +23,7 @@ jobs:
|
||||
cache-dependency-path: backend/go.sum
|
||||
- name: Verify Go version
|
||||
run: |
|
||||
go version | grep -q 'go1.27.3'
|
||||
go version | grep -q 'go1.27.4'
|
||||
- name: Run govulncheck
|
||||
working-directory: backend
|
||||
run: |
|
||||
|
||||
+1
-1
@@ -53,7 +53,7 @@ npm install -g pnpm
|
||||
|
||||
### CI 要求
|
||||
|
||||
- Go 版本必须是 **1.27.0**:三个 workflow 都用 `go-version-file: backend/go.mod` 取版本,随后硬断言 `go version | grep -q 'go1.27.0'`。升级 Go 时要同时改 `backend/go.mod`、`backend-ci.yml`(两处)、`release.yml`、`security-scan.yml` 里的这句断言,**以及三个 Dockerfile 里的 Go 构建镜像**(`Dockerfile` / `deploy/Dockerfile` 的 `ARG GOLANG_IMAGE`、`backend/Dockerfile` 的 `FROM golang:`)。前者漏了 CI 会在版本校验步骤直接失败;**后者漏了 CI 不会报,而是等到有人用这些 Dockerfile 构建时才失败**(`go.mod requires go >= X (running Y; GOTOOLCHAIN=local)`)。
|
||||
- Go 版本必须是 **1.27.4**:三个 workflow 都用 `go-version-file: backend/go.mod` 取版本,随后硬断言 `go version | grep -q 'go1.27.4'`。升级 Go 时要同时改 `backend/go.mod`、`backend-ci.yml`(两处)、`release.yml`、`security-scan.yml` 里的这句断言,**以及三个 Dockerfile 里的 Go 构建镜像**(`Dockerfile` / `deploy/Dockerfile` 的 `ARG GOLANG_IMAGE`、`backend/Dockerfile` 的 `FROM golang:`)。前者漏了 CI 会在版本校验步骤直接失败;**后者漏了 CI 不会报,而是等到有人用这些 Dockerfile 构建时才失败**(`go.mod requires go >= X (running Y; GOTOOLCHAIN=local)`)。
|
||||
- 前端使用 `pnpm install --frozen-lockfile`,必须提交 `pnpm-lock.yaml`
|
||||
|
||||
### 本地测试命令
|
||||
|
||||
+1
-1
@@ -8,7 +8,7 @@
|
||||
# =============================================================================
|
||||
|
||||
ARG NODE_IMAGE=node:24-alpine
|
||||
ARG GOLANG_IMAGE=golang:1.27.3-alpine
|
||||
ARG GOLANG_IMAGE=golang:1.27.4-alpine
|
||||
ARG ALPINE_IMAGE=alpine:3.21
|
||||
ARG POSTGRES_IMAGE=postgres:18-alpine
|
||||
ARG GOPROXY=https://goproxy.cn,direct
|
||||
|
||||
@@ -11,6 +11,7 @@ FRONTEND_CRITICAL_VITEST := \
|
||||
src/components/account/__tests__/OpenAIQuotaResetCell.spark_shadow.spec.ts \
|
||||
src/constants/__tests__/platforms.spec.ts \
|
||||
src/components/account/__tests__/credentialsBuilder.platformCatalog.spec.ts \
|
||||
src/components/account/__tests__/CNProviderQuotaCell.spec.ts \
|
||||
src/components/account/__tests__/CreateAccountModal.spec.ts \
|
||||
src/components/account/__tests__/EditAccountModal.spec.ts \
|
||||
src/components/account/__tests__/credentialsBuilder.spec.ts \
|
||||
|
||||
@@ -117,11 +117,6 @@ Please read the following carefully before using this project:
|
||||
<td>Thanks to FennoAI for sponsoring this project! FennoAI is a high-stability, high-performance API relay provider for enterprise R&D teams and developers, compatible with the OpenAI and Anthropic protocols and seamlessly integrating with mainstream AI coding tools such as Codex, Claude Code, and OpenCode. The platform delivers enterprise-grade stability, supporting call volumes of 100 billion tokens per day, and supports business-to-business settlement and invoicing for both domestic and overseas entities to meet enterprise R&D and procurement needs. As an exclusive benefit for Sub2API users, purchase a subscription via the <a href="https://api.fenno.ai/s/dC4k">exclusive link</a> to get $50 worth of Coding Plan credit for only $1.99. Referral rewards are also available: invite friends to purchase and earn up to 20% commission — the more you invite, the more you earn.</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://lanox.ai/?c=6"><img src="assets/partners/logos/lanox.jpg" alt="LanoX AI" width="150"></a></td>
|
||||
<td>Thank you to LanoX AI for sponsoring this project! <a href="https://lanox.ai/?c=6">LanoX AI</a> provides stable, cost-effective global model access services for developers, teams, and enterprises. 🎁 New User Benefits — Claim millions of free tokens, plus 500+ free models for easier low-cost testing, validation, and deployment 🧠 Global Leading Models — GPT · Claude · Gemini · Qwen · Grok... 🎬 Multimodal Creation — Seedance 2.0 · GPT Image · Gemini Nano Banana 🛡️ Enterprise-Grade Reliability — High availability 💎 native capability output 💎 no intelligence degradation 💎 no model mixing 💎 transparent usage and billing 💎 💰 Lower API Costs — Top-tier models from as low as 10% of official pricing, with clear documentation, simple integration, invoicing support, and enterprise-scale batch usage 🏢 Enterprise Choice — Ideal for AI products, Agents, content platforms, and R&D teams with high-volume model usage</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://www.rapidproxy.io/?ref=sub2api"><img src="assets/partners/logos/rapidproxy.jpg" alt="RapidProxy" width="150"></a></td>
|
||||
<td><a href="https://www.rapidproxy.io/?ref=sub2api">RapidProxy</a> is a data collection proxy solution built for developers, providing stable and reliable residential proxy services. With 90M+ global residential IPs and 200+ country coverage, intelligent rotation, and precise geo-targeting, it helps projects such as web scraping, AI data training, SEO monitoring, and e-commerce data analysis break through access restrictions and improve data collection efficiency. It supports mainstream automation frameworks such as Playwright, Selenium, and Puppeteer, with prices as low as $0.65/GB — <a href="https://www.rapidproxy.io/?ref=sub2api">start your free test now</a>.</td>
|
||||
@@ -184,7 +179,12 @@ Please read the following carefully before using this project:
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://massivetokens.com/signup?ref=SUB2API"><img src="assets/partners/logos/massivetokens.jpg" alt="Massive Tokens" width="150"></a></td>
|
||||
<td><a href="https://massivetokens.com/signup?ref=SUB2API">Massive Tokens</a> supplies Claude API access at wholesale per-token prices to businesses and high-volume developers. It serves the standard Anthropic Messages API, so it works with Claude Code, Sub2API, LiteLLM and One API without code changes. Sign up with code SUB2API for 5% off every call.</td>
|
||||
<td><a href="https://massivetokens.com/signup?ref=SUB2API">Massive Tokens</a> supplies Claude API access at wholesale per-token prices to businesses and high-volume developers. It serves the standard Anthropic Messages API, so it works with Claude Code, Sub2API, LiteLLM and One API without code changes. Sign up with code SUB2API for 5% off every call, then join our Telegram group @massivetokens (<a href="https://t.me/massivetokens">https://t.me/massivetokens</a>) and ask an admin for $10 in credits.</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://www.dataeyes.vip/?promoter_code=9dkfv2r3"><img src="assets/partners/logos/DataEyesAI.png" alt="DataEyesAI" width="150"></a></td>
|
||||
<td><a href="https://www.dataeyes.vip/?promoter_code=9dkfv2r3">DataEyesAI</a> is an all-in-one AI API platform for developers and businesses, offering unified access to leading models including OpenAI, Claude, and Gemini for AI coding and text, image, audio, and video generation. It supports popular AI coding tools such as Claude Code and Codex, with pay-as-you-go pricing, real-time usage and cost monitoring, and 24/7 technical support to simplify model integration and keep development costs under control. New users can sign up through <a href="https://www.dataeyes.vip/?promoter_code=9dkfv2r3">this link</a> to claim usage credits. From coding to multimodal creation, start your AI journey in one place!</td>
|
||||
</tr>
|
||||
|
||||
</table>
|
||||
|
||||
+6
-6
@@ -120,11 +120,6 @@
|
||||
<td>感谢 FennoAI 赞助本项目!FennoAI 是一家面向企业研发团队和开发者的高稳定、高性能 API 中转服务商,兼容 OpenAI 与 Anthropic 协议,可无缝接入 Codex、Claude Code、OpenCode 等主流 AI 编程工具。平台具备企业级稳定性,可支撑千亿 Token/日的调用规模,并支持境内外主体公对公结算及开票,满足企业级研发与采购需求。作为 Sub2API 用户专属福利,通过<a href="https://api.fenno.ai/s/dC4k">专属链接</a>购买订阅,仅需 1.99 美元即可获得价值 50 美元的 Coding Plan 额度。同时支持邀请奖励,邀请好友购买最高可获得 20% 返佣,邀请越多,奖励越高。</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://lanox.ai/?c=6"><img src="assets/partners/logos/lanox.jpg" alt="LanoX AI" width="150"></a></td>
|
||||
<td>感谢 LanoX AI 对本项目的赞助!<a href="https://lanox.ai/?c=6">LanoX AI</a> 为开发者、团队与企业提供稳定、高性价比的全球模型接入服务。 🎁 新用户福利 — 免费领取 百万 Token ,更有500+ 免费模型 — 低成本测试、验证、部署更轻松 🧠 全球主流模型 — GPT · Claude · Gemini · Qwen · Grok... 🎬 多模态创作 — Seedance 2.0 · GPT Image · Gemini Nano Banana 🛡️ 企业级稳定服务 — 高可用💎原生能力输出💎不降智💎不混模💎调用与计费透明💎 💰 更低调用成本 — 顶级模型低至官方价 1 折起,文档清晰、接入简单、支持开票与企业批量调用 🏢 企业优选 — 适用于 AI 产品、Agent、内容平台、研发团队批量调用</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://www.rapidproxy.io/?ref=sub2api"><img src="assets/partners/logos/rapidproxy.jpg" alt="RapidProxy" width="150"></a></td>
|
||||
<td><a href="https://www.rapidproxy.io/?ref=sub2api">RapidProxy</a> 是面向开发者的数据采集代理解决方案,提供稳定可靠的住宅代理服务。通过 9000 万+全球住宅 IP和 200+国家覆盖、智能轮换机制和精准地区定位能力,帮助爬虫、AI 数据训练、SEO 监控、电商数据分析等项目突破访问限制,提高数据采集效率。支持 Playwright、Selenium、Puppeteer 等主流自动化框架,价格低至 $0.65/GB,<a href="https://www.rapidproxy.io/?ref=sub2api">立即免费测试吧</a>。</td>
|
||||
@@ -187,7 +182,12 @@
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://massivetokens.com/signup?ref=SUB2API"><img src="assets/partners/logos/massivetokens.jpg" alt="Massive Tokens" width="150"></a></td>
|
||||
<td><a href="https://massivetokens.com/signup?ref=SUB2API">Massive Tokens</a> 以批发价向企业和大用量开发者提供 Claude API。提供标准的 Anthropic Messages API,Claude Code、Sub2API、LiteLLM、One API 无需改代码即可接入。使用邀请码 SUB2API 注册,每次调用立减 5%。</td>
|
||||
<td><a href="https://massivetokens.com/signup?ref=SUB2API">Massive Tokens</a> 以批发价向企业和大用量开发者提供 Claude API。提供标准的 Anthropic Messages API,Claude Code、Sub2API、LiteLLM、One API 无需改代码即可接入。使用邀请码 SUB2API 注册,每次调用立减 5%;注册后加入 Telegram 群 @massivetokens (<a href="https://t.me/massivetokens">https://t.me/massivetokens</a>),向管理员申请 $10 额度。</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://www.dataeyes.vip/?promoter_code=9dkfv2r3"><img src="assets/partners/logos/DataEyesAI.png" alt="DataEyesAI" width="150"></a></td>
|
||||
<td><a href="https://www.dataeyes.vip/?promoter_code=9dkfv2r3">DataEyesAI</a> 是面向开发者与企业的一站式 AI API 服务平台,通过统一接口接入 OpenAI、Claude、Gemini 等主流模型,覆盖 AI 编程及文本、图像、音频、视频生成。支持 Claude Code、Codex 等主流 AI 编程工具,提供按量付费、实时用量与成本监控,以及 7×24 小时技术支持,让模型接入更便捷、开发成本更可控。新用户通过<a href="https://www.dataeyes.vip/?promoter_code=9dkfv2r3">此链接</a>注册,可领取使用额度,从代码开发到多模态创作,一站开启 AI 应用之旅!</td>
|
||||
</tr>
|
||||
|
||||
</table>
|
||||
|
||||
+6
-6
@@ -119,11 +119,6 @@
|
||||
<td>FennoAI のご支援に感謝します!FennoAI は、企業の研究開発チームと開発者向けの高安定・高性能 API 中継サービスプロバイダーです。OpenAI と Anthropic のプロトコルに対応し、Codex、Claude Code、OpenCode などの主要 AI コーディングツールにシームレスに接続できます。エンタープライズ級の安定性を備え、1 日あたり千億規模の Token 呼び出しに対応。国内外法人間の企業間決済と請求書発行もサポートし、企業の研究開発・調達ニーズに応えます。Sub2API ユーザー限定特典として、<a href="https://api.fenno.ai/s/dC4k">専用リンク</a>からサブスクリプションを購入すると、わずか 1.99 ドルで 50 ドル相当の Coding Plan クレジットを獲得できます。さらに招待報酬にも対応しており、友達の購入で最大 20% の還元を獲得可能。招待が多いほど、報酬も増えます。</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://lanox.ai/?c=6"><img src="assets/partners/logos/lanox.jpg" alt="LanoX AI" width="150"></a></td>
|
||||
<td>本プロジェクトをご支援いただいている <a href="https://lanox.ai/?c=6">LanoX AI</a> に感謝します!LanoX AI は、開発者、チーム、企業向けに、安定性とコストパフォーマンスに優れたグローバルモデル接続サービスを提供しています。 🎁 新規ユーザー特典 — 数百万 Token を無料で獲得可能。さらに 500+ の無料モデルで、低コストなテスト、検証、デプロイをより簡単に 🧠 世界の主要モデル — GPT · Claude · Gemini · Qwen · Grok... 🎬 マルチモーダル制作 — Seedance 2.0 · GPT Image · Gemini Nano Banana 🛡️ エンタープライズ級の安定性 — 高可用性 💎 ネイティブ能力の出力 💎 性能劣化なし 💎 モデル混在なし 💎 利用量と課金が透明 💎 💰 より低い利用コスト — トップモデルを公式価格の 1 割から利用可能。明確なドキュメント、簡単な接続、請求書発行、企業向け一括利用に対応 🏢 企業に最適 — AI プロダクト、Agent、コンテンツプラットフォーム、大量利用する開発チームに最適</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://www.rapidproxy.io/?ref=sub2api"><img src="assets/partners/logos/rapidproxy.jpg" alt="RapidProxy" width="150"></a></td>
|
||||
<td><a href="https://www.rapidproxy.io/?ref=sub2api">RapidProxy</a> は開発者向けのデータ収集プロキシソリューションであり、安定して信頼できる住宅用プロキシサービスを提供します。9,000 万以上のグローバル住宅 IP と 200 以上の国・地域のカバー、インテリジェントなローテーション機構、精密な地域ターゲティング機能により、クローラー、AI データ学習、SEO モニタリング、EC データ分析などのプロジェクトがアクセス制限を突破し、データ収集の効率を高めます。Playwright、Selenium、Puppeteer などの主要な自動化フレームワークに対応し、料金は $0.65/GB から。<a href="https://www.rapidproxy.io/?ref=sub2api">今すぐ無料でお試しください</a>。</td>
|
||||
@@ -181,7 +176,12 @@
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://massivetokens.com/signup?ref=SUB2API"><img src="assets/partners/logos/massivetokens.jpg" alt="Massive Tokens" width="150"></a></td>
|
||||
<td><a href="https://massivetokens.com/signup?ref=SUB2API">Massive Tokens</a> は、企業や大量に利用する開発者向けに、Claude API を token 単位の卸売価格で提供しています。標準の Anthropic Messages API を提供しているため、Claude Code、Sub2API、LiteLLM、One API とコードを変更せずに連携できます。招待コード SUB2API で登録すると、すべての呼び出しが 5% オフになります。</td>
|
||||
<td><a href="https://massivetokens.com/signup?ref=SUB2API">Massive Tokens</a> は、企業や大量に利用する開発者向けに、Claude API を token 単位の卸売価格で提供しています。標準の Anthropic Messages API を提供しているため、Claude Code、Sub2API、LiteLLM、One API とコードを変更せずに連携できます。招待コード SUB2API で登録すると、すべての呼び出しが 5% オフになります。登録後は Telegram グループ @massivetokens (<a href="https://t.me/massivetokens">https://t.me/massivetokens</a>) に参加し、管理者に $10 分のクレジットをリクエストしてください。</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://www.dataeyes.vip/?promoter_code=9dkfv2r3"><img src="assets/partners/logos/DataEyesAI.png" alt="DataEyesAI" width="150"></a></td>
|
||||
<td><a href="https://www.dataeyes.vip/?promoter_code=9dkfv2r3">DataEyesAI</a> は、開発者と企業向けのワンストップ AI API プラットフォームです。統一 API を通じて OpenAI、Claude、Gemini などの主要モデルを利用でき、AI コーディングからテキスト・画像・音声・動画の生成まで幅広く対応しています。Claude Code や Codex などの主要な AI コーディングツールに対応し、従量課金、リアルタイムの利用状況・コスト監視、24時間365日のテクニカルサポートを提供。モデル連携をより手軽にし、開発コストを管理しやすくします。<a href="https://www.dataeyes.vip/?promoter_code=9dkfv2r3">こちらのリンク</a>から新規登録すると、利用クレジットを受け取れます。コード開発からマルチモーダル制作まで、AI 活用をここから始めましょう!</td>
|
||||
</tr>
|
||||
|
||||
</table>
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 4.4 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 10 KiB |
+1
-1
@@ -1,4 +1,4 @@
|
||||
FROM golang:1.27.2-alpine
|
||||
FROM golang:1.27.4-alpine
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
|
||||
@@ -1 +1 @@
|
||||
0.2.20
|
||||
0.2.21
|
||||
@@ -111,6 +111,7 @@ func provideCleanup(
|
||||
emailQueue *service.EmailQueueService,
|
||||
billingCache *service.BillingCacheService,
|
||||
usageRecordWorkerPool *service.UsageRecordWorkerPool,
|
||||
usageBillingLanes *service.UsageBillingLaneCombiner,
|
||||
balanceNotify *service.BalanceNotifyService,
|
||||
digestSessions *service.DigestSessionStore,
|
||||
subscriptionService *service.SubscriptionService,
|
||||
@@ -331,6 +332,10 @@ func provideCleanup(
|
||||
}
|
||||
return nil
|
||||
}},
|
||||
{"UsageBillingLaneCombiner", func() error {
|
||||
usageBillingLanes.Stop()
|
||||
return nil
|
||||
}},
|
||||
{"OAuthService", func() error {
|
||||
oauth.Stop()
|
||||
return nil
|
||||
|
||||
@@ -105,7 +105,9 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
|
||||
usageLogRepository := repository.NewUsageLogRepository(client, db)
|
||||
usageService := service.NewUsageService(usageLogRepository, userRepository, client, apiKeyAuthCacheInvalidator)
|
||||
opsRepository := repository.NewOpsRepository(db)
|
||||
usageBillingRepository := repository.NewUsageBillingRepository(client, db)
|
||||
usageBillingBatchRepository := repository.NewUsageBillingRepository(client, db)
|
||||
usageBillingLaneCombiner := service.NewUsageBillingLaneCombiner(usageBillingBatchRepository)
|
||||
usageBillingRepository := service.ProvideUsageBillingRepository(usageBillingLaneCombiner)
|
||||
gatewayCache := repository.NewGatewayCache(redisClient)
|
||||
schedulerOutboxRepository := repository.NewSchedulerOutboxRepository(db)
|
||||
schedulerSnapshotService := service.ProvideSchedulerSnapshotService(schedulerCache, schedulerOutboxRepository, accountRepository, groupRepository, configConfig)
|
||||
@@ -359,7 +361,7 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
|
||||
channelMonitorRunner := service.ProvideChannelMonitorRunner(channelMonitorService, settingService, channelMonitorQuotaFetcher)
|
||||
channelMonitorV2Aggregator := service.ProvideChannelMonitorV2Aggregator(channelMonitorV2Repository, db, settingService)
|
||||
userPlatformQuotaUsageFlusher := service.ProvideUserPlatformQuotaUsageFlusher(configConfig, billingCache, serviceUserPlatformQuotaRepository, timingWheelService)
|
||||
v := provideCleanup(client, redisClient, opsMetricsCollector, opsAggregationService, opsAlertEvaluatorService, opsCleanupService, opsScheduledReportService, opsSystemLogSink, opsService, opsIngressRejectAggregator, apiKeyService, authCacheInvalidationWorker, schedulerSnapshotService, tokenRefreshService, accountExpiryService, cnProviderBalanceCheckService, openAICodexVersionSyncService, claudeCodeVersionSyncService, proxyExpiryService, subscriptionExpiryService, usageCleanupService, idempotencyCleanupService, geminiCachedContentService, batchImageCleanupService, batchImageWorkerRuntime, pricingService, emailQueueService, billingCacheService, usageRecordWorkerPool, balanceNotifyService, digestSessionStore, subscriptionService, oAuthService, openAIOAuthService, geminiOAuthService, antigravityOAuthService, grokOAuthService, openAIGatewayService, scheduledTestRunnerService, backupService, paymentOrderExpiryService, channelMonitorRunner, channelMonitorV2Aggregator, userPlatformQuotaUsageFlusher, upstreamBillingProbeService, ollamaCloudUsageService, openCodeGoUsageService, auditLogService, openAIQuotaAutoResetService, promptService, pluginManager)
|
||||
v := provideCleanup(client, redisClient, opsMetricsCollector, opsAggregationService, opsAlertEvaluatorService, opsCleanupService, opsScheduledReportService, opsSystemLogSink, opsService, opsIngressRejectAggregator, apiKeyService, authCacheInvalidationWorker, schedulerSnapshotService, tokenRefreshService, accountExpiryService, cnProviderBalanceCheckService, openAICodexVersionSyncService, claudeCodeVersionSyncService, proxyExpiryService, subscriptionExpiryService, usageCleanupService, idempotencyCleanupService, geminiCachedContentService, batchImageCleanupService, batchImageWorkerRuntime, pricingService, emailQueueService, billingCacheService, usageRecordWorkerPool, usageBillingLaneCombiner, balanceNotifyService, digestSessionStore, subscriptionService, oAuthService, openAIOAuthService, geminiOAuthService, antigravityOAuthService, grokOAuthService, openAIGatewayService, scheduledTestRunnerService, backupService, paymentOrderExpiryService, channelMonitorRunner, channelMonitorV2Aggregator, userPlatformQuotaUsageFlusher, upstreamBillingProbeService, ollamaCloudUsageService, openCodeGoUsageService, auditLogService, openAIQuotaAutoResetService, promptService, pluginManager)
|
||||
application := &Application{
|
||||
Server: httpServer,
|
||||
PromptAudit: promptService,
|
||||
@@ -426,6 +428,7 @@ func provideCleanup(
|
||||
emailQueue *service.EmailQueueService,
|
||||
billingCache *service.BillingCacheService,
|
||||
usageRecordWorkerPool *service.UsageRecordWorkerPool,
|
||||
usageBillingLanes *service.UsageBillingLaneCombiner,
|
||||
balanceNotify *service.BalanceNotifyService,
|
||||
digestSessions *service.DigestSessionStore,
|
||||
subscriptionService *service.SubscriptionService,
|
||||
@@ -645,6 +648,10 @@ func provideCleanup(
|
||||
}
|
||||
return nil
|
||||
}},
|
||||
{"UsageBillingLaneCombiner", func() error {
|
||||
usageBillingLanes.Stop()
|
||||
return nil
|
||||
}},
|
||||
{"OAuthService", func() error {
|
||||
oauth.Stop()
|
||||
return nil
|
||||
|
||||
@@ -81,6 +81,7 @@ func TestProvideCleanup_WithMinimalDependencies_NoPanic(t *testing.T) {
|
||||
emailQueueSvc,
|
||||
billingCacheSvc,
|
||||
&service.UsageRecordWorkerPool{},
|
||||
nil, // usageBillingLanes
|
||||
service.ProvideBalanceNotifyService(nil, nil, nil, nil),
|
||||
service.NewDigestSessionStore(),
|
||||
&service.SubscriptionService{},
|
||||
|
||||
+12
-1
@@ -128,6 +128,8 @@ type Group struct {
|
||||
AllowLive bool `json:"allow_live,omitempty"`
|
||||
// 是否强制此 OpenAI/Composite 分组请求使用 service_tier=priority
|
||||
ForceOpenaiFast bool `json:"force_openai_fast,omitempty"`
|
||||
// 是否对支持 Ultrafast 的模型强制使用 service_tier=ultrafast(优先于 force_openai_fast)
|
||||
ForceOpenaiUltrafast bool `json:"force_openai_ultrafast,omitempty"`
|
||||
// 是否让此 OpenAI/Composite 分组的 Fast 请求按 Standard 价格计费
|
||||
FreeOpenaiFast bool `json:"free_openai_fast,omitempty"`
|
||||
// 仅允许非 apikey 类型账号关联到此分组
|
||||
@@ -264,7 +266,7 @@ func (*Group) scanValues(columns []string) ([]any, error) {
|
||||
switch columns[i] {
|
||||
case group.FieldI18n, group.FieldVideoModelPrices, group.FieldModelPricing, group.FieldModelRouting, group.FieldSupportedModelScopes, group.FieldMessagesDispatchModelConfig, group.FieldModelAllowlist, group.FieldCodexModelsManifestConfig, group.FieldReasoningEffortMappings:
|
||||
values[i] = new([]byte)
|
||||
case group.FieldPeakRateEnabled, group.FieldIsExclusive, group.FieldAllowImageGeneration, group.FieldAllowBatchImageGeneration, group.FieldImageCountBilling, group.FieldImageRateIndependent, group.FieldVideoRateIndependent, group.FieldLongContextPricingEnabled, group.FieldClaudeCodeOnly, group.FieldModelRoutingEnabled, group.FieldMcpXMLInject, group.FieldAllowMessagesDispatch, group.FieldAllowLive, group.FieldForceOpenaiFast, group.FieldFreeOpenaiFast, group.FieldRequireOauthOnly, group.FieldRequirePrivacySet, group.FieldProfitControlEnabled:
|
||||
case group.FieldPeakRateEnabled, group.FieldIsExclusive, group.FieldAllowImageGeneration, group.FieldAllowBatchImageGeneration, group.FieldImageCountBilling, group.FieldImageRateIndependent, group.FieldVideoRateIndependent, group.FieldLongContextPricingEnabled, group.FieldClaudeCodeOnly, group.FieldModelRoutingEnabled, group.FieldMcpXMLInject, group.FieldAllowMessagesDispatch, group.FieldAllowLive, group.FieldForceOpenaiFast, group.FieldForceOpenaiUltrafast, group.FieldFreeOpenaiFast, group.FieldRequireOauthOnly, group.FieldRequirePrivacySet, group.FieldProfitControlEnabled:
|
||||
values[i] = new(sql.NullBool)
|
||||
case group.FieldRateMultiplier, group.FieldPeakRateMultiplier, group.FieldDailyLimitUsd, group.FieldWeeklyLimitUsd, group.FieldMonthlyLimitUsd, group.FieldImageRateMultiplier, group.FieldImagePrice1k, group.FieldImagePrice2k, group.FieldImagePrice4k, group.FieldBatchImageDiscountMultiplier, group.FieldBatchImageHoldMultiplier, group.FieldVideoRateMultiplier, group.FieldVideoPrice480p, group.FieldVideoPrice720p, group.FieldVideoPrice1080p, group.FieldWebSearchPricePerCall, group.FieldSearchPricePer1k, group.FieldAudioRealtimePricePerMin, group.FieldAudioTtsPricePerMillionChars, group.FieldAudioSttPricePerHour, group.FieldProfitMinMargin, group.FieldProfitSafetyBuffer:
|
||||
values[i] = new(sql.NullFloat64)
|
||||
@@ -648,6 +650,12 @@ func (_m *Group) assignValues(columns []string, values []any) error {
|
||||
} else if value.Valid {
|
||||
_m.ForceOpenaiFast = value.Bool
|
||||
}
|
||||
case group.FieldForceOpenaiUltrafast:
|
||||
if value, ok := values[i].(*sql.NullBool); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field force_openai_ultrafast", values[i])
|
||||
} else if value.Valid {
|
||||
_m.ForceOpenaiUltrafast = value.Bool
|
||||
}
|
||||
case group.FieldFreeOpenaiFast:
|
||||
if value, ok := values[i].(*sql.NullBool); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field free_openai_fast", values[i])
|
||||
@@ -1016,6 +1024,9 @@ func (_m *Group) String() string {
|
||||
builder.WriteString("force_openai_fast=")
|
||||
builder.WriteString(fmt.Sprintf("%v", _m.ForceOpenaiFast))
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("force_openai_ultrafast=")
|
||||
builder.WriteString(fmt.Sprintf("%v", _m.ForceOpenaiUltrafast))
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("free_openai_fast=")
|
||||
builder.WriteString(fmt.Sprintf("%v", _m.FreeOpenaiFast))
|
||||
builder.WriteString(", ")
|
||||
|
||||
@@ -124,6 +124,8 @@ const (
|
||||
FieldAllowLive = "allow_live"
|
||||
// FieldForceOpenaiFast holds the string denoting the force_openai_fast field in the database.
|
||||
FieldForceOpenaiFast = "force_openai_fast"
|
||||
// FieldForceOpenaiUltrafast holds the string denoting the force_openai_ultrafast field in the database.
|
||||
FieldForceOpenaiUltrafast = "force_openai_ultrafast"
|
||||
// FieldFreeOpenaiFast holds the string denoting the free_openai_fast field in the database.
|
||||
FieldFreeOpenaiFast = "free_openai_fast"
|
||||
// FieldRequireOauthOnly holds the string denoting the require_oauth_only field in the database.
|
||||
@@ -281,6 +283,7 @@ var Columns = []string{
|
||||
FieldAllowMessagesDispatch,
|
||||
FieldAllowLive,
|
||||
FieldForceOpenaiFast,
|
||||
FieldForceOpenaiUltrafast,
|
||||
FieldFreeOpenaiFast,
|
||||
FieldRequireOauthOnly,
|
||||
FieldRequirePrivacySet,
|
||||
@@ -410,6 +413,8 @@ var (
|
||||
DefaultAllowLive bool
|
||||
// DefaultForceOpenaiFast holds the default value on creation for the "force_openai_fast" field.
|
||||
DefaultForceOpenaiFast bool
|
||||
// DefaultForceOpenaiUltrafast holds the default value on creation for the "force_openai_ultrafast" field.
|
||||
DefaultForceOpenaiUltrafast bool
|
||||
// DefaultFreeOpenaiFast holds the default value on creation for the "free_openai_fast" field.
|
||||
DefaultFreeOpenaiFast bool
|
||||
// DefaultRequireOauthOnly holds the default value on creation for the "require_oauth_only" field.
|
||||
@@ -699,6 +704,11 @@ func ByForceOpenaiFast(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldForceOpenaiFast, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByForceOpenaiUltrafast orders the results by the force_openai_ultrafast field.
|
||||
func ByForceOpenaiUltrafast(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldForceOpenaiUltrafast, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByFreeOpenaiFast orders the results by the free_openai_fast field.
|
||||
func ByFreeOpenaiFast(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldFreeOpenaiFast, opts...).ToFunc()
|
||||
|
||||
@@ -300,6 +300,11 @@ func ForceOpenaiFast(v bool) predicate.Group {
|
||||
return predicate.Group(sql.FieldEQ(FieldForceOpenaiFast, v))
|
||||
}
|
||||
|
||||
// ForceOpenaiUltrafast applies equality check predicate on the "force_openai_ultrafast" field. It's identical to ForceOpenaiUltrafastEQ.
|
||||
func ForceOpenaiUltrafast(v bool) predicate.Group {
|
||||
return predicate.Group(sql.FieldEQ(FieldForceOpenaiUltrafast, v))
|
||||
}
|
||||
|
||||
// FreeOpenaiFast applies equality check predicate on the "free_openai_fast" field. It's identical to FreeOpenaiFastEQ.
|
||||
func FreeOpenaiFast(v bool) predicate.Group {
|
||||
return predicate.Group(sql.FieldEQ(FieldFreeOpenaiFast, v))
|
||||
@@ -2310,6 +2315,16 @@ func ForceOpenaiFastNEQ(v bool) predicate.Group {
|
||||
return predicate.Group(sql.FieldNEQ(FieldForceOpenaiFast, v))
|
||||
}
|
||||
|
||||
// ForceOpenaiUltrafastEQ applies the EQ predicate on the "force_openai_ultrafast" field.
|
||||
func ForceOpenaiUltrafastEQ(v bool) predicate.Group {
|
||||
return predicate.Group(sql.FieldEQ(FieldForceOpenaiUltrafast, v))
|
||||
}
|
||||
|
||||
// ForceOpenaiUltrafastNEQ applies the NEQ predicate on the "force_openai_ultrafast" field.
|
||||
func ForceOpenaiUltrafastNEQ(v bool) predicate.Group {
|
||||
return predicate.Group(sql.FieldNEQ(FieldForceOpenaiUltrafast, v))
|
||||
}
|
||||
|
||||
// FreeOpenaiFastEQ applies the EQ predicate on the "free_openai_fast" field.
|
||||
func FreeOpenaiFastEQ(v bool) predicate.Group {
|
||||
return predicate.Group(sql.FieldEQ(FieldFreeOpenaiFast, v))
|
||||
|
||||
@@ -738,6 +738,20 @@ func (_c *GroupCreate) SetNillableForceOpenaiFast(v *bool) *GroupCreate {
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetForceOpenaiUltrafast sets the "force_openai_ultrafast" field.
|
||||
func (_c *GroupCreate) SetForceOpenaiUltrafast(v bool) *GroupCreate {
|
||||
_c.mutation.SetForceOpenaiUltrafast(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetNillableForceOpenaiUltrafast sets the "force_openai_ultrafast" field if the given value is not nil.
|
||||
func (_c *GroupCreate) SetNillableForceOpenaiUltrafast(v *bool) *GroupCreate {
|
||||
if v != nil {
|
||||
_c.SetForceOpenaiUltrafast(*v)
|
||||
}
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetFreeOpenaiFast sets the "free_openai_fast" field.
|
||||
func (_c *GroupCreate) SetFreeOpenaiFast(v bool) *GroupCreate {
|
||||
_c.mutation.SetFreeOpenaiFast(v)
|
||||
@@ -1183,6 +1197,10 @@ func (_c *GroupCreate) defaults() error {
|
||||
v := group.DefaultForceOpenaiFast
|
||||
_c.mutation.SetForceOpenaiFast(v)
|
||||
}
|
||||
if _, ok := _c.mutation.ForceOpenaiUltrafast(); !ok {
|
||||
v := group.DefaultForceOpenaiUltrafast
|
||||
_c.mutation.SetForceOpenaiUltrafast(v)
|
||||
}
|
||||
if _, ok := _c.mutation.FreeOpenaiFast(); !ok {
|
||||
v := group.DefaultFreeOpenaiFast
|
||||
_c.mutation.SetFreeOpenaiFast(v)
|
||||
@@ -1395,6 +1413,9 @@ func (_c *GroupCreate) check() error {
|
||||
if _, ok := _c.mutation.ForceOpenaiFast(); !ok {
|
||||
return &ValidationError{Name: "force_openai_fast", err: errors.New(`ent: missing required field "Group.force_openai_fast"`)}
|
||||
}
|
||||
if _, ok := _c.mutation.ForceOpenaiUltrafast(); !ok {
|
||||
return &ValidationError{Name: "force_openai_ultrafast", err: errors.New(`ent: missing required field "Group.force_openai_ultrafast"`)}
|
||||
}
|
||||
if _, ok := _c.mutation.FreeOpenaiFast(); !ok {
|
||||
return &ValidationError{Name: "free_openai_fast", err: errors.New(`ent: missing required field "Group.free_openai_fast"`)}
|
||||
}
|
||||
@@ -1695,6 +1716,10 @@ func (_c *GroupCreate) createSpec() (*Group, *sqlgraph.CreateSpec) {
|
||||
_spec.SetField(group.FieldForceOpenaiFast, field.TypeBool, value)
|
||||
_node.ForceOpenaiFast = value
|
||||
}
|
||||
if value, ok := _c.mutation.ForceOpenaiUltrafast(); ok {
|
||||
_spec.SetField(group.FieldForceOpenaiUltrafast, field.TypeBool, value)
|
||||
_node.ForceOpenaiUltrafast = value
|
||||
}
|
||||
if value, ok := _c.mutation.FreeOpenaiFast(); ok {
|
||||
_spec.SetField(group.FieldFreeOpenaiFast, field.TypeBool, value)
|
||||
_node.FreeOpenaiFast = value
|
||||
@@ -2801,6 +2826,18 @@ func (u *GroupUpsert) UpdateForceOpenaiFast() *GroupUpsert {
|
||||
return u
|
||||
}
|
||||
|
||||
// SetForceOpenaiUltrafast sets the "force_openai_ultrafast" field.
|
||||
func (u *GroupUpsert) SetForceOpenaiUltrafast(v bool) *GroupUpsert {
|
||||
u.Set(group.FieldForceOpenaiUltrafast, v)
|
||||
return u
|
||||
}
|
||||
|
||||
// UpdateForceOpenaiUltrafast sets the "force_openai_ultrafast" field to the value that was provided on create.
|
||||
func (u *GroupUpsert) UpdateForceOpenaiUltrafast() *GroupUpsert {
|
||||
u.SetExcluded(group.FieldForceOpenaiUltrafast)
|
||||
return u
|
||||
}
|
||||
|
||||
// SetFreeOpenaiFast sets the "free_openai_fast" field.
|
||||
func (u *GroupUpsert) SetFreeOpenaiFast(v bool) *GroupUpsert {
|
||||
u.Set(group.FieldFreeOpenaiFast, v)
|
||||
@@ -4078,6 +4115,20 @@ func (u *GroupUpsertOne) UpdateForceOpenaiFast() *GroupUpsertOne {
|
||||
})
|
||||
}
|
||||
|
||||
// SetForceOpenaiUltrafast sets the "force_openai_ultrafast" field.
|
||||
func (u *GroupUpsertOne) SetForceOpenaiUltrafast(v bool) *GroupUpsertOne {
|
||||
return u.Update(func(s *GroupUpsert) {
|
||||
s.SetForceOpenaiUltrafast(v)
|
||||
})
|
||||
}
|
||||
|
||||
// UpdateForceOpenaiUltrafast sets the "force_openai_ultrafast" field to the value that was provided on create.
|
||||
func (u *GroupUpsertOne) UpdateForceOpenaiUltrafast() *GroupUpsertOne {
|
||||
return u.Update(func(s *GroupUpsert) {
|
||||
s.UpdateForceOpenaiUltrafast()
|
||||
})
|
||||
}
|
||||
|
||||
// SetFreeOpenaiFast sets the "free_openai_fast" field.
|
||||
func (u *GroupUpsertOne) SetFreeOpenaiFast(v bool) *GroupUpsertOne {
|
||||
return u.Update(func(s *GroupUpsert) {
|
||||
@@ -5552,6 +5603,20 @@ func (u *GroupUpsertBulk) UpdateForceOpenaiFast() *GroupUpsertBulk {
|
||||
})
|
||||
}
|
||||
|
||||
// SetForceOpenaiUltrafast sets the "force_openai_ultrafast" field.
|
||||
func (u *GroupUpsertBulk) SetForceOpenaiUltrafast(v bool) *GroupUpsertBulk {
|
||||
return u.Update(func(s *GroupUpsert) {
|
||||
s.SetForceOpenaiUltrafast(v)
|
||||
})
|
||||
}
|
||||
|
||||
// UpdateForceOpenaiUltrafast sets the "force_openai_ultrafast" field to the value that was provided on create.
|
||||
func (u *GroupUpsertBulk) UpdateForceOpenaiUltrafast() *GroupUpsertBulk {
|
||||
return u.Update(func(s *GroupUpsert) {
|
||||
s.UpdateForceOpenaiUltrafast()
|
||||
})
|
||||
}
|
||||
|
||||
// SetFreeOpenaiFast sets the "free_openai_fast" field.
|
||||
func (u *GroupUpsertBulk) SetFreeOpenaiFast(v bool) *GroupUpsertBulk {
|
||||
return u.Update(func(s *GroupUpsert) {
|
||||
|
||||
@@ -1023,6 +1023,20 @@ func (_u *GroupUpdate) SetNillableForceOpenaiFast(v *bool) *GroupUpdate {
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetForceOpenaiUltrafast sets the "force_openai_ultrafast" field.
|
||||
func (_u *GroupUpdate) SetForceOpenaiUltrafast(v bool) *GroupUpdate {
|
||||
_u.mutation.SetForceOpenaiUltrafast(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableForceOpenaiUltrafast sets the "force_openai_ultrafast" field if the given value is not nil.
|
||||
func (_u *GroupUpdate) SetNillableForceOpenaiUltrafast(v *bool) *GroupUpdate {
|
||||
if v != nil {
|
||||
_u.SetForceOpenaiUltrafast(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetFreeOpenaiFast sets the "free_openai_fast" field.
|
||||
func (_u *GroupUpdate) SetFreeOpenaiFast(v bool) *GroupUpdate {
|
||||
_u.mutation.SetFreeOpenaiFast(v)
|
||||
@@ -1887,6 +1901,9 @@ func (_u *GroupUpdate) sqlSave(ctx context.Context) (_node int, err error) {
|
||||
if value, ok := _u.mutation.ForceOpenaiFast(); ok {
|
||||
_spec.SetField(group.FieldForceOpenaiFast, field.TypeBool, value)
|
||||
}
|
||||
if value, ok := _u.mutation.ForceOpenaiUltrafast(); ok {
|
||||
_spec.SetField(group.FieldForceOpenaiUltrafast, field.TypeBool, value)
|
||||
}
|
||||
if value, ok := _u.mutation.FreeOpenaiFast(); ok {
|
||||
_spec.SetField(group.FieldFreeOpenaiFast, field.TypeBool, value)
|
||||
}
|
||||
@@ -3243,6 +3260,20 @@ func (_u *GroupUpdateOne) SetNillableForceOpenaiFast(v *bool) *GroupUpdateOne {
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetForceOpenaiUltrafast sets the "force_openai_ultrafast" field.
|
||||
func (_u *GroupUpdateOne) SetForceOpenaiUltrafast(v bool) *GroupUpdateOne {
|
||||
_u.mutation.SetForceOpenaiUltrafast(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableForceOpenaiUltrafast sets the "force_openai_ultrafast" field if the given value is not nil.
|
||||
func (_u *GroupUpdateOne) SetNillableForceOpenaiUltrafast(v *bool) *GroupUpdateOne {
|
||||
if v != nil {
|
||||
_u.SetForceOpenaiUltrafast(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetFreeOpenaiFast sets the "free_openai_fast" field.
|
||||
func (_u *GroupUpdateOne) SetFreeOpenaiFast(v bool) *GroupUpdateOne {
|
||||
_u.mutation.SetFreeOpenaiFast(v)
|
||||
@@ -4137,6 +4168,9 @@ func (_u *GroupUpdateOne) sqlSave(ctx context.Context) (_node *Group, err error)
|
||||
if value, ok := _u.mutation.ForceOpenaiFast(); ok {
|
||||
_spec.SetField(group.FieldForceOpenaiFast, field.TypeBool, value)
|
||||
}
|
||||
if value, ok := _u.mutation.ForceOpenaiUltrafast(); ok {
|
||||
_spec.SetField(group.FieldForceOpenaiUltrafast, field.TypeBool, value)
|
||||
}
|
||||
if value, ok := _u.mutation.FreeOpenaiFast(); ok {
|
||||
_spec.SetField(group.FieldFreeOpenaiFast, field.TypeBool, value)
|
||||
}
|
||||
|
||||
@@ -957,6 +957,7 @@ var (
|
||||
{Name: "allow_messages_dispatch", Type: field.TypeBool, Default: false},
|
||||
{Name: "allow_live", Type: field.TypeBool, Default: false},
|
||||
{Name: "force_openai_fast", Type: field.TypeBool, Default: false},
|
||||
{Name: "force_openai_ultrafast", Type: field.TypeBool, Default: false},
|
||||
{Name: "free_openai_fast", Type: field.TypeBool, Default: false},
|
||||
{Name: "require_oauth_only", Type: field.TypeBool, Default: false},
|
||||
{Name: "require_privacy_set", Type: field.TypeBool, Default: false},
|
||||
|
||||
+55
-1
@@ -22161,6 +22161,7 @@ type GroupMutation struct {
|
||||
allow_messages_dispatch *bool
|
||||
allow_live *bool
|
||||
force_openai_fast *bool
|
||||
force_openai_ultrafast *bool
|
||||
free_openai_fast *bool
|
||||
require_oauth_only *bool
|
||||
require_privacy_set *bool
|
||||
@@ -25058,6 +25059,42 @@ func (m *GroupMutation) ResetForceOpenaiFast() {
|
||||
m.force_openai_fast = nil
|
||||
}
|
||||
|
||||
// SetForceOpenaiUltrafast sets the "force_openai_ultrafast" field.
|
||||
func (m *GroupMutation) SetForceOpenaiUltrafast(b bool) {
|
||||
m.force_openai_ultrafast = &b
|
||||
}
|
||||
|
||||
// ForceOpenaiUltrafast returns the value of the "force_openai_ultrafast" field in the mutation.
|
||||
func (m *GroupMutation) ForceOpenaiUltrafast() (r bool, exists bool) {
|
||||
v := m.force_openai_ultrafast
|
||||
if v == nil {
|
||||
return
|
||||
}
|
||||
return *v, true
|
||||
}
|
||||
|
||||
// OldForceOpenaiUltrafast returns the old "force_openai_ultrafast" field's value of the Group entity.
|
||||
// If the Group object wasn't provided to the builder, the object is fetched from the database.
|
||||
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
|
||||
func (m *GroupMutation) OldForceOpenaiUltrafast(ctx context.Context) (v bool, err error) {
|
||||
if !m.op.Is(OpUpdateOne) {
|
||||
return v, errors.New("OldForceOpenaiUltrafast is only allowed on UpdateOne operations")
|
||||
}
|
||||
if m.id == nil || m.oldValue == nil {
|
||||
return v, errors.New("OldForceOpenaiUltrafast requires an ID field in the mutation")
|
||||
}
|
||||
oldValue, err := m.oldValue(ctx)
|
||||
if err != nil {
|
||||
return v, fmt.Errorf("querying old value for OldForceOpenaiUltrafast: %w", err)
|
||||
}
|
||||
return oldValue.ForceOpenaiUltrafast, nil
|
||||
}
|
||||
|
||||
// ResetForceOpenaiUltrafast resets all changes to the "force_openai_ultrafast" field.
|
||||
func (m *GroupMutation) ResetForceOpenaiUltrafast() {
|
||||
m.force_openai_ultrafast = nil
|
||||
}
|
||||
|
||||
// SetFreeOpenaiFast sets the "free_openai_fast" field.
|
||||
func (m *GroupMutation) SetFreeOpenaiFast(b bool) {
|
||||
m.free_openai_fast = &b
|
||||
@@ -25995,7 +26032,7 @@ func (m *GroupMutation) Type() string {
|
||||
// order to get all numeric fields that were incremented/decremented, call
|
||||
// AddedFields().
|
||||
func (m *GroupMutation) Fields() []string {
|
||||
fields := make([]string, 0, 68)
|
||||
fields := make([]string, 0, 69)
|
||||
if m.created_at != nil {
|
||||
fields = append(fields, group.FieldCreatedAt)
|
||||
}
|
||||
@@ -26158,6 +26195,9 @@ func (m *GroupMutation) Fields() []string {
|
||||
if m.force_openai_fast != nil {
|
||||
fields = append(fields, group.FieldForceOpenaiFast)
|
||||
}
|
||||
if m.force_openai_ultrafast != nil {
|
||||
fields = append(fields, group.FieldForceOpenaiUltrafast)
|
||||
}
|
||||
if m.free_openai_fast != nil {
|
||||
fields = append(fields, group.FieldFreeOpenaiFast)
|
||||
}
|
||||
@@ -26316,6 +26356,8 @@ func (m *GroupMutation) Field(name string) (ent.Value, bool) {
|
||||
return m.AllowLive()
|
||||
case group.FieldForceOpenaiFast:
|
||||
return m.ForceOpenaiFast()
|
||||
case group.FieldForceOpenaiUltrafast:
|
||||
return m.ForceOpenaiUltrafast()
|
||||
case group.FieldFreeOpenaiFast:
|
||||
return m.FreeOpenaiFast()
|
||||
case group.FieldRequireOauthOnly:
|
||||
@@ -26461,6 +26503,8 @@ func (m *GroupMutation) OldField(ctx context.Context, name string) (ent.Value, e
|
||||
return m.OldAllowLive(ctx)
|
||||
case group.FieldForceOpenaiFast:
|
||||
return m.OldForceOpenaiFast(ctx)
|
||||
case group.FieldForceOpenaiUltrafast:
|
||||
return m.OldForceOpenaiUltrafast(ctx)
|
||||
case group.FieldFreeOpenaiFast:
|
||||
return m.OldFreeOpenaiFast(ctx)
|
||||
case group.FieldRequireOauthOnly:
|
||||
@@ -26876,6 +26920,13 @@ func (m *GroupMutation) SetField(name string, value ent.Value) error {
|
||||
}
|
||||
m.SetForceOpenaiFast(v)
|
||||
return nil
|
||||
case group.FieldForceOpenaiUltrafast:
|
||||
v, ok := value.(bool)
|
||||
if !ok {
|
||||
return fmt.Errorf("unexpected type %T for field %s", value, name)
|
||||
}
|
||||
m.SetForceOpenaiUltrafast(v)
|
||||
return nil
|
||||
case group.FieldFreeOpenaiFast:
|
||||
v, ok := value.(bool)
|
||||
if !ok {
|
||||
@@ -27647,6 +27698,9 @@ func (m *GroupMutation) ResetField(name string) error {
|
||||
case group.FieldForceOpenaiFast:
|
||||
m.ResetForceOpenaiFast()
|
||||
return nil
|
||||
case group.FieldForceOpenaiUltrafast:
|
||||
m.ResetForceOpenaiUltrafast()
|
||||
return nil
|
||||
case group.FieldFreeOpenaiFast:
|
||||
m.ResetFreeOpenaiFast()
|
||||
return nil
|
||||
|
||||
@@ -1183,66 +1183,70 @@ func init() {
|
||||
groupDescForceOpenaiFast := groupFields[50].Descriptor()
|
||||
// group.DefaultForceOpenaiFast holds the default value on creation for the force_openai_fast field.
|
||||
group.DefaultForceOpenaiFast = groupDescForceOpenaiFast.Default.(bool)
|
||||
// groupDescForceOpenaiUltrafast is the schema descriptor for force_openai_ultrafast field.
|
||||
groupDescForceOpenaiUltrafast := groupFields[51].Descriptor()
|
||||
// group.DefaultForceOpenaiUltrafast holds the default value on creation for the force_openai_ultrafast field.
|
||||
group.DefaultForceOpenaiUltrafast = groupDescForceOpenaiUltrafast.Default.(bool)
|
||||
// groupDescFreeOpenaiFast is the schema descriptor for free_openai_fast field.
|
||||
groupDescFreeOpenaiFast := groupFields[51].Descriptor()
|
||||
groupDescFreeOpenaiFast := groupFields[52].Descriptor()
|
||||
// group.DefaultFreeOpenaiFast holds the default value on creation for the free_openai_fast field.
|
||||
group.DefaultFreeOpenaiFast = groupDescFreeOpenaiFast.Default.(bool)
|
||||
// groupDescRequireOauthOnly is the schema descriptor for require_oauth_only field.
|
||||
groupDescRequireOauthOnly := groupFields[52].Descriptor()
|
||||
groupDescRequireOauthOnly := groupFields[53].Descriptor()
|
||||
// group.DefaultRequireOauthOnly holds the default value on creation for the require_oauth_only field.
|
||||
group.DefaultRequireOauthOnly = groupDescRequireOauthOnly.Default.(bool)
|
||||
// groupDescRequirePrivacySet is the schema descriptor for require_privacy_set field.
|
||||
groupDescRequirePrivacySet := groupFields[53].Descriptor()
|
||||
groupDescRequirePrivacySet := groupFields[54].Descriptor()
|
||||
// group.DefaultRequirePrivacySet holds the default value on creation for the require_privacy_set field.
|
||||
group.DefaultRequirePrivacySet = groupDescRequirePrivacySet.Default.(bool)
|
||||
// groupDescDefaultMappedModel is the schema descriptor for default_mapped_model field.
|
||||
groupDescDefaultMappedModel := groupFields[54].Descriptor()
|
||||
groupDescDefaultMappedModel := groupFields[55].Descriptor()
|
||||
// group.DefaultDefaultMappedModel holds the default value on creation for the default_mapped_model field.
|
||||
group.DefaultDefaultMappedModel = groupDescDefaultMappedModel.Default.(string)
|
||||
// group.DefaultMappedModelValidator is a validator for the "default_mapped_model" field. It is called by the builders before save.
|
||||
group.DefaultMappedModelValidator = groupDescDefaultMappedModel.Validators[0].(func(string) error)
|
||||
// groupDescMessagesDispatchModelConfig is the schema descriptor for messages_dispatch_model_config field.
|
||||
groupDescMessagesDispatchModelConfig := groupFields[55].Descriptor()
|
||||
groupDescMessagesDispatchModelConfig := groupFields[56].Descriptor()
|
||||
// group.DefaultMessagesDispatchModelConfig holds the default value on creation for the messages_dispatch_model_config field.
|
||||
group.DefaultMessagesDispatchModelConfig = groupDescMessagesDispatchModelConfig.Default.(domain.OpenAIMessagesDispatchModelConfig)
|
||||
// groupDescModelAllowlist is the schema descriptor for model_allowlist field.
|
||||
groupDescModelAllowlist := groupFields[56].Descriptor()
|
||||
groupDescModelAllowlist := groupFields[57].Descriptor()
|
||||
// group.DefaultModelAllowlist holds the default value on creation for the model_allowlist field.
|
||||
group.DefaultModelAllowlist = groupDescModelAllowlist.Default.(domain.GroupModelAllowlist)
|
||||
// groupDescCodexModelsManifestConfig is the schema descriptor for codex_models_manifest_config field.
|
||||
groupDescCodexModelsManifestConfig := groupFields[57].Descriptor()
|
||||
groupDescCodexModelsManifestConfig := groupFields[58].Descriptor()
|
||||
// group.DefaultCodexModelsManifestConfig holds the default value on creation for the codex_models_manifest_config field.
|
||||
group.DefaultCodexModelsManifestConfig = groupDescCodexModelsManifestConfig.Default.(domain.GroupCodexModelsManifestConfig)
|
||||
// groupDescRpmLimit is the schema descriptor for rpm_limit field.
|
||||
groupDescRpmLimit := groupFields[58].Descriptor()
|
||||
groupDescRpmLimit := groupFields[59].Descriptor()
|
||||
// group.DefaultRpmLimit holds the default value on creation for the rpm_limit field.
|
||||
group.DefaultRpmLimit = groupDescRpmLimit.Default.(int)
|
||||
// groupDescMaxReasoningEffort is the schema descriptor for max_reasoning_effort field.
|
||||
groupDescMaxReasoningEffort := groupFields[59].Descriptor()
|
||||
groupDescMaxReasoningEffort := groupFields[60].Descriptor()
|
||||
// group.DefaultMaxReasoningEffort holds the default value on creation for the max_reasoning_effort field.
|
||||
group.DefaultMaxReasoningEffort = groupDescMaxReasoningEffort.Default.(string)
|
||||
// group.MaxReasoningEffortValidator is a validator for the "max_reasoning_effort" field. It is called by the builders before save.
|
||||
group.MaxReasoningEffortValidator = groupDescMaxReasoningEffort.Validators[0].(func(string) error)
|
||||
// groupDescMaxReasoningEffortOverLimit is the schema descriptor for max_reasoning_effort_over_limit field.
|
||||
groupDescMaxReasoningEffortOverLimit := groupFields[60].Descriptor()
|
||||
groupDescMaxReasoningEffortOverLimit := groupFields[61].Descriptor()
|
||||
// group.DefaultMaxReasoningEffortOverLimit holds the default value on creation for the max_reasoning_effort_over_limit field.
|
||||
group.DefaultMaxReasoningEffortOverLimit = groupDescMaxReasoningEffortOverLimit.Default.(string)
|
||||
// group.MaxReasoningEffortOverLimitValidator is a validator for the "max_reasoning_effort_over_limit" field. It is called by the builders before save.
|
||||
group.MaxReasoningEffortOverLimitValidator = groupDescMaxReasoningEffortOverLimit.Validators[0].(func(string) error)
|
||||
// groupDescReasoningEffortMappings is the schema descriptor for reasoning_effort_mappings field.
|
||||
groupDescReasoningEffortMappings := groupFields[61].Descriptor()
|
||||
groupDescReasoningEffortMappings := groupFields[62].Descriptor()
|
||||
// group.DefaultReasoningEffortMappings holds the default value on creation for the reasoning_effort_mappings field.
|
||||
group.DefaultReasoningEffortMappings = groupDescReasoningEffortMappings.Default.([]domain.ReasoningEffortMapping)
|
||||
// groupDescProfitControlEnabled is the schema descriptor for profit_control_enabled field.
|
||||
groupDescProfitControlEnabled := groupFields[62].Descriptor()
|
||||
groupDescProfitControlEnabled := groupFields[63].Descriptor()
|
||||
// group.DefaultProfitControlEnabled holds the default value on creation for the profit_control_enabled field.
|
||||
group.DefaultProfitControlEnabled = groupDescProfitControlEnabled.Default.(bool)
|
||||
// groupDescProfitMinMargin is the schema descriptor for profit_min_margin field.
|
||||
groupDescProfitMinMargin := groupFields[63].Descriptor()
|
||||
groupDescProfitMinMargin := groupFields[64].Descriptor()
|
||||
// group.DefaultProfitMinMargin holds the default value on creation for the profit_min_margin field.
|
||||
group.DefaultProfitMinMargin = groupDescProfitMinMargin.Default.(float64)
|
||||
// groupDescProfitSafetyBuffer is the schema descriptor for profit_safety_buffer field.
|
||||
groupDescProfitSafetyBuffer := groupFields[64].Descriptor()
|
||||
groupDescProfitSafetyBuffer := groupFields[65].Descriptor()
|
||||
// group.DefaultProfitSafetyBuffer holds the default value on creation for the profit_safety_buffer field.
|
||||
group.DefaultProfitSafetyBuffer = groupDescProfitSafetyBuffer.Default.(float64)
|
||||
idempotencyrecordMixin := schema.IdempotencyRecord{}.Mixin()
|
||||
|
||||
@@ -253,6 +253,9 @@ func (Group) Fields() []ent.Field {
|
||||
field.Bool("force_openai_fast").
|
||||
Default(false).
|
||||
Comment("是否强制此 OpenAI/Composite 分组请求使用 service_tier=priority"),
|
||||
field.Bool("force_openai_ultrafast").
|
||||
Default(false).
|
||||
Comment("是否对支持 Ultrafast 的模型强制使用 service_tier=ultrafast(优先于 force_openai_fast)"),
|
||||
field.Bool("free_openai_fast").
|
||||
Default(false).
|
||||
Comment("是否让此 OpenAI/Composite 分组的 Fast 请求按 Standard 价格计费"),
|
||||
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
module github.com/Wei-Shaw/sub2api
|
||||
|
||||
go 1.27.3
|
||||
go 1.27.4
|
||||
|
||||
require (
|
||||
entgo.io/ent v0.14.5
|
||||
@@ -23,6 +23,7 @@ require (
|
||||
github.com/go-playground/validator/v10 v10.14.0
|
||||
github.com/go-webauthn/webauthn v0.17.4
|
||||
github.com/golang-jwt/jwt/v5 v5.3.1
|
||||
github.com/google/jsonschema-go v0.4.2
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/google/wire v0.7.0
|
||||
github.com/gorilla/websocket v1.5.3
|
||||
@@ -130,7 +131,6 @@ require (
|
||||
github.com/google/go-cmp v0.7.0 // indirect
|
||||
github.com/google/go-querystring v1.1.0 // indirect
|
||||
github.com/google/go-tpm v0.9.8 // indirect
|
||||
github.com/google/jsonschema-go v0.4.2 // indirect
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.3 // indirect
|
||||
github.com/hashicorp/hcl v1.0.0 // indirect
|
||||
github.com/hashicorp/hcl/v2 v2.18.1 // indirect
|
||||
|
||||
@@ -1025,7 +1025,7 @@ type CircuitBreakerConfig struct {
|
||||
}
|
||||
|
||||
type ConcurrencyConfig struct {
|
||||
// PingInterval: 并发等待期间的 SSE ping 间隔(秒)
|
||||
// PingInterval: 并发等待期间的 SSE ping 间隔(秒),0 禁用 ping
|
||||
PingInterval int `mapstructure:"ping_interval"`
|
||||
}
|
||||
|
||||
@@ -3887,8 +3887,8 @@ func (c *Config) Validate() error {
|
||||
if c.Ops.Cleanup.Enabled && strings.TrimSpace(c.Ops.Cleanup.Schedule) == "" {
|
||||
return fmt.Errorf("ops.cleanup.schedule is required when ops.cleanup.enabled=true")
|
||||
}
|
||||
if c.Concurrency.PingInterval < 5 || c.Concurrency.PingInterval > 30 {
|
||||
return fmt.Errorf("concurrency.ping_interval must be between 5-30 seconds")
|
||||
if c.Concurrency.PingInterval != 0 && (c.Concurrency.PingInterval < 5 || c.Concurrency.PingInterval > 30) {
|
||||
return fmt.Errorf("concurrency.ping_interval must be 0 (disabled) or between 5-30 seconds")
|
||||
}
|
||||
if c.Gateway.Grok.FreeQuotaSoftGateEnabled {
|
||||
if c.Gateway.Grok.FreeQuotaTokenLimit <= 0 {
|
||||
|
||||
@@ -1577,18 +1577,20 @@ func TestValidateOpsCleanupScheduleRequired(t *testing.T) {
|
||||
|
||||
func TestValidateConcurrencyPingInterval(t *testing.T) {
|
||||
resetViperWithJWTSecret(t)
|
||||
|
||||
cfg, err := Load()
|
||||
if err != nil {
|
||||
t.Fatalf("Load() error: %v", err)
|
||||
}
|
||||
cfg.Concurrency.PingInterval = 3
|
||||
err = cfg.Validate()
|
||||
if err == nil {
|
||||
t.Fatalf("Validate() expected error for concurrency.ping_interval")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "concurrency.ping_interval") {
|
||||
t.Fatalf("Validate() expected concurrency.ping_interval error, got: %v", err)
|
||||
for _, interval := range []int{-1, 0, 1, 3, 4, 5, 10, 30, 31} {
|
||||
cfg, err := Load()
|
||||
if err != nil {
|
||||
t.Fatalf("Load() error: %v", err)
|
||||
}
|
||||
cfg.Concurrency.PingInterval = interval
|
||||
err = cfg.Validate()
|
||||
valid := interval == 0 || (interval >= 5 && interval <= 30)
|
||||
if valid && err != nil {
|
||||
t.Errorf("Validate() interval %d: %v", interval, err)
|
||||
}
|
||||
if !valid && (err == nil || !strings.Contains(err.Error(), "concurrency.ping_interval")) {
|
||||
t.Errorf("Validate() interval %d: expected concurrency.ping_interval error, got %v", interval, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -178,7 +178,9 @@ var DefaultAntigravityModelMapping = map[string]string{
|
||||
"gemini-3.8-flash-low": "gemini-3.8-flash-low",
|
||||
"gemini-3.8-flash-medium": "gemini-3.8-flash-medium",
|
||||
"gemini-3.8-flash-tiered": "gemini-3.8-flash-tiered",
|
||||
// Gemini 4 Argon tiered models
|
||||
// Gemini 4 models
|
||||
// Carbon uses the published model ID; do not infer Argon-style tier aliases.
|
||||
"gemini-4-carbon": "gemini-4-carbon",
|
||||
"gemini-4-argon": "gemini-4-argon-high",
|
||||
"gemini-4-argon-high": "gemini-4-argon-high",
|
||||
"gemini-4-argon-low": "gemini-4-argon-low",
|
||||
|
||||
@@ -107,6 +107,7 @@ func TestDefaultAntigravityModelMapping_Gemini38FlashModels(t *testing.T) {
|
||||
|
||||
func TestDefaultAntigravityModelMapping_Gemini4ArgonAndClaude55Models(t *testing.T) {
|
||||
cases := map[string]string{
|
||||
"gemini-4-carbon": "gemini-4-carbon",
|
||||
"gemini-4-argon": "gemini-4-argon-high",
|
||||
"gemini-4-argon-high": "gemini-4-argon-high",
|
||||
"gemini-4-argon-low": "gemini-4-argon-low",
|
||||
|
||||
@@ -239,6 +239,7 @@ type CreateGroupRequest struct {
|
||||
AllowMessagesDispatch bool `json:"allow_messages_dispatch"`
|
||||
AllowLive bool `json:"allow_live"`
|
||||
ForceOpenAIFast bool `json:"force_openai_fast"`
|
||||
ForceOpenAIUltrafast bool `json:"force_openai_ultrafast"`
|
||||
FreeOpenAIFast bool `json:"free_openai_fast"`
|
||||
RequireOAuthOnly bool `json:"require_oauth_only"`
|
||||
RequirePrivacySet bool `json:"require_privacy_set"`
|
||||
@@ -316,6 +317,7 @@ type UpdateGroupRequest struct {
|
||||
AllowMessagesDispatch *bool `json:"allow_messages_dispatch"`
|
||||
AllowLive *bool `json:"allow_live"`
|
||||
ForceOpenAIFast *bool `json:"force_openai_fast"`
|
||||
ForceOpenAIUltrafast *bool `json:"force_openai_ultrafast"`
|
||||
FreeOpenAIFast *bool `json:"free_openai_fast"`
|
||||
RequireOAuthOnly *bool `json:"require_oauth_only"`
|
||||
RequirePrivacySet *bool `json:"require_privacy_set"`
|
||||
@@ -719,6 +721,7 @@ func (h *GroupHandler) Create(c *gin.Context) {
|
||||
AllowMessagesDispatch: req.AllowMessagesDispatch,
|
||||
AllowLive: req.AllowLive,
|
||||
ForceOpenAIFast: req.ForceOpenAIFast,
|
||||
ForceOpenAIUltrafast: req.ForceOpenAIUltrafast,
|
||||
FreeOpenAIFast: req.FreeOpenAIFast,
|
||||
RequireOAuthOnly: req.RequireOAuthOnly,
|
||||
RequirePrivacySet: req.RequirePrivacySet,
|
||||
@@ -867,6 +870,7 @@ func (h *GroupHandler) Update(c *gin.Context) {
|
||||
AllowMessagesDispatch: req.AllowMessagesDispatch,
|
||||
AllowLive: req.AllowLive,
|
||||
ForceOpenAIFast: req.ForceOpenAIFast,
|
||||
ForceOpenAIUltrafast: req.ForceOpenAIUltrafast,
|
||||
FreeOpenAIFast: req.FreeOpenAIFast,
|
||||
RequireOAuthOnly: req.RequireOAuthOnly,
|
||||
RequirePrivacySet: req.RequirePrivacySet,
|
||||
|
||||
@@ -25,3 +25,21 @@ func TestGroupRequestsDecodeForceOpenAIFast(t *testing.T) {
|
||||
require.Nil(t, omitted.ForceOpenAIFast)
|
||||
require.Nil(t, omitted.FreeOpenAIFast)
|
||||
}
|
||||
|
||||
func TestGroupRequestsDecodeForceOpenAIUltrafast(t *testing.T) {
|
||||
var createReq CreateGroupRequest
|
||||
require.NoError(t, json.Unmarshal([]byte(`{"name":"ultrafast","force_openai_ultrafast":true}`), &createReq))
|
||||
require.True(t, createReq.ForceOpenAIUltrafast)
|
||||
require.False(t, createReq.ForceOpenAIFast)
|
||||
|
||||
var updateReq UpdateGroupRequest
|
||||
require.NoError(t, json.Unmarshal([]byte(`{"force_openai_fast":false,"force_openai_ultrafast":true}`), &updateReq))
|
||||
require.NotNil(t, updateReq.ForceOpenAIUltrafast)
|
||||
require.True(t, *updateReq.ForceOpenAIUltrafast)
|
||||
require.NotNil(t, updateReq.ForceOpenAIFast)
|
||||
require.False(t, *updateReq.ForceOpenAIFast)
|
||||
|
||||
var omitted UpdateGroupRequest
|
||||
require.NoError(t, json.Unmarshal([]byte(`{}`), &omitted))
|
||||
require.Nil(t, omitted.ForceOpenAIUltrafast)
|
||||
}
|
||||
@@ -23,3 +23,18 @@ func TestGroupMapperExposesForceOpenAIFastOnlyToAdmins(t *testing.T) {
|
||||
require.Contains(t, string(adminJSON), `"force_openai_fast":true`)
|
||||
require.Contains(t, string(adminJSON), `"free_openai_fast":true`)
|
||||
}
|
||||
|
||||
func TestGroupMapperExposesForceOpenAIUltrafastOnlyToAdmins(t *testing.T) {
|
||||
group := &service.Group{
|
||||
ID: 7, Name: "ultrafast", Platform: service.PlatformOpenAI, Status: service.StatusActive, ForceOpenAIUltrafast: true,
|
||||
}
|
||||
|
||||
userJSON, err := json.Marshal(GroupFromService(group))
|
||||
require.NoError(t, err)
|
||||
require.NotContains(t, string(userJSON), "force_openai_ultrafast")
|
||||
|
||||
adminJSON, err := json.Marshal(GroupFromServiceAdmin(group))
|
||||
require.NoError(t, err)
|
||||
require.Contains(t, string(adminJSON), `"force_openai_ultrafast":true`)
|
||||
require.Contains(t, string(adminJSON), `"force_openai_fast":false`)
|
||||
}
|
||||
@@ -149,6 +149,7 @@ func GroupFromServiceAdmin(g *service.Group) *AdminGroup {
|
||||
out := &AdminGroup{
|
||||
Group: groupFromServiceBase(g),
|
||||
ForceOpenAIFast: g.ForceOpenAIFast,
|
||||
ForceOpenAIUltrafast: g.ForceOpenAIUltrafast,
|
||||
FreeOpenAIFast: g.FreeOpenAIFast,
|
||||
ProfitControlEnabled: g.ProfitControlEnabled,
|
||||
ProfitMinMargin: g.ProfitMinMargin,
|
||||
|
||||
@@ -172,7 +172,8 @@ type Group struct {
|
||||
type AdminGroup struct {
|
||||
Group
|
||||
// ForceOpenAIFast 是管理端请求策略,用户侧分组 DTO 无需暴露。
|
||||
ForceOpenAIFast bool `json:"force_openai_fast"`
|
||||
ForceOpenAIFast bool `json:"force_openai_fast"`
|
||||
ForceOpenAIUltrafast bool `json:"force_openai_ultrafast"`
|
||||
// FreeOpenAIFast 是管理端计费策略,用户侧分组 DTO 无需暴露。
|
||||
FreeOpenAIFast bool `json:"free_openai_fast"`
|
||||
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
//go:build unit
|
||||
|
||||
package handler
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/tlsfingerprint"
|
||||
middleware "github.com/Wei-Shaw/sub2api/internal/server/middleware"
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
type compatEffortPolicyUpstream struct {
|
||||
service.HTTPUpstream
|
||||
bodies [][]byte
|
||||
}
|
||||
|
||||
func (u *compatEffortPolicyUpstream) DoWithTLS(req *http.Request, _ string, _ int64, _ int, _ *tlsfingerprint.Profile) (*http.Response, error) {
|
||||
body, err := io.ReadAll(req.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
u.bodies = append(u.bodies, body)
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: http.Header{"Content-Type": []string{"text/event-stream"}},
|
||||
Body: io.NopCloser(strings.NewReader(compatStreamUsagePartialStream + compatStreamUsageCompletion)),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func TestGatewayCompatibilityHandlersReasoningEffortPolicy(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
const model = "claude-sonnet-4.5"
|
||||
for _, endpoint := range []string{"chat/completions", "responses"} {
|
||||
for _, platform := range []string{service.PlatformAnthropic, service.PlatformComposite} {
|
||||
for _, stream := range []bool{false, true} {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
effort string
|
||||
ceiling string
|
||||
overLimit string
|
||||
mappings []service.ReasoningEffortMapping
|
||||
want string
|
||||
denied bool
|
||||
}{
|
||||
{name: "ceiling", effort: "high", ceiling: "medium", want: "medium"},
|
||||
{name: "mapping", effort: "high", mappings: []service.ReasoningEffortMapping{{From: "high", To: "low"}}, want: "low"},
|
||||
{name: "mapping then ceiling", effort: "low", ceiling: "medium", mappings: []service.ReasoningEffortMapping{{From: "low", To: "high"}}, want: "medium"},
|
||||
{name: "model mapping", effort: "high", mappings: []service.ReasoningEffortMapping{{From: "high", To: "low", MatchType: "exact", Model: model}}, want: "low"},
|
||||
{name: "other model mapping", effort: "high", mappings: []service.ReasoningEffortMapping{{From: "high", To: "low", MatchType: "exact", Model: "other-model"}}, want: "high"},
|
||||
{name: "deny ceiling", effort: "high", ceiling: "medium", overLimit: service.ReasoningEffortOverLimitDeny, denied: true},
|
||||
{name: "deny mapping", effort: "high", mappings: []service.ReasoningEffortMapping{{From: "high", To: "deny"}}, denied: true},
|
||||
{name: "within ceiling", effort: "low", ceiling: "medium", want: "low"},
|
||||
{name: "no policy", effort: "high", want: "high"},
|
||||
{name: "omitted", ceiling: "medium"},
|
||||
} {
|
||||
t.Run(fmt.Sprintf("%s/%s/stream=%t/%s", endpoint, platform, stream, tc.name), func(t *testing.T) {
|
||||
cfg := &config.Config{}
|
||||
groupID := int64(9400)
|
||||
group := &service.Group{
|
||||
ID: groupID, Hydrated: true, Platform: platform, Status: service.StatusActive, RateMultiplier: 1,
|
||||
MaxReasoningEffort: tc.ceiling, MaxReasoningEffortOverLimit: tc.overLimit, ReasoningEffortMappings: tc.mappings,
|
||||
}
|
||||
account := &service.Account{
|
||||
ID: 9401, Platform: service.PlatformAnthropic, Type: service.AccountTypeAPIKey,
|
||||
Status: service.StatusActive, Schedulable: true, Concurrency: 1,
|
||||
Credentials: map[string]any{"api_key": "test-key"},
|
||||
AccountGroups: []service.AccountGroup{{AccountID: 9401, GroupID: groupID}},
|
||||
}
|
||||
cache := &countingGatewaySchedulerCache{fakeSchedulerCache: &fakeSchedulerCache{accounts: []*service.Account{account}}}
|
||||
snapshot := service.NewSchedulerSnapshotService(cache, nil, nil, nil, nil)
|
||||
upstream := &compatEffortPolicyUpstream{}
|
||||
usageRepo := &openAIWSUsageHandlerUsageLogRepoStub{created: make(chan *service.UsageLog, 1)}
|
||||
billingRepo := &compatStreamUsageBillingRepo{}
|
||||
billingCache := service.NewBillingCacheService(newHandlerInflightCache(100), nil, nil, nil, nil, nil, cfg, nil)
|
||||
t.Cleanup(billingCache.Stop)
|
||||
gateway := service.NewGatewayService(
|
||||
nil, &fakeGroupRepo{group: group}, usageRepo, billingRepo, nil, nil, nil, nil, cfg,
|
||||
snapshot, nil, service.NewBillingService(cfg, nil), nil, nil, nil, upstream,
|
||||
&service.DeferredService{}, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil,
|
||||
)
|
||||
h := &GatewayHandler{
|
||||
gatewayService: gateway, billingCacheService: billingCache, cfg: cfg, maxAccountSwitches: 1,
|
||||
concurrencyHelper: NewConcurrencyHelper(service.NewConcurrencyService(&fakeConcurrencyCache{}), SSEPingFormatClaude, 0),
|
||||
}
|
||||
|
||||
request := map[string]any{"model": model, "stream": stream}
|
||||
if endpoint == "chat/completions" {
|
||||
request["messages"] = []map[string]string{{"role": "user", "content": "hello"}}
|
||||
if tc.effort != "" {
|
||||
request["reasoning_effort"] = tc.effort
|
||||
}
|
||||
} else {
|
||||
request["input"] = "hello"
|
||||
if tc.effort != "" {
|
||||
request["reasoning"] = map[string]string{"effort": tc.effort}
|
||||
}
|
||||
}
|
||||
body, err := json.Marshal(request)
|
||||
require.NoError(t, err)
|
||||
recorder := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(recorder)
|
||||
ctx := context.WithValue(context.Background(), ctxkey.Group, group)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/v1/"+endpoint, bytes.NewReader(body)).WithContext(ctx)
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
apiKey := &service.APIKey{
|
||||
ID: 9402, UserID: 9403, GroupID: &groupID, Group: group,
|
||||
User: &service.User{ID: 9403, Balance: 100},
|
||||
}
|
||||
c.Set(string(middleware.ContextKeyAPIKey), apiKey)
|
||||
c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: 9403})
|
||||
if endpoint == "chat/completions" {
|
||||
h.ChatCompletions(c)
|
||||
} else {
|
||||
h.Responses(c)
|
||||
}
|
||||
|
||||
if tc.denied {
|
||||
require.Equal(t, http.StatusForbidden, recorder.Code, recorder.Body.String())
|
||||
errorField := "error.type"
|
||||
if endpoint == "responses" {
|
||||
errorField = "error.code"
|
||||
}
|
||||
require.Equal(t, "permission_error", gjson.Get(recorder.Body.String(), errorField).String())
|
||||
require.Empty(t, upstream.bodies)
|
||||
require.Zero(t, cache.snapshotCalls.Load(), "local policy denial precedes account selection")
|
||||
require.Empty(t, usageRepo.created)
|
||||
require.Empty(t, billingRepo.commands)
|
||||
return
|
||||
}
|
||||
// Check the final Anthropic request, beyond handler parsing and both protocol conversions.
|
||||
require.Equal(t, http.StatusOK, recorder.Code, recorder.Body.String())
|
||||
require.Len(t, upstream.bodies, 1)
|
||||
require.Equal(t, tc.want, gjson.GetBytes(upstream.bodies[0], "output_config.effort").String())
|
||||
require.Equal(t, model, gjson.GetBytes(upstream.bodies[0], "model").String())
|
||||
require.Contains(t, recorder.Body.String(), "partial")
|
||||
require.Len(t, usageRepo.created, 1)
|
||||
usage := <-usageRepo.created
|
||||
if tc.effort == "" {
|
||||
require.Nil(t, usage.RequestedReasoningEffort)
|
||||
} else {
|
||||
require.Equal(t, &tc.effort, usage.RequestedReasoningEffort)
|
||||
require.Equal(t, &tc.want, usage.ReasoningEffort)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -80,7 +80,7 @@ func NewGatewayHandler(
|
||||
cfg *config.Config,
|
||||
settingService *service.SettingService,
|
||||
) *GatewayHandler {
|
||||
pingInterval := time.Duration(0)
|
||||
pingInterval := defaultPingInterval
|
||||
maxAccountSwitches := 10
|
||||
maxAccountSwitchesGemini := 3
|
||||
if cfg != nil {
|
||||
@@ -915,6 +915,10 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
|
||||
if fs.ForceCacheBilling {
|
||||
requestCtx = service.WithForceCacheBilling(requestCtx)
|
||||
}
|
||||
if channelMapping.Mapped {
|
||||
// 选号按客户端模型,转发按渠道映射后的模型:模型级账号状态按选号模型记录。
|
||||
requestCtx = service.WithGatewaySchedulingModel(requestCtx, reqModel)
|
||||
}
|
||||
// 记录 Forward 前已写入字节数,Forward 后若增加则说明 SSE 内容已发,禁止 failover
|
||||
writerSizeBeforeForward := c.Writer.Size()
|
||||
if account.Platform == service.PlatformAntigravity && account.Type != service.AccountTypeAPIKey {
|
||||
@@ -1127,8 +1131,12 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
|
||||
// - 粘性账号因负载/RPM 被跳过、选中了其他账号:不覆盖原绑定,
|
||||
// 下次请求粘性账号恢复后仍可命中
|
||||
if sessionKey != "" && (sessionBoundAccountID == 0 || sessionBoundAccountID == account.ID) {
|
||||
if err := h.gatewayService.BindStickySession(c.Request.Context(), currentAPIKey.GroupID, sessionKey, account.ID); err != nil {
|
||||
reqLog.Warn("gateway.bind_sticky_session_failed", zap.Int64("account_id", account.ID), zap.Error(err))
|
||||
// Forward has completed; finish the bounded write even if the client disconnects.
|
||||
bindCtx, cancelBind := context.WithTimeout(context.WithoutCancel(c.Request.Context()), 5*time.Second)
|
||||
bindErr := h.gatewayService.BindStickySession(bindCtx, currentAPIKey.GroupID, sessionKey, account.ID)
|
||||
cancelBind()
|
||||
if bindErr != nil {
|
||||
reqLog.Warn("gateway.bind_sticky_session_failed", zap.Int64("account_id", account.ID), zap.Error(bindErr))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -85,6 +85,12 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) {
|
||||
if rejectSystemOneOnlyPlatform(c, apiKey, h.chatCompletionsErrorResponse) {
|
||||
return
|
||||
}
|
||||
if cappedBody, changed, err := applyOpenAIReasoningEffortPolicyForRequest(c, apiKey, body); err != nil {
|
||||
respondOpenAIReasoningEffortPolicyError(c, err, h.chatCompletionsErrorResponse)
|
||||
return
|
||||
} else if changed {
|
||||
body = cappedBody
|
||||
}
|
||||
reqStream, ok := parseOpenAICompatibleStream(body)
|
||||
if !ok {
|
||||
h.chatCompletionsErrorResponse(c, http.StatusBadRequest, "invalid_request_error", invalidStreamFieldTypeMessage)
|
||||
@@ -390,6 +396,7 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) {
|
||||
zap.Bool("upstream_error_response_already_written", upstreamErrorAlreadyCommunicated),
|
||||
zap.Error(err),
|
||||
)
|
||||
h.gatewayService.ReleaseStickySessionAfterCommittedNoContent(context.WithoutCancel(c.Request.Context()), apiKey.GroupID, selectionSessionHash, account.ID, err)
|
||||
if result != nil {
|
||||
submitForwardUsage(result)
|
||||
}
|
||||
|
||||
@@ -85,6 +85,12 @@ func (h *GatewayHandler) Responses(c *gin.Context) {
|
||||
if rejectSystemOneOnlyPlatform(c, apiKey, h.responsesErrorResponse) {
|
||||
return
|
||||
}
|
||||
if cappedBody, changed, err := applyOpenAIReasoningEffortPolicyForRequest(c, apiKey, body); err != nil {
|
||||
respondOpenAIReasoningEffortPolicyError(c, err, h.responsesErrorResponse)
|
||||
return
|
||||
} else if changed {
|
||||
body = cappedBody
|
||||
}
|
||||
reqStream, ok := parseOpenAICompatibleStream(body)
|
||||
if !ok {
|
||||
h.responsesErrorResponse(c, http.StatusBadRequest, "invalid_request_error", invalidStreamFieldTypeMessage)
|
||||
@@ -373,6 +379,9 @@ func (h *GatewayHandler) Responses(c *gin.Context) {
|
||||
zap.Bool("upstream_error_response_already_written", upstreamErrorAlreadyCommunicated),
|
||||
zap.Error(err),
|
||||
)
|
||||
// The response is already committed, so the client retries; send that
|
||||
// retry through scheduling again instead of back to this account.
|
||||
h.gatewayService.ReleaseStickySessionAfterCommittedNoContent(context.WithoutCancel(requestCtx), apiKey.GroupID, sessionHash, account.ID, err)
|
||||
if result != nil {
|
||||
submitForwardUsage(result)
|
||||
}
|
||||
|
||||
@@ -172,7 +172,7 @@ type ConcurrencyHelper struct {
|
||||
|
||||
// NewConcurrencyHelper creates a new ConcurrencyHelper
|
||||
func NewConcurrencyHelper(concurrencyService *service.ConcurrencyService, pingFormat SSEPingFormat, pingInterval time.Duration) *ConcurrencyHelper {
|
||||
if pingInterval <= 0 {
|
||||
if pingInterval < 0 {
|
||||
pingInterval = defaultPingInterval
|
||||
}
|
||||
return &ConcurrencyHelper{
|
||||
@@ -380,7 +380,7 @@ func (h *ConcurrencyHelper) waitForSlotWithPingTimeout(c *gin.Context, slotType
|
||||
}
|
||||
|
||||
// Determine if ping is needed (streaming + ping format defined)
|
||||
needPing := isStream && h.pingFormat != ""
|
||||
needPing := isStream && h.pingFormat != "" && h.pingInterval > 0
|
||||
|
||||
var flusher http.Flusher
|
||||
if needPing {
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestConcurrencyWaitPingInterval(t *testing.T) {
|
||||
for _, slotType := range []string{"user", "account"} {
|
||||
for _, format := range []SSEPingFormat{SSEPingFormatClaude, SSEPingFormatComment} {
|
||||
for _, interval := range []time.Duration{0, time.Millisecond} {
|
||||
t.Run(slotType+"/"+string(format)+"/"+interval.String(), func(t *testing.T) {
|
||||
cache := &helperConcurrencyCacheStub{}
|
||||
helper := NewConcurrencyHelper(service.NewConcurrencyService(cache), format, interval)
|
||||
require.Equal(t, interval, helper.pingInterval)
|
||||
recorder := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(recorder)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/", nil)
|
||||
started := false
|
||||
_, err := helper.waitForSlotWithPingTimeout(c, slotType, 1, 1, 150*time.Millisecond, true, &started, false)
|
||||
var concurrencyErr *ConcurrencyError
|
||||
require.ErrorAs(t, err, &concurrencyErr)
|
||||
require.True(t, concurrencyErr.IsTimeout)
|
||||
if interval == 0 {
|
||||
require.False(t, started)
|
||||
require.False(t, c.Writer.Written())
|
||||
require.False(t, recorder.Flushed)
|
||||
require.Empty(t, recorder.Body.String())
|
||||
require.Empty(t, recorder.Header().Get("Content-Type"))
|
||||
c.JSON(http.StatusTooManyRequests, gin.H{"error": "busy"})
|
||||
require.Equal(t, http.StatusTooManyRequests, recorder.Code)
|
||||
} else {
|
||||
require.True(t, started)
|
||||
require.True(t, recorder.Flushed)
|
||||
require.Contains(t, recorder.Body.String(), string(format))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestConcurrencyWaitWithoutPingAcquiresSlot(t *testing.T) {
|
||||
for _, slotType := range []string{"user", "account"} {
|
||||
t.Run(slotType, func(t *testing.T) {
|
||||
cache := &helperConcurrencyCacheStub{userSeq: []bool{true}, accountSeq: []bool{true}}
|
||||
helper := NewConcurrencyHelper(service.NewConcurrencyService(cache), SSEPingFormatClaude, 0)
|
||||
recorder := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(recorder)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/", nil)
|
||||
started := false
|
||||
release, err := helper.waitForSlotWithPingTimeout(c, slotType, 1, 1, time.Second, true, &started, false)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, release)
|
||||
release()
|
||||
require.False(t, started)
|
||||
require.False(t, c.Writer.Written())
|
||||
require.Empty(t, recorder.Body.String())
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
//go:build unit
|
||||
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
middleware "github.com/Wei-Shaw/sub2api/internal/server/middleware"
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
type stickyWritebackContextKey struct{}
|
||||
|
||||
type stickyWritebackCall struct {
|
||||
err error
|
||||
groupID int64
|
||||
account int64
|
||||
session string
|
||||
ttl time.Duration
|
||||
value any
|
||||
deadline time.Time
|
||||
}
|
||||
|
||||
type stickyWritebackCache struct {
|
||||
service.GatewayCache
|
||||
accountID int64
|
||||
finished bool
|
||||
calls []stickyWritebackCall
|
||||
}
|
||||
|
||||
func (s *stickyWritebackCache) GetSessionAccountID(context.Context, int64, string) (int64, error) {
|
||||
return s.accountID, nil
|
||||
}
|
||||
|
||||
func (s *stickyWritebackCache) SetSessionAccountID(ctx context.Context, groupID int64, session string, account int64, ttl time.Duration) error {
|
||||
if s.finished {
|
||||
deadline, _ := ctx.Deadline()
|
||||
s.calls = append(s.calls, stickyWritebackCall{
|
||||
err: ctx.Err(), groupID: groupID, account: account, session: session, ttl: ttl,
|
||||
value: ctx.Value(stickyWritebackContextKey{}), deadline: deadline,
|
||||
})
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
s.accountID = account
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *stickyWritebackCache) RefreshSessionTTL(context.Context, int64, string, time.Duration) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *stickyWritebackCache) DeleteSessionAccountID(context.Context, int64, string) error {
|
||||
s.accountID = 0
|
||||
return nil
|
||||
}
|
||||
|
||||
type stickyWritebackBody struct {
|
||||
io.Reader
|
||||
finish func()
|
||||
}
|
||||
|
||||
func (b *stickyWritebackBody) Close() error {
|
||||
b.finish()
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestGatewayMessagesStickyWritebackAfterForward(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
for _, stream := range []bool{false, true} {
|
||||
name := "buffered"
|
||||
if stream {
|
||||
name = "streaming"
|
||||
}
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
bound int64
|
||||
cancel bool
|
||||
fail bool
|
||||
wantWrites int
|
||||
}{
|
||||
{name: "new binding", wantWrites: 1},
|
||||
{name: "new binding after disconnect", cancel: true, wantWrites: 1},
|
||||
{name: "refresh binding", bound: 9401, wantWrites: 1},
|
||||
{name: "refresh after disconnect", bound: 9401, cancel: true, wantWrites: 1},
|
||||
{name: "different binding", bound: 9499, cancel: true},
|
||||
{name: "forward failed", cancel: true, fail: true},
|
||||
} {
|
||||
t.Run(name+"/"+tt.name, func(t *testing.T) {
|
||||
groupID := int64(9400)
|
||||
group := &service.Group{ID: groupID, Hydrated: true, Platform: service.PlatformAnthropic, Status: service.StatusActive, RateMultiplier: 1}
|
||||
account := &service.Account{
|
||||
ID: 9401, Platform: service.PlatformAnthropic, Type: service.AccountTypeAPIKey,
|
||||
Status: service.StatusActive, Schedulable: true, Concurrency: 1,
|
||||
Credentials: map[string]any{"api_key": "test-key"},
|
||||
Extra: map[string]any{"anthropic_passthrough": true},
|
||||
AccountGroups: []service.AccountGroup{{AccountID: 9401, GroupID: groupID}},
|
||||
}
|
||||
cache := &stickyWritebackCache{accountID: tt.bound}
|
||||
ctx := context.WithValue(context.Background(), stickyWritebackContextKey{}, "request-scoped value")
|
||||
ctx, cancel := context.WithTimeout(ctx, 4*time.Second)
|
||||
t.Cleanup(cancel)
|
||||
responseBody := `{"id":"msg_1","type":"message","role":"assistant","model":"claude-sonnet-4.5","content":[{"type":"text","text":"ok"}],"stop_reason":"end_turn","usage":{"input_tokens":1,"output_tokens":1}}`
|
||||
contentType := "application/json"
|
||||
if stream {
|
||||
responseBody = compatStreamUsagePartialStream + compatStreamUsageCompletion
|
||||
contentType = "text/event-stream"
|
||||
}
|
||||
status := http.StatusOK
|
||||
if tt.fail {
|
||||
status = http.StatusBadRequest
|
||||
responseBody = `{"type":"error","error":{"type":"invalid_request_error","message":"invalid input"}}`
|
||||
}
|
||||
upstream := &compatStreamUsageUpstream{response: &http.Response{
|
||||
StatusCode: status,
|
||||
Header: http.Header{"Content-Type": []string{contentType}},
|
||||
Body: &stickyWritebackBody{Reader: strings.NewReader(responseBody), finish: func() {
|
||||
// Forward closes its upstream body on return. Cancel precisely
|
||||
// after that work, before the handler's terminal sticky write.
|
||||
cache.finished = true
|
||||
if tt.cancel {
|
||||
cancel()
|
||||
}
|
||||
}},
|
||||
}}
|
||||
cfg := &config.Config{RunMode: config.RunModeSimple}
|
||||
other := *account
|
||||
other.ID = 9499
|
||||
other.Schedulable = false
|
||||
snapshot := service.NewSchedulerSnapshotService(&fakeSchedulerCache{accounts: []*service.Account{account, &other}}, nil, nil, nil, nil)
|
||||
gw := service.NewGatewayService(
|
||||
nil, &fakeGroupRepo{group: group}, nil, nil, nil, nil, nil, cache, cfg,
|
||||
snapshot, nil, service.NewBillingService(cfg, nil), nil, nil, nil, upstream,
|
||||
&service.DeferredService{}, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil,
|
||||
)
|
||||
billingCache := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil)
|
||||
t.Cleanup(billingCache.Stop)
|
||||
h := &GatewayHandler{
|
||||
gatewayService: gw, billingCacheService: billingCache, cfg: cfg, maxAccountSwitches: 1,
|
||||
concurrencyHelper: NewConcurrencyHelper(service.NewConcurrencyService(&fakeConcurrencyCache{}), SSEPingFormatClaude, 0),
|
||||
}
|
||||
requestBody := `{"model":"claude-sonnet-4.5","max_tokens":16,"stream":false,"messages":[{"role":"user","content":"sticky writeback test"}]}`
|
||||
if stream {
|
||||
requestBody = strings.Replace(requestBody, `"stream":false`, `"stream":true`, 1)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", strings.NewReader(requestBody)).WithContext(ctx)
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
key := &service.APIKey{ID: 9402, UserID: 9403, GroupID: &groupID, Group: group, User: &service.User{ID: 9403, Balance: 100}}
|
||||
c.Set(string(middleware.ContextKeyAPIKey), key)
|
||||
c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: 9403})
|
||||
|
||||
h.Messages(c)
|
||||
|
||||
require.Equal(t, 1, upstream.calls)
|
||||
require.True(t, cache.finished)
|
||||
require.Equal(t, status, rec.Code)
|
||||
if tt.cancel {
|
||||
require.ErrorIs(t, ctx.Err(), context.Canceled)
|
||||
}
|
||||
require.Len(t, cache.calls, tt.wantWrites)
|
||||
for _, call := range cache.calls {
|
||||
require.NoError(t, call.err, "a completed upstream request must retain its terminal sticky write")
|
||||
require.Equal(t, groupID, call.groupID)
|
||||
require.Equal(t, account.ID, call.account)
|
||||
require.NotEmpty(t, call.session)
|
||||
require.Positive(t, call.ttl)
|
||||
require.Equal(t, "request-scoped value", call.value)
|
||||
require.False(t, call.deadline.IsZero(), "the detached cache write must have a deadline")
|
||||
require.WithinDuration(t, time.Now(), call.deadline, 5*time.Second)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -275,6 +275,7 @@ func (h *GatewayHandler) GeminiCachedContentsCreate(c *gin.Context) {
|
||||
Result: &service.ForwardResult{
|
||||
Model: modelName, UpstreamModel: mappedModel,
|
||||
Usage: service.ClaudeUsage{InputTokens: int(tokens)}, CacheStorageTokenHours: storageTokenHours,
|
||||
UpstreamPriceMultiplier: service.VertexUpstreamPriceMultiplier(account, mappedModel, ""),
|
||||
},
|
||||
APIKey: apiKey, User: apiKey.User, Subscription: subscription, PricingAt: pricingAt, ChannelUsageFields: usageFields,
|
||||
})
|
||||
@@ -674,15 +675,17 @@ func (h *GatewayHandler) submitGeminiCachedContentUsage(
|
||||
if inputTokens <= 0 && storageTokenHours <= 0 {
|
||||
return
|
||||
}
|
||||
priceMultiplier := service.VertexUpstreamPriceMultiplier(account, upstreamModel, "")
|
||||
if upstreamModel == model {
|
||||
upstreamModel = ""
|
||||
}
|
||||
result := &service.ForwardResult{
|
||||
RequestID: requestID,
|
||||
Model: model,
|
||||
UpstreamModel: upstreamModel,
|
||||
Usage: service.ClaudeUsage{InputTokens: inputTokens},
|
||||
CacheStorageTokenHours: storageTokenHours,
|
||||
RequestID: requestID,
|
||||
Model: model,
|
||||
UpstreamModel: upstreamModel,
|
||||
Usage: service.ClaudeUsage{InputTokens: inputTokens},
|
||||
CacheStorageTokenHours: storageTokenHours,
|
||||
UpstreamPriceMultiplier: priceMultiplier,
|
||||
}
|
||||
inboundEndpoint := GetInboundEndpoint(c)
|
||||
upstreamEndpoint := GetUpstreamEndpoint(c, account.Platform)
|
||||
|
||||
@@ -13,7 +13,6 @@ import (
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/domain"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/antigravity"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/gemini"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/googleapi"
|
||||
@@ -468,16 +467,8 @@ func (h *GatewayHandler) GeminiV1BetaModels(c *gin.Context) {
|
||||
sessionHash = extractGeminiCLISessionHash(c, body)
|
||||
}
|
||||
if sessionHash == "" && cachedContentBinding == nil {
|
||||
// Fallback: 使用通用的会话哈希生成逻辑(适用于其他客户端)
|
||||
parsedReq, _ := service.ParseGatewayRequest(service.NewRequestBodyRef(body), domain.PlatformGemini)
|
||||
if parsedReq != nil {
|
||||
parsedReq.SessionContext = &service.SessionContext{
|
||||
ClientIP: ip.GetClientIP(c),
|
||||
UserAgent: c.GetHeader("User-Agent"),
|
||||
APIKeyID: apiKey.ID,
|
||||
}
|
||||
}
|
||||
sessionHash = h.gatewayService.GenerateSessionHash(parsedReq)
|
||||
// 其他客户端:按 API Key + 模型 + tools + systemInstruction + 第一条 user contents 的 parts 生成内容哈希
|
||||
sessionHash = service.GenerateGeminiContentSessionHash(apiKey.ID, reqModel, body)
|
||||
}
|
||||
sessionKey := sessionHash
|
||||
if sessionHash != "" {
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
//go:build unit
|
||||
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
func TestGrokImagesPreservesUpstreamErrorOnSyncAndAsyncRoutes(t *testing.T) {
|
||||
for _, oauth := range []bool{false, true} {
|
||||
accountType := "api-key"
|
||||
if oauth {
|
||||
accountType = "oauth"
|
||||
}
|
||||
for _, async := range []bool{false, true} {
|
||||
route := "sync"
|
||||
if async {
|
||||
route = "async"
|
||||
}
|
||||
t.Run(accountType+"/"+route, func(t *testing.T) {
|
||||
h, slots, _, upstream := newGrokMediaSlotHandler(t, oauth, false)
|
||||
h.grokMediaEligibilityProber = grokMediaSlotProber(func(context.Context, int64) (bool, string, error) {
|
||||
return true, "test account is eligible", nil
|
||||
})
|
||||
upstream.call = func(req *http.Request, _ int64) (*http.Response, error) {
|
||||
assert.Equal(t, "/v1/images/edits", req.URL.Path)
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusBadRequest,
|
||||
Header: http.Header{"Content-Type": {"application/json"}},
|
||||
Body: io.NopCloser(strings.NewReader(`{"code":"invalid_image","error":"Image could not be decoded: https://example.test/image?access_token=secret&size=1","debug":"private upstream diagnostic"}`)),
|
||||
}, nil
|
||||
}
|
||||
c, recorder := grokMediaSlotContext(context.Background(), true)
|
||||
path := "/v1/images/edits"
|
||||
if async {
|
||||
path += "/async"
|
||||
}
|
||||
c.Request = httptest.NewRequest(http.MethodPost, path, strings.NewReader(`{"model":"grok-imagine-image","prompt":"test","image":{"url":"https://example.test/input.png"}}`))
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
|
||||
var responseBody []byte
|
||||
if async {
|
||||
store := &asyncImageMemoryStore{tasks: make(map[string]*service.ImageTaskRecord)}
|
||||
tasks := service.NewImageTaskServiceWithUploader(store, nil, time.Hour, time.Minute)
|
||||
asyncHandler := NewAsyncImageHandler(tasks, h)
|
||||
asyncHandler.Submit(c)
|
||||
require.Equal(t, http.StatusAccepted, recorder.Code, recorder.Body.String())
|
||||
taskID := gjson.GetBytes(recorder.Body.Bytes(), "task_id").String()
|
||||
owner := service.ImageTaskOwner{UserID: 10, APIKeyID: 20}
|
||||
require.Eventually(t, func() bool {
|
||||
task, err := tasks.Get(context.Background(), owner, taskID)
|
||||
return err == nil && task.Status != service.ImageTaskStatusProcessing
|
||||
}, time.Second, 10*time.Millisecond)
|
||||
poll, pollRecorder := grokMediaSlotContext(context.Background(), false)
|
||||
poll.Params[0].Key, poll.Params[0].Value = "task_id", taskID
|
||||
asyncHandler.Get(poll)
|
||||
require.Equal(t, http.StatusOK, pollRecorder.Code)
|
||||
responseBody = pollRecorder.Body.Bytes()
|
||||
require.Equal(t, service.ImageTaskStatusFailed, gjson.GetBytes(responseBody, "status").String())
|
||||
require.Equal(t, int64(http.StatusBadRequest), gjson.GetBytes(responseBody, "http_status").Int())
|
||||
} else {
|
||||
h.GrokImages(c)
|
||||
require.Equal(t, http.StatusBadRequest, recorder.Code, recorder.Body.String())
|
||||
responseBody = recorder.Body.Bytes()
|
||||
}
|
||||
require.Equal(t, "Image could not be decoded: https://example.test/image?access_token=***&size=1", gjson.GetBytes(responseBody, "error.message").String())
|
||||
require.Equal(t, "invalid_image", gjson.GetBytes(responseBody, "error.code").String())
|
||||
require.Equal(t, "invalid_request_error", gjson.GetBytes(responseBody, "error.type").String())
|
||||
require.NotContains(t, string(responseBody), "secret")
|
||||
require.NotContains(t, string(responseBody), "private upstream diagnostic")
|
||||
require.Equal(t, 1, upstream.calls, "deterministic image errors must not retry another account")
|
||||
slots.assertReleased(t)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
//go:build unit
|
||||
|
||||
package handler
|
||||
|
||||
import (
|
||||
"math/rand"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestCodexCallOutputGateSkipsDeclaredToolsWithoutCandidate(t *testing.T) {
|
||||
body := []byte(`{"model":"gpt-5","tools":[{"type":"function","name":"automation_update"},{"type":"function","name":"create_thread"}],` +
|
||||
`"input":[{"type":"function_call","call_id":"c1","name":"shell"},{"type":"function_call_output","call_id":"c1","output":"ok"}]}`)
|
||||
require.False(t, mayContainCodexCallOutputCandidate(body, "automation_update"))
|
||||
require.False(t, mayContainCodexCallOutputCandidate(body, "create_thread", "send_message_to_thread"))
|
||||
for name, normalize := range map[string]func([]byte) ([]byte, bool){
|
||||
"untrusted": normalizeCodexUntrustedContext,
|
||||
"automation": normalizeCodexAutomationBootstrap,
|
||||
"delegation": normalizeCodexDelegationBootstrap,
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
allocs := testing.AllocsPerRun(10, func() {
|
||||
got, changed := normalize(body)
|
||||
if changed || &got[0] != &body[0] {
|
||||
t.Fatal("non-candidate body must be returned unchanged")
|
||||
}
|
||||
})
|
||||
require.Zero(t, allocs)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Whenever the ungated bootstrap path rewrites a body, the gate must admit it.
|
||||
func TestCodexCallOutputGateAdmitsEveryRewrite(t *testing.T) {
|
||||
u := func(hex string) string { return `\` + "u" + hex }
|
||||
output := mustJSON(t, codexAutomationBootstrap("wiki", "never", automationBootstrapPrompt))
|
||||
items := []string{
|
||||
`{"type":"function_call_output","namespace":"codex_app","name":"automation_update","output":` + output + `}`,
|
||||
`{"type":"function_call_output","namespace":"codex_app","name":"` + u("0061") + `utomation_update","output":` + output + `}`,
|
||||
`{"` + u("0074") + `ype":"function_call_output","namespace":"codex_app","name":"automation_update","output":` + output + `}`,
|
||||
`{"type":"function_call_output","namespace":"codex_app","name":"automation_update","name":"other","output":` + output + `}`,
|
||||
`{"type":"function_call_output","call_id":"c","output":"ok"}`,
|
||||
`{"type":"message","role":"user","content":"automation_update function_call_output caf` + u("00e9") + `"}`,
|
||||
`{"type":"function_call","call_id":"c","name":"automation_update"}`,
|
||||
}
|
||||
rng := rand.New(rand.NewSource(11))
|
||||
rewrites := 0
|
||||
for i := 0; i < 3000; i++ {
|
||||
var parts []string
|
||||
for n := rng.Intn(3); n >= 0; n-- {
|
||||
parts = append(parts, items[rng.Intn(len(items))])
|
||||
}
|
||||
body := []byte(`{"model":"gpt-5","tools":[{"type":"function","name":"automation_update"}],"input":[` + strings.Join(parts, ",") + `]}`)
|
||||
_, rewritten := normalizeCodexCallOutputBootstrap(body, isCodexAutomationCandidate, false)
|
||||
if rewritten {
|
||||
rewrites++
|
||||
require.True(t, mayContainCodexCallOutputCandidate(body, "automation_update"), "%s", body)
|
||||
}
|
||||
}
|
||||
require.Positive(t, rewrites)
|
||||
}
|
||||
@@ -364,7 +364,7 @@ func NewOpenAIGatewayHandler(
|
||||
opsService *service.OpsService,
|
||||
cfg *config.Config,
|
||||
) *OpenAIGatewayHandler {
|
||||
pingInterval := time.Duration(0)
|
||||
pingInterval := defaultPingInterval
|
||||
maxAccountSwitches := 3
|
||||
if cfg != nil {
|
||||
pingInterval = time.Duration(cfg.Concurrency.PingInterval) * time.Second
|
||||
@@ -489,9 +489,9 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) {
|
||||
} else if changed {
|
||||
body = cappedBody
|
||||
}
|
||||
if normalizedBody, changed := normalizeCodexPageContext(body); changed {
|
||||
if normalizedBody, changed := normalizeCodexUntrustedContext(body); changed {
|
||||
body = normalizedBody
|
||||
reqLog.Info("openai.codex_page_context_normalized",
|
||||
reqLog.Info("openai.codex_untrusted_context_normalized",
|
||||
zap.String("normalization", "call_output_to_user_message"),
|
||||
)
|
||||
}
|
||||
@@ -1413,7 +1413,7 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) {
|
||||
defaultMappedModel := strings.TrimSpace(effectiveMappedModel)
|
||||
// 应用渠道模型映射到请求体
|
||||
forwardBody := mappedBodyForMessages(channelMappingMsg.Mapped, channelMappingMsg.MappedModel)
|
||||
writerSizeBeforeForward := c.Writer.Size()
|
||||
writerSizeBeforeForward := service.OpenAICompactKeepaliveAdjustedWrittenSize(c)
|
||||
result, err := func() (*service.OpenAIForwardResult, error) {
|
||||
defer func() {
|
||||
if accountReleaseFunc != nil {
|
||||
@@ -1501,11 +1501,16 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) {
|
||||
)
|
||||
return
|
||||
}
|
||||
if c.Writer.Size() != writerSizeBeforeForward {
|
||||
if !openAIForwardMayFailover(c, writerSizeBeforeForward, failoverErr) {
|
||||
h.gatewayService.ObserveOpenAIAccountHealthFailure(c.Request.Context(), account, err)
|
||||
h.handleAnthropicFailoverExhausted(c, failoverErr, true)
|
||||
return
|
||||
}
|
||||
// Only keepalive bytes were written, so failover may continue, but
|
||||
// every later error must be written as an SSE event.
|
||||
if c.Writer.Written() {
|
||||
streamStarted = true
|
||||
}
|
||||
if failoverErr.ShouldReportAccountScheduleFailure() {
|
||||
h.gatewayService.ReportOpenAIAccountScheduleResult(account, openAIAccountScheduleModel(c, account, currentRoutingModel, false, nil), false, nil, err)
|
||||
}
|
||||
@@ -1663,16 +1668,24 @@ func (h *OpenAIGatewayHandler) handleAnthropicFailoverExhausted(c *gin.Context,
|
||||
h.anthropicStreamingAwareError(c, status, "api_error", failoverErr.ClientMessage, streamStarted)
|
||||
return
|
||||
}
|
||||
// A failed or error frame that triggered the failover no longer reaches the
|
||||
// client in-band, so its error passthrough rule is applied here instead.
|
||||
if status, errType, msg, ok := service.ApplyOpenAIStreamFailedFrameRule(c, failoverErr); ok {
|
||||
h.anthropicStreamingAwareError(c, status, errType, msg, streamStarted)
|
||||
return
|
||||
}
|
||||
status, errType, errMsg := h.mapUpstreamError(failoverErr.StatusCode)
|
||||
h.anthropicStreamingAwareError(c, status, errType, errMsg, streamStarted)
|
||||
}
|
||||
|
||||
// ensureAnthropicErrorResponse writes a fallback Anthropic error if no response was written.
|
||||
func (h *OpenAIGatewayHandler) ensureAnthropicErrorResponse(c *gin.Context, streamStarted bool) bool {
|
||||
if c == nil || c.Writer == nil || c.Writer.Written() {
|
||||
// Keepalive pings alone do not count as a written response, but they do
|
||||
// commit the response as SSE, so the fallback must then be an SSE event.
|
||||
if c == nil || c.Writer == nil || service.OpenAICompactKeepaliveAdjustedWrittenSize(c) >= 0 {
|
||||
return false
|
||||
}
|
||||
h.anthropicStreamingAwareError(c, http.StatusBadGateway, "api_error", "Upstream request failed", streamStarted)
|
||||
h.anthropicStreamingAwareError(c, http.StatusBadGateway, "api_error", "Upstream request failed", streamStarted || c.Writer.Written())
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -1729,11 +1742,23 @@ func normalizeCodexAutomationBootstrap(body []byte) ([]byte, bool) {
|
||||
// mayContainCodexCallOutputCandidate is a necessary condition for a bootstrap
|
||||
// candidate, checked before the full uniqueness scan and decode. Its type and
|
||||
// tool name are JSON strings, which appear literally unless a \u escape spells
|
||||
// their letters; without either, normalization cannot change the body.
|
||||
// their letters; without either, normalization cannot change the body. Escapes
|
||||
// that real clients emit (control characters, HTML-safe and non-ASCII runes)
|
||||
// cannot spell those letters and must not force the full decode.
|
||||
//
|
||||
// Tool declarations carry the same names, so a literal hit is confirmed by a
|
||||
// zero-copy scan for an input item of type function_call_output whose name
|
||||
// starts with one of toolNames. The full path rejects bodies with duplicate
|
||||
// members, and without duplicates the scan reads the same values as the
|
||||
// decoder.
|
||||
func mayContainCodexCallOutputCandidate(body []byte, toolNames ...string) bool {
|
||||
if bytes.Contains(body, []byte(`\u`)) {
|
||||
return true
|
||||
if !service.JSONMayEscapePlainASCII(body) && !containsCodexCallOutputLiterals(body, toolNames) {
|
||||
return false
|
||||
}
|
||||
return service.ResponsesInputHasFunctionCallOutputNamed(body, toolNames...)
|
||||
}
|
||||
|
||||
func containsCodexCallOutputLiterals(body []byte, toolNames []string) bool {
|
||||
if !bytes.Contains(body, []byte("function_call_output")) {
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -0,0 +1,336 @@
|
||||
//go:build unit
|
||||
|
||||
package handler
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
"github.com/Wei-Shaw/sub2api/internal/model"
|
||||
"github.com/Wei-Shaw/sub2api/internal/server/middleware"
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/tidwall/gjson"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
const (
|
||||
preContentHandlerCreated = `data: {"type":"response.created","response":{"id":"resp_pc","object":"response","model":"gpt-5.4","status":"in_progress","output":[]}}` + "\n\n"
|
||||
preContentHandlerFailed = `data: {"type":"response.failed","response":{"status":"failed","error":{"code":"server_error","message":"An error occurred while processing your request."}}}` + "\n\n"
|
||||
preContentHandlerSuccess = preContentHandlerCreated +
|
||||
`data: {"type":"response.output_item.added","output_index":0,"item":{"id":"msg_1","type":"message","role":"assistant","content":[]}}` + "\n\n" +
|
||||
`data: {"type":"response.output_text.delta","output_index":0,"content_index":0,"delta":"answer from second account"}` + "\n\n" +
|
||||
`data: {"type":"response.completed","response":{"id":"resp_pc","object":"response","model":"gpt-5.4","status":"completed","output":[],"usage":{"input_tokens":3,"output_tokens":4,"total_tokens":7}}}` + "\n\n"
|
||||
)
|
||||
|
||||
// preContentFailoverUpstream hands each upstream request to respond, which
|
||||
// gets the 1-based call number.
|
||||
type preContentFailoverUpstream struct {
|
||||
service.HTTPUpstream
|
||||
mu sync.Mutex
|
||||
hits []int64
|
||||
respond func(call int) (*http.Response, error)
|
||||
}
|
||||
|
||||
func (u *preContentFailoverUpstream) Do(req *http.Request, _ string, accountID int64, _ int) (*http.Response, error) {
|
||||
if req.Body != nil {
|
||||
_, _ = io.Copy(io.Discard, req.Body)
|
||||
}
|
||||
u.mu.Lock()
|
||||
u.hits = append(u.hits, accountID)
|
||||
call := len(u.hits)
|
||||
u.mu.Unlock()
|
||||
return u.respond(call)
|
||||
}
|
||||
|
||||
func (u *preContentFailoverUpstream) calls() int {
|
||||
u.mu.Lock()
|
||||
defer u.mu.Unlock()
|
||||
return len(u.hits)
|
||||
}
|
||||
|
||||
func preContentSSEResponse(body io.ReadCloser) *http.Response {
|
||||
return &http.Response{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"text/event-stream"}}, Body: body}
|
||||
}
|
||||
|
||||
// preContentStallThenFail stalls past one keepalive tick after the first event
|
||||
// and then fails with failed.
|
||||
func preContentStallThenFail(failed string) *http.Response {
|
||||
pr, pw := io.Pipe()
|
||||
go func() {
|
||||
_, _ = io.WriteString(pw, preContentHandlerCreated)
|
||||
time.Sleep(1300 * time.Millisecond)
|
||||
_, _ = io.WriteString(pw, failed)
|
||||
_ = pw.Close()
|
||||
}()
|
||||
return preContentSSEResponse(pr)
|
||||
}
|
||||
|
||||
type unexpectedEOFReader struct{}
|
||||
|
||||
func (unexpectedEOFReader) Read([]byte) (int, error) { return 0, io.ErrUnexpectedEOF }
|
||||
|
||||
type preContentFailoverScenario struct {
|
||||
accounts []service.Account
|
||||
respond func(call int) (*http.Response, error)
|
||||
passthrough *service.ErrorPassthroughService
|
||||
requestBody string
|
||||
}
|
||||
|
||||
func preContentAccounts(count int) []service.Account {
|
||||
accounts := make([]service.Account, 0, count)
|
||||
for i := 0; i < count; i++ {
|
||||
accounts = append(accounts, service.Account{
|
||||
ID: int64(9201 + i), Name: "openai-apikey", Platform: service.PlatformOpenAI, Type: service.AccountTypeAPIKey,
|
||||
Status: service.StatusActive, Schedulable: true, Concurrency: 1, Priority: i + 1,
|
||||
Credentials: map[string]any{"api_key": "sk-test", "base_url": "http://upstream.example"},
|
||||
})
|
||||
}
|
||||
return accounts
|
||||
}
|
||||
|
||||
func servePreContentFailoverMessages(t *testing.T, accountCount int) (*httptest.ResponseRecorder, *preContentFailoverUpstream) {
|
||||
t.Helper()
|
||||
return serveMessagesScenario(t, preContentFailoverScenario{
|
||||
accounts: preContentAccounts(accountCount),
|
||||
respond: func(call int) (*http.Response, error) {
|
||||
if call == 1 {
|
||||
return preContentStallThenFail(preContentHandlerFailed), nil
|
||||
}
|
||||
return preContentSSEResponse(io.NopCloser(strings.NewReader(preContentHandlerSuccess))), nil
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func serveMessagesScenario(t *testing.T, sc preContentFailoverScenario) (*httptest.ResponseRecorder, *preContentFailoverUpstream) {
|
||||
t.Helper()
|
||||
gin.SetMode(gin.TestMode)
|
||||
groupID := int64(9101)
|
||||
repo := &grokCredentialHandlerRepo{accounts: sc.accounts, missingOnGet: map[int64]bool{}}
|
||||
upstream := &preContentFailoverUpstream{respond: sc.respond}
|
||||
cfg := &config.Config{RunMode: config.RunModeSimple}
|
||||
cfg.Gateway.MaxAccountSwitches = 3
|
||||
cfg.Gateway.StreamKeepaliveInterval = 1
|
||||
cfg.Security.URLAllowlist.AllowInsecureHTTP = true
|
||||
billingCache := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil)
|
||||
t.Cleanup(billingCache.Stop)
|
||||
gateway := service.NewOpenAIGatewayService(
|
||||
repo, nil, nil, nil, nil, nil, nil, cfg, nil, nil,
|
||||
service.NewBillingService(cfg, nil), nil, billingCache, upstream,
|
||||
&service.DeferredService{}, nil, nil, nil, nil, nil, nil, nil,
|
||||
)
|
||||
cache := &concurrencyCacheMock{
|
||||
acquireUserSlotFn: func(context.Context, int64, int, string) (bool, error) { return true, nil },
|
||||
acquireAccountSlotFn: func(context.Context, int64, int, string) (bool, error) { return true, nil },
|
||||
}
|
||||
h := NewOpenAIGatewayHandler(gateway, service.NewConcurrencyService(cache), billingCache, &service.APIKeyService{}, nil, sc.passthrough, nil, nil, cfg)
|
||||
apiKey := &service.APIKey{
|
||||
ID: 9102, GroupID: &groupID,
|
||||
User: &service.User{ID: 9103, Status: service.StatusActive},
|
||||
Group: &service.Group{ID: groupID, Platform: service.PlatformOpenAI, Status: service.StatusActive, AllowMessagesDispatch: true},
|
||||
}
|
||||
router := gin.New()
|
||||
router.Use(func(c *gin.Context) {
|
||||
c.Set(string(middleware.ContextKeyAPIKey), apiKey)
|
||||
c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: apiKey.User.ID, Concurrency: 1})
|
||||
service.BindErrorPassthroughService(c, sc.passthrough)
|
||||
c.Next()
|
||||
})
|
||||
router.POST("/v1/messages", h.Messages)
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
requestBody := sc.requestBody
|
||||
if requestBody == "" {
|
||||
requestBody = `{"model":"gpt-5.4","max_tokens":32,"messages":[{"role":"user","content":"hello"}],"stream":true}`
|
||||
}
|
||||
req := httptest.NewRequest(http.MethodPost, "/v1/messages", bytes.NewBufferString(requestBody))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
router.ServeHTTP(rec, req)
|
||||
return rec, upstream
|
||||
}
|
||||
|
||||
// requireEndsWithSSEError checks that a response already committed as SSE ends
|
||||
// with an Anthropic error event and never carries a bare JSON line.
|
||||
func requireEndsWithSSEError(t *testing.T, body string) {
|
||||
t.Helper()
|
||||
lastEvent := body[strings.LastIndex(strings.TrimRight(body, "\n"), "\n\n")+2:]
|
||||
require.True(t, strings.HasPrefix(lastEvent, "event: error\ndata: {"), "last event: %q", lastEvent)
|
||||
require.Contains(t, lastEvent, `"type":"error"`)
|
||||
for _, line := range strings.Split(body, "\n") {
|
||||
require.False(t, strings.HasPrefix(line, "{"), "bare JSON line in SSE body: %q", line)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenAIMessagesFailsOverAfterKeepaliveOnlyWrite(t *testing.T) {
|
||||
rec, upstream := servePreContentFailoverMessages(t, 2)
|
||||
|
||||
body := rec.Body.String()
|
||||
require.Equal(t, 2, upstream.calls(), "body: %q", body)
|
||||
require.Equal(t, 1, strings.Count(body, "event: message_start"), "body: %q", body)
|
||||
require.Contains(t, body, "answer from second account")
|
||||
}
|
||||
|
||||
func TestOpenAIMessagesKeepaliveThenFailoverExhaustedEndsWithSSEError(t *testing.T) {
|
||||
rec, upstream := servePreContentFailoverMessages(t, 1)
|
||||
|
||||
body := rec.Body.String()
|
||||
require.Equal(t, 1, upstream.calls(), "body: %q", body)
|
||||
require.Contains(t, body, "event: ping")
|
||||
requireEndsWithSSEError(t, body)
|
||||
}
|
||||
|
||||
func TestOpenAIMessagesFailoverThenSecondAccountReadErrorEndsWithSSEError(t *testing.T) {
|
||||
rec, upstream := serveMessagesScenario(t, preContentFailoverScenario{
|
||||
accounts: preContentAccounts(2),
|
||||
respond: func(call int) (*http.Response, error) {
|
||||
if call == 1 {
|
||||
return preContentStallThenFail(preContentHandlerFailed), nil
|
||||
}
|
||||
return preContentSSEResponse(io.NopCloser(unexpectedEOFReader{})), nil
|
||||
},
|
||||
})
|
||||
|
||||
body := rec.Body.String()
|
||||
require.Equal(t, 2, upstream.calls(), "body: %q", body)
|
||||
require.NotContains(t, body, "message_start")
|
||||
requireEndsWithSSEError(t, body)
|
||||
}
|
||||
|
||||
func TestOpenAIMessagesFailoverThenSecondAccountCredentialErrorEndsWithSSEError(t *testing.T) {
|
||||
accounts := preContentAccounts(2)
|
||||
accounts[1].Credentials = map[string]any{"base_url": "http://upstream.example"}
|
||||
rec, upstream := serveMessagesScenario(t, preContentFailoverScenario{
|
||||
accounts: accounts,
|
||||
respond: func(call int) (*http.Response, error) {
|
||||
return preContentStallThenFail(preContentHandlerFailed), nil
|
||||
},
|
||||
})
|
||||
|
||||
body := rec.Body.String()
|
||||
require.Equal(t, 1, upstream.calls(), "body: %q", body)
|
||||
require.NotContains(t, body, "message_start")
|
||||
requireEndsWithSSEError(t, body)
|
||||
}
|
||||
|
||||
func TestOpenAIMessagesSlotAcquireFailureAfterKeepaliveIsSSE(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil)
|
||||
c.Header("Content-Type", "text/event-stream")
|
||||
_, err := io.WriteString(c.Writer, "event: ping\ndata: {\"type\":\"ping\"}\n\n")
|
||||
require.NoError(t, err)
|
||||
streamStarted := true
|
||||
|
||||
h := &OpenAIGatewayHandler{}
|
||||
selection := &service.AccountSelectionResult{Account: &service.Account{ID: 9201}}
|
||||
_, result := h.acquireResponsesAccountSlot(c, nil, "", selection, true, &streamStarted, zap.NewNop())
|
||||
|
||||
require.Equal(t, openAISlotAcquireFailed, result)
|
||||
body := rec.Body.String()
|
||||
lastEvent := body[strings.LastIndex(strings.TrimRight(body, "\n"), "\n\n")+2:]
|
||||
require.True(t, strings.HasPrefix(lastEvent, "event: error\ndata: {"), "last event: %q", lastEvent)
|
||||
}
|
||||
|
||||
func newFailedFrameCodeRule(code string) *service.ErrorPassthroughService {
|
||||
status := http.StatusTeapot
|
||||
rule := &model.ErrorPassthroughRule{
|
||||
ID: 1, Name: "frame code rule", Enabled: true, Priority: 1,
|
||||
Keywords: []string{code}, MatchMode: model.MatchModeAny,
|
||||
Platforms: []string{model.PlatformOpenAI}, ResponseCode: &status, PassthroughBody: true,
|
||||
}
|
||||
return service.NewErrorPassthroughService(&errorPassthroughRepoStub{rules: []*model.ErrorPassthroughRule{rule}}, nil)
|
||||
}
|
||||
|
||||
// A failed frame that triggers a failover is no longer written in-band, so its
|
||||
// passthrough rule has to apply once the failover is exhausted. The rule is
|
||||
// keyed on the frame's own code, which the generic failover envelope lacks.
|
||||
func TestOpenAIMessagesFailoverExhaustedAppliesFailedFrameRule(t *testing.T) {
|
||||
rec, upstream := serveMessagesScenario(t, preContentFailoverScenario{
|
||||
accounts: preContentAccounts(1),
|
||||
passthrough: newFailedFrameCodeRule("rate_limit_exceeded"),
|
||||
respond: func(call int) (*http.Response, error) {
|
||||
failed := `data: {"type":"response.failed","response":{"status":"failed","error":{"code":"rate_limit_exceeded","message":"Rate limit reached for gpt-5.4"}}}` + "\n\n"
|
||||
return preContentSSEResponse(io.NopCloser(strings.NewReader(preContentHandlerCreated + failed))), nil
|
||||
},
|
||||
})
|
||||
|
||||
body := rec.Body.String()
|
||||
t.Logf("status=%d body=%q", rec.Code, body)
|
||||
require.Equal(t, 1, upstream.calls(), "body: %q", body)
|
||||
require.Equal(t, http.StatusTeapot, rec.Code, "body: %q", body)
|
||||
require.Equal(t, "upstream_error", gjson.Get(body, "error.type").String(), "body: %q", body)
|
||||
require.Equal(t, "Rate limit reached for gpt-5.4", gjson.Get(body, "error.message").String(), "body: %q", body)
|
||||
}
|
||||
|
||||
const preContentRateLimitFailed = `data: {"type":"response.failed","response":{"status":"failed","error":{"code":"rate_limit_exceeded","message":"Rate limit reached for gpt-5.4"}}}` + "\n\n"
|
||||
|
||||
func requireFailedFrameRuleJSON(t *testing.T, rec *httptest.ResponseRecorder) {
|
||||
t.Helper()
|
||||
body := rec.Body.String()
|
||||
t.Logf("status=%d content-type=%q body=%q", rec.Code, rec.Header().Get("Content-Type"), body)
|
||||
require.Equal(t, http.StatusTeapot, rec.Code, "body: %q", body)
|
||||
require.Contains(t, rec.Header().Get("Content-Type"), "application/json")
|
||||
require.Equal(t, "upstream_error", gjson.Get(body, "error.type").String(), "body: %q", body)
|
||||
require.Equal(t, "Rate limit reached for gpt-5.4", gjson.Get(body, "error.message").String(), "body: %q", body)
|
||||
}
|
||||
|
||||
// The failed frame is the first event of the stream, so it triggers the
|
||||
// failover before any output and used to reach the generic mapping unchecked.
|
||||
func TestOpenAIMessagesFirstEventFailedFrameExhaustedAppliesRule(t *testing.T) {
|
||||
rec, upstream := serveMessagesScenario(t, preContentFailoverScenario{
|
||||
accounts: preContentAccounts(1),
|
||||
passthrough: newFailedFrameCodeRule("rate_limit_exceeded"),
|
||||
respond: func(call int) (*http.Response, error) {
|
||||
return preContentSSEResponse(io.NopCloser(strings.NewReader(preContentRateLimitFailed))), nil
|
||||
},
|
||||
})
|
||||
|
||||
require.Equal(t, 1, upstream.calls())
|
||||
requireFailedFrameRuleJSON(t, rec)
|
||||
}
|
||||
|
||||
func TestOpenAIMessagesNonStreamFailedFrameExhaustedAppliesRule(t *testing.T) {
|
||||
rec, upstream := serveMessagesScenario(t, preContentFailoverScenario{
|
||||
accounts: preContentAccounts(1),
|
||||
passthrough: newFailedFrameCodeRule("rate_limit_exceeded"),
|
||||
requestBody: `{"model":"gpt-5.4","max_tokens":32,"messages":[{"role":"user","content":"hello"}],"stream":false}`,
|
||||
respond: func(call int) (*http.Response, error) {
|
||||
return preContentSSEResponse(io.NopCloser(strings.NewReader(preContentHandlerCreated + preContentRateLimitFailed))), nil
|
||||
},
|
||||
})
|
||||
|
||||
require.Equal(t, 1, upstream.calls())
|
||||
requireFailedFrameRuleJSON(t, rec)
|
||||
}
|
||||
|
||||
// A failover triggered by an HTTP status keeps the built-in exhaustion mapping:
|
||||
// no passthrough rule is looked up for it.
|
||||
func TestOpenAIMessagesHTTPStatusFailoverExhaustedIgnoresPassthroughRule(t *testing.T) {
|
||||
rec, upstream := serveMessagesScenario(t, preContentFailoverScenario{
|
||||
accounts: preContentAccounts(1),
|
||||
passthrough: newFailedFrameCodeRule("rate_limit_exceeded"),
|
||||
respond: func(call int) (*http.Response, error) {
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusBadGateway,
|
||||
Header: http.Header{"Content-Type": []string{"application/json"}},
|
||||
Body: io.NopCloser(strings.NewReader(`{"error":{"code":"rate_limit_exceeded","message":"Rate limit reached for gpt-5.4"}}`)),
|
||||
}, nil
|
||||
},
|
||||
})
|
||||
|
||||
body := rec.Body.String()
|
||||
t.Logf("status=%d body=%q", rec.Code, body)
|
||||
require.Equal(t, 1, upstream.calls(), "body: %q", body)
|
||||
require.NotEqual(t, http.StatusTeapot, rec.Code, "body: %q", body)
|
||||
require.Equal(t, "Upstream service temporarily unavailable", gjson.Get(body, "error.message").String(), "body: %q", body)
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
//go:build unit
|
||||
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"testing/iotest"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/tlsfingerprint"
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
type nativeEndpointUpstream struct {
|
||||
service.HTTPUpstream
|
||||
mode string
|
||||
paths []string
|
||||
}
|
||||
|
||||
func (u *nativeEndpointUpstream) Do(req *http.Request, _ string, _ int64, _ int) (*http.Response, error) {
|
||||
u.paths = append(u.paths, req.URL.Path)
|
||||
if u.mode == "transport error" {
|
||||
return nil, errors.New("synthetic upstream transport failure")
|
||||
}
|
||||
body, err := io.ReadAll(req.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
response := &http.Response{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"application/json"}}}
|
||||
switch u.mode {
|
||||
case "HTTP error":
|
||||
response.StatusCode = http.StatusBadRequest
|
||||
response.Body = io.NopCloser(strings.NewReader(`{"error":{"type":"invalid_request_error","message":"synthetic rejection"}}`))
|
||||
case "body read error":
|
||||
response.Body = io.NopCloser(iotest.ErrReader(errors.New("synthetic body read failure")))
|
||||
default:
|
||||
if gjson.GetBytes(body, "stream").Bool() {
|
||||
response.Header.Set("Content-Type", "text/event-stream")
|
||||
response.Body = io.NopCloser(strings.NewReader(compatStreamUsagePartialStream + compatStreamUsageCompletion))
|
||||
} else {
|
||||
response.Body = io.NopCloser(strings.NewReader(`{"id":"msg_1","type":"message","role":"assistant","model":"k3","content":[{"type":"text","text":"partial"}],"stop_reason":"end_turn","usage":{"input_tokens":12,"output_tokens":7}}`))
|
||||
}
|
||||
}
|
||||
return response, nil
|
||||
}
|
||||
|
||||
func (u *nativeEndpointUpstream) DoWithTLS(req *http.Request, proxy string, accountID int64, concurrency int, _ *tlsfingerprint.Profile) (*http.Response, error) {
|
||||
return u.Do(req, proxy, accountID, concurrency)
|
||||
}
|
||||
|
||||
func TestOpenAINativeAnthropicEndpointDiagnostics(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
for _, route := range []struct {
|
||||
name string
|
||||
path string
|
||||
protocol string
|
||||
platform string
|
||||
}{
|
||||
{"messages", "/v1/messages", service.APIProtocolAnthropic, service.PlatformKimi},
|
||||
{"chat", "/v1/chat/completions", service.APIProtocolAnthropic, service.PlatformKimi},
|
||||
{"responses", "/v1/responses", service.APIProtocolAnthropic, service.PlatformKimi},
|
||||
{"adaptive messages", "/v1/messages", service.APIProtocolAdaptive, service.PlatformZhipu},
|
||||
} {
|
||||
for _, stream := range []bool{false, true} {
|
||||
for _, mode := range []string{"transport error", "HTTP error", "body read error", "success"} {
|
||||
t.Run(fmt.Sprintf("%s/stream=%t/%s", route.name, stream, mode), func(t *testing.T) {
|
||||
upstream := &nativeEndpointUpstream{mode: mode}
|
||||
cfg := &config.Config{Security: config.SecurityConfig{URLAllowlist: config.URLAllowlistConfig{AllowInsecureHTTP: true}}}
|
||||
gateway := service.NewOpenAIGatewayService(
|
||||
nil, nil, nil, nil, nil, nil, nil, cfg, nil, nil, nil, nil, nil, upstream,
|
||||
nil, nil, nil, nil, nil, nil, nil, nil,
|
||||
)
|
||||
account := &service.Account{
|
||||
ID: 9501, Platform: route.platform, Type: service.AccountTypeAPIKey,
|
||||
Credentials: map[string]any{
|
||||
"api_key": "test-key", "api_protocol": route.protocol,
|
||||
"base_url": "http://anthropic.example",
|
||||
"api_base_urls": map[string]any{
|
||||
service.APIProtocolAnthropic: "http://anthropic.example",
|
||||
service.APIProtocolChatCompletions: "http://chat.example",
|
||||
},
|
||||
},
|
||||
}
|
||||
model := "k3"
|
||||
if route.protocol == service.APIProtocolAdaptive {
|
||||
require.False(t, account.SupportsNativeCNResponses())
|
||||
model = "glm-5.3"
|
||||
}
|
||||
request := map[string]any{"model": model, "stream": stream}
|
||||
if route.path == "/v1/responses" {
|
||||
request["input"] = "hello"
|
||||
} else {
|
||||
request["messages"] = []map[string]string{{"role": "user", "content": "hello"}}
|
||||
request["max_tokens"] = 32
|
||||
}
|
||||
body, err := json.Marshal(request)
|
||||
require.NoError(t, err)
|
||||
recorder := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(recorder)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, route.path, strings.NewReader(string(body)))
|
||||
// The same Gin context can retain an earlier attempt's protocol.
|
||||
service.SetActualOpenAIUpstreamEndpoint(c, EndpointChatCompletions)
|
||||
var result *service.OpenAIForwardResult
|
||||
switch route.path {
|
||||
case "/v1/messages":
|
||||
result, err = gateway.ForwardAsAnthropic(context.Background(), c, account, body, "", "")
|
||||
case "/v1/chat/completions":
|
||||
result, err = gateway.ForwardAsChatCompletions(context.Background(), c, account, body, "", "")
|
||||
default:
|
||||
result, err = gateway.Forward(context.Background(), c, account, body)
|
||||
}
|
||||
if mode == "success" {
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, result)
|
||||
require.Equal(t, EndpointMessages, result.UpstreamEndpoint)
|
||||
require.Contains(t, recorder.Body.String(), "partial")
|
||||
} else {
|
||||
require.Error(t, err)
|
||||
if mode != "body read error" {
|
||||
require.Nil(t, result, "error diagnostics must work without a forward result")
|
||||
}
|
||||
}
|
||||
require.Len(t, upstream.paths, 1)
|
||||
require.True(t, strings.HasSuffix(upstream.paths[0], EndpointMessages), "the request actually used native Anthropic: %v", upstream.paths)
|
||||
// This is the endpoint reader used when writing operations errors and result-less usage.
|
||||
require.Equal(t, EndpointMessages, GetUpstreamEndpoint(c, account.Platform))
|
||||
require.Equal(t, EndpointMessages, service.GetActualOpenAIUpstreamEndpoint(c))
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -11,10 +11,10 @@ import (
|
||||
|
||||
var codexSelectedPageName = regexp.MustCompile(`^codex_apps_selected_page_part_([1-9][0-9]*)_of_([1-9][0-9]*)$`)
|
||||
|
||||
// Desktop injects page snapshots as standalone outputs, without a model tool call.
|
||||
// Keep them as untrusted user text, including on history replay and mixed bootstrap turns.
|
||||
func normalizeCodexPageContext(body []byte) ([]byte, bool) {
|
||||
if !mayContainCodexCallOutputCandidate(body, "codex_apps_open_page", "codex_apps_selected_page_part_") || !hasUniqueJSONMembers(body) {
|
||||
// Codex injects external context as standalone outputs, without a model tool call.
|
||||
// Use the legacy user-message representation for HTTP Responses interoperability.
|
||||
func normalizeCodexUntrustedContext(body []byte) ([]byte, bool) {
|
||||
if !mayContainCodexCallOutputCandidate(body, "codex_apps_open_page", "codex_apps_selected_page_part_", "browser_info", "goal_objective", "untrusted_context") || !hasUniqueJSONMembers(body) {
|
||||
return body, false
|
||||
}
|
||||
var request map[string]json.RawMessage
|
||||
@@ -46,15 +46,19 @@ func normalizeCodexPageContext(body []byte) ([]byte, bool) {
|
||||
}
|
||||
}
|
||||
name, output := readString("name"), readString("output")
|
||||
if !validCodexPageContext(name, output) {
|
||||
if !validCodexUntrustedContext(name, output) {
|
||||
continue
|
||||
}
|
||||
text := "<external_" + name + ">" + output + "</external_" + name + ">"
|
||||
if validCodexPageContext(name, output) {
|
||||
text = "<external_" + name + ">\n" + output + "\n</external_" + name + ">"
|
||||
}
|
||||
message := map[string]any{
|
||||
"type": "message",
|
||||
"role": "user",
|
||||
"content": []map[string]string{{
|
||||
"type": "input_text",
|
||||
"text": "<external_" + name + ">\n" + output + "\n</external_" + name + ">",
|
||||
"text": text,
|
||||
}},
|
||||
}
|
||||
encoded, err := json.Marshal(message)
|
||||
@@ -79,6 +83,15 @@ func normalizeCodexPageContext(body []byte) ([]byte, bool) {
|
||||
return encoded, true
|
||||
}
|
||||
|
||||
func validCodexUntrustedContext(name, output string) bool {
|
||||
switch name {
|
||||
case "browser_info", "goal_objective", "untrusted_context":
|
||||
return strings.TrimSpace(output) != ""
|
||||
default:
|
||||
return validCodexPageContext(name, output)
|
||||
}
|
||||
}
|
||||
|
||||
func validCodexPageContext(name, output string) bool {
|
||||
if name == "codex_apps_open_page" {
|
||||
return validCodexPageSnapshot(output)
|
||||
|
||||
@@ -34,7 +34,7 @@ func TestNormalizeCodexPageContextFirstMessage(t *testing.T) {
|
||||
require.Equal(t, 400, w.Code)
|
||||
require.Contains(t, w.Body.String(), "function_call_output requires call_id")
|
||||
|
||||
got, changed := normalizeCodexPageContext(body)
|
||||
got, changed := normalizeCodexUntrustedContext(body)
|
||||
require.True(t, changed)
|
||||
w = httptest.NewRecorder()
|
||||
c, _ = gin.CreateTestContext(w)
|
||||
@@ -49,14 +49,130 @@ func TestNormalizeCodexPageContextFirstMessage(t *testing.T) {
|
||||
require.False(t, item.Get("id").Exists())
|
||||
}
|
||||
require.Equal(t, "hello", gjson.GetBytes(got, "input.2.content").String())
|
||||
again, changed := normalizeCodexPageContext(got)
|
||||
again, changed := normalizeCodexUntrustedContext(got)
|
||||
require.False(t, changed)
|
||||
require.Equal(t, got, again)
|
||||
}
|
||||
|
||||
func TestNormalizeCodexAdditionalUntrustedContext(t *testing.T) {
|
||||
// AdditionalContextToolOutput derives names from caller-provided context keys.
|
||||
// Codex 0.169.0 enables this representation by default (openai/codex#60487).
|
||||
for _, name := range []string{"browser_info", "goal_objective", "untrusted_context"} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
output := "external context\nline two"
|
||||
body := pageContextRequest(t, pageContextItem(name, output),
|
||||
map[string]any{"role": "user", "content": "continue"})
|
||||
h := &OpenAIGatewayHandler{}
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
require.False(t, h.validateFunctionCallOutputRequest(c, body, zap.NewNop()))
|
||||
|
||||
got, changed := normalizeCodexUntrustedContext(body)
|
||||
require.True(t, changed)
|
||||
w = httptest.NewRecorder()
|
||||
c, _ = gin.CreateTestContext(w)
|
||||
require.True(t, h.validateFunctionCallOutputRequest(c, got, zap.NewNop()))
|
||||
require.False(t, c.Writer.Written())
|
||||
item := gjson.GetBytes(got, "input.0")
|
||||
require.Equal(t, "message", item.Get("type").String())
|
||||
require.Equal(t, "user", item.Get("role").String())
|
||||
require.Equal(t, "<external_"+name+">"+output+"</external_"+name+">", item.Get("content.0.text").String())
|
||||
require.False(t, item.Get("call_id").Exists())
|
||||
require.Equal(t, "continue", gjson.GetBytes(got, "input.1.content").String())
|
||||
again, changed := normalizeCodexUntrustedContext(got)
|
||||
require.False(t, changed)
|
||||
require.Equal(t, got, again)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeCodexAdditionalUntrustedContextPreservesRealAndMalformedOutputs(t *testing.T) {
|
||||
for _, name := range []string{"browser_info", "goal_objective", "untrusted_context"} {
|
||||
for _, override := range []map[string]any{
|
||||
{"call_id": "call_real"},
|
||||
{"call_id": nil},
|
||||
{"call_id": 42},
|
||||
{"namespace": "other"},
|
||||
{"namespace": nil},
|
||||
{"namespace": 42},
|
||||
{"output": []any{map[string]any{"type": "encrypted_content", "encrypted_content": "sealed"}}},
|
||||
{"output": " "},
|
||||
{"output": nil},
|
||||
} {
|
||||
item := pageContextItem(name, "context")
|
||||
for key, value := range override {
|
||||
item[key] = value
|
||||
}
|
||||
body := pageContextRequest(t, item)
|
||||
got, changed := normalizeCodexUntrustedContext(body)
|
||||
require.False(t, changed, "name=%s override=%v", name, override)
|
||||
require.Equal(t, body, got)
|
||||
}
|
||||
item := pageContextItem(name, "context")
|
||||
delete(item, "namespace")
|
||||
body := pageContextRequest(t, item)
|
||||
got, changed := normalizeCodexUntrustedContext(body)
|
||||
require.False(t, changed)
|
||||
require.Equal(t, body, got)
|
||||
}
|
||||
// Recognized external context cannot make an unrelated tool result valid.
|
||||
body := pageContextRequest(t, pageContextItem("browser_info", "tab"),
|
||||
pageContextItem("read_file", "result"))
|
||||
got, changed := normalizeCodexUntrustedContext(body)
|
||||
require.True(t, changed)
|
||||
h := &OpenAIGatewayHandler{}
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
require.False(t, h.validateFunctionCallOutputRequest(c, got, zap.NewNop()))
|
||||
require.Equal(t, 400, w.Code)
|
||||
|
||||
// Keep historical calls, prior response and exact numeric metadata intact.
|
||||
body = []byte(`{"model":"gpt-5","previous_response_id":"resp_history","metadata":{"large":9007199254740993},"input":[{"type":"function_call","name":"read_file","call_id":"call_real","arguments":"{}"},{"type":"function_call_output","call_id":"call_real","output":"result"},{"type":"function_call_output","namespace":"agent","name":"goal_objective","output":"finish"}]}`)
|
||||
got, changed = normalizeCodexUntrustedContext(body)
|
||||
require.True(t, changed)
|
||||
require.Equal(t, "resp_history", gjson.GetBytes(got, "previous_response_id").String())
|
||||
require.Equal(t, "9007199254740993", gjson.GetBytes(got, "metadata.large").Raw)
|
||||
for _, index := range []string{"input.0", "input.1"} {
|
||||
require.JSONEq(t, gjson.GetBytes(body, index).Raw, gjson.GetBytes(got, index).Raw)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeCodexAdditionalUntrustedContextBlankCallIDsAndMixedInput(t *testing.T) {
|
||||
names := []string{"browser_info", "goal_objective", "untrusted_context"}
|
||||
for _, callID := range []string{"", " \t\n"} {
|
||||
items := make([]any, 0, len(names))
|
||||
for _, name := range names {
|
||||
item := pageContextItem(name, "context for "+name)
|
||||
item["call_id"] = callID
|
||||
delete(item, "id")
|
||||
items = append(items, item)
|
||||
}
|
||||
got, changed := normalizeCodexUntrustedContext(pageContextRequest(t, items...))
|
||||
require.True(t, changed)
|
||||
require.Len(t, gjson.GetBytes(got, "input").Array(), len(names))
|
||||
for i, item := range gjson.GetBytes(got, "input").Array() {
|
||||
require.Equal(t, "user", item.Get("role").String())
|
||||
require.Equal(t, "<external_"+names[i]+">context for "+names[i]+"</external_"+names[i]+">", item.Get("content.0.text").String())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeCodexAdditionalUntrustedContextRejectsDuplicateMembers(t *testing.T) {
|
||||
for _, name := range []string{"browser_info", "goal_objective", "untrusted_context"} {
|
||||
for _, body := range []string{
|
||||
`{"input":[{"type":"function_call_output","namespace":"agent","name":"` + name + `","call_id":"real","call_id":"","output":"context"}]}`,
|
||||
`{"input":[{"type":"function_call_output","namespace":"agent","name":"` + name + `","output":"first","output":"second"}]}`,
|
||||
} {
|
||||
got, changed := normalizeCodexUntrustedContext([]byte(body))
|
||||
require.False(t, changed)
|
||||
require.Equal(t, body, string(got))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeCodexPageContextPreservesHistoryAndToolValidation(t *testing.T) {
|
||||
body := []byte(`{"model":"gpt-5","previous_response_id":"resp_history","metadata":{"large":9007199254740993},"input":[{"type":"function_call","name":"read_file","call_id":"call_real","arguments":"{}"},{"type":"function_call_output","call_id":"call_real","output":"result"},{"type":"function_call_output","namespace":"agent","name":"codex_apps_open_page","output":"{\"page_id\":\"page_1\"}"}]}`)
|
||||
got, changed := normalizeCodexPageContext(body)
|
||||
got, changed := normalizeCodexUntrustedContext(body)
|
||||
require.True(t, changed)
|
||||
require.Equal(t, "resp_history", gjson.GetBytes(got, "previous_response_id").String())
|
||||
require.Equal(t, "9007199254740993", gjson.GetBytes(got, "metadata.large").Raw)
|
||||
@@ -66,7 +182,7 @@ func TestNormalizeCodexPageContextPreservesHistoryAndToolValidation(t *testing.T
|
||||
|
||||
badTool := pageContextItem("read_file", "result")
|
||||
body = pageContextRequest(t, pageContextItem("codex_apps_open_page", `{"page_id":null}`), badTool)
|
||||
got, changed = normalizeCodexPageContext(body)
|
||||
got, changed = normalizeCodexUntrustedContext(body)
|
||||
require.True(t, changed)
|
||||
require.True(t, service.ValidateFunctionCallOutputContextBytes(got).HasFunctionCallOutputMissingCallID)
|
||||
}
|
||||
@@ -77,7 +193,7 @@ func TestNormalizeCodexPageContextMixedBootstrap(t *testing.T) {
|
||||
{"type": "function_call_output", "namespace": "codex_app", "name": "automation_update", "output": "<heartbeat><automation_id>test</automation_id></heartbeat>"},
|
||||
} {
|
||||
body := pageContextRequest(t, pageContextItem("codex_apps_open_page", `{"page_id":null}`), item)
|
||||
got, changed := normalizeCodexPageContext(body)
|
||||
got, changed := normalizeCodexUntrustedContext(body)
|
||||
require.True(t, changed)
|
||||
got, _ = normalizeCodexAutomationBootstrap(got)
|
||||
got, _ = normalizeCodexDelegationBootstrap(got)
|
||||
@@ -89,7 +205,7 @@ func TestNormalizeCodexPageContextMultipart(t *testing.T) {
|
||||
first := "Companion Page snapshot part 1 of 2:\n" + `{"page_id":"page1","document_view":"hello`
|
||||
second := "Companion Page snapshot part 2 of 2:\n" + ` world"}`
|
||||
body := pageContextRequest(t, pageContextItem("codex_apps_selected_page_part_1_of_2", first), pageContextItem("codex_apps_selected_page_part_2_of_2", second))
|
||||
got, changed := normalizeCodexPageContext(body)
|
||||
got, changed := normalizeCodexUntrustedContext(body)
|
||||
require.True(t, changed)
|
||||
require.Contains(t, gjson.GetBytes(got, "input.0.content.0.text").String(), first)
|
||||
require.Contains(t, gjson.GetBytes(got, "input.1.content.0.text").String(), second)
|
||||
@@ -119,7 +235,7 @@ func TestNormalizeCodexPageContextRejectsUnrelatedOrMalformedItems(t *testing.T)
|
||||
item := pageContextItem("codex_apps_open_page", `{"page_id":null}`)
|
||||
item[tc.key] = tc.value
|
||||
body := pageContextRequest(t, item)
|
||||
got, changed := normalizeCodexPageContext(body)
|
||||
got, changed := normalizeCodexUntrustedContext(body)
|
||||
require.False(t, changed)
|
||||
require.Equal(t, body, got)
|
||||
})
|
||||
@@ -128,7 +244,7 @@ func TestNormalizeCodexPageContextRejectsUnrelatedOrMalformedItems(t *testing.T)
|
||||
`{"input":[{"type":"function_call_output","namespace":"agent","name":"codex_apps_open_page","call_id":"real","call_id":"","output":"{\"page_id\":null}"}]}`,
|
||||
`{"input":[{"type":"function_call_output","namespace":"agent","name":"codex_apps_open_page","output":"{\"page_id\":null}"}]} trailing`,
|
||||
} {
|
||||
got, changed := normalizeCodexPageContext([]byte(body))
|
||||
got, changed := normalizeCodexUntrustedContext([]byte(body))
|
||||
require.False(t, changed)
|
||||
require.Equal(t, body, string(got))
|
||||
}
|
||||
|
||||
@@ -417,6 +417,9 @@ func (h *UsageHandler) Stats(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
stats.TotalAccountCost = nil
|
||||
for i := range stats.Endpoints {
|
||||
stats.Endpoints[i].AccountCost = 0
|
||||
}
|
||||
stats.UpstreamEndpoints = nil
|
||||
stats.EndpointPaths = nil
|
||||
|
||||
|
||||
@@ -27,7 +27,7 @@ func NewUserMsgQueueHelper(
|
||||
pingFormat SSEPingFormat,
|
||||
pingInterval time.Duration,
|
||||
) *UserMsgQueueHelper {
|
||||
if pingInterval <= 0 {
|
||||
if pingInterval < 0 {
|
||||
pingInterval = defaultPingInterval
|
||||
}
|
||||
return &UserMsgQueueHelper{
|
||||
@@ -86,7 +86,7 @@ func (h *UserMsgQueueHelper) waitForLockWithPing(
|
||||
streamStarted *bool,
|
||||
reqLog *zap.Logger,
|
||||
) (func(), error) {
|
||||
needPing := isStream && h.pingFormat != ""
|
||||
needPing := isStream && h.pingFormat != "" && h.pingInterval > 0
|
||||
|
||||
var flusher http.Flusher
|
||||
if needPing {
|
||||
@@ -196,7 +196,7 @@ func (h *UserMsgQueueHelper) ThrottleWithPing(
|
||||
)
|
||||
|
||||
// 延迟期间发送 SSE ping(复用 waitForLockWithPing 的 ping 逻辑)
|
||||
needPing := isStream && h.pingFormat != ""
|
||||
needPing := isStream && h.pingFormat != "" && h.pingInterval > 0
|
||||
var flusher http.Flusher
|
||||
if needPing {
|
||||
flusher, _ = c.Writer.(http.Flusher)
|
||||
|
||||
@@ -348,7 +348,7 @@ func (a *Alipay) Refund(ctx context.Context, req payment.RefundRequest) (*paymen
|
||||
return nil, err
|
||||
}
|
||||
|
||||
outRequestNo := fmt.Sprintf("%s%s%d", req.OrderID, alipayRefundRequestSep, time.Now().UnixNano())
|
||||
outRequestNo := fmt.Sprintf("%s%s%s", req.OrderID, alipayRefundRequestSep, alipayRefundRequestNoSuffix(req.Amount))
|
||||
result, err := alipayTradeRefund(ctx, client, alipay.TradeRefund{
|
||||
OutTradeNo: req.OrderID,
|
||||
RefundAmount: req.Amount,
|
||||
@@ -374,6 +374,18 @@ func (a *Alipay) Refund(ctx context.Context, req payment.RefundRequest) (*paymen
|
||||
}, nil
|
||||
}
|
||||
|
||||
// alipayRefundRequestNoSuffix 生成跨重试稳定的 out_request_no 后缀。
|
||||
// 支付宝把相同的 out_request_no 视为同一次退款请求;如果重试换号,
|
||||
// "网关已受理但返回错误"后的重试会变成第二笔真实退款。
|
||||
// 与 wxpayRefundID 一致,用金额区分同一订单的不同退款金额。
|
||||
func alipayRefundRequestNoSuffix(amount string) string {
|
||||
normalized := strings.NewReplacer(".", "", "-", "").Replace(strings.TrimSpace(amount))
|
||||
if normalized == "" {
|
||||
return "0"
|
||||
}
|
||||
return normalized
|
||||
}
|
||||
|
||||
// QueryRefund 通过 alipay.trade.fastpay.refund.query 查询退款终态。refund_status 为 REFUND_SUCCESS
|
||||
// 表示成功;退款发起超过宽限期仍查不到记录表示支付宝未受理或退款失败;其余情况视为仍在处理中。
|
||||
func (a *Alipay) QueryRefund(ctx context.Context, req payment.RefundQueryRequest) (*payment.RefundResponse, error) {
|
||||
|
||||
@@ -480,6 +480,67 @@ func TestAlipayRefundRecordsOutRequestNoAsRefundID(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// out_request_no 必须跨重试稳定:支付宝把相同的 out_request_no 视为同一次退款请求。
|
||||
// 如果重试生成新的请求号,一次"网关已受理但返回错误"的重试会退两次。
|
||||
func TestAlipayRefundOutRequestNoIsStableAcrossRetries(t *testing.T) {
|
||||
origRefund := alipayTradeRefund
|
||||
t.Cleanup(func() { alipayTradeRefund = origRefund })
|
||||
|
||||
var outRequestNos []string
|
||||
alipayTradeRefund = func(_ context.Context, _ *alipay.Client, param alipay.TradeRefund) (*alipay.TradeRefundRsp, error) {
|
||||
outRequestNos = append(outRequestNos, param.OutRequestNo)
|
||||
return &alipay.TradeRefundRsp{TradeNo: "2026101522001", FundChange: alipayFundChangeYes}, nil
|
||||
}
|
||||
|
||||
provider := &Alipay{client: &alipay.Client{}}
|
||||
req := payment.RefundRequest{OrderID: "sub2_7", Amount: "12.50", Reason: "r"}
|
||||
for i := 0; i < 2; i++ {
|
||||
if _, err := provider.Refund(context.Background(), req); err != nil {
|
||||
t.Fatalf("Refund() error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
if len(outRequestNos) != 2 {
|
||||
t.Fatalf("got %d refund calls, want 2", len(outRequestNos))
|
||||
}
|
||||
if outRequestNos[0] != "sub2_7-refund-1250" {
|
||||
t.Fatalf("out_request_no = %q, want sub2_7-refund-1250", outRequestNos[0])
|
||||
}
|
||||
if outRequestNos[0] != outRequestNos[1] {
|
||||
t.Fatalf("out_request_no changed across retries: %q != %q", outRequestNos[0], outRequestNos[1])
|
||||
}
|
||||
}
|
||||
|
||||
// 模拟支付宝的幂等语义:相同的 out_request_no 只产生一笔真实退款。
|
||||
// 重试时如果请求号变了,钱会被退两次;稳定请求号下只退一次。
|
||||
func TestAlipayRefundRetryDoesNotDoubleRefund(t *testing.T) {
|
||||
origRefund := alipayTradeRefund
|
||||
t.Cleanup(func() { alipayTradeRefund = origRefund })
|
||||
|
||||
const refundCents = 1250
|
||||
refundedCents := 0
|
||||
seen := make(map[string]struct{})
|
||||
alipayTradeRefund = func(_ context.Context, _ *alipay.Client, param alipay.TradeRefund) (*alipay.TradeRefundRsp, error) {
|
||||
if _, ok := seen[param.OutRequestNo]; !ok {
|
||||
seen[param.OutRequestNo] = struct{}{}
|
||||
refundedCents += refundCents
|
||||
}
|
||||
return &alipay.TradeRefundRsp{TradeNo: "2026101522001", FundChange: alipayFundChangeYes}, nil
|
||||
}
|
||||
|
||||
provider := &Alipay{client: &alipay.Client{}}
|
||||
req := payment.RefundRequest{OrderID: "sub2_7", Amount: "12.50", Reason: "r"}
|
||||
for i := 0; i < 2; i++ {
|
||||
if _, err := provider.Refund(context.Background(), req); err != nil {
|
||||
t.Fatalf("Refund() error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
if refundedCents != refundCents {
|
||||
t.Fatalf("retry refunded %d cents, want %d (one refund only)", refundedCents, refundCents)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAlipayQueryRefundMapsStatus(t *testing.T) {
|
||||
origQuery := alipayTradeFastPayRefundQuery
|
||||
t.Cleanup(func() { alipayTradeFastPayRefundQuery = origQuery })
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
package antigravity
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestCarbonGenerationThinkingLevels(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name, body, level string
|
||||
thoughts bool
|
||||
}{
|
||||
{"default", `{}`, "", false},
|
||||
{"low", `{"output_config":{"effort":"low"}}`, "low", false},
|
||||
{"medium", `{"output_config":{"effort":"medium"}}`, "medium", false},
|
||||
{"high", `{"output_config":{"effort":"high"}}`, "high", false},
|
||||
{"disabled wins", `{"thinking":{"type":"disabled"},"output_config":{"effort":"high"}}`, "low", false},
|
||||
{"low budget", `{"thinking":{"type":"enabled","budget_tokens":1024}}`, "low", true},
|
||||
{"medium budget", `{"thinking":{"type":"enabled","budget_tokens":4096}}`, "medium", true},
|
||||
{"high budget", `{"thinking":{"type":"enabled","budget_tokens":32768}}`, "high", true},
|
||||
{"adaptive default", `{"thinking":{"type":"adaptive"}}`, "", true},
|
||||
{"effort wins", `{"thinking":{"type":"enabled","budget_tokens":32768},"output_config":{"effort":"medium"}}`, "medium", true},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
var req ClaudeRequest
|
||||
require.NoError(t, json.Unmarshal([]byte(tc.body), &req))
|
||||
req.Model = "gemini-4-carbon"
|
||||
req.MaxTokens = 1000
|
||||
config := buildGenerationConfig(&req)
|
||||
data, err := json.Marshal(config)
|
||||
require.NoError(t, err)
|
||||
require.NotContains(t, string(data), "thinkingBudget")
|
||||
require.Equal(t, 1000, config.MaxOutputTokens, "Carbon budgets must not raise output limits")
|
||||
if tc.level == "" && !tc.thoughts {
|
||||
require.Nil(t, config.ThinkingConfig)
|
||||
return
|
||||
}
|
||||
require.NotNil(t, config.ThinkingConfig)
|
||||
require.Equal(t, tc.level, config.ThinkingConfig.ThinkingLevel)
|
||||
require.Equal(t, tc.thoughts, config.ThinkingConfig.IncludeThoughts)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCarbonTierPreservesUpstreamSelection(t *testing.T) {
|
||||
for _, tier := range []string{"low", "medium", "high"} {
|
||||
cfg := buildGenerationConfig(&ClaudeRequest{Model: "gemini-4-carbon-" + tier, Thinking: &ThinkingConfig{Type: "enabled", BudgetTokens: 32768}, OutputConfig: &ClaudeOutputConfig{Effort: "low"}})
|
||||
require.NotNil(t, cfg.ThinkingConfig)
|
||||
require.True(t, cfg.ThinkingConfig.IncludeThoughts)
|
||||
require.Empty(t, cfg.ThinkingConfig.ThinkingLevel)
|
||||
require.Zero(t, cfg.ThinkingConfig.ThinkingBudget)
|
||||
}
|
||||
// Other models retain the existing budget behavior.
|
||||
cfg := buildGenerationConfig(&ClaudeRequest{Model: "claude-sonnet-4-6", Thinking: &ThinkingConfig{Type: "enabled", BudgetTokens: 4096}})
|
||||
require.Equal(t, 4096, cfg.ThinkingConfig.ThinkingBudget)
|
||||
require.Empty(t, cfg.ThinkingConfig.ThinkingLevel)
|
||||
}
|
||||
|
||||
func TestCarbonTransformUsesMappedModelForThinking(t *testing.T) {
|
||||
req := &ClaudeRequest{Model: "client-alias", MaxTokens: 4096, Messages: []ClaudeMessage{{Role: "user", Content: json.RawMessage(`"hello"`)}}, Thinking: &ThinkingConfig{Type: "enabled", BudgetTokens: 4096}}
|
||||
data, err := TransformClaudeToGeminiWithOptions(req, "project", "gemini-4-carbon", TransformOptions{})
|
||||
require.NoError(t, err)
|
||||
require.Contains(t, string(data), `"thinkingLevel":"medium"`)
|
||||
require.NotContains(t, string(data), `thinkingBudget`)
|
||||
require.NotContains(t, string(data), `stopSequences`)
|
||||
}
|
||||
@@ -9,17 +9,23 @@ import (
|
||||
|
||||
// ClaudeRequest Claude Messages API 请求
|
||||
type ClaudeRequest struct {
|
||||
Model string `json:"model"`
|
||||
Messages []ClaudeMessage `json:"messages"`
|
||||
MaxTokens int `json:"max_tokens,omitempty"`
|
||||
System json.RawMessage `json:"system,omitempty"` // string 或 []SystemBlock
|
||||
Stream bool `json:"stream,omitempty"`
|
||||
Temperature *float64 `json:"temperature,omitempty"`
|
||||
TopP *float64 `json:"top_p,omitempty"`
|
||||
TopK *int `json:"top_k,omitempty"`
|
||||
Tools []ClaudeTool `json:"tools,omitempty"`
|
||||
Thinking *ThinkingConfig `json:"thinking,omitempty"`
|
||||
Metadata *ClaudeMetadata `json:"metadata,omitempty"`
|
||||
Model string `json:"model"`
|
||||
Messages []ClaudeMessage `json:"messages"`
|
||||
MaxTokens int `json:"max_tokens,omitempty"`
|
||||
System json.RawMessage `json:"system,omitempty"` // string 或 []SystemBlock
|
||||
Stream bool `json:"stream,omitempty"`
|
||||
Temperature *float64 `json:"temperature,omitempty"`
|
||||
TopP *float64 `json:"top_p,omitempty"`
|
||||
TopK *int `json:"top_k,omitempty"`
|
||||
Tools []ClaudeTool `json:"tools,omitempty"`
|
||||
Thinking *ThinkingConfig `json:"thinking,omitempty"`
|
||||
Metadata *ClaudeMetadata `json:"metadata,omitempty"`
|
||||
OutputConfig *ClaudeOutputConfig `json:"output_config,omitempty"`
|
||||
}
|
||||
|
||||
// ClaudeOutputConfig carries the requested reasoning effort.
|
||||
type ClaudeOutputConfig struct {
|
||||
Effort string `json:"effort,omitempty"`
|
||||
}
|
||||
|
||||
// ClaudeMessage Claude 消息
|
||||
@@ -214,6 +220,7 @@ var geminiModels = []modelDef{
|
||||
{ID: "gemini-3.8-flash-low", DisplayName: "Gemini 3.8 Flash Low", CreatedAt: "2026-09-02T00:00:00Z", IsReasoning: true},
|
||||
{ID: "gemini-3.8-flash-medium", DisplayName: "Gemini 3.8 Flash Medium", CreatedAt: "2026-09-02T00:00:00Z", IsReasoning: true},
|
||||
{ID: "gemini-3.8-flash-tiered", DisplayName: "Gemini 3.8 Flash", CreatedAt: "2026-09-02T00:00:00Z", IsReasoning: true},
|
||||
{ID: "gemini-4-carbon", DisplayName: "Gemini 4 Carbon", CreatedAt: "2026-11-10T00:00:00Z", IsReasoning: true},
|
||||
{ID: "gemini-4-argon-high", DisplayName: "Gemini 4 Argon (High)", CreatedAt: "2026-10-13T00:00:00Z", IsReasoning: true},
|
||||
{ID: "gemini-4-argon-low", DisplayName: "Gemini 4 Argon (Low)", CreatedAt: "2026-10-13T00:00:00Z", IsReasoning: true},
|
||||
{ID: "gemini-4-argon-medium", DisplayName: "Gemini 4 Argon (Medium)", CreatedAt: "2026-10-13T00:00:00Z", IsReasoning: true},
|
||||
|
||||
@@ -15,6 +15,7 @@ func TestDefaultModels_ContainsNewAndLegacyImageModels(t *testing.T) {
|
||||
}
|
||||
|
||||
requiredIDs := []string{
|
||||
"gemini-4-carbon",
|
||||
"claude-fable-5-1",
|
||||
"claude-fable-5",
|
||||
"claude-opus-4-8",
|
||||
@@ -80,6 +81,9 @@ func TestClaudeContentItem_ThinkingAlwaysHasSignature(t *testing.T) {
|
||||
func TestIsGeminiReasoningModel_IncludesProAgent(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
if !IsGeminiReasoningModel("gemini-4-carbon") {
|
||||
t.Fatal("expected Carbon to be recognized as a Gemini reasoning model")
|
||||
}
|
||||
if !IsGeminiReasoningModel("gemini-pro-agent") {
|
||||
t.Fatal("expected gemini-pro-agent to be recognized as a Gemini reasoning model")
|
||||
}
|
||||
|
||||
@@ -84,8 +84,9 @@ type GeminiImageConfig struct {
|
||||
|
||||
// GeminiThinkingConfig Gemini thinking 配置
|
||||
type GeminiThinkingConfig struct {
|
||||
IncludeThoughts bool `json:"includeThoughts"`
|
||||
ThinkingBudget int `json:"thinkingBudget,omitempty"`
|
||||
IncludeThoughts bool `json:"includeThoughts"`
|
||||
ThinkingBudget int `json:"thinkingBudget,omitempty"`
|
||||
ThinkingLevel string `json:"thinkingLevel,omitempty"`
|
||||
}
|
||||
|
||||
// GeminiToolDeclaration Gemini 工具声明
|
||||
|
||||
@@ -696,6 +696,45 @@ func isAntigravityOpusHighTierModel(model string) bool {
|
||||
strings.HasPrefix(lower, "claude-opus-4-8")
|
||||
}
|
||||
|
||||
// carbonThinkingConfig preserves the upstream default when no effort is specified.
|
||||
// https://aistudio.google.com/docs/whats-new-gemini-4-carbon
|
||||
func carbonThinkingConfig(req *ClaudeRequest, bareModel bool) *GeminiThinkingConfig {
|
||||
cfg := &GeminiThinkingConfig{}
|
||||
if req.Thinking != nil {
|
||||
cfg.IncludeThoughts = req.Thinking.Type == "enabled" || req.Thinking.Type == "adaptive"
|
||||
}
|
||||
if bareModel {
|
||||
if req.OutputConfig != nil {
|
||||
switch strings.ToLower(strings.TrimSpace(req.OutputConfig.Effort)) {
|
||||
case "none", "minimal", "low":
|
||||
cfg.ThinkingLevel = "low"
|
||||
case "medium":
|
||||
cfg.ThinkingLevel = "medium"
|
||||
case "high", "xhigh", "max":
|
||||
cfg.ThinkingLevel = "high"
|
||||
}
|
||||
}
|
||||
if req.Thinking != nil {
|
||||
if req.Thinking.Type == "disabled" {
|
||||
cfg.ThinkingLevel = "low"
|
||||
} else if cfg.ThinkingLevel == "" && req.Thinking.Type == "enabled" && req.Thinking.BudgetTokens > 0 {
|
||||
switch {
|
||||
case req.Thinking.BudgetTokens <= 1024:
|
||||
cfg.ThinkingLevel = "low"
|
||||
case req.Thinking.BudgetTokens <= 8192:
|
||||
cfg.ThinkingLevel = "medium"
|
||||
default:
|
||||
cfg.ThinkingLevel = "high"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if !cfg.IncludeThoughts && cfg.ThinkingLevel == "" {
|
||||
return nil
|
||||
}
|
||||
return cfg
|
||||
}
|
||||
|
||||
func buildGenerationConfig(req *ClaudeRequest) *GeminiGenerationConfig {
|
||||
maxLimit := maxOutputTokensLimit(req.Model)
|
||||
config := &GeminiGenerationConfig{
|
||||
@@ -712,8 +751,16 @@ func buildGenerationConfig(req *ClaudeRequest) *GeminiGenerationConfig {
|
||||
config.MaxOutputTokens = req.MaxTokens
|
||||
}
|
||||
|
||||
// Carbon accepts thinking levels rather than token budgets. Tiered IDs, when
|
||||
// supplied by the account catalog, already select the level upstream.
|
||||
carbonModel := strings.TrimPrefix(strings.ToLower(strings.TrimSpace(req.Model)), "models/")
|
||||
isCarbon := carbonModel == "gemini-4-carbon" || carbonModel == "gemini-4-carbon-low" || carbonModel == "gemini-4-carbon-medium" || carbonModel == "gemini-4-carbon-high"
|
||||
if isCarbon {
|
||||
config.ThinkingConfig = carbonThinkingConfig(req, carbonModel == "gemini-4-carbon")
|
||||
}
|
||||
|
||||
// Thinking 配置
|
||||
if req.Thinking != nil && (req.Thinking.Type == "enabled" || req.Thinking.Type == "adaptive") {
|
||||
if !isCarbon && req.Thinking != nil && (req.Thinking.Type == "enabled" || req.Thinking.Type == "adaptive") {
|
||||
config.ThinkingConfig = &GeminiThinkingConfig{
|
||||
IncludeThoughts: true,
|
||||
}
|
||||
|
||||
@@ -376,24 +376,15 @@ func cleanJSONSchemaRecursive(value any) any {
|
||||
}
|
||||
}
|
||||
|
||||
// 8. [SAFETY] 处理缺失 items 的 Array (Gemini 严苛要求 array 必须声明 items Schema)
|
||||
// 8. Gemini 只允许 array 携带 items,且 items 必须是非空 Schema 对象。
|
||||
if t, _ := schemaMap["type"].(string); t == "array" {
|
||||
itemsVal, hasItems := schemaMap["items"]
|
||||
needDefaultItems := false
|
||||
if !hasItems || itemsVal == nil {
|
||||
needDefaultItems = true
|
||||
} else if itemsMap, ok := itemsVal.(map[string]any); ok {
|
||||
if len(itemsMap) == 0 {
|
||||
needDefaultItems = true
|
||||
}
|
||||
} else if _, isBool := itemsVal.(bool); isBool {
|
||||
needDefaultItems = true
|
||||
}
|
||||
if needDefaultItems {
|
||||
if items, ok := schemaMap["items"].(map[string]any); !ok || len(items) == 0 {
|
||||
schemaMap["items"] = map[string]any{
|
||||
"type": "string",
|
||||
}
|
||||
}
|
||||
} else {
|
||||
delete(schemaMap, "items")
|
||||
}
|
||||
|
||||
// 9. [SAFETY] Required 字段对齐
|
||||
|
||||
@@ -206,6 +206,16 @@ func anthropicMsgToResponsesItems(m AnthropicMessage) ([]ResponsesInputItem, err
|
||||
return anthropicUserToResponses(m.Content)
|
||||
case "assistant":
|
||||
return anthropicAssistantToResponses(m.Content)
|
||||
case "system":
|
||||
// Mid-conversation system turns (e.g. hook output) keep system-level
|
||||
// authority: Responses uses developer for them, not user.
|
||||
items, err := anthropicUserToResponses(m.Content)
|
||||
for i := range items {
|
||||
if items[i].Role == "user" {
|
||||
items[i].Role = "developer"
|
||||
}
|
||||
}
|
||||
return items, err
|
||||
default:
|
||||
return anthropicUserToResponses(m.Content)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
package apicompat
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
// A system message in the middle of an Anthropic conversation (e.g. hook
|
||||
// output) must reach Responses as a developer item, not as user input.
|
||||
func TestAnthropicToResponses_MidConversationSystemBecomesDeveloper(t *testing.T) {
|
||||
out, err := AnthropicToResponses(&AnthropicRequest{
|
||||
Model: "gpt-5.2",
|
||||
MaxTokens: 64,
|
||||
Messages: []AnthropicMessage{
|
||||
{Role: "user", Content: json.RawMessage(`"hi"`)},
|
||||
{Role: "system", Content: json.RawMessage(`[{"type":"text","text":"hook output"}]`)},
|
||||
{Role: "system", Content: json.RawMessage(`"extra context"`)},
|
||||
},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
input := gjson.ParseBytes(out.Input).Array()
|
||||
require.Len(t, input, 3)
|
||||
require.Equal(t, "user", input[0].Get("role").String())
|
||||
require.Equal(t, "developer", input[1].Get("role").String())
|
||||
require.Equal(t, "hook output", input[1].Get("content.0.text").String())
|
||||
require.Equal(t, "developer", input[2].Get("role").String())
|
||||
require.Equal(t, "extra context", input[2].Get("content.0.text").String())
|
||||
}
|
||||
@@ -445,6 +445,38 @@ func TestChatCompletionsToResponses_ResponseFormatJsonSchema(t *testing.T) {
|
||||
}`, string(resp.Text.Format))
|
||||
}
|
||||
|
||||
func TestChatCompletionsToResponses_ResponseFormatJsonSchemaDefaultsStrictFalse(t *testing.T) {
|
||||
req := &ChatCompletionsRequest{
|
||||
Model: "gpt-4o",
|
||||
Messages: []ChatMessage{{Role: "user", Content: json.RawMessage(`"Return structured JSON"`)}},
|
||||
ResponseFormat: json.RawMessage(`{
|
||||
"type":"json_schema",
|
||||
"json_schema":{
|
||||
"name":"answer",
|
||||
"schema":{
|
||||
"type":"object",
|
||||
"properties":{"ok":{"type":"boolean"}},
|
||||
"required":["ok"]
|
||||
}
|
||||
}
|
||||
}`),
|
||||
}
|
||||
|
||||
resp, err := ChatCompletionsToResponses(req)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, resp.Text)
|
||||
assert.JSONEq(t, `{
|
||||
"type":"json_schema",
|
||||
"name":"answer",
|
||||
"schema":{
|
||||
"type":"object",
|
||||
"properties":{"ok":{"type":"boolean"}},
|
||||
"required":["ok"]
|
||||
},
|
||||
"strict":false
|
||||
}`, string(resp.Text.Format))
|
||||
}
|
||||
|
||||
func TestChatCompletionsToResponses_ImageURL(t *testing.T) {
|
||||
content := `[{"type":"text","text":"Describe this"},{"type":"image_url","image_url":{"url":"data:image/png;base64,abc123"}}]`
|
||||
req := &ChatCompletionsRequest{
|
||||
|
||||
@@ -23,6 +23,11 @@ func chatResponseFormatToResponsesTextFormat(raw json.RawMessage) json.RawMessag
|
||||
return raw
|
||||
}
|
||||
schema["type"] = rawJSONString("json_schema")
|
||||
// Chat Completions defaults strict to false while Responses defaults to strict,
|
||||
// so make the intended mode explicit to avoid the upstream rejecting the schema.
|
||||
if _, ok := schema["strict"]; !ok {
|
||||
schema["strict"] = json.RawMessage("false")
|
||||
}
|
||||
|
||||
out, err := json.Marshal(schema)
|
||||
if err != nil {
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
package apicompat
|
||||
|
||||
import "strings"
|
||||
|
||||
// IsServerSideSearchCall reports whether a Responses output item is a search
|
||||
// that the xAI server runs itself, so the client has nothing to execute.
|
||||
//
|
||||
// xAI documents the Responses API form of X Search as a custom_tool_call whose
|
||||
// call_id starts with xs_, and attachment search as one whose call_id starts
|
||||
// with as_; both are "handled by the xAI server"
|
||||
// (https://docs.x.ai/developers/tools/tool-usage-details, "Using Responses API"
|
||||
// table; https://docs.x.ai/developers/tools/x-search, "How X Search Works").
|
||||
// A custom_tool_call without these prefixes is a client tool call.
|
||||
//
|
||||
// This is the only place the prefix rule lives. Converters that turn
|
||||
// custom_tool_call items into client tool calls skip items for which it
|
||||
// returns true when the caller says the upstream is xAI, and Grok search
|
||||
// counting includes them.
|
||||
func IsServerSideSearchCall(itemType, callID string) bool {
|
||||
if itemType != "custom_tool_call" {
|
||||
return false
|
||||
}
|
||||
return strings.HasPrefix(callID, "xs_") || strings.HasPrefix(callID, "as_")
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
package apicompat
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// serverSideSearchStream is the event sequence of one custom_tool_call item
|
||||
// followed by a text answer, in the shape xAI documents for X Search.
|
||||
func serverSideSearchStream(callID, name string) []*ResponsesStreamEvent {
|
||||
item := ResponsesOutput{Type: "custom_tool_call", ID: "ctc_1", CallID: callID, Name: name, Input: `{"query":"q"}`, Status: "completed"}
|
||||
added := ResponsesOutput{Type: "custom_tool_call", ID: "ctc_1", CallID: callID, Name: name}
|
||||
message := ResponsesOutput{Type: "message", ID: "msg_1", Role: "assistant", Content: []ResponsesContentPart{{Type: "output_text", Text: "found it"}}}
|
||||
return []*ResponsesStreamEvent{
|
||||
{Type: "response.created", Response: &ResponsesResponse{ID: "resp_1"}},
|
||||
{Type: "response.output_item.added", OutputIndex: 0, Item: &added},
|
||||
{Type: "response.custom_tool_call_input.delta", OutputIndex: 0, ItemID: "ctc_1", Delta: `{"query":"q"}`},
|
||||
{Type: "response.custom_tool_call_input.done", OutputIndex: 0, ItemID: "ctc_1", Input: `{"query":"q"}`},
|
||||
{Type: "response.output_item.done", OutputIndex: 0, Item: &item},
|
||||
{Type: "response.output_text.delta", OutputIndex: 1, Delta: "found it"},
|
||||
{Type: "response.output_item.done", OutputIndex: 1, Item: &message},
|
||||
{Type: "response.completed", Response: &ResponsesResponse{ID: "resp_1", Status: "completed", Output: []ResponsesOutput{item, message}}},
|
||||
}
|
||||
}
|
||||
|
||||
func anthropicEventsOf(events []*ResponsesStreamEvent, xai bool) []AnthropicStreamEvent {
|
||||
state := NewResponsesEventToAnthropicState()
|
||||
state.XAIServerSideSearch = xai
|
||||
var out []AnthropicStreamEvent
|
||||
for _, event := range events {
|
||||
out = append(out, ResponsesEventToAnthropicEvents(event, state)...)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func chatChunksOf(events []*ResponsesStreamEvent, xai bool) []ChatCompletionsChunk {
|
||||
state := NewResponsesEventToChatState()
|
||||
state.XAIServerSideSearch = xai
|
||||
var out []ChatCompletionsChunk
|
||||
for _, event := range events {
|
||||
out = append(out, ResponsesEventToChatChunks(event, state)...)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func anthropicToolUseStarts(events []AnthropicStreamEvent) int {
|
||||
count := 0
|
||||
for _, event := range events {
|
||||
if event.Type == "content_block_start" && event.ContentBlock != nil && event.ContentBlock.Type == "tool_use" {
|
||||
count++
|
||||
}
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
func anthropicStopReason(events []AnthropicStreamEvent) string {
|
||||
for _, event := range events {
|
||||
if event.Type == "message_delta" && event.Delta != nil {
|
||||
return event.Delta.StopReason
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func chatToolCallChunks(chunks []ChatCompletionsChunk) int {
|
||||
count := 0
|
||||
for _, chunk := range chunks {
|
||||
for _, choice := range chunk.Choices {
|
||||
count += len(choice.Delta.ToolCalls)
|
||||
}
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
func chatFinishReason(chunks []ChatCompletionsChunk) string {
|
||||
for _, chunk := range chunks {
|
||||
for _, choice := range chunk.Choices {
|
||||
if choice.FinishReason != nil {
|
||||
return *choice.FinishReason
|
||||
}
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func TestResponsesEventToAnthropicEvents_ServerSideSearchIsNotToolUse(t *testing.T) {
|
||||
for _, tt := range []struct {
|
||||
name, callID, toolName string
|
||||
xai bool
|
||||
wantToolUse int
|
||||
wantStop string
|
||||
}{
|
||||
{"x search", "xs_123", "x_keyword_search", true, 0, "end_turn"},
|
||||
{"attachment search", "as_456", "attachment_search", true, 0, "end_turn"},
|
||||
{"client custom tool", "call_9", "exec", true, 1, "tool_use"},
|
||||
{"x search call id on a non-xAI upstream", "xs_123", "x_keyword_search", false, 1, "tool_use"},
|
||||
{"attachment search call id on a non-xAI upstream", "as_456", "attachment_search", false, 1, "tool_use"},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
events := anthropicEventsOf(serverSideSearchStream(tt.callID, tt.toolName), tt.xai)
|
||||
require.Equal(t, tt.wantToolUse, anthropicToolUseStarts(events))
|
||||
require.Equal(t, tt.wantStop, anthropicStopReason(events))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestResponsesEventToAnthropicEvents_ServerSideSearchKeepsClientToolCall(t *testing.T) {
|
||||
stream := serverSideSearchStream("xs_123", "x_keyword_search")
|
||||
client := ResponsesOutput{Type: "custom_tool_call", ID: "ctc_2", CallID: "call_9", Name: "exec", Input: "dir"}
|
||||
clientAdded := ResponsesOutput{Type: "custom_tool_call", ID: "ctc_2", CallID: "call_9", Name: "exec"}
|
||||
mixed := append([]*ResponsesStreamEvent{}, stream[:len(stream)-1]...)
|
||||
mixed = append(mixed,
|
||||
&ResponsesStreamEvent{Type: "response.output_item.added", OutputIndex: 2, Item: &clientAdded},
|
||||
&ResponsesStreamEvent{Type: "response.custom_tool_call_input.delta", OutputIndex: 2, ItemID: "ctc_2", Delta: "dir"},
|
||||
&ResponsesStreamEvent{Type: "response.output_item.done", OutputIndex: 2, Item: &client},
|
||||
&ResponsesStreamEvent{Type: "response.completed", Response: &ResponsesResponse{ID: "resp_1", Status: "completed"}},
|
||||
)
|
||||
|
||||
events := anthropicEventsOf(mixed, true)
|
||||
require.Equal(t, 1, anthropicToolUseStarts(events))
|
||||
require.Equal(t, "tool_use", anthropicStopReason(events))
|
||||
}
|
||||
|
||||
func TestResponsesEventToChatChunks_ServerSideSearchIsNotToolCall(t *testing.T) {
|
||||
for _, tt := range []struct {
|
||||
name, callID, toolName string
|
||||
xai bool
|
||||
wantToolCalls int
|
||||
wantFinish string
|
||||
}{
|
||||
{"x search", "xs_123", "x_keyword_search", true, 0, "stop"},
|
||||
{"attachment search", "as_456", "attachment_search", true, 0, "stop"},
|
||||
{"client custom tool", "call_9", "exec", true, 2, "tool_calls"},
|
||||
{"x search call id on a non-xAI upstream", "xs_123", "x_keyword_search", false, 2, "tool_calls"},
|
||||
{"attachment search call id on a non-xAI upstream", "as_456", "attachment_search", false, 2, "tool_calls"},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
chunks := chatChunksOf(serverSideSearchStream(tt.callID, tt.toolName), tt.xai)
|
||||
// A client call is announced once and then carries its input delta.
|
||||
require.Equal(t, tt.wantToolCalls, chatToolCallChunks(chunks))
|
||||
require.Equal(t, tt.wantFinish, chatFinishReason(chunks))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBufferedResponseAccumulator_ServerSideSearchIsNotRebuiltAsFunctionCall(t *testing.T) {
|
||||
rebuild := func(callID, name string, xai bool) []ResponsesOutput {
|
||||
acc := NewBufferedResponseAccumulator()
|
||||
acc.XAIServerSideSearch = xai
|
||||
for _, event := range serverSideSearchStream(callID, name) {
|
||||
if event.Type == "response.completed" {
|
||||
continue
|
||||
}
|
||||
acc.ProcessEvent(event)
|
||||
}
|
||||
resp := &ResponsesResponse{ID: "resp_1", Status: "completed"}
|
||||
acc.SupplementResponseOutput(resp)
|
||||
return resp.Output
|
||||
}
|
||||
|
||||
client := rebuild("call_9", "exec", true)
|
||||
require.Equal(t, "function_call", client[len(client)-1].Type)
|
||||
require.Equal(t, "call_9", client[len(client)-1].CallID)
|
||||
|
||||
for _, callID := range []string{"xs_123", "as_456"} {
|
||||
notXAI := rebuild(callID, "x_keyword_search", false)
|
||||
require.Equal(t, "function_call", notXAI[len(notXAI)-1].Type, "without the xAI switch the item is rebuilt as before")
|
||||
|
||||
output := rebuild(callID, "x_keyword_search", true)
|
||||
for _, item := range output {
|
||||
require.NotEqual(t, "function_call", item.Type, "a server-side search is not a client function call")
|
||||
}
|
||||
last := output[len(output)-1]
|
||||
require.Equal(t, "custom_tool_call", last.Type)
|
||||
require.Equal(t, callID, last.CallID)
|
||||
require.Equal(t, `{"query":"q"}`, last.Input)
|
||||
|
||||
resp := &ResponsesResponse{ID: "resp_1", Status: "completed", Output: output}
|
||||
message := ResponsesToAnthropic(resp, "m")
|
||||
require.Equal(t, "end_turn", *message.StopReason)
|
||||
for _, block := range message.Content {
|
||||
require.NotEqual(t, "tool_use", block.Type)
|
||||
}
|
||||
chat := ResponsesToChatCompletions(resp, "m")
|
||||
require.Empty(t, chat.Choices[0].Message.ToolCalls)
|
||||
require.Equal(t, "stop", chat.Choices[0].FinishReason)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package apicompat
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestIsServerSideSearchCall(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
itemType string
|
||||
callID string
|
||||
want bool
|
||||
}{
|
||||
{"x search", "custom_tool_call", "xs_123", true},
|
||||
{"attachment search", "custom_tool_call", "as_456", true},
|
||||
{"padded call id is not a prefix match", "custom_tool_call", " xs_123", false},
|
||||
{"client custom tool", "custom_tool_call", "call_9", false},
|
||||
{"prefix is not a substring", "custom_tool_call", "call_xs_9", false},
|
||||
{"no call id", "custom_tool_call", "", false},
|
||||
{"function call keeps its client meaning", "function_call", "xs_123", false},
|
||||
{"other server-side item types are separate items", "x_search_call", "xs_123", false},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
require.Equal(t, tt.want, IsServerSideSearchCall(tt.itemType, tt.callID))
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -190,6 +190,11 @@ type ResponsesEventToAnthropicState struct {
|
||||
PendingThinkingSignature string
|
||||
HasToolCall bool
|
||||
|
||||
// XAIServerSideSearch is set by callers whose upstream is xAI. A
|
||||
// custom_tool_call that IsServerSideSearchCall then never becomes a tool_use
|
||||
// block, because xAI runs it itself.
|
||||
XAIServerSideSearch bool
|
||||
|
||||
// OutputIndexToBlockIdx maps Responses output_index → Anthropic content block index.
|
||||
OutputIndexToBlockIdx map[int]int
|
||||
|
||||
@@ -349,6 +354,9 @@ func resToAnthHandleOutputItemAdded(evt *ResponsesStreamEvent, state *ResponsesE
|
||||
// function_call 与 custom_tool_call(custom/freeform 工具,如新版 apply_patch)
|
||||
// 同样映射为 Anthropic 的 tool_use 块。
|
||||
case "function_call", "custom_tool_call":
|
||||
if state.XAIServerSideSearch && IsServerSideSearchCall(evt.Item.Type, evt.Item.CallID) {
|
||||
return nil
|
||||
}
|
||||
var events []AnthropicStreamEvent
|
||||
events = append(events, closeCurrentBlock(state)...)
|
||||
|
||||
|
||||
@@ -131,6 +131,11 @@ type ResponsesEventToChatState struct {
|
||||
argumentBuffers map[int]*strings.Builder
|
||||
IncludeUsage bool
|
||||
Usage *ChatUsage
|
||||
|
||||
// XAIServerSideSearch is set by callers whose upstream is xAI. A
|
||||
// custom_tool_call that IsServerSideSearchCall then never becomes a tool
|
||||
// call, because xAI runs it itself.
|
||||
XAIServerSideSearch bool
|
||||
}
|
||||
|
||||
// NewResponsesEventToChatState returns an initialised stream state.
|
||||
@@ -266,6 +271,9 @@ func resToChatHandleOutputItemAdded(evt *ResponsesStreamEvent, state *ResponsesE
|
||||
if evt.Item == nil || (evt.Item.Type != "function_call" && evt.Item.Type != "custom_tool_call") {
|
||||
return nil
|
||||
}
|
||||
if state.XAIServerSideSearch && IsServerSideSearchCall(evt.Item.Type, evt.Item.CallID) {
|
||||
return nil
|
||||
}
|
||||
|
||||
state.SawToolCall = true
|
||||
idx := state.NextToolCallIndex
|
||||
@@ -503,7 +511,11 @@ type bufferedFuncCall struct {
|
||||
Name string
|
||||
Namespace string
|
||||
EncryptedFunctionArgs json.RawMessage
|
||||
EncryptedContent string
|
||||
Args strings.Builder
|
||||
// ServerSideSearch marks a custom_tool_call the xAI server ran itself; it
|
||||
// is rebuilt as that item, never as a client function_call.
|
||||
ServerSideSearch bool
|
||||
}
|
||||
|
||||
// BufferedResponseAccumulator collects content from Responses SSE delta events
|
||||
@@ -515,6 +527,11 @@ type BufferedResponseAccumulator struct {
|
||||
reasoning strings.Builder
|
||||
funcCalls []bufferedFuncCall
|
||||
outputIndexToFuncIdx map[int]int
|
||||
|
||||
// XAIServerSideSearch is set by callers whose upstream is xAI. A
|
||||
// custom_tool_call that IsServerSideSearchCall is then rebuilt as that item
|
||||
// instead of as a client function_call.
|
||||
XAIServerSideSearch bool
|
||||
}
|
||||
|
||||
// NewBufferedResponseAccumulator returns an initialised accumulator.
|
||||
@@ -547,6 +564,8 @@ func (a *BufferedResponseAccumulator) ProcessEvent(event *ResponsesStreamEvent)
|
||||
Name: event.Item.Name,
|
||||
Namespace: event.Item.Namespace,
|
||||
EncryptedFunctionArgs: event.Item.EncryptedFunctionArgs,
|
||||
EncryptedContent: event.Item.EncryptedContent,
|
||||
ServerSideSearch: a.XAIServerSideSearch && IsServerSideSearchCall(event.Item.Type, event.Item.CallID),
|
||||
})
|
||||
}
|
||||
case "response.function_call_arguments.delta", "response.custom_tool_call_input.delta":
|
||||
@@ -610,12 +629,22 @@ func (a *BufferedResponseAccumulator) BuildOutput() []ResponsesOutput {
|
||||
}
|
||||
|
||||
for i := range a.funcCalls {
|
||||
if a.funcCalls[i].ServerSideSearch {
|
||||
out = append(out, ResponsesOutput{
|
||||
Type: "custom_tool_call",
|
||||
CallID: a.funcCalls[i].CallID,
|
||||
Name: a.funcCalls[i].Name,
|
||||
Input: a.funcCalls[i].Args.String(),
|
||||
})
|
||||
continue
|
||||
}
|
||||
out = append(out, ResponsesOutput{
|
||||
Type: "function_call",
|
||||
CallID: a.funcCalls[i].CallID,
|
||||
Name: a.funcCalls[i].Name,
|
||||
Namespace: a.funcCalls[i].Namespace,
|
||||
EncryptedFunctionArgs: a.funcCalls[i].EncryptedFunctionArgs,
|
||||
EncryptedContent: a.funcCalls[i].EncryptedContent,
|
||||
Arguments: a.funcCalls[i].Args.String(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -31,6 +31,7 @@ const (
|
||||
BetaContextManagement = "context-management-2025-06-27"
|
||||
BetaThinkingBindingControls = "thinking-binding-controls-2026-08-01"
|
||||
BetaMidConversationOutputConfig = "mid-conversation-output-config-2026-07-01"
|
||||
BetaPerTurnControl = "per-turn-control-2026-07-01"
|
||||
BetaExtendedCacheTTL = "extended-cache-ttl-2025-04-11"
|
||||
|
||||
// server-side refusal fallback beta 字段族(beta Messages API 专有)。
|
||||
@@ -253,7 +254,7 @@ func DefaultModelIDs() []string {
|
||||
}
|
||||
|
||||
// DefaultTestModel 测试时使用的默认模型
|
||||
const DefaultTestModel = "claude-sonnet-4-5-20250929"
|
||||
const DefaultTestModel = "claude-sonnet-4-6"
|
||||
|
||||
// ModelIDOverrides Claude OAuth 请求需要的模型 ID 映射
|
||||
var ModelIDOverrides = map[string]string{
|
||||
|
||||
@@ -4,7 +4,7 @@ import "testing"
|
||||
|
||||
func TestSupportsMultimodalFunctionResponses(t *testing.T) {
|
||||
for model, want := range map[string]bool{
|
||||
"gemini-3-pro": true, "gemini-3.8-flash": true, "gemini-4-argon": true,
|
||||
"gemini-3-pro": true, "gemini-3.8-flash": true, "gemini-4-argon": true, "gemini-4-carbon": true,
|
||||
"models/gemini-3-flash-preview": true, "gemini-2.5-flash": false,
|
||||
"claude-sonnet-4-6": false, "client-alias": false, "": false,
|
||||
} {
|
||||
|
||||
@@ -35,6 +35,7 @@ func DefaultModels() []Model {
|
||||
{Name: "models/gemini-3.7-flash", SupportedGenerationMethods: methods},
|
||||
{Name: "models/gemini-3.8-flash", SupportedGenerationMethods: methods},
|
||||
{Name: "models/gemini-4-argon", SupportedGenerationMethods: methods},
|
||||
{Name: "models/gemini-4-carbon", SupportedGenerationMethods: methods},
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@ func TestDefaultModels_ContainsFallbackCatalogModels(t *testing.T) {
|
||||
}
|
||||
|
||||
required := []string{
|
||||
"models/gemini-4-carbon",
|
||||
"models/gemini-3-pro-image",
|
||||
"models/gemini-3.1-pro-preview-customtools",
|
||||
"models/gemini-3.1-flash-image",
|
||||
@@ -41,3 +42,14 @@ func TestHasFallbackModel_RecognizesCustomtoolsModel(t *testing.T) {
|
||||
t.Fatalf("did not expect unknown model to exist in fallback catalog")
|
||||
}
|
||||
}
|
||||
|
||||
func TestHasFallbackModel_Carbon(t *testing.T) {
|
||||
for _, model := range []string{"gemini-4-carbon", "models/gemini-4-carbon"} {
|
||||
if !HasFallbackModel(model) {
|
||||
t.Fatalf("expected Carbon fallback: %s", model)
|
||||
}
|
||||
}
|
||||
if HasFallbackModel("gemini-4-carbon-preview") {
|
||||
t.Fatal("must not invent a preview alias")
|
||||
}
|
||||
}
|
||||
@@ -28,6 +28,7 @@ var DefaultModels = []Model{
|
||||
{ID: "gemini-3.7-flash", Type: "model", DisplayName: "Gemini 3.7 Flash", CreatedAt: ""},
|
||||
{ID: "gemini-3.8-flash", Type: "model", DisplayName: "Gemini 3.8 Flash", CreatedAt: ""},
|
||||
{ID: "gemini-4-argon", Type: "model", DisplayName: "Gemini 4 Argon", CreatedAt: ""},
|
||||
{ID: "gemini-4-carbon", Type: "model", DisplayName: "Gemini 4 Carbon", CreatedAt: ""},
|
||||
}
|
||||
|
||||
// GoogleOneModels is the conservative model set exposed for legacy Google One
|
||||
|
||||
@@ -11,6 +11,7 @@ func TestDefaultModels_ContainsImageModels(t *testing.T) {
|
||||
}
|
||||
|
||||
required := []string{
|
||||
"gemini-4-carbon",
|
||||
"gemini-3.1-flash-image",
|
||||
"gemini-3-pro-image",
|
||||
DefaultTestModel,
|
||||
@@ -32,7 +33,7 @@ func TestGoogleOneModels_ExcludeUnsupportedNewAndImageModels(t *testing.T) {
|
||||
t.Fatalf("expected Google One model %q to map to itself", id)
|
||||
}
|
||||
}
|
||||
for _, id := range []string{"gemini-2.5-flash-image", "gemini-3.1-flash-image", "gemini-3.5-flash"} {
|
||||
for _, id := range []string{"gemini-2.5-flash-image", "gemini-3.1-flash-image", "gemini-3.5-flash", "gemini-4-carbon"} {
|
||||
if _, ok := mapping[id]; ok {
|
||||
t.Fatalf("did not expect unsupported Google One model %q", id)
|
||||
}
|
||||
|
||||
@@ -111,8 +111,9 @@ type EndpointStat struct {
|
||||
Endpoint string `json:"endpoint"`
|
||||
Requests int64 `json:"requests"`
|
||||
TotalTokens int64 `json:"total_tokens"`
|
||||
Cost float64 `json:"cost"` // 标准计费
|
||||
ActualCost float64 `json:"actual_cost"` // 实际扣除
|
||||
Cost float64 `json:"cost"` // 标准计费
|
||||
ActualCost float64 `json:"actual_cost"` // 实际扣除
|
||||
AccountCost float64 `json:"account_cost,omitempty"` // 账号成本(仅管理员接口返回)
|
||||
}
|
||||
|
||||
// GroupUsageSummary represents today's, yesterday's, and cumulative cost for a single group.
|
||||
|
||||
@@ -1478,10 +1478,38 @@ func (r *accountRepository) BatchUpdateLastUsed(ctx context.Context, updates map
|
||||
caseSQL += " END, updated_at = NOW() WHERE id = ANY($" + itoa(idx) + ") AND deleted_at IS NULL"
|
||||
args = append(args, pq.Array(ids))
|
||||
|
||||
_, err := r.sql.ExecContext(ctx, caseSQL, args...)
|
||||
// 同一事务内先按 id 升序锁定目标行再更新,与计费合并事务锁多个账号行的顺序一致;
|
||||
// 锁强度与更新非键列相同,不阻塞引用 accounts 的外键检查。
|
||||
exec := r.sql
|
||||
var tx *sql.Tx
|
||||
if db, ok := r.sql.(*sql.DB); ok {
|
||||
var err error
|
||||
if tx, err = db.BeginTx(ctx, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() {
|
||||
if tx != nil {
|
||||
_ = tx.Rollback()
|
||||
}
|
||||
}()
|
||||
exec = tx
|
||||
}
|
||||
rows, err := exec.QueryContext(ctx, "SELECT id FROM accounts WHERE id = ANY($1) AND deleted_at IS NULL ORDER BY id FOR NO KEY UPDATE", pq.Array(ids))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := rows.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := exec.ExecContext(ctx, caseSQL, args...); err != nil {
|
||||
return err
|
||||
}
|
||||
if tx != nil {
|
||||
if err := tx.Commit(); err != nil {
|
||||
return err
|
||||
}
|
||||
tx = nil
|
||||
}
|
||||
lastUsedPayload := make(map[string]int64, len(updates))
|
||||
for id, ts := range updates {
|
||||
lastUsedPayload[strconv.FormatInt(id, 10)] = ts.Unix()
|
||||
@@ -2690,6 +2718,49 @@ func (r *accountRepository) ClearModelRateLimits(ctx context.Context, id int64)
|
||||
return nil
|
||||
}
|
||||
|
||||
// ClearModelRateLimit 删除 model_rate_limits 中指定的单个 scope。
|
||||
// 与 ClearModelRateLimits 的全量清除不同,这里只解封一个模型窗口,
|
||||
// 不会把其他模型或并发新写入的限流一起抹掉。
|
||||
func (r *accountRepository) ClearModelRateLimit(ctx context.Context, id int64, scope string) error {
|
||||
if strings.TrimSpace(scope) == "" {
|
||||
return nil
|
||||
}
|
||||
if scoped := r.accountTransactionScope(ctx); scoped != r {
|
||||
return scoped.ClearModelRateLimit(ctx, id, scope)
|
||||
}
|
||||
client := clientFromContext(ctx, r.client)
|
||||
result, err := client.ExecContext(
|
||||
ctx,
|
||||
`UPDATE accounts SET
|
||||
extra = jsonb_set(
|
||||
COALESCE(extra, '{}'::jsonb),
|
||||
'{model_rate_limits}'::text[],
|
||||
COALESCE(extra->'model_rate_limits', '{}'::jsonb) - $1::text,
|
||||
true
|
||||
),
|
||||
updated_at = NOW()
|
||||
WHERE id = $2 AND deleted_at IS NULL`,
|
||||
strings.TrimSpace(scope),
|
||||
id,
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
affected, err := result.RowsAffected()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if affected == 0 {
|
||||
return service.ErrAccountNotFound
|
||||
}
|
||||
if err := enqueueSchedulerOutbox(ctx, r.sql, service.SchedulerOutboxEventAccountChanged, &id, nil, nil); err != nil {
|
||||
logger.LegacyPrintf("repository.account", "[SchedulerOutbox] enqueue clear model rate limit scope failed: account=%d err=%v", id, err)
|
||||
}
|
||||
r.syncSchedulerAccountSnapshot(ctx, id)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *accountRepository) UpdateSessionWindow(ctx context.Context, id int64, start, end *time.Time, status string) error {
|
||||
builder := r.client.Account.Update().
|
||||
Where(dbaccount.IDEQ(id)).
|
||||
@@ -2714,8 +2785,11 @@ func (r *accountRepository) UpdateSessionWindow(ctx context.Context, id int64, s
|
||||
}
|
||||
|
||||
func (r *accountRepository) UpdateSessionWindowEnd(ctx context.Context, id int64, end time.Time) error {
|
||||
// Active five-hour quota reads must advance both bounds. Keeping the old
|
||||
// start would charge the previous window against the new window's cost limit.
|
||||
_, err := r.client.Account.Update().
|
||||
Where(dbaccount.IDEQ(id)).
|
||||
SetSessionWindowStart(end.Add(-5 * time.Hour)).
|
||||
SetSessionWindowEnd(end).
|
||||
Save(ctx)
|
||||
if err != nil {
|
||||
|
||||
@@ -212,6 +212,7 @@ func (r *apiKeyRepository) GetByKeyForAuth(ctx context.Context, key string) (*se
|
||||
group.FieldAllowMessagesDispatch,
|
||||
group.FieldAllowLive,
|
||||
group.FieldForceOpenaiFast,
|
||||
group.FieldForceOpenaiUltrafast,
|
||||
group.FieldFreeOpenaiFast,
|
||||
group.FieldDefaultMappedModel,
|
||||
group.FieldMessagesDispatchModelConfig,
|
||||
@@ -1028,6 +1029,7 @@ func groupEntityToService(g *dbent.Group) *service.Group {
|
||||
AllowMessagesDispatch: g.AllowMessagesDispatch,
|
||||
AllowLive: g.AllowLive,
|
||||
ForceOpenAIFast: g.ForceOpenaiFast,
|
||||
ForceOpenAIUltrafast: g.ForceOpenaiUltrafast,
|
||||
FreeOpenAIFast: g.FreeOpenaiFast,
|
||||
RequireOAuthOnly: g.RequireOauthOnly,
|
||||
RequirePrivacySet: g.RequirePrivacySet,
|
||||
|
||||
@@ -44,3 +44,36 @@ func TestGetByKeyForAuthCarriesGroupForceOpenAIFast(t *testing.T) {
|
||||
require.True(t, got.Group.ForceOpenAIFast)
|
||||
require.True(t, got.Group.FreeOpenAIFast)
|
||||
}
|
||||
|
||||
func TestGetByKeyForAuthCarriesGroupForceOpenAIUltrafast(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
suffix := time.Now().UnixNano()
|
||||
group := mustCreateGroup(t, integrationEntClient, &service.Group{
|
||||
Name: fmt.Sprintf("ultrafast-proj-group-%d", suffix), Platform: service.PlatformOpenAI,
|
||||
RateMultiplier: 1, ForceOpenAIUltrafast: true,
|
||||
})
|
||||
user := mustCreateUser(t, integrationEntClient, &service.User{
|
||||
Email: fmt.Sprintf("ultrafast-proj-%d@example.com", suffix), Concurrency: 5,
|
||||
})
|
||||
groupID := group.ID
|
||||
keyValue := fmt.Sprintf("sk-ultrafast-proj-%d", suffix)
|
||||
apiKeyRepo := NewAPIKeyRepository(integrationEntClient, integrationDB)
|
||||
key := &service.APIKey{UserID: user.ID, GroupID: &groupID, Key: keyValue, Name: "ultrafast-proj", Status: service.StatusActive}
|
||||
require.NoError(t, apiKeyRepo.Create(ctx, key))
|
||||
t.Cleanup(func() {
|
||||
_, err := integrationDB.ExecContext(ctx, "DELETE FROM auth_cache_invalidation_outbox WHERE cache_key = encode(sha256(convert_to($1, 'UTF8')), 'hex')", keyValue)
|
||||
require.NoError(t, err)
|
||||
_, err = integrationDB.ExecContext(ctx, "DELETE FROM api_keys WHERE id = $1", key.ID)
|
||||
require.NoError(t, err)
|
||||
_, err = integrationDB.ExecContext(ctx, "DELETE FROM users WHERE id = $1", user.ID)
|
||||
require.NoError(t, err)
|
||||
_, err = integrationDB.ExecContext(ctx, "DELETE FROM groups WHERE id = $1", group.ID)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
|
||||
got, err := apiKeyRepo.GetByKeyForAuth(ctx, keyValue)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, got.Group)
|
||||
require.True(t, got.Group.ForceOpenAIUltrafast)
|
||||
require.False(t, got.Group.ForceOpenAIFast)
|
||||
}
|
||||
@@ -2,11 +2,15 @@ package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/usagestats"
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/stretchr/testify/suite"
|
||||
)
|
||||
@@ -61,6 +65,87 @@ func (s *ClaudeUsageServiceSuite) TestFetchUsage_Success() {
|
||||
require.Equal(s.T(), "oauth-2025-04-20", captured.anthropicBeta, "anthropic-beta header mismatch")
|
||||
}
|
||||
|
||||
type claudeUsageWindowAccountRepo struct {
|
||||
service.AccountRepository
|
||||
account *service.Account
|
||||
}
|
||||
|
||||
func (r *claudeUsageWindowAccountRepo) GetByID(context.Context, int64) (*service.Account, error) {
|
||||
return r.account, nil
|
||||
}
|
||||
|
||||
func (r *claudeUsageWindowAccountRepo) UpdateExtra(_ context.Context, _ int64, updates map[string]any) error {
|
||||
for key, value := range updates {
|
||||
r.account.Extra[key] = value
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type claudeUsageWindowLogRepo struct {
|
||||
service.UsageLogRepository
|
||||
}
|
||||
|
||||
func (*claudeUsageWindowLogRepo) GetAccountWindowStats(context.Context, int64, time.Time) (*usagestats.AccountStats, error) {
|
||||
return &usagestats.AccountStats{}, nil
|
||||
}
|
||||
|
||||
func TestClaudeUsageFetcher_ScopedFableRoundTrip(t *testing.T) {
|
||||
resetAt := time.Now().Add(72 * time.Hour).UTC().Truncate(time.Microsecond)
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
percent string
|
||||
legacy string
|
||||
wantUsage float64
|
||||
}{
|
||||
{name: "scoped", percent: "5.25", wantUsage: 5.25},
|
||||
{name: "zero overrides passive", percent: "0", wantUsage: 0},
|
||||
{name: "missing falls back to passive", percent: "null", wantUsage: 87},
|
||||
{name: "legacy takes precedence", percent: "5.25", legacy: fmt.Sprintf(`{"utilization":56,"resets_at":%q}`, resetAt.Format(time.RFC3339Nano)), wantUsage: 56},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
legacy := tc.legacy
|
||||
if legacy == "" {
|
||||
legacy = "null"
|
||||
}
|
||||
requests := make(chan [2]string, 2)
|
||||
srv := newLocalTestServer(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
requests <- [2]string{r.Method, r.URL.Path}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = fmt.Fprintf(w, `{"five_hour":{"utilization":12},"seven_day_overage_included":%s,"limits":[{"kind":"weekly_scoped","group":"weekly","percent":%s,"resets_at":%q,"scope":{"model":{"display_name":"Fable"},"surface":null},"is_active":false}]}`, legacy, tc.percent, resetAt.Format(time.RFC3339Nano))
|
||||
}))
|
||||
defer srv.Close()
|
||||
fetcher := &claudeUsageService{usageURL: srv.URL + "/api/oauth/usage", allowPrivateHosts: true}
|
||||
account := &service.Account{
|
||||
ID: 1, Platform: service.PlatformAnthropic, Type: service.AccountTypeOAuth,
|
||||
Status: service.StatusActive, Credentials: map[string]any{"access_token": "test-token"},
|
||||
Extra: map[string]any{
|
||||
"passive_usage_7d_oi_utilization": 0.87,
|
||||
"passive_usage_7d_oi_reset": resetAt.Unix(),
|
||||
},
|
||||
}
|
||||
repo := &claudeUsageWindowAccountRepo{account: account}
|
||||
svc := service.NewAccountUsageService(repo, &claudeUsageWindowLogRepo{}, fetcher,
|
||||
nil, nil, nil, nil, nil, service.NewUsageCache(), nil, nil)
|
||||
for range 2 {
|
||||
usage, err := svc.GetUsageForAccount(t.Context(), account)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, usage.SevenDayFable)
|
||||
require.Equal(t, tc.wantUsage, usage.SevenDayFable.Utilization)
|
||||
require.NotNil(t, usage.SevenDayFable.ResetsAt)
|
||||
require.Equal(t, resetAt.Unix(), usage.SevenDayFable.ResetsAt.Unix())
|
||||
}
|
||||
passive, err := svc.GetPassiveUsage(t.Context(), account.ID)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, passive.SevenDayFable)
|
||||
require.InDelta(t, tc.wantUsage, passive.SevenDayFable.Utilization, 1e-9)
|
||||
require.Equal(t, resetAt.Unix(), passive.SevenDayFable.ResetsAt.Unix())
|
||||
require.InDelta(t, tc.wantUsage/100, account.Extra["passive_usage_7d_oi_utilization"], 1e-9)
|
||||
require.Len(t, requests, 1, "the second query must reuse the decoded API response")
|
||||
require.Equal(t, [2]string{"GET", "/api/oauth/usage"}, <-requests)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func (s *ClaudeUsageServiceSuite) TestFetchUsage_NonOK() {
|
||||
s.srv = newLocalTestServer(s.T(), http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
|
||||
@@ -3,6 +3,8 @@ package repository
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"database/sql/driver"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
@@ -17,36 +19,43 @@ type groupUsageRollupSnapshot struct {
|
||||
valid bool
|
||||
closedBefore string // date,历史日桶的右开边界
|
||||
retainedDate string // retained_from 在服务端时区内的日期,历史日桶的左闭边界
|
||||
tailStart time.Time // 尾段(还没进日桶的那部分 usage_logs)的起点
|
||||
tailStart time.Time // 尾段(还没进日桶的那部分 usage_logs)的起点,不早于 expired_before
|
||||
}
|
||||
|
||||
// readGroupUsageRollupSnapshot 读一次汇总水位并在 Go 侧判定有效性。
|
||||
//
|
||||
// 判定条件与原先 SQL 里的 state_values CTE 完全一致:
|
||||
// 恰好一行、时区名与当前服务端配置相同、且水位不在未来。
|
||||
// expired_before 之前的 usage_logs 已超出保留期:无论水位是否有效都不进入尾段,
|
||||
// 其所在日之前的日桶也不读取。
|
||||
func (r *usageLogRepository) readGroupUsageRollupSnapshot(ctx context.Context, timezoneName, todayDate string) (groupUsageRollupSnapshot, error) {
|
||||
epoch := time.Unix(0, 0).UTC()
|
||||
invalid := groupUsageRollupSnapshot{
|
||||
closedBefore: "1970-01-01",
|
||||
retainedDate: "1970-01-01",
|
||||
tailStart: epoch,
|
||||
}
|
||||
|
||||
var rowCount int
|
||||
var closedBefore sql.NullString
|
||||
var retainedFrom sql.NullTime
|
||||
var stateTimezone sql.NullString
|
||||
var expiredBefore sql.NullTime
|
||||
if err := scanSingleRow(ctx, r.sql, `
|
||||
SELECT
|
||||
COUNT(*),
|
||||
MAX(closed_before)::text,
|
||||
MAX(retained_from),
|
||||
MAX(timezone_name)
|
||||
MAX(timezone_name),
|
||||
MAX(expired_before)
|
||||
FROM usage_group_rollup_state
|
||||
WHERE id = 1
|
||||
`, nil, &rowCount, &closedBefore, &retainedFrom, &stateTimezone); err != nil {
|
||||
`, nil, &rowCount, &closedBefore, &retainedFrom, &stateTimezone, &expiredBefore); err != nil {
|
||||
return groupUsageRollupSnapshot{}, fmt.Errorf("读取分组用量汇总水位: %w", err)
|
||||
}
|
||||
|
||||
tailFloor := time.Unix(0, 0).UTC()
|
||||
if rowCount == 1 && expiredBefore.Valid && expiredBefore.Time.After(tailFloor) {
|
||||
tailFloor = expiredBefore.Time.UTC()
|
||||
}
|
||||
invalid := groupUsageRollupSnapshot{
|
||||
closedBefore: "1970-01-01",
|
||||
retainedDate: "1970-01-01",
|
||||
tailStart: tailFloor,
|
||||
}
|
||||
if rowCount != 1 || !closedBefore.Valid || !retainedFrom.Valid ||
|
||||
!stateTimezone.Valid || stateTimezone.String != timezoneName ||
|
||||
closedBefore.String > todayDate {
|
||||
@@ -58,11 +67,19 @@ func (r *usageLogRepository) readGroupUsageRollupSnapshot(ctx context.Context, t
|
||||
// 水位值解析不出来,按无效处理:宁可多扫一次,也不要算错钱。
|
||||
return invalid, nil //nolint:nilerr // 与上面的 valid 判定同语义,均降级为全量重算
|
||||
}
|
||||
tailStart = tailStart.UTC()
|
||||
if tailFloor.After(tailStart) {
|
||||
tailStart = tailFloor
|
||||
}
|
||||
retainedDate := service.GroupUsageDate(retainedFrom.Time)
|
||||
if expiredDate := service.GroupUsageDate(tailFloor); expiredDate > retainedDate {
|
||||
retainedDate = expiredDate
|
||||
}
|
||||
return groupUsageRollupSnapshot{
|
||||
valid: true,
|
||||
closedBefore: closedBefore.String,
|
||||
retainedDate: service.GroupUsageDate(retainedFrom.Time),
|
||||
tailStart: tailStart.UTC(),
|
||||
retainedDate: retainedDate,
|
||||
tailStart: tailStart,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -162,94 +179,287 @@ func (r *usageLogRepository) getAllGroupUsageSummaryFromRollups(ctx context.Cont
|
||||
return results, nil
|
||||
}
|
||||
|
||||
const (
|
||||
groupUsageRollupBuildLockSQL = "SELECT pg_try_advisory_lock(hashtext('usage_group_daily_rollups:build'))"
|
||||
groupUsageRollupBuildUnlockSQL = "SELECT pg_advisory_unlock(hashtext('usage_group_daily_rollups:build'))"
|
||||
// groupUsageRollupBuildMaxRounds 限定一次同步内因并发变更重算脏区间的轮数;
|
||||
// 未收敛的部分保持未发布,由下一次同步继续。
|
||||
groupUsageRollupBuildMaxRounds = 3
|
||||
)
|
||||
|
||||
var errGroupUsageRollupBuildPreempted = errors.New("分组用量汇总重建登记已被替换")
|
||||
|
||||
// groupUsageRollupBuildPlan 是一轮日桶重建:用 [rowsFrom, rowsBefore) 的 usage_logs
|
||||
// 重算 [startDate, targetDate) 的日桶,并清理 retainedDate 之前的日桶。
|
||||
type groupUsageRollupBuildPlan struct {
|
||||
startDate string
|
||||
targetDate string
|
||||
retainedDate string
|
||||
rowsFrom time.Time
|
||||
rowsBefore time.Time
|
||||
timezoneName string
|
||||
}
|
||||
|
||||
// groupUsageRollupTxRunner 在一个事务里执行 fn。
|
||||
type groupUsageRollupTxRunner func(ctx context.Context, fn func(q sqlExecutor) error) error
|
||||
|
||||
// SyncGroupUsageRollups 将服务端配置时区今日以前的用量发布为分组日桶。
|
||||
//
|
||||
// 每轮分三个事务:登记(FOR UPDATE,写入 building_until)、计算(FOR KEY SHARE,重算日桶)、
|
||||
// 发布(FOR UPDATE,水位推进到 build_dirty_from 或目标日期)。usage_logs 写入与失效触发器只持
|
||||
// FOR KEY SHARE,因此只与登记、发布这两个短事务串行,计算阶段不阻塞写入。
|
||||
// 以 *sql.DB 构造时,整个过程持有会话级 advisory lock,同一时刻只有一个重建;
|
||||
// 以事务构造时,三个阶段在调用方事务内顺序执行。
|
||||
func (r *dashboardAggregationRepository) SyncGroupUsageRollups(ctx context.Context, todayStart time.Time) error {
|
||||
if r == nil || r.sql == nil {
|
||||
return nil
|
||||
}
|
||||
todayStart = service.GroupUsageTodayStart(todayStart)
|
||||
if db, ok := r.sql.(*sql.DB); ok {
|
||||
tx, err := db.BeginTx(ctx, nil)
|
||||
db, ok := r.sql.(*sql.DB)
|
||||
if !ok {
|
||||
return syncGroupUsageRollupRounds(ctx, func(ctx context.Context, fn func(q sqlExecutor) error) error {
|
||||
return fn(r.sql)
|
||||
}, todayStart)
|
||||
}
|
||||
|
||||
upToDate, err := groupUsageRollupsUpToDate(ctx, db, todayStart)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if upToDate {
|
||||
return nil
|
||||
}
|
||||
|
||||
conn, err := db.Conn(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var locked bool
|
||||
if err := scanSingleRow(ctx, conn, groupUsageRollupBuildLockSQL, nil, &locked); err != nil {
|
||||
// 查询出错时服务端可能已授予锁,丢弃该物理连接以免锁随连接回到连接池。
|
||||
discardGroupUsageRollupBuildConn(conn)
|
||||
return fmt.Errorf("获取分组用量汇总重建锁: %w", err)
|
||||
}
|
||||
if !locked {
|
||||
return conn.Close()
|
||||
}
|
||||
defer releaseGroupUsageRollupBuildLock(conn)
|
||||
|
||||
return syncGroupUsageRollupRounds(ctx, func(ctx context.Context, fn func(q sqlExecutor) error) error {
|
||||
tx, err := conn.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
txRepo := newDashboardAggregationRepositoryWithSQL(tx)
|
||||
if err := txRepo.syncGroupUsageRollupsInTx(ctx, todayStart); err != nil {
|
||||
if err := fn(tx); err != nil {
|
||||
_ = tx.Rollback()
|
||||
return err
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
return r.syncGroupUsageRollupsInTx(ctx, todayStart)
|
||||
}, todayStart)
|
||||
}
|
||||
|
||||
func (r *dashboardAggregationRepository) syncGroupUsageRollupsInTx(ctx context.Context, todayStart time.Time) error {
|
||||
// releaseGroupUsageRollupBuildLock 释放重建锁;释放失败时丢弃该物理连接,由服务端随会话结束释放锁,
|
||||
// 避免锁随连接回到连接池。
|
||||
func releaseGroupUsageRollupBuildLock(conn *sql.Conn) {
|
||||
unlockCtx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
||||
defer cancel()
|
||||
var unlocked bool
|
||||
if err := scanSingleRow(unlockCtx, conn, groupUsageRollupBuildUnlockSQL, nil, &unlocked); err != nil || !unlocked {
|
||||
discardGroupUsageRollupBuildConn(conn)
|
||||
return
|
||||
}
|
||||
_ = conn.Close()
|
||||
}
|
||||
|
||||
// discardGroupUsageRollupBuildConn 关闭底层物理连接而不是归还连接池,会话级锁随会话结束释放。
|
||||
func discardGroupUsageRollupBuildConn(conn *sql.Conn) {
|
||||
_ = conn.Raw(func(any) error { return driver.ErrBadConn })
|
||||
_ = conn.Close()
|
||||
}
|
||||
|
||||
// groupUsageRollupsUpToDate 不加锁地判断今日以前的日桶是否已全部发布。
|
||||
func groupUsageRollupsUpToDate(ctx context.Context, q sqlQueryer, todayStart time.Time) (bool, error) {
|
||||
var closedBefore string
|
||||
var previousRetainedFrom time.Time
|
||||
var stateTimezoneName string
|
||||
if err := scanSingleRow(ctx, r.sql, `
|
||||
SELECT closed_before::text, retained_from, timezone_name
|
||||
var idle bool
|
||||
err := scanSingleRow(ctx, q, `
|
||||
SELECT closed_before::text, timezone_name, building_until IS NULL
|
||||
FROM usage_group_rollup_state
|
||||
WHERE id = 1
|
||||
`, nil, &closedBefore, &stateTimezoneName, &idle)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("读取分组用量汇总水位: %w", err)
|
||||
}
|
||||
return idle &&
|
||||
closedBefore == service.GroupUsageDate(todayStart) &&
|
||||
stateTimezoneName == service.GroupUsageTimezoneName(), nil
|
||||
}
|
||||
|
||||
func syncGroupUsageRollupRounds(ctx context.Context, run groupUsageRollupTxRunner, todayStart time.Time) error {
|
||||
for range groupUsageRollupBuildMaxRounds {
|
||||
var plan *groupUsageRollupBuildPlan
|
||||
if err := run(ctx, func(q sqlExecutor) error {
|
||||
var err error
|
||||
plan, err = beginGroupUsageRollupBuild(ctx, q, todayStart)
|
||||
return err
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
if plan == nil {
|
||||
return nil
|
||||
}
|
||||
if err := run(ctx, func(q sqlExecutor) error {
|
||||
return buildGroupUsageRollups(ctx, q, plan)
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
var dirty bool
|
||||
if err := run(ctx, func(q sqlExecutor) error {
|
||||
var err error
|
||||
dirty, err = publishGroupUsageRollups(ctx, q, plan)
|
||||
return err
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
if !dirty {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// beginGroupUsageRollupBuild 在 FOR UPDATE 下确定重建区间并登记 building_until。
|
||||
// 日桶已发布到今日时返回 nil。
|
||||
func beginGroupUsageRollupBuild(ctx context.Context, q sqlExecutor, todayStart time.Time) (*groupUsageRollupBuildPlan, error) {
|
||||
var closedBefore string
|
||||
var retainedFrom time.Time
|
||||
var stateTimezoneName string
|
||||
var expiredBefore time.Time
|
||||
var buildingUntil sql.NullString
|
||||
if err := scanSingleRow(ctx, q, `
|
||||
SELECT closed_before::text, retained_from, timezone_name, expired_before, building_until::text
|
||||
FROM usage_group_rollup_state
|
||||
WHERE id = 1
|
||||
FOR UPDATE
|
||||
`, nil, &closedBefore, &previousRetainedFrom, &stateTimezoneName); err != nil {
|
||||
return fmt.Errorf("读取分组用量汇总水位: %w", err)
|
||||
`, nil, &closedBefore, &retainedFrom, &stateTimezoneName, &expiredBefore, &buildingUntil); err != nil {
|
||||
return nil, fmt.Errorf("读取分组用量汇总水位: %w", err)
|
||||
}
|
||||
|
||||
todayDate := service.GroupUsageDate(todayStart)
|
||||
timezoneName := service.GroupUsageTimezoneName()
|
||||
timezoneChanged := stateTimezoneName != timezoneName
|
||||
var closedTime time.Time
|
||||
if !timezoneChanged {
|
||||
var err error
|
||||
closedTime, err = service.ParseGroupUsageDate(closedBefore)
|
||||
closedTime, err := service.ParseGroupUsageDate(closedBefore)
|
||||
if err != nil {
|
||||
return fmt.Errorf("解析分组用量汇总水位 %q: %w", closedBefore, err)
|
||||
return nil, fmt.Errorf("解析分组用量汇总水位 %q: %w", closedBefore, err)
|
||||
}
|
||||
todayDateTime, err := service.ParseGroupUsageDate(todayDate)
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
if closedTime.After(todayDateTime) {
|
||||
return fmt.Errorf("分组用量汇总水位位于未来: %s", closedBefore)
|
||||
return nil, fmt.Errorf("分组用量汇总水位位于未来: %s", closedBefore)
|
||||
}
|
||||
if closedBefore == todayDate {
|
||||
return nil
|
||||
if buildingUntil.Valid {
|
||||
if _, err := q.ExecContext(ctx, `
|
||||
UPDATE usage_group_rollup_state
|
||||
SET building_until = NULL,
|
||||
build_dirty_from = NULL,
|
||||
updated_at = NOW()
|
||||
WHERE id = 1
|
||||
`); err != nil {
|
||||
return nil, fmt.Errorf("清除分组用量汇总重建登记: %w", err)
|
||||
}
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
}
|
||||
|
||||
var earliest sql.NullTime
|
||||
if err := scanSingleRow(ctx, r.sql, "SELECT MIN(created_at) FROM usage_logs", nil, &earliest); err != nil {
|
||||
return fmt.Errorf("读取最早用量记录: %w", err)
|
||||
}
|
||||
retainedFrom := todayStart
|
||||
if earliest.Valid {
|
||||
retainedFrom = earliest.Time.UTC()
|
||||
// 可读日桶从 retained_from 所在日开始,且不早于保留下界。
|
||||
if retainedFrom.Before(expiredBefore) {
|
||||
retainedFrom = expiredBefore
|
||||
}
|
||||
// closed_before 不晚于保留起点时,可读日桶为空,按保留起点全量重建;否则从水位续建。
|
||||
retainedDate := service.GroupUsageDate(retainedFrom)
|
||||
retainedDateTime, err := service.ParseGroupUsageDate(retainedDate)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
rebuildStartDate := retainedDate
|
||||
if !timezoneChanged && closedTime.After(retainedDateTime) {
|
||||
rebuildStartDate = closedBefore
|
||||
}
|
||||
rebuildStart, err := service.ParseGroupUsageDate(rebuildStartDate)
|
||||
if err != nil {
|
||||
return err
|
||||
startDate := closedBefore
|
||||
if timezoneChanged || closedBefore <= retainedDate {
|
||||
var earliest sql.NullTime
|
||||
if err := scanSingleRow(ctx, q, `
|
||||
SELECT MIN(created_at)
|
||||
FROM usage_logs
|
||||
WHERE created_at >= $1
|
||||
`, []any{expiredBefore.UTC()}, &earliest); err != nil {
|
||||
return nil, fmt.Errorf("读取最早用量记录: %w", err)
|
||||
}
|
||||
retainedFrom = todayStart
|
||||
if earliest.Valid {
|
||||
retainedFrom = earliest.Time.UTC()
|
||||
}
|
||||
retainedDate = service.GroupUsageDate(retainedFrom)
|
||||
startDate = retainedDate
|
||||
}
|
||||
|
||||
if _, err := r.sql.ExecContext(ctx, `
|
||||
if _, err := q.ExecContext(ctx, `
|
||||
UPDATE usage_group_rollup_state
|
||||
SET closed_before = $1::date,
|
||||
retained_from = $2,
|
||||
timezone_name = $3,
|
||||
building_until = $4::date,
|
||||
build_dirty_from = NULL,
|
||||
updated_at = NOW()
|
||||
WHERE id = 1
|
||||
`, startDate, retainedFrom.UTC(), timezoneName, todayDate); err != nil {
|
||||
return nil, fmt.Errorf("登记分组用量汇总重建: %w", err)
|
||||
}
|
||||
|
||||
startTime, err := service.ParseGroupUsageDate(startDate)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rowsFrom := startTime.UTC()
|
||||
if expiredBefore.After(rowsFrom) {
|
||||
rowsFrom = expiredBefore.UTC()
|
||||
}
|
||||
return &groupUsageRollupBuildPlan{
|
||||
startDate: startDate,
|
||||
targetDate: todayDate,
|
||||
retainedDate: retainedDate,
|
||||
rowsFrom: rowsFrom,
|
||||
rowsBefore: todayStart.UTC(),
|
||||
timezoneName: timezoneName,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// buildGroupUsageRollups 重算 [startDate, targetDate) 的日桶,只写入本地日期不早于 startDate 的桶。
|
||||
// 状态行只持 FOR KEY SHARE,与 usage_logs 写入和失效触发器兼容;登记与发布的 FOR UPDATE 须等待本事务结束。
|
||||
func buildGroupUsageRollups(ctx context.Context, q sqlExecutor, plan *groupUsageRollupBuildPlan) error {
|
||||
var buildingUntil sql.NullString
|
||||
var stateTimezoneName string
|
||||
if err := scanSingleRow(ctx, q, `
|
||||
SELECT building_until::text, timezone_name
|
||||
FROM usage_group_rollup_state
|
||||
WHERE id = 1
|
||||
FOR KEY SHARE
|
||||
`, nil, &buildingUntil, &stateTimezoneName); err != nil {
|
||||
return fmt.Errorf("读取分组用量汇总重建登记: %w", err)
|
||||
}
|
||||
if !buildingUntil.Valid || buildingUntil.String != plan.targetDate || stateTimezoneName != plan.timezoneName {
|
||||
return errGroupUsageRollupBuildPreempted
|
||||
}
|
||||
|
||||
if _, err := q.ExecContext(ctx, `
|
||||
DELETE FROM usage_group_daily_rollups
|
||||
WHERE bucket_date < $1::date
|
||||
OR (bucket_date >= $2::date AND bucket_date < $3::date)
|
||||
OR bucket_date >= $3::date
|
||||
`, retainedDate, rebuildStartDate, todayDate); err != nil {
|
||||
OR bucket_date >= $2::date
|
||||
`, plan.retainedDate, plan.startDate); err != nil {
|
||||
return fmt.Errorf("清理分组用量日桶: %w", err)
|
||||
}
|
||||
|
||||
if _, err := r.sql.ExecContext(ctx, `
|
||||
if _, err := q.ExecContext(ctx, `
|
||||
INSERT INTO usage_group_daily_rollups (bucket_date, group_id, actual_cost, computed_at)
|
||||
SELECT
|
||||
(created_at AT TIME ZONE $3::text)::date AS bucket_date,
|
||||
@@ -260,51 +470,82 @@ func (r *dashboardAggregationRepository) syncGroupUsageRollupsInTx(ctx context.C
|
||||
WHERE group_id IS NOT NULL
|
||||
AND created_at >= $1
|
||||
AND created_at < $2
|
||||
AND (created_at AT TIME ZONE $3::text)::date >= $4::date
|
||||
GROUP BY 1, 2
|
||||
ON CONFLICT (bucket_date, group_id)
|
||||
DO UPDATE SET
|
||||
actual_cost = EXCLUDED.actual_cost,
|
||||
computed_at = EXCLUDED.computed_at
|
||||
`, rebuildStart.UTC(), todayStart.UTC(), timezoneName); err != nil {
|
||||
`, plan.rowsFrom, plan.rowsBefore, plan.timezoneName, plan.startDate); err != nil {
|
||||
return fmt.Errorf("重建分组用量日桶: %w", err)
|
||||
}
|
||||
|
||||
if _, err := r.sql.ExecContext(ctx, `
|
||||
UPDATE usage_group_rollup_state
|
||||
SET closed_before = $1::date,
|
||||
retained_from = $2,
|
||||
timezone_name = $3,
|
||||
updated_at = NOW()
|
||||
WHERE id = 1
|
||||
`, todayDate, retainedFrom, timezoneName); err != nil {
|
||||
return fmt.Errorf("更新分组用量汇总水位: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func lockGroupUsageRollupState(ctx context.Context, tx *sql.Tx) error {
|
||||
var id int16
|
||||
if err := tx.QueryRowContext(ctx, `
|
||||
SELECT id
|
||||
// publishGroupUsageRollups 在 FOR UPDATE 下发布本轮结果并清除登记,返回是否存在需要重算的脏区间。
|
||||
//
|
||||
// 登记之后 [startDate, targetDate) 内的源记录变更都记入了 build_dirty_from,[startDate, build_dirty_from)
|
||||
// 的日桶与计算快照一致;水位低于 startDate 说明有未记脏的失效,此时发布不越过当前水位。
|
||||
func publishGroupUsageRollups(ctx context.Context, q sqlExecutor, plan *groupUsageRollupBuildPlan) (bool, error) {
|
||||
var closedBefore string
|
||||
var buildingUntil sql.NullString
|
||||
var dirtyFrom sql.NullString
|
||||
if err := scanSingleRow(ctx, q, `
|
||||
SELECT closed_before::text, building_until::text, build_dirty_from::text
|
||||
FROM usage_group_rollup_state
|
||||
WHERE id = 1
|
||||
FOR UPDATE
|
||||
`).Scan(&id); err != nil {
|
||||
return fmt.Errorf("锁定分组用量汇总水位: %w", err)
|
||||
`, nil, &closedBefore, &buildingUntil, &dirtyFrom); err != nil {
|
||||
return false, fmt.Errorf("读取分组用量汇总重建登记: %w", err)
|
||||
}
|
||||
if !buildingUntil.Valid || buildingUntil.String != plan.targetDate {
|
||||
return false, errGroupUsageRollupBuildPreempted
|
||||
}
|
||||
|
||||
publishBefore := plan.targetDate
|
||||
dirty := false
|
||||
if dirtyFrom.Valid && dirtyFrom.String < publishBefore {
|
||||
publishBefore = dirtyFrom.String
|
||||
dirty = true
|
||||
}
|
||||
if closedBefore < plan.startDate && closedBefore < publishBefore {
|
||||
publishBefore = closedBefore
|
||||
dirty = true
|
||||
}
|
||||
|
||||
if _, err := q.ExecContext(ctx, `
|
||||
UPDATE usage_group_rollup_state
|
||||
SET closed_before = $1::date,
|
||||
building_until = NULL,
|
||||
build_dirty_from = NULL,
|
||||
updated_at = NOW()
|
||||
WHERE id = 1
|
||||
`, publishBefore); err != nil {
|
||||
return false, fmt.Errorf("发布分组用量汇总水位: %w", err)
|
||||
}
|
||||
return dirty, nil
|
||||
}
|
||||
|
||||
// expireGroupUsageRollupsBefore 把保留下界推进到 cutoff:早于 cutoff 的 usage_logs 不属于任何可读日桶,
|
||||
// 删除它们不触发失效。cutoff 须为服务端配置时区的自然日零点,使边界日桶不包含被删除的记录。
|
||||
func expireGroupUsageRollupsBefore(ctx context.Context, q sqlExecutor, cutoff time.Time) error {
|
||||
if _, err := q.ExecContext(ctx, `
|
||||
UPDATE usage_group_rollup_state
|
||||
SET expired_before = GREATEST(expired_before, $1),
|
||||
retained_from = GREATEST(retained_from, $1),
|
||||
updated_at = NOW()
|
||||
WHERE id = 1
|
||||
`, cutoff.UTC()); err != nil {
|
||||
return fmt.Errorf("推进分组用量汇总保留下界: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func invalidateGroupUsageRollupsAt(ctx context.Context, tx *sql.Tx, affectedAt time.Time) error {
|
||||
timezoneName := service.GroupUsageTimezoneName()
|
||||
_, err := tx.ExecContext(ctx, `
|
||||
UPDATE usage_group_rollup_state
|
||||
SET closed_before = LEAST(
|
||||
closed_before,
|
||||
($1::timestamptz AT TIME ZONE $2::text)::date
|
||||
),
|
||||
updated_at = NOW()
|
||||
WHERE id = 1
|
||||
`, affectedAt.UTC(), timezoneName)
|
||||
// invalidateGroupUsageRollupsAt 使 affectedAt 所在自然日及之后的日桶失效;早于保留下界的时刻不生效。
|
||||
func invalidateGroupUsageRollupsAt(ctx context.Context, q sqlExecutor, affectedAt time.Time) error {
|
||||
_, err := q.ExecContext(ctx,
|
||||
"SELECT invalidate_group_usage_rollups_at($1, $2)",
|
||||
affectedAt.UTC(), service.GroupUsageTimezoneName(),
|
||||
)
|
||||
return err
|
||||
}
|
||||
@@ -5,61 +5,146 @@ package repository
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"database/sql/driver"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/DATA-DOG/go-sqlmock"
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/lib/pq"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestDashboardAggregationRepositorySyncGroupUsageRollupsNoopsAtCurrentDate(t *testing.T) {
|
||||
const (
|
||||
groupRollupPrecheckQuery = `SELECT closed_before::text, timezone_name, building_until IS NULL`
|
||||
groupRollupLockQuery = `SELECT pg_try_advisory_lock\(hashtext\('usage_group_daily_rollups:build'\)\)`
|
||||
groupRollupUnlockQuery = `SELECT pg_advisory_unlock\(hashtext\('usage_group_daily_rollups:build'\)\)`
|
||||
groupRollupBeginQuery = `(?s)SELECT closed_before::text, retained_from, timezone_name, expired_before, building_until::text.*FOR UPDATE`
|
||||
groupRollupBuildQuery = `(?s)SELECT building_until::text, timezone_name.*FOR KEY SHARE`
|
||||
groupRollupPublishQuery = `(?s)SELECT closed_before::text, building_until::text, build_dirty_from::text.*FOR UPDATE`
|
||||
groupRollupRegisterExec = `(?s)UPDATE usage_group_rollup_state.*building_until = \$4::date`
|
||||
groupRollupPublishExec = `(?s)UPDATE usage_group_rollup_state.*SET closed_before = \$1::date,\s+building_until = NULL`
|
||||
groupRollupExpireExec = `(?s)UPDATE usage_group_rollup_state.*expired_before = GREATEST\(expired_before, \$1\)`
|
||||
groupRollupInvalidateSQL = `SELECT invalidate_group_usage_rollups_at\(\$1, \$2\)`
|
||||
)
|
||||
|
||||
var groupRollupEpoch = time.Unix(0, 0).UTC()
|
||||
|
||||
func expectGroupRollupPrecheck(mock sqlmock.Sqlmock, closedBefore, timezoneName string, idle bool) {
|
||||
mock.ExpectQuery(groupRollupPrecheckQuery).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"closed_before", "timezone_name", "idle"}).
|
||||
AddRow(closedBefore, timezoneName, idle))
|
||||
}
|
||||
|
||||
func expectGroupRollupLock(mock sqlmock.Sqlmock, locked bool) {
|
||||
mock.ExpectQuery(groupRollupLockQuery).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"locked"}).AddRow(locked))
|
||||
}
|
||||
|
||||
func expectGroupRollupUnlock(mock sqlmock.Sqlmock) {
|
||||
mock.ExpectQuery(groupRollupUnlockQuery).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"unlocked"}).AddRow(true))
|
||||
}
|
||||
|
||||
func groupRollupBeginRows(closedBefore string, retainedFrom time.Time, timezoneName string, expiredBefore time.Time, buildingUntil any) *sqlmock.Rows {
|
||||
return sqlmock.NewRows([]string{"closed_before", "retained_from", "timezone_name", "expired_before", "building_until"}).
|
||||
AddRow(closedBefore, retainedFrom, timezoneName, expiredBefore, buildingUntil)
|
||||
}
|
||||
|
||||
// expectGroupRollupRound 期望一轮完整的登记、计算、发布。
|
||||
func expectGroupRollupRound(
|
||||
mock sqlmock.Sqlmock,
|
||||
begin *sqlmock.Rows,
|
||||
minCreatedAt *sqlmock.Rows,
|
||||
minCreatedAfter time.Time,
|
||||
register []any,
|
||||
deleteArgs []any,
|
||||
insertArgs []any,
|
||||
publishRows *sqlmock.Rows,
|
||||
publishBefore string,
|
||||
) {
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectQuery(groupRollupBeginQuery).WillReturnRows(begin)
|
||||
if minCreatedAt != nil {
|
||||
mock.ExpectQuery(`(?s)SELECT MIN\(created_at\)\s+FROM usage_logs\s+WHERE created_at >= \$1`).
|
||||
WithArgs(minCreatedAfter).
|
||||
WillReturnRows(minCreatedAt)
|
||||
}
|
||||
mock.ExpectExec(groupRollupRegisterExec).
|
||||
WithArgs(toDriverValues(register)...).
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
mock.ExpectCommit()
|
||||
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectQuery(groupRollupBuildQuery).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"building_until", "timezone_name"}).AddRow(register[3], register[2]))
|
||||
mock.ExpectExec(`DELETE FROM usage_group_daily_rollups`).
|
||||
WithArgs(toDriverValues(deleteArgs)...).
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
mock.ExpectExec(`INSERT INTO usage_group_daily_rollups`).
|
||||
WithArgs(toDriverValues(append(append([]any{}, insertArgs...), register[0]))...).
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
mock.ExpectCommit()
|
||||
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectQuery(groupRollupPublishQuery).WillReturnRows(publishRows)
|
||||
mock.ExpectExec(groupRollupPublishExec).
|
||||
WithArgs(publishBefore).
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
mock.ExpectCommit()
|
||||
}
|
||||
|
||||
func toDriverValues(values []any) []driver.Value {
|
||||
args := make([]driver.Value, 0, len(values))
|
||||
for _, value := range values {
|
||||
args = append(args, sqlmockValue{value: value})
|
||||
}
|
||||
return args
|
||||
}
|
||||
|
||||
// sqlmockValue 按时刻比较 time.Time(忽略 Location),其余值按相等比较。
|
||||
type sqlmockValue struct{ value any }
|
||||
|
||||
func (v sqlmockValue) Match(actual driver.Value) bool {
|
||||
if expectedTime, ok := v.value.(time.Time); ok {
|
||||
actualTime, ok := actual.(time.Time)
|
||||
return ok && actualTime.Equal(expectedTime)
|
||||
}
|
||||
return actual == v.value
|
||||
}
|
||||
|
||||
func publishRows(closedBefore, buildingUntil string, dirtyFrom any) *sqlmock.Rows {
|
||||
return sqlmock.NewRows([]string{"closed_before", "building_until", "build_dirty_from"}).
|
||||
AddRow(closedBefore, buildingUntil, dirtyFrom)
|
||||
}
|
||||
|
||||
func TestDashboardAggregationRepositorySyncGroupUsageRollupsNoopsWithoutLockingAtCurrentDate(t *testing.T) {
|
||||
setGroupUsageRollupTestTimezone(t)
|
||||
db, mock := newSQLMock(t)
|
||||
repo := newDashboardAggregationRepositoryWithSQL(db)
|
||||
todayStart := time.Date(2026, 8, 13, 16, 0, 0, 0, time.UTC)
|
||||
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectQuery(`SELECT closed_before::text, retained_from.*FOR UPDATE`).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"closed_before", "retained_from", "timezone_name"}).
|
||||
AddRow("2026-08-14", time.Unix(0, 0).UTC(), "Asia/Shanghai"))
|
||||
mock.ExpectCommit()
|
||||
expectGroupRollupPrecheck(mock, "2026-08-14", "Asia/Shanghai", true)
|
||||
|
||||
require.NoError(t, repo.SyncGroupUsageRollups(context.Background(), todayStart))
|
||||
require.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
|
||||
func TestDashboardAggregationRepositorySyncGroupUsageRollupsRebuildsWhenTimezoneChanges(t *testing.T) {
|
||||
useGroupUsageRepositoryTestTimezone(t, "America/New_York")
|
||||
|
||||
func TestDashboardAggregationRepositorySyncGroupUsageRollupsSkipsWhenAnotherBuildHoldsLock(t *testing.T) {
|
||||
setGroupUsageRollupTestTimezone(t)
|
||||
db, mock := newSQLMock(t)
|
||||
repo := newDashboardAggregationRepositoryWithSQL(db)
|
||||
todayStart := time.Date(2026, 3, 9, 4, 0, 0, 0, time.UTC)
|
||||
retainedFrom := time.Date(2026, 3, 1, 5, 0, 0, 0, time.UTC)
|
||||
todayStart := time.Date(2026, 8, 13, 16, 0, 0, 0, time.UTC)
|
||||
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectQuery(`SELECT closed_before::text, retained_from.*FOR UPDATE`).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"closed_before", "retained_from", "timezone_name"}).
|
||||
AddRow("2026-03-09", time.Unix(0, 0).UTC(), "Asia/Shanghai"))
|
||||
mock.ExpectQuery(`SELECT MIN\(created_at\) FROM usage_logs`).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"min"}).AddRow(retainedFrom))
|
||||
mock.ExpectExec(`DELETE FROM usage_group_daily_rollups`).
|
||||
WithArgs("2026-03-01", "2026-03-01", "2026-03-09").
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
mock.ExpectExec(`INSERT INTO usage_group_daily_rollups`).
|
||||
WithArgs(retainedFrom, todayStart, "America/New_York").
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
mock.ExpectExec(`UPDATE usage_group_rollup_state`).
|
||||
WithArgs("2026-03-09", retainedFrom, "America/New_York").
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
mock.ExpectCommit()
|
||||
expectGroupRollupPrecheck(mock, "2026-08-13", "Asia/Shanghai", true)
|
||||
expectGroupRollupLock(mock, false)
|
||||
|
||||
require.NoError(t, repo.SyncGroupUsageRollups(context.Background(), todayStart))
|
||||
require.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
|
||||
func TestDashboardAggregationRepositorySyncGroupUsageRollupsPublishesWatermarkLast(t *testing.T) {
|
||||
func TestDashboardAggregationRepositorySyncGroupUsageRollupsBuildsAndPublishesInSeparateTransactions(t *testing.T) {
|
||||
setGroupUsageRollupTestTimezone(t)
|
||||
db, mock := newSQLMock(t)
|
||||
repo := newDashboardAggregationRepositoryWithSQL(db)
|
||||
@@ -67,22 +152,209 @@ func TestDashboardAggregationRepositorySyncGroupUsageRollupsPublishesWatermarkLa
|
||||
retainedFrom := time.Date(2026, 5, 1, 3, 0, 0, 0, time.UTC)
|
||||
rebuildStart := time.Date(2026, 8, 12, 16, 0, 0, 0, time.UTC)
|
||||
|
||||
expectGroupRollupPrecheck(mock, "2026-08-13", "Asia/Shanghai", true)
|
||||
expectGroupRollupLock(mock, true)
|
||||
expectGroupRollupRound(mock,
|
||||
groupRollupBeginRows("2026-08-13", retainedFrom, "Asia/Shanghai", groupRollupEpoch, nil),
|
||||
nil, time.Time{},
|
||||
[]any{"2026-08-13", retainedFrom, "Asia/Shanghai", "2026-08-14"},
|
||||
[]any{"2026-05-01", "2026-08-13"},
|
||||
[]any{rebuildStart, todayStart, "Asia/Shanghai"},
|
||||
publishRows("2026-08-13", "2026-08-14", nil),
|
||||
"2026-08-14",
|
||||
)
|
||||
expectGroupRollupUnlock(mock)
|
||||
|
||||
require.NoError(t, repo.SyncGroupUsageRollups(context.Background(), todayStart))
|
||||
require.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
|
||||
func TestDashboardAggregationRepositorySyncGroupUsageRollupsRebuildsDirtyRangeBeforeFullPublish(t *testing.T) {
|
||||
setGroupUsageRollupTestTimezone(t)
|
||||
db, mock := newSQLMock(t)
|
||||
repo := newDashboardAggregationRepositoryWithSQL(db)
|
||||
todayStart := time.Date(2026, 8, 13, 16, 0, 0, 0, time.UTC)
|
||||
retainedFrom := time.Date(2026, 5, 1, 3, 0, 0, 0, time.UTC)
|
||||
|
||||
expectGroupRollupPrecheck(mock, "2026-08-11", "Asia/Shanghai", true)
|
||||
expectGroupRollupLock(mock, true)
|
||||
// 第一轮计算期间有 08-12 的迟到写入:只发布到 08-12。
|
||||
expectGroupRollupRound(mock,
|
||||
groupRollupBeginRows("2026-08-11", retainedFrom, "Asia/Shanghai", groupRollupEpoch, nil),
|
||||
nil, time.Time{},
|
||||
[]any{"2026-08-11", retainedFrom, "Asia/Shanghai", "2026-08-14"},
|
||||
[]any{"2026-05-01", "2026-08-11"},
|
||||
[]any{time.Date(2026, 8, 10, 16, 0, 0, 0, time.UTC), todayStart, "Asia/Shanghai"},
|
||||
publishRows("2026-08-11", "2026-08-14", "2026-08-12"),
|
||||
"2026-08-12",
|
||||
)
|
||||
// 第二轮只重算脏日期之后的区间。
|
||||
expectGroupRollupRound(mock,
|
||||
groupRollupBeginRows("2026-08-12", retainedFrom, "Asia/Shanghai", groupRollupEpoch, nil),
|
||||
nil, time.Time{},
|
||||
[]any{"2026-08-12", retainedFrom, "Asia/Shanghai", "2026-08-14"},
|
||||
[]any{"2026-05-01", "2026-08-12"},
|
||||
[]any{time.Date(2026, 8, 11, 16, 0, 0, 0, time.UTC), todayStart, "Asia/Shanghai"},
|
||||
publishRows("2026-08-12", "2026-08-14", nil),
|
||||
"2026-08-14",
|
||||
)
|
||||
expectGroupRollupUnlock(mock)
|
||||
|
||||
require.NoError(t, repo.SyncGroupUsageRollups(context.Background(), todayStart))
|
||||
require.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
|
||||
func TestDashboardAggregationRepositorySyncGroupUsageRollupsStopsAfterMaxRoundsWithoutOverPublishing(t *testing.T) {
|
||||
setGroupUsageRollupTestTimezone(t)
|
||||
db, mock := newSQLMock(t)
|
||||
repo := newDashboardAggregationRepositoryWithSQL(db)
|
||||
todayStart := time.Date(2026, 8, 13, 16, 0, 0, 0, time.UTC)
|
||||
retainedFrom := time.Date(2026, 5, 1, 3, 0, 0, 0, time.UTC)
|
||||
|
||||
expectGroupRollupPrecheck(mock, "2026-08-12", "Asia/Shanghai", true)
|
||||
expectGroupRollupLock(mock, true)
|
||||
for range groupUsageRollupBuildMaxRounds {
|
||||
expectGroupRollupRound(mock,
|
||||
groupRollupBeginRows("2026-08-12", retainedFrom, "Asia/Shanghai", groupRollupEpoch, nil),
|
||||
nil, time.Time{},
|
||||
[]any{"2026-08-12", retainedFrom, "Asia/Shanghai", "2026-08-14"},
|
||||
[]any{"2026-05-01", "2026-08-12"},
|
||||
[]any{time.Date(2026, 8, 11, 16, 0, 0, 0, time.UTC), todayStart, "Asia/Shanghai"},
|
||||
publishRows("2026-08-12", "2026-08-14", "2026-08-12"),
|
||||
"2026-08-12",
|
||||
)
|
||||
}
|
||||
expectGroupRollupUnlock(mock)
|
||||
|
||||
require.NoError(t, repo.SyncGroupUsageRollups(context.Background(), todayStart))
|
||||
require.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
|
||||
func TestDashboardAggregationRepositorySyncGroupUsageRollupsPublishKeepsUnmarkedInvalidation(t *testing.T) {
|
||||
setGroupUsageRollupTestTimezone(t)
|
||||
db, mock := newSQLMock(t)
|
||||
repo := newDashboardAggregationRepositoryWithSQL(db)
|
||||
todayStart := time.Date(2026, 8, 13, 16, 0, 0, 0, time.UTC)
|
||||
retainedFrom := time.Date(2026, 5, 1, 3, 0, 0, 0, time.UTC)
|
||||
|
||||
expectGroupRollupPrecheck(mock, "2026-08-13", "Asia/Shanghai", true)
|
||||
expectGroupRollupLock(mock, true)
|
||||
// 计算期间水位被后退到 08-10 而没有记脏:发布不越过 08-10。
|
||||
expectGroupRollupRound(mock,
|
||||
groupRollupBeginRows("2026-08-13", retainedFrom, "Asia/Shanghai", groupRollupEpoch, nil),
|
||||
nil, time.Time{},
|
||||
[]any{"2026-08-13", retainedFrom, "Asia/Shanghai", "2026-08-14"},
|
||||
[]any{"2026-05-01", "2026-08-13"},
|
||||
[]any{time.Date(2026, 8, 12, 16, 0, 0, 0, time.UTC), todayStart, "Asia/Shanghai"},
|
||||
publishRows("2026-08-10", "2026-08-14", nil),
|
||||
"2026-08-10",
|
||||
)
|
||||
expectGroupRollupRound(mock,
|
||||
groupRollupBeginRows("2026-08-10", retainedFrom, "Asia/Shanghai", groupRollupEpoch, nil),
|
||||
nil, time.Time{},
|
||||
[]any{"2026-08-10", retainedFrom, "Asia/Shanghai", "2026-08-14"},
|
||||
[]any{"2026-05-01", "2026-08-10"},
|
||||
[]any{time.Date(2026, 8, 9, 16, 0, 0, 0, time.UTC), todayStart, "Asia/Shanghai"},
|
||||
publishRows("2026-08-10", "2026-08-14", nil),
|
||||
"2026-08-14",
|
||||
)
|
||||
expectGroupRollupUnlock(mock)
|
||||
|
||||
require.NoError(t, repo.SyncGroupUsageRollups(context.Background(), todayStart))
|
||||
require.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
|
||||
func TestDashboardAggregationRepositorySyncGroupUsageRollupsRebuildsWhenTimezoneChanges(t *testing.T) {
|
||||
useGroupUsageRepositoryTestTimezone(t, "America/New_York")
|
||||
db, mock := newSQLMock(t)
|
||||
repo := newDashboardAggregationRepositoryWithSQL(db)
|
||||
todayStart := time.Date(2026, 3, 9, 4, 0, 0, 0, time.UTC)
|
||||
retainedFrom := time.Date(2026, 3, 1, 5, 0, 0, 0, time.UTC)
|
||||
|
||||
expectGroupRollupPrecheck(mock, "2026-03-09", "Asia/Shanghai", true)
|
||||
expectGroupRollupLock(mock, true)
|
||||
expectGroupRollupRound(mock,
|
||||
groupRollupBeginRows("2026-03-09", groupRollupEpoch, "Asia/Shanghai", groupRollupEpoch, nil),
|
||||
sqlmock.NewRows([]string{"min"}).AddRow(retainedFrom), groupRollupEpoch,
|
||||
[]any{"2026-03-01", retainedFrom, "America/New_York", "2026-03-09"},
|
||||
[]any{"2026-03-01", "2026-03-01"},
|
||||
[]any{retainedFrom, todayStart, "America/New_York"},
|
||||
publishRows("2026-03-01", "2026-03-09", nil),
|
||||
"2026-03-09",
|
||||
)
|
||||
expectGroupRollupUnlock(mock)
|
||||
|
||||
require.NoError(t, repo.SyncGroupUsageRollups(context.Background(), todayStart))
|
||||
require.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
|
||||
func TestDashboardAggregationRepositorySyncGroupUsageRollupsFullRebuildExcludesExpiredRows(t *testing.T) {
|
||||
setGroupUsageRollupTestTimezone(t)
|
||||
db, mock := newSQLMock(t)
|
||||
repo := newDashboardAggregationRepositoryWithSQL(db)
|
||||
todayStart := time.Date(2026, 8, 13, 16, 0, 0, 0, time.UTC)
|
||||
// 保留下界不在 Asia/Shanghai 的日界上(例如在其他时区下推进):重建只计入下界之后的记录。
|
||||
expiredBefore := time.Date(2026, 5, 1, 18, 0, 0, 0, time.UTC)
|
||||
earliestRetained := time.Date(2026, 5, 1, 19, 0, 0, 0, time.UTC)
|
||||
|
||||
expectGroupRollupPrecheck(mock, "1970-01-01", "Asia/Shanghai", true)
|
||||
expectGroupRollupLock(mock, true)
|
||||
expectGroupRollupRound(mock,
|
||||
groupRollupBeginRows("1970-01-01", groupRollupEpoch, "Asia/Shanghai", expiredBefore, nil),
|
||||
sqlmock.NewRows([]string{"min"}).AddRow(earliestRetained), expiredBefore,
|
||||
[]any{"2026-05-02", earliestRetained, "Asia/Shanghai", "2026-08-14"},
|
||||
[]any{"2026-05-02", "2026-05-02"},
|
||||
[]any{expiredBefore, todayStart, "Asia/Shanghai"},
|
||||
publishRows("2026-05-02", "2026-08-14", nil),
|
||||
"2026-08-14",
|
||||
)
|
||||
expectGroupRollupUnlock(mock)
|
||||
|
||||
require.NoError(t, repo.SyncGroupUsageRollups(context.Background(), todayStart))
|
||||
require.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
|
||||
func TestDashboardAggregationRepositorySyncGroupUsageRollupsKeepsRetainedFromAtExpiredFloor(t *testing.T) {
|
||||
setGroupUsageRollupTestTimezone(t)
|
||||
db, mock := newSQLMock(t)
|
||||
repo := newDashboardAggregationRepositoryWithSQL(db)
|
||||
todayStart := time.Date(2026, 8, 13, 16, 0, 0, 0, time.UTC)
|
||||
staleRetainedFrom := time.Date(2026, 5, 1, 3, 0, 0, 0, time.UTC)
|
||||
expiredBefore := time.Date(2026, 5, 14, 16, 0, 0, 0, time.UTC)
|
||||
|
||||
expectGroupRollupPrecheck(mock, "2026-08-13", "Asia/Shanghai", true)
|
||||
expectGroupRollupLock(mock, true)
|
||||
// retained_from 早于保留下界(例如被其他版本的同步改写):登记与清理都以保留下界为起点。
|
||||
expectGroupRollupRound(mock,
|
||||
groupRollupBeginRows("2026-08-13", staleRetainedFrom, "Asia/Shanghai", expiredBefore, nil),
|
||||
nil, time.Time{},
|
||||
[]any{"2026-08-13", expiredBefore, "Asia/Shanghai", "2026-08-14"},
|
||||
[]any{"2026-05-15", "2026-08-13"},
|
||||
[]any{time.Date(2026, 8, 12, 16, 0, 0, 0, time.UTC), todayStart, "Asia/Shanghai"},
|
||||
publishRows("2026-08-13", "2026-08-14", nil),
|
||||
"2026-08-14",
|
||||
)
|
||||
expectGroupRollupUnlock(mock)
|
||||
|
||||
require.NoError(t, repo.SyncGroupUsageRollups(context.Background(), todayStart))
|
||||
require.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
|
||||
func TestDashboardAggregationRepositorySyncGroupUsageRollupsClearsStaleBuildMarkWhenPublished(t *testing.T) {
|
||||
setGroupUsageRollupTestTimezone(t)
|
||||
db, mock := newSQLMock(t)
|
||||
repo := newDashboardAggregationRepositoryWithSQL(db)
|
||||
todayStart := time.Date(2026, 8, 13, 16, 0, 0, 0, time.UTC)
|
||||
|
||||
expectGroupRollupPrecheck(mock, "2026-08-14", "Asia/Shanghai", false)
|
||||
expectGroupRollupLock(mock, true)
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectQuery(`SELECT closed_before::text, retained_from.*FOR UPDATE`).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"closed_before", "retained_from", "timezone_name"}).
|
||||
AddRow("2026-08-13", time.Unix(0, 0).UTC(), "Asia/Shanghai"))
|
||||
mock.ExpectQuery(`SELECT MIN\(created_at\) FROM usage_logs`).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"min"}).AddRow(retainedFrom))
|
||||
mock.ExpectExec(`DELETE FROM usage_group_daily_rollups`).
|
||||
WithArgs("2026-05-01", "2026-08-13", "2026-08-14").
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
mock.ExpectExec(`INSERT INTO usage_group_daily_rollups`).
|
||||
WithArgs(rebuildStart, todayStart, "Asia/Shanghai").
|
||||
WillReturnResult(sqlmock.NewResult(0, 2))
|
||||
mock.ExpectExec(`UPDATE usage_group_rollup_state`).
|
||||
WithArgs("2026-08-14", retainedFrom, "Asia/Shanghai").
|
||||
mock.ExpectQuery(groupRollupBeginQuery).
|
||||
WillReturnRows(groupRollupBeginRows("2026-08-14", groupRollupEpoch, "Asia/Shanghai", groupRollupEpoch, "2026-08-14"))
|
||||
mock.ExpectExec(`(?s)UPDATE usage_group_rollup_state\s+SET building_until = NULL`).
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
mock.ExpectCommit()
|
||||
expectGroupRollupUnlock(mock)
|
||||
|
||||
require.NoError(t, repo.SyncGroupUsageRollups(context.Background(), todayStart))
|
||||
require.NoError(t, mock.ExpectationsWereMet())
|
||||
@@ -94,17 +366,44 @@ func TestDashboardAggregationRepositorySyncGroupUsageRollupsRejectsFutureWaterma
|
||||
repo := newDashboardAggregationRepositoryWithSQL(db)
|
||||
todayStart := time.Date(2026, 8, 13, 16, 0, 0, 0, time.UTC)
|
||||
|
||||
expectGroupRollupPrecheck(mock, "2026-08-15", "Asia/Shanghai", true)
|
||||
expectGroupRollupLock(mock, true)
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectQuery(`SELECT closed_before::text, retained_from.*FOR UPDATE`).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"closed_before", "retained_from", "timezone_name"}).
|
||||
AddRow("2026-08-15", time.Unix(0, 0).UTC(), "Asia/Shanghai"))
|
||||
mock.ExpectQuery(groupRollupBeginQuery).
|
||||
WillReturnRows(groupRollupBeginRows("2026-08-15", groupRollupEpoch, "Asia/Shanghai", groupRollupEpoch, nil))
|
||||
mock.ExpectRollback()
|
||||
expectGroupRollupUnlock(mock)
|
||||
|
||||
err := repo.SyncGroupUsageRollups(context.Background(), todayStart)
|
||||
require.ErrorContains(t, err, "未来")
|
||||
require.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
|
||||
func TestDashboardAggregationRepositorySyncGroupUsageRollupsAbortsWhenBuildMarkReplaced(t *testing.T) {
|
||||
setGroupUsageRollupTestTimezone(t)
|
||||
db, mock := newSQLMock(t)
|
||||
repo := newDashboardAggregationRepositoryWithSQL(db)
|
||||
todayStart := time.Date(2026, 8, 13, 16, 0, 0, 0, time.UTC)
|
||||
retainedFrom := time.Date(2026, 5, 1, 3, 0, 0, 0, time.UTC)
|
||||
|
||||
expectGroupRollupPrecheck(mock, "2026-08-13", "Asia/Shanghai", true)
|
||||
expectGroupRollupLock(mock, true)
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectQuery(groupRollupBeginQuery).
|
||||
WillReturnRows(groupRollupBeginRows("2026-08-13", retainedFrom, "Asia/Shanghai", groupRollupEpoch, nil))
|
||||
mock.ExpectExec(groupRollupRegisterExec).WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
mock.ExpectCommit()
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectQuery(groupRollupBuildQuery).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"building_until", "timezone_name"}).AddRow(nil, "Asia/Shanghai"))
|
||||
mock.ExpectRollback()
|
||||
expectGroupRollupUnlock(mock)
|
||||
|
||||
err := repo.SyncGroupUsageRollups(context.Background(), todayStart)
|
||||
require.ErrorIs(t, err, errGroupUsageRollupBuildPreempted)
|
||||
require.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
|
||||
func TestDashboardAggregationRepositoryRecomputeRangeInvalidatesGroupRollupsBeforeDashboardRebuild(t *testing.T) {
|
||||
setGroupUsageRollupTestTimezone(t)
|
||||
db, mock := newSQLMock(t)
|
||||
@@ -112,12 +411,10 @@ func TestDashboardAggregationRepositoryRecomputeRangeInvalidatesGroupRollupsBefo
|
||||
start := time.Date(2026, 8, 1, 3, 0, 0, 0, time.UTC)
|
||||
end := start.Add(time.Hour)
|
||||
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectQuery(`SELECT id FROM usage_group_rollup_state.*FOR UPDATE`).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(1))
|
||||
mock.ExpectExec(`UPDATE usage_group_rollup_state`).
|
||||
mock.ExpectExec(groupRollupInvalidateSQL).
|
||||
WithArgs(start, "Asia/Shanghai").
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
WillReturnResult(sqlmock.NewResult(0, 0))
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectExec(`DELETE FROM usage_dashboard_hourly`).
|
||||
WillReturnError(sql.ErrConnDone)
|
||||
mock.ExpectRollback()
|
||||
@@ -127,25 +424,17 @@ func TestDashboardAggregationRepositoryRecomputeRangeInvalidatesGroupRollupsBefo
|
||||
require.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
|
||||
func TestDashboardAggregationRepositoryRecomputeRangeRebuildsGroupRollupsBeforeCommit(t *testing.T) {
|
||||
func TestDashboardAggregationRepositoryRecomputeRangeLeavesGroupRollupRebuildToSync(t *testing.T) {
|
||||
setGroupUsageRollupTestTimezone(t)
|
||||
db, mock := newSQLMock(t)
|
||||
repo := newDashboardAggregationRepositoryWithSQL(db)
|
||||
start := time.Date(2026, 8, 1, 3, 0, 0, 0, time.UTC)
|
||||
end := start.Add(time.Hour)
|
||||
fixedNow := time.Date(2026, 8, 14, 8, 0, 0, 0, time.UTC)
|
||||
repo.clock = func() time.Time { return fixedNow }
|
||||
todayStart := service.GroupUsageTodayStart(fixedNow)
|
||||
startDate := service.GroupUsageDate(start)
|
||||
rebuildStart, err := service.ParseGroupUsageDate(startDate)
|
||||
require.NoError(t, err)
|
||||
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectQuery(`SELECT id FROM usage_group_rollup_state.*FOR UPDATE`).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(1))
|
||||
mock.ExpectExec(`UPDATE usage_group_rollup_state`).
|
||||
mock.ExpectExec(groupRollupInvalidateSQL).
|
||||
WithArgs(start, "Asia/Shanghai").
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
WillReturnResult(sqlmock.NewResult(0, 0))
|
||||
mock.ExpectBegin()
|
||||
for _, query := range []string{
|
||||
`DELETE FROM usage_dashboard_hourly WHERE`,
|
||||
`DELETE FROM usage_dashboard_hourly_users WHERE`,
|
||||
@@ -158,71 +447,67 @@ func TestDashboardAggregationRepositoryRecomputeRangeRebuildsGroupRollupsBeforeC
|
||||
} {
|
||||
mock.ExpectExec(query).WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
}
|
||||
mock.ExpectQuery(`SELECT closed_before::text, retained_from.*FOR UPDATE`).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"closed_before", "retained_from", "timezone_name"}).
|
||||
AddRow(startDate, time.Unix(0, 0).UTC(), "Asia/Shanghai"))
|
||||
mock.ExpectQuery(`SELECT MIN\(created_at\) FROM usage_logs`).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"min"}).AddRow(start))
|
||||
mock.ExpectExec(`DELETE FROM usage_group_daily_rollups`).
|
||||
WithArgs(startDate, startDate, service.GroupUsageDate(todayStart)).
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
mock.ExpectExec(`INSERT INTO usage_group_daily_rollups`).
|
||||
WithArgs(rebuildStart.UTC(), todayStart.UTC(), "Asia/Shanghai").
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
mock.ExpectExec(`UPDATE usage_group_rollup_state`).
|
||||
WithArgs(service.GroupUsageDate(todayStart), start, "Asia/Shanghai").
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
mock.ExpectCommit()
|
||||
|
||||
require.NoError(t, repo.RecomputeRange(context.Background(), start, end))
|
||||
require.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
|
||||
func TestDashboardAggregationRepositoryCleanupUsageLogsNonPartitionedInvalidatesEachBatchAndSyncs(t *testing.T) {
|
||||
func TestDashboardAggregationRepositoryRecomputeRangeStopsWhenInvalidationFails(t *testing.T) {
|
||||
setGroupUsageRollupTestTimezone(t)
|
||||
db, mock := newSQLMock(t)
|
||||
repo := newDashboardAggregationRepositoryWithSQL(db)
|
||||
cutoff := time.Date(2026, 7, 1, 0, 0, 0, 0, time.UTC)
|
||||
earliestDeletedAt := time.Date(2026, 5, 3, 2, 0, 0, 0, time.UTC)
|
||||
start := time.Date(2026, 8, 1, 3, 0, 0, 0, time.UTC)
|
||||
|
||||
mock.ExpectExec(groupRollupInvalidateSQL).
|
||||
WithArgs(start, "Asia/Shanghai").
|
||||
WillReturnError(sql.ErrConnDone)
|
||||
|
||||
err := repo.RecomputeRange(context.Background(), start, start.Add(time.Hour))
|
||||
require.ErrorIs(t, err, sql.ErrConnDone)
|
||||
require.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
|
||||
func TestDashboardAggregationRepositoryCleanupUsageLogsExpiresWholeDaysBeforeDeleting(t *testing.T) {
|
||||
setGroupUsageRollupTestTimezone(t)
|
||||
db, mock := newSQLMock(t)
|
||||
repo := newDashboardAggregationRepositoryWithSQL(db)
|
||||
// 2026-07-01 13:00 +08 对齐到 2026-07-01 00:00 +08。
|
||||
cutoff := time.Date(2026, 7, 1, 5, 0, 0, 0, time.UTC)
|
||||
alignedCutoff := time.Date(2026, 6, 30, 16, 0, 0, 0, time.UTC)
|
||||
fixedNow := time.Date(2026, 8, 14, 8, 0, 0, 0, time.UTC)
|
||||
repo.clock = func() time.Time { return fixedNow }
|
||||
todayStart := service.GroupUsageTodayStart(fixedNow)
|
||||
|
||||
mock.ExpectExec(groupRollupExpireExec).
|
||||
WithArgs(alignedCutoff).
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
mock.ExpectQuery(`SELECT EXISTS`).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"exists"}).AddRow(false))
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectQuery(`SELECT id FROM usage_group_rollup_state.*FOR UPDATE`).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(1))
|
||||
mock.ExpectQuery(`(?s)DELETE FROM usage_logs.*RETURNING created_at`).
|
||||
WithArgs(cutoff, usageLogsCleanupBatchSize).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"created_at"}).
|
||||
AddRow(earliestDeletedAt.Add(time.Hour)).
|
||||
AddRow(earliestDeletedAt))
|
||||
mock.ExpectExec(`UPDATE usage_group_rollup_state`).
|
||||
WithArgs(earliestDeletedAt, "Asia/Shanghai").
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
mock.ExpectCommit()
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectQuery(`SELECT closed_before::text, retained_from.*FOR UPDATE`).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"closed_before", "retained_from", "timezone_name"}).
|
||||
AddRow(service.GroupUsageDate(todayStart), time.Unix(0, 0).UTC(), "Asia/Shanghai"))
|
||||
mock.ExpectCommit()
|
||||
mock.ExpectExec(`(?s)SELECT tableoid, ctid.*ORDER BY created_at ASC, id ASC.*DELETE FROM usage_logs`).
|
||||
WithArgs(alignedCutoff, usageLogsCleanupBatchSize).
|
||||
WillReturnResult(sqlmock.NewResult(0, usageLogsCleanupBatchSize))
|
||||
mock.ExpectExec(`(?s)SELECT tableoid, ctid.*DELETE FROM usage_logs`).
|
||||
WithArgs(alignedCutoff, usageLogsCleanupBatchSize).
|
||||
WillReturnResult(sqlmock.NewResult(0, 3))
|
||||
expectGroupRollupPrecheck(mock, service.GroupUsageDate(service.GroupUsageTodayStart(fixedNow)), "Asia/Shanghai", true)
|
||||
|
||||
require.NoError(t, repo.CleanupUsageLogs(context.Background(), cutoff))
|
||||
require.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
|
||||
func TestDashboardAggregationRepositoryCleanupUsageLogsPartitionedSortsAndInvalidatesEachDropBeforeSync(t *testing.T) {
|
||||
setGroupUsageRollupTestTimezone(t)
|
||||
func TestDashboardAggregationRepositoryCleanupUsageLogsPartitionedInvalidatesRetainedRowsAfterDrop(t *testing.T) {
|
||||
useGroupUsageRepositoryTestTimezone(t, "UTC")
|
||||
db, mock := newSQLMock(t)
|
||||
repo := newDashboardAggregationRepositoryWithSQL(db)
|
||||
cutoff := time.Date(2026, 7, 18, 0, 0, 0, 0, time.UTC)
|
||||
aprilStart := time.Date(2026, 4, 1, 0, 0, 0, 0, time.UTC)
|
||||
juneStart := time.Date(2026, 6, 1, 0, 0, 0, 0, time.UTC)
|
||||
fixedNow := time.Date(2026, 8, 14, 8, 0, 0, 0, time.UTC)
|
||||
cutoff := time.Date(2026, 7, 1, 0, 0, 0, 0, time.UTC)
|
||||
fixedNow := time.Date(2026, 9, 29, 8, 0, 0, 0, time.UTC)
|
||||
repo.clock = func() time.Time { return fixedNow }
|
||||
todayStart := service.GroupUsageTodayStart(fixedNow)
|
||||
// 6 月分区建于 UTC-5 会话时区,上界是 07-01 05:00 UTC,包含保留下界之后的记录。
|
||||
retainedInJunePartition := time.Date(2026, 7, 1, 3, 0, 0, 0, time.UTC)
|
||||
|
||||
mock.ExpectExec(groupRollupExpireExec).
|
||||
WithArgs(cutoff).
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
mock.ExpectQuery(`SELECT EXISTS`).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"exists"}).AddRow(true))
|
||||
mock.ExpectQuery(`SELECT c.relname`).
|
||||
@@ -232,78 +517,120 @@ func TestDashboardAggregationRepositoryCleanupUsageLogsPartitionedSortsAndInvali
|
||||
AddRow("usage_logs_202604").
|
||||
AddRow("usage_logs_202607"))
|
||||
|
||||
for _, partition := range []struct {
|
||||
name string
|
||||
start time.Time
|
||||
}{
|
||||
{name: "usage_logs_202604", start: aprilStart},
|
||||
{name: "usage_logs_202606", start: juneStart},
|
||||
} {
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectQuery(`SELECT id FROM usage_group_rollup_state.*FOR UPDATE`).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(1))
|
||||
mock.ExpectExec(`UPDATE usage_group_rollup_state`).
|
||||
WithArgs(partition.start, "Asia/Shanghai").
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
mock.ExpectExec(`DROP TABLE IF EXISTS "` + partition.name + `"`).
|
||||
WillReturnResult(sqlmock.NewResult(0, 0))
|
||||
mock.ExpectCommit()
|
||||
}
|
||||
// The boundary partition is pruned by exact timestamp. tableoid is required
|
||||
// because ctid alone can also identify a retained row in another partition.
|
||||
// 4 月分区全部早于保留下界:直接删除。
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectQuery(`SELECT id FROM usage_group_rollup_state.*FOR UPDATE`).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(1))
|
||||
mock.ExpectQuery(`(?s)SELECT tableoid, ctid.*WHERE created_at < \$1.*WHERE \(tableoid, ctid\) IN.*RETURNING created_at`).
|
||||
mock.ExpectExec(`SET LOCAL lock_timeout = '3000ms'`).WillReturnResult(sqlmock.NewResult(0, 0))
|
||||
mock.ExpectQuery(`(?s)SELECT expired_before\s+FROM usage_group_rollup_state.*FOR KEY SHARE`).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"expired_before"}).AddRow(cutoff))
|
||||
mock.ExpectQuery(`SELECT MIN\(created_at\) FROM "usage_logs_202604" WHERE created_at >= \$1`).
|
||||
WithArgs(cutoff).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"min"}).AddRow(nil))
|
||||
mock.ExpectExec(`DROP TABLE IF EXISTS "usage_logs_202604"`).
|
||||
WillReturnResult(sqlmock.NewResult(0, 0))
|
||||
mock.ExpectCommit()
|
||||
// 6 月分区含保留下界之后的记录:删除后按其中最早时刻失效。
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectExec(`SET LOCAL lock_timeout = '3000ms'`).WillReturnResult(sqlmock.NewResult(0, 0))
|
||||
mock.ExpectQuery(`(?s)SELECT expired_before\s+FROM usage_group_rollup_state.*FOR KEY SHARE`).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"expired_before"}).AddRow(cutoff))
|
||||
mock.ExpectQuery(`SELECT MIN\(created_at\) FROM "usage_logs_202606" WHERE created_at >= \$1`).
|
||||
WithArgs(cutoff).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"min"}).AddRow(retainedInJunePartition))
|
||||
mock.ExpectExec(`DROP TABLE IF EXISTS "usage_logs_202606"`).
|
||||
WillReturnResult(sqlmock.NewResult(0, 0))
|
||||
mock.ExpectExec(groupRollupInvalidateSQL).
|
||||
WithArgs(retainedInJunePartition, "UTC").
|
||||
WillReturnResult(sqlmock.NewResult(0, 0))
|
||||
mock.ExpectCommit()
|
||||
// 边界分区按精确时间删除;tableoid 区分不同分区里相同的 ctid。
|
||||
mock.ExpectExec(`(?s)SELECT tableoid, ctid.*WHERE created_at < \$1.*WHERE \(tableoid, ctid\) IN`).
|
||||
WithArgs(cutoff, usageLogsCleanupBatchSize).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"created_at"}).AddRow(cutoff.Add(-time.Hour)))
|
||||
mock.ExpectExec(`UPDATE usage_group_rollup_state`).
|
||||
WithArgs(cutoff.Add(-time.Hour), "Asia/Shanghai").
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
mock.ExpectCommit()
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectQuery(`SELECT closed_before::text, retained_from.*FOR UPDATE`).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"closed_before", "retained_from", "timezone_name"}).
|
||||
AddRow(service.GroupUsageDate(todayStart), time.Unix(0, 0).UTC(), "Asia/Shanghai"))
|
||||
mock.ExpectCommit()
|
||||
expectGroupRollupPrecheck(mock, service.GroupUsageDate(service.GroupUsageTodayStart(fixedNow)), "UTC", true)
|
||||
|
||||
require.NoError(t, repo.CleanupUsageLogs(context.Background(), cutoff))
|
||||
require.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
|
||||
func TestDashboardAggregationRepositoryCleanupUsageLogsNonPartitionedFailureRollsBackWithoutSync(t *testing.T) {
|
||||
func TestDashboardAggregationRepositoryCleanupUsageLogsStopsWhenExpireFails(t *testing.T) {
|
||||
setGroupUsageRollupTestTimezone(t)
|
||||
db, mock := newSQLMock(t)
|
||||
repo := newDashboardAggregationRepositoryWithSQL(db)
|
||||
cutoff := time.Date(2026, 7, 1, 0, 0, 0, 0, time.UTC)
|
||||
deletedAt := time.Date(2026, 5, 3, 2, 0, 0, 0, time.UTC)
|
||||
cutoff := time.Date(2026, 6, 30, 16, 0, 0, 0, time.UTC)
|
||||
|
||||
mock.ExpectQuery(`SELECT EXISTS`).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"exists"}).AddRow(false))
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectQuery(`SELECT id FROM usage_group_rollup_state.*FOR UPDATE`).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(1))
|
||||
mock.ExpectQuery(`(?s)SELECT tableoid, ctid.*ORDER BY created_at ASC, id ASC.*DELETE FROM usage_logs.*RETURNING created_at`).
|
||||
WithArgs(cutoff, usageLogsCleanupBatchSize).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"created_at"}).AddRow(deletedAt))
|
||||
mock.ExpectExec(`UPDATE usage_group_rollup_state`).
|
||||
WithArgs(deletedAt, "Asia/Shanghai").
|
||||
mock.ExpectExec(groupRollupExpireExec).
|
||||
WithArgs(cutoff).
|
||||
WillReturnError(sql.ErrConnDone)
|
||||
mock.ExpectRollback()
|
||||
|
||||
err := repo.CleanupUsageLogs(context.Background(), cutoff)
|
||||
require.ErrorIs(t, err, sql.ErrConnDone)
|
||||
require.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
|
||||
func TestDashboardAggregationRepositoryCleanupUsageLogsBatchFailureStopsWithoutSync(t *testing.T) {
|
||||
setGroupUsageRollupTestTimezone(t)
|
||||
db, mock := newSQLMock(t)
|
||||
repo := newDashboardAggregationRepositoryWithSQL(db)
|
||||
cutoff := time.Date(2026, 6, 30, 16, 0, 0, 0, time.UTC)
|
||||
|
||||
mock.ExpectExec(groupRollupExpireExec).
|
||||
WithArgs(cutoff).
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
mock.ExpectQuery(`SELECT EXISTS`).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"exists"}).AddRow(false))
|
||||
mock.ExpectExec(`(?s)SELECT tableoid, ctid.*DELETE FROM usage_logs`).
|
||||
WithArgs(cutoff, usageLogsCleanupBatchSize).
|
||||
WillReturnError(sql.ErrConnDone)
|
||||
|
||||
err := repo.CleanupUsageLogs(context.Background(), cutoff)
|
||||
require.ErrorIs(t, err, sql.ErrConnDone)
|
||||
require.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
|
||||
func TestDashboardAggregationRepositoryCleanupUsageLogsSkipsPartitionWhenDropLockTimesOut(t *testing.T) {
|
||||
setGroupUsageRollupTestTimezone(t)
|
||||
db, mock := newSQLMock(t)
|
||||
repo := newDashboardAggregationRepositoryWithSQL(db)
|
||||
cutoff := time.Date(2026, 7, 17, 16, 0, 0, 0, time.UTC)
|
||||
fixedNow := time.Date(2026, 8, 14, 8, 0, 0, 0, time.UTC)
|
||||
repo.clock = func() time.Time { return fixedNow }
|
||||
|
||||
mock.ExpectExec(groupRollupExpireExec).
|
||||
WithArgs(cutoff).
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
mock.ExpectQuery(`SELECT EXISTS`).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"exists"}).AddRow(true))
|
||||
mock.ExpectQuery(`SELECT c.relname`).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"relname"}).AddRow("usage_logs_202604"))
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectExec(`SET LOCAL lock_timeout`).WillReturnResult(sqlmock.NewResult(0, 0))
|
||||
mock.ExpectQuery(`(?s)SELECT expired_before\s+FROM usage_group_rollup_state.*FOR KEY SHARE`).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"expired_before"}).AddRow(cutoff))
|
||||
mock.ExpectQuery(`SELECT MIN\(created_at\) FROM "usage_logs_202604"`).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"min"}).AddRow(nil))
|
||||
mock.ExpectExec(`DROP TABLE IF EXISTS "usage_logs_202604"`).
|
||||
WillReturnError(&pq.Error{Code: "55P03", Message: "canceling statement due to lock timeout"})
|
||||
mock.ExpectRollback()
|
||||
// 分区保留,其中的过期记录由按行删除清理。
|
||||
mock.ExpectExec(`(?s)SELECT tableoid, ctid.*DELETE FROM usage_logs`).
|
||||
WithArgs(cutoff, usageLogsCleanupBatchSize).
|
||||
WillReturnResult(sqlmock.NewResult(0, 5))
|
||||
expectGroupRollupPrecheck(mock, service.GroupUsageDate(service.GroupUsageTodayStart(fixedNow)), "Asia/Shanghai", true)
|
||||
|
||||
require.NoError(t, repo.CleanupUsageLogs(context.Background(), cutoff))
|
||||
require.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
|
||||
func TestDashboardAggregationRepositoryCleanupUsageLogsPartitionFailureRollsBackAndStops(t *testing.T) {
|
||||
setGroupUsageRollupTestTimezone(t)
|
||||
db, mock := newSQLMock(t)
|
||||
repo := newDashboardAggregationRepositoryWithSQL(db)
|
||||
cutoff := time.Date(2026, 7, 18, 0, 0, 0, 0, time.UTC)
|
||||
aprilStart := time.Date(2026, 4, 1, 0, 0, 0, 0, time.UTC)
|
||||
cutoff := time.Date(2026, 7, 17, 16, 0, 0, 0, time.UTC)
|
||||
dropErr := errors.New("drop partition failed")
|
||||
|
||||
mock.ExpectExec(groupRollupExpireExec).
|
||||
WithArgs(cutoff).
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
mock.ExpectQuery(`SELECT EXISTS`).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"exists"}).AddRow(true))
|
||||
mock.ExpectQuery(`SELECT c.relname`).
|
||||
@@ -311,11 +638,11 @@ func TestDashboardAggregationRepositoryCleanupUsageLogsPartitionFailureRollsBack
|
||||
AddRow("usage_logs_202606").
|
||||
AddRow("usage_logs_202604"))
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectQuery(`SELECT id FROM usage_group_rollup_state.*FOR UPDATE`).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(1))
|
||||
mock.ExpectExec(`UPDATE usage_group_rollup_state`).
|
||||
WithArgs(aprilStart, "Asia/Shanghai").
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
mock.ExpectExec(`SET LOCAL lock_timeout`).WillReturnResult(sqlmock.NewResult(0, 0))
|
||||
mock.ExpectQuery(`(?s)SELECT expired_before\s+FROM usage_group_rollup_state.*FOR KEY SHARE`).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"expired_before"}).AddRow(cutoff))
|
||||
mock.ExpectQuery(`SELECT MIN\(created_at\) FROM "usage_logs_202604"`).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"min"}).AddRow(nil))
|
||||
mock.ExpectExec(`DROP TABLE IF EXISTS "usage_logs_202604"`).
|
||||
WillReturnError(dropErr)
|
||||
mock.ExpectRollback()
|
||||
|
||||
@@ -3,6 +3,7 @@ package repository
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"sort"
|
||||
@@ -20,6 +21,9 @@ type dashboardAggregationRepository struct {
|
||||
}
|
||||
|
||||
const usageLogsCleanupBatchSize = 10000
|
||||
|
||||
// usageLogsPartitionDropLockTimeout 限定删除分区时等待父表锁的时长。
|
||||
const usageLogsPartitionDropLockTimeout = 3 * time.Second
|
||||
const usageBillingDedupCleanupBatchSize = 10000
|
||||
|
||||
// NewDashboardAggregationRepository 创建仪表盘预聚合仓储。
|
||||
@@ -131,29 +135,22 @@ func (r *dashboardAggregationRepository) RecomputeRange(ctx context.Context, sta
|
||||
dayEnd = dayEnd.Add(24 * time.Hour)
|
||||
}
|
||||
|
||||
// 分组日桶从 start 所在自然日起失效,由后台同步重建;失效语句独立提交,不与看板重算共享事务。
|
||||
if err := invalidateGroupUsageRollupsAt(ctx, r.sql, start); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 尽量使用事务保证范围内的一致性(允许在非 *sql.DB 的情况下退化为非事务执行)。
|
||||
if db, ok := r.sql.(*sql.DB); ok {
|
||||
tx, err := db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := lockGroupUsageRollupState(ctx, tx); err != nil {
|
||||
_ = tx.Rollback()
|
||||
return err
|
||||
}
|
||||
if err := invalidateGroupUsageRollupsAt(ctx, tx, start); err != nil {
|
||||
_ = tx.Rollback()
|
||||
return err
|
||||
}
|
||||
txRepo := newDashboardAggregationRepositoryWithSQL(tx)
|
||||
if err := txRepo.recomputeRangeInTx(ctx, hourStart, hourEnd, dayStart, dayEnd); err != nil {
|
||||
_ = tx.Rollback()
|
||||
return err
|
||||
}
|
||||
if err := txRepo.syncGroupUsageRollupsInTx(ctx, service.GroupUsageTodayStart(r.now())); err != nil {
|
||||
_ = tx.Rollback()
|
||||
return err
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
return r.recomputeRangeInTx(ctx, hourStart, hourEnd, dayStart, dayEnd)
|
||||
@@ -230,7 +227,13 @@ func (r *dashboardAggregationRepository) CleanupAggregates(ctx context.Context,
|
||||
return nil
|
||||
}
|
||||
|
||||
// CleanupUsageLogs 删除服务端配置时区内 cutoff 所在自然日零点之前的 usage_logs。
|
||||
// 删除前先把分组日汇总的保留下界推进到该零点,被删除的记录不触发日桶失效。
|
||||
func (r *dashboardAggregationRepository) CleanupUsageLogs(ctx context.Context, cutoff time.Time) error {
|
||||
cutoff = service.GroupUsageTodayStart(cutoff)
|
||||
if err := expireGroupUsageRollupsBefore(ctx, r.sql, cutoff); err != nil {
|
||||
return err
|
||||
}
|
||||
isPartitioned, err := r.isUsageLogsPartitioned(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -249,19 +252,7 @@ func (r *dashboardAggregationRepository) CleanupUsageLogs(ctx context.Context, c
|
||||
}
|
||||
|
||||
func (r *dashboardAggregationRepository) cleanupUsageLogsBatches(ctx context.Context, cutoff time.Time) error {
|
||||
db, transactional := r.sql.(*sql.DB)
|
||||
for {
|
||||
if transactional {
|
||||
affected, err := cleanupUsageLogsBatchWithRollupInvalidation(ctx, db, cutoff)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if affected < usageLogsCleanupBatchSize {
|
||||
return nil
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
res, err := r.sql.ExecContext(ctx, `
|
||||
WITH victims AS (
|
||||
SELECT tableoid, ctid
|
||||
@@ -286,66 +277,6 @@ func (r *dashboardAggregationRepository) cleanupUsageLogsBatches(ctx context.Con
|
||||
}
|
||||
}
|
||||
|
||||
func cleanupUsageLogsBatchWithRollupInvalidation(ctx context.Context, db *sql.DB, cutoff time.Time) (int64, error) {
|
||||
tx, err := db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
rollback := func(err error) (int64, error) {
|
||||
_ = tx.Rollback()
|
||||
return 0, err
|
||||
}
|
||||
|
||||
if err := lockGroupUsageRollupState(ctx, tx); err != nil {
|
||||
return rollback(err)
|
||||
}
|
||||
rows, err := tx.QueryContext(ctx, `
|
||||
WITH victims AS (
|
||||
SELECT tableoid, ctid
|
||||
FROM usage_logs
|
||||
WHERE created_at < $1
|
||||
ORDER BY created_at ASC, id ASC
|
||||
LIMIT $2
|
||||
)
|
||||
DELETE FROM usage_logs
|
||||
WHERE (tableoid, ctid) IN (SELECT tableoid, ctid FROM victims)
|
||||
RETURNING created_at
|
||||
`, cutoff.UTC(), usageLogsCleanupBatchSize)
|
||||
if err != nil {
|
||||
return rollback(err)
|
||||
}
|
||||
|
||||
var affected int64
|
||||
var earliestDeletedAt time.Time
|
||||
for rows.Next() {
|
||||
var deletedAt time.Time
|
||||
if err := rows.Scan(&deletedAt); err != nil {
|
||||
_ = rows.Close()
|
||||
return rollback(err)
|
||||
}
|
||||
affected++
|
||||
if earliestDeletedAt.IsZero() || deletedAt.Before(earliestDeletedAt) {
|
||||
earliestDeletedAt = deletedAt
|
||||
}
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
_ = rows.Close()
|
||||
return rollback(err)
|
||||
}
|
||||
if err := rows.Close(); err != nil {
|
||||
return rollback(err)
|
||||
}
|
||||
if affected > 0 {
|
||||
if err := invalidateGroupUsageRollupsAt(ctx, tx, earliestDeletedAt); err != nil {
|
||||
return rollback(err)
|
||||
}
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return affected, nil
|
||||
}
|
||||
|
||||
func (r *dashboardAggregationRepository) CleanupUsageBillingDedup(ctx context.Context, cutoff time.Time) error {
|
||||
for {
|
||||
res, err := r.sql.ExecContext(ctx, `
|
||||
@@ -630,40 +561,69 @@ func (r *dashboardAggregationRepository) dropUsageLogsPartitions(ctx context.Con
|
||||
sort.Slice(partitions, func(i, j int) bool {
|
||||
return partitions[i].month.Before(partitions[j].month)
|
||||
})
|
||||
if db, ok := r.sql.(*sql.DB); ok {
|
||||
for _, partition := range partitions {
|
||||
if err := dropUsageLogsPartitionWithRollupInvalidation(ctx, db, partition.name, partition.month); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
for _, partition := range partitions {
|
||||
if _, err := r.sql.ExecContext(ctx, fmt.Sprintf("DROP TABLE IF EXISTS %s", pq.QuoteIdentifier(partition.name))); err != nil {
|
||||
if err := r.dropUsageLogsPartition(ctx, partition.name); err != nil {
|
||||
// 父表锁等待超时:保留该分区,其中的过期记录由随后的按行删除清理,空分区在下次清理时删除。
|
||||
if isPostgresLockNotAvailable(err) {
|
||||
log.Printf("[DashboardAggregation] 删除分区 %s 等待锁超时,本次改为按行删除", partition.name)
|
||||
continue
|
||||
}
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func dropUsageLogsPartitionWithRollupInvalidation(ctx context.Context, db *sql.DB, name string, monthStart time.Time) error {
|
||||
func isPostgresLockNotAvailable(err error) bool {
|
||||
var pqErr *pq.Error
|
||||
return errors.As(err, &pqErr) && pqErr.Code == "55P03"
|
||||
}
|
||||
|
||||
// dropUsageLogsPartition 删除一个 usage_logs 月分区。分区内不早于保留下界的记录参与分组日汇总,
|
||||
// 删除后按其中最早的时刻使日桶失效;状态行的 FOR KEY SHARE 使失效与重建的登记、发布串行。
|
||||
// DROP 需要父表 ACCESS EXCLUSIVE 锁,排队期间会挡住 usage_logs 写入,因此限定锁等待时长。
|
||||
func (r *dashboardAggregationRepository) dropUsageLogsPartition(ctx context.Context, name string) error {
|
||||
drop := func(q sqlExecutor) error {
|
||||
var expiredBefore time.Time
|
||||
if err := scanSingleRow(ctx, q, `
|
||||
SELECT expired_before
|
||||
FROM usage_group_rollup_state
|
||||
WHERE id = 1
|
||||
FOR KEY SHARE
|
||||
`, nil, &expiredBefore); err != nil {
|
||||
return fmt.Errorf("读取分组用量汇总保留下界: %w", err)
|
||||
}
|
||||
var earliestRetained sql.NullTime
|
||||
if err := scanSingleRow(ctx, q,
|
||||
fmt.Sprintf("SELECT MIN(created_at) FROM %s WHERE created_at >= $1", pq.QuoteIdentifier(name)),
|
||||
[]any{expiredBefore.UTC()}, &earliestRetained,
|
||||
); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := q.ExecContext(ctx, fmt.Sprintf("DROP TABLE IF EXISTS %s", pq.QuoteIdentifier(name))); err != nil {
|
||||
return err
|
||||
}
|
||||
if earliestRetained.Valid {
|
||||
return invalidateGroupUsageRollupsAt(ctx, q, earliestRetained.Time)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
db, ok := r.sql.(*sql.DB)
|
||||
if !ok {
|
||||
return drop(r.sql)
|
||||
}
|
||||
tx, err := db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
rollback := func(err error) error {
|
||||
if _, err := tx.ExecContext(ctx, fmt.Sprintf("SET LOCAL lock_timeout = '%dms'", usageLogsPartitionDropLockTimeout.Milliseconds())); err != nil {
|
||||
_ = tx.Rollback()
|
||||
return err
|
||||
}
|
||||
|
||||
if err := lockGroupUsageRollupState(ctx, tx); err != nil {
|
||||
return rollback(err)
|
||||
}
|
||||
if err := invalidateGroupUsageRollupsAt(ctx, tx, monthStart); err != nil {
|
||||
return rollback(err)
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, fmt.Sprintf("DROP TABLE IF EXISTS %s", pq.QuoteIdentifier(name))); err != nil {
|
||||
return rollback(err)
|
||||
if err := drop(tx); err != nil {
|
||||
_ = tx.Rollback()
|
||||
return err
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
@@ -91,6 +91,7 @@ func mustCreateGroup(t *testing.T, client *dbent.Client, g *service.Group) *serv
|
||||
SetRateMultiplier(g.RateMultiplier).
|
||||
SetIsExclusive(g.IsExclusive).
|
||||
SetForceOpenaiFast(g.ForceOpenAIFast).
|
||||
SetForceOpenaiUltrafast(g.ForceOpenAIUltrafast).
|
||||
SetFreeOpenaiFast(g.FreeOpenAIFast).
|
||||
SetModelAllowlist(service.DomainGroupModelAllowlist(g.ModelAllowlist)).
|
||||
SetCodexModelsManifestConfig(g.CodexModelsManifestConfig).
|
||||
|
||||
@@ -138,6 +138,7 @@ func createGroupRecord(ctx context.Context, client *dbent.Client, groupIn *servi
|
||||
SetAllowMessagesDispatch(groupIn.AllowMessagesDispatch).
|
||||
SetAllowLive(groupIn.AllowLive).
|
||||
SetForceOpenaiFast(groupIn.ForceOpenAIFast).
|
||||
SetForceOpenaiUltrafast(groupIn.ForceOpenAIUltrafast).
|
||||
SetFreeOpenaiFast(groupIn.FreeOpenAIFast).
|
||||
SetRequireOauthOnly(groupIn.RequireOAuthOnly).
|
||||
SetRequirePrivacySet(groupIn.RequirePrivacySet).
|
||||
@@ -323,6 +324,7 @@ func (r *groupRepository) Update(ctx context.Context, groupIn *service.Group) er
|
||||
SetAllowMessagesDispatch(groupIn.AllowMessagesDispatch).
|
||||
SetAllowLive(groupIn.AllowLive).
|
||||
SetForceOpenaiFast(groupIn.ForceOpenAIFast).
|
||||
SetForceOpenaiUltrafast(groupIn.ForceOpenAIUltrafast).
|
||||
SetFreeOpenaiFast(groupIn.FreeOpenAIFast).
|
||||
SetRequireOauthOnly(groupIn.RequireOAuthOnly).
|
||||
SetRequirePrivacySet(groupIn.RequirePrivacySet).
|
||||
|
||||
@@ -0,0 +1,652 @@
|
||||
//go:build integration
|
||||
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lib/pq"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// 计算阶段持有状态行 FOR KEY SHARE 期间,usage_logs 的当天写入、迟到写入与窗口内删除都不等待;
|
||||
// 迟到写入与删除记入 build_dirty_from,同步重算脏区间后发布到今日,日桶与明细逐日一致。
|
||||
func TestGroupUsageRollupSyncDoesNotBlockUsageWritesDuringBuild(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
|
||||
defer cancel()
|
||||
useGroupUsageRepositoryTestTimezone(t, "Asia/Shanghai")
|
||||
schema := createGroupUsageRollupTriggerTestSchema(t, ctx, false)
|
||||
db := openGroupUsageRollupSchemaDB(t, schema, "Asia/Shanghai")
|
||||
todayStart := time.Date(2026, 8, 13, 16, 0, 0, 0, time.UTC)
|
||||
|
||||
execGroupUsageRollupSQL(t, ctx, db, `
|
||||
INSERT INTO groups (id) VALUES (10), (20);
|
||||
INSERT INTO users (id) VALUES (1);
|
||||
INSERT INTO usage_logs (id, user_id, group_id, actual_cost, created_at) VALUES
|
||||
(1, 1, 10, 1, TIMESTAMPTZ '2026-08-10 09:00:00+08'),
|
||||
(2, 1, 10, 2, TIMESTAMPTZ '2026-08-11 09:00:00+08'),
|
||||
(3, 1, 20, 4, TIMESTAMPTZ '2026-08-12 09:00:00+08'),
|
||||
(4, 1, 10, 8, TIMESTAMPTZ '2026-08-13 09:00:00+08');
|
||||
INSERT INTO usage_group_daily_rollups (bucket_date, group_id, actual_cost)
|
||||
VALUES (DATE '2026-08-10', 10, 1);
|
||||
UPDATE usage_group_rollup_state
|
||||
SET closed_before = DATE '2026-08-11',
|
||||
retained_from = TIMESTAMPTZ '2026-08-10 09:00:00+08',
|
||||
timezone_name = 'Asia/Shanghai'
|
||||
WHERE id = 1;
|
||||
`)
|
||||
|
||||
// 让计算阶段停在清理日桶这一步:此时它已持有状态行的 FOR KEY SHARE。
|
||||
blocker, err := db.BeginTx(ctx, nil)
|
||||
require.NoError(t, err)
|
||||
defer func() { _ = blocker.Rollback() }()
|
||||
_, err = blocker.ExecContext(ctx, "LOCK TABLE usage_group_daily_rollups IN SHARE MODE")
|
||||
require.NoError(t, err)
|
||||
|
||||
repo := newDashboardAggregationRepositoryWithSQL(db)
|
||||
syncDone := make(chan error, 1)
|
||||
go func() { syncDone <- repo.SyncGroupUsageRollups(ctx, todayStart) }()
|
||||
waitForBlockedGroupUsageRollupStatement(t, ctx, "DELETE FROM usage_group_daily_rollups")
|
||||
|
||||
writeCtx, writeCancel := context.WithTimeout(ctx, 3*time.Second)
|
||||
defer writeCancel()
|
||||
execGroupUsageRollupSQL(t, writeCtx, db, `
|
||||
INSERT INTO usage_logs (id, user_id, group_id, actual_cost, created_at)
|
||||
VALUES (5, 1, 20, 16, TIMESTAMPTZ '2026-08-12 18:00:00+08')
|
||||
`)
|
||||
execGroupUsageRollupSQL(t, writeCtx, db, `
|
||||
INSERT INTO usage_logs (id, user_id, group_id, actual_cost, created_at)
|
||||
VALUES (6, 1, 10, 32, TIMESTAMPTZ '2026-08-14 09:00:00+08')
|
||||
`)
|
||||
execGroupUsageRollupSQL(t, writeCtx, db, `DELETE FROM usage_logs WHERE id = 2`)
|
||||
|
||||
state := readGroupUsageRollupTestState(t, ctx, db)
|
||||
require.Equal(t, "2026-08-11", state.closedBefore)
|
||||
require.Equal(t, "2026-08-14", state.buildingUntil.String)
|
||||
require.Equal(t, "2026-08-11", state.buildDirtyFrom.String)
|
||||
|
||||
require.NoError(t, blocker.Rollback())
|
||||
select {
|
||||
case err := <-syncDone:
|
||||
require.NoError(t, err)
|
||||
case <-ctx.Done():
|
||||
t.Fatal("等待分组日桶同步完成超时")
|
||||
}
|
||||
|
||||
state = readGroupUsageRollupTestState(t, ctx, db)
|
||||
require.Equal(t, "2026-08-14", state.closedBefore)
|
||||
require.False(t, state.buildingUntil.Valid)
|
||||
require.False(t, state.buildDirtyFrom.Valid)
|
||||
requireGroupUsageRollupsMatchUsageLogs(t, ctx, db, "Asia/Shanghai", state.retainedFrom, todayStart)
|
||||
|
||||
summary := groupUsageSummaryByGroup(t, ctx, db, todayStart)
|
||||
require.InDelta(t, 41, summary[10][0], 1e-9)
|
||||
require.InDelta(t, 32, summary[10][1], 1e-9)
|
||||
require.InDelta(t, 8, summary[10][2], 1e-9)
|
||||
require.InDelta(t, 20, summary[20][0], 1e-9)
|
||||
require.InDelta(t, 0, summary[20][1], 1e-9)
|
||||
require.InDelta(t, 0, summary[20][2], 1e-9)
|
||||
}
|
||||
|
||||
// 保留期清理按整日推进保留下界后删除:发布水位不动,过期记录的写入不触发失效,
|
||||
// 窗口内的删除照常使日桶失效。
|
||||
func TestGroupUsageRollupRetentionCleanupKeepsPublishedWatermark(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
|
||||
defer cancel()
|
||||
useGroupUsageRepositoryTestTimezone(t, "Asia/Shanghai")
|
||||
schema := createGroupUsageRollupTriggerTestSchema(t, ctx, false)
|
||||
db := openGroupUsageRollupSchemaDB(t, schema, "Asia/Shanghai")
|
||||
todayStart := time.Date(2026, 8, 9, 16, 0, 0, 0, time.UTC)
|
||||
|
||||
execGroupUsageRollupSQL(t, ctx, db, `
|
||||
INSERT INTO groups (id) VALUES (10), (20);
|
||||
INSERT INTO users (id) VALUES (1);
|
||||
INSERT INTO usage_logs (id, user_id, group_id, actual_cost, created_at) VALUES
|
||||
(1, 1, 10, 1, TIMESTAMPTZ '2026-08-01 10:00:00+08'),
|
||||
(2, 1, 10, 2, TIMESTAMPTZ '2026-08-02 05:00:00+08'),
|
||||
(3, 1, 10, 4, TIMESTAMPTZ '2026-08-02 20:00:00+08'),
|
||||
(4, 1, 20, 8, TIMESTAMPTZ '2026-08-05 12:00:00+08'),
|
||||
(5, 1, 10, 16, TIMESTAMPTZ '2026-08-10 08:00:00+08');
|
||||
`)
|
||||
|
||||
repo := newDashboardAggregationRepositoryWithSQL(db)
|
||||
repo.clock = func() time.Time { return todayStart.Add(10 * time.Hour) }
|
||||
require.NoError(t, repo.SyncGroupUsageRollups(ctx, todayStart))
|
||||
require.Equal(t, "2026-08-10", readGroupUsageRollupTestState(t, ctx, db).closedBefore)
|
||||
|
||||
shanghai, err := time.LoadLocation("Asia/Shanghai")
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, repo.CleanupUsageLogs(ctx, time.Date(2026, 8, 2, 12, 0, 0, 0, shanghai)))
|
||||
|
||||
alignedCutoff := time.Date(2026, 8, 2, 0, 0, 0, 0, shanghai)
|
||||
state := readGroupUsageRollupTestState(t, ctx, db)
|
||||
require.Equal(t, "2026-08-10", state.closedBefore)
|
||||
require.True(t, state.expiredBefore.Equal(alignedCutoff), "expired_before=%s", state.expiredBefore)
|
||||
require.True(t, state.retainedFrom.Equal(alignedCutoff), "retained_from=%s", state.retainedFrom)
|
||||
require.False(t, state.buildingUntil.Valid)
|
||||
|
||||
var remaining []int64
|
||||
rows, err := db.QueryContext(ctx, "SELECT id FROM usage_logs ORDER BY id")
|
||||
require.NoError(t, err)
|
||||
for rows.Next() {
|
||||
var id int64
|
||||
require.NoError(t, rows.Scan(&id))
|
||||
remaining = append(remaining, id)
|
||||
}
|
||||
require.NoError(t, rows.Err())
|
||||
require.NoError(t, rows.Close())
|
||||
require.Equal(t, []int64{2, 3, 4, 5}, remaining)
|
||||
|
||||
requireGroupUsageRollupsMatchUsageLogs(t, ctx, db, "Asia/Shanghai", alignedCutoff, todayStart)
|
||||
summary := groupUsageSummaryByGroup(t, ctx, db, todayStart)
|
||||
require.InDelta(t, 22, summary[10][0], 1e-9)
|
||||
require.InDelta(t, 16, summary[10][1], 1e-9)
|
||||
require.InDelta(t, 8, summary[20][0], 1e-9)
|
||||
|
||||
execGroupUsageRollupSQL(t, ctx, db, `
|
||||
INSERT INTO usage_logs (id, user_id, group_id, actual_cost, created_at)
|
||||
VALUES (6, 1, 10, 100, TIMESTAMPTZ '2026-08-01 12:00:00+08')
|
||||
`)
|
||||
require.Equal(t, "2026-08-10", readGroupUsageRollupTestState(t, ctx, db).closedBefore)
|
||||
summary = groupUsageSummaryByGroup(t, ctx, db, todayStart)
|
||||
require.InDelta(t, 22, summary[10][0], 1e-9)
|
||||
|
||||
execGroupUsageRollupSQL(t, ctx, db, `DELETE FROM usage_logs WHERE id = 4`)
|
||||
require.Equal(t, "2026-08-05", readGroupUsageRollupTestState(t, ctx, db).closedBefore)
|
||||
summary = groupUsageSummaryByGroup(t, ctx, db, todayStart)
|
||||
require.InDelta(t, 0, summary[20][0], 1e-9)
|
||||
require.InDelta(t, 22, summary[10][0], 1e-9)
|
||||
}
|
||||
|
||||
func TestGroupUsageRollupTriggersIgnoreRowsBeforeExpiredFloor(t *testing.T) {
|
||||
for _, partitioned := range []bool{false, true} {
|
||||
name := "ordinary"
|
||||
if partitioned {
|
||||
name = "partitioned"
|
||||
}
|
||||
t.Run(name, func(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
schema := createGroupUsageRollupTriggerTestSchema(t, ctx, partitioned)
|
||||
tx := beginGroupUsageRollupTriggerTestTx(t, ctx, schema)
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
require.NoError(t, setGroupUsageRollupTriggerTimeZone(ctx, tx, "Asia/Shanghai"))
|
||||
|
||||
_, err := tx.ExecContext(ctx, `
|
||||
INSERT INTO groups (id) VALUES (10);
|
||||
INSERT INTO users (id) VALUES (1);
|
||||
INSERT INTO usage_logs (id, user_id, group_id, actual_cost, created_at) VALUES
|
||||
(1, 1, 10, 1, TIMESTAMPTZ '2020-01-15 08:00:00+08'),
|
||||
(2, 1, 10, 2, TIMESTAMPTZ '2020-02-05 08:00:00+08');
|
||||
UPDATE usage_group_rollup_state
|
||||
SET closed_before = DATE '2020-03-01',
|
||||
expired_before = TIMESTAMPTZ '2020-02-01 00:00:00+08'
|
||||
WHERE id = 1;
|
||||
DELETE FROM usage_logs WHERE id = 1;
|
||||
INSERT INTO usage_logs (id, user_id, group_id, actual_cost, created_at)
|
||||
VALUES (3, 1, 10, 4, TIMESTAMPTZ '2020-01-20 08:00:00+08');
|
||||
UPDATE usage_logs SET actual_cost = 5 WHERE id = 3;
|
||||
`)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "2020-03-01", readGroupUsageRollupTestStateTx(t, ctx, tx).closedBefore)
|
||||
|
||||
// 把过期记录改到保留窗口内,按新日期失效。
|
||||
_, err = tx.ExecContext(ctx, `
|
||||
UPDATE usage_logs SET created_at = TIMESTAMPTZ '2020-02-20 08:00:00+08' WHERE id = 3
|
||||
`)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "2020-02-20", readGroupUsageRollupTestStateTx(t, ctx, tx).closedBefore)
|
||||
|
||||
_, err = tx.ExecContext(ctx, `DELETE FROM usage_logs WHERE id = 2`)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "2020-02-05", readGroupUsageRollupTestStateTx(t, ctx, tx).closedBefore)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGroupUsageRollupTriggersMarkDirtyDuringBuild(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
schema := createGroupUsageRollupTriggerTestSchema(t, ctx, false)
|
||||
tx := beginGroupUsageRollupTriggerTestTx(t, ctx, schema)
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
require.NoError(t, setGroupUsageRollupTriggerTimeZone(ctx, tx, "Asia/Shanghai"))
|
||||
|
||||
_, err := tx.ExecContext(ctx, `
|
||||
INSERT INTO groups (id) VALUES (10);
|
||||
INSERT INTO users (id) VALUES (1);
|
||||
UPDATE usage_group_rollup_state
|
||||
SET closed_before = DATE '2020-01-05',
|
||||
building_until = DATE '2020-01-10'
|
||||
WHERE id = 1;
|
||||
INSERT INTO usage_logs (id, user_id, group_id, actual_cost, created_at)
|
||||
VALUES (1, 1, 10, 1, TIMESTAMPTZ '2020-01-12 08:00:00+08');
|
||||
`)
|
||||
require.NoError(t, err)
|
||||
state := readGroupUsageRollupTestStateTx(t, ctx, tx)
|
||||
require.Equal(t, "2020-01-05", state.closedBefore)
|
||||
require.False(t, state.buildDirtyFrom.Valid)
|
||||
|
||||
_, err = tx.ExecContext(ctx, `
|
||||
INSERT INTO usage_logs (id, user_id, group_id, actual_cost, created_at)
|
||||
VALUES (2, 1, 10, 1, TIMESTAMPTZ '2020-01-07 08:00:00+08')
|
||||
`)
|
||||
require.NoError(t, err)
|
||||
state = readGroupUsageRollupTestStateTx(t, ctx, tx)
|
||||
require.Equal(t, "2020-01-05", state.closedBefore)
|
||||
require.Equal(t, "2020-01-07", state.buildDirtyFrom.String)
|
||||
|
||||
_, err = tx.ExecContext(ctx, `
|
||||
INSERT INTO usage_logs (id, user_id, group_id, actual_cost, created_at)
|
||||
VALUES (3, 1, 10, 1, TIMESTAMPTZ '2020-01-03 08:00:00+08')
|
||||
`)
|
||||
require.NoError(t, err)
|
||||
state = readGroupUsageRollupTestStateTx(t, ctx, tx)
|
||||
require.Equal(t, "2020-01-03", state.closedBefore)
|
||||
require.Equal(t, "2020-01-03", state.buildDirtyFrom.String)
|
||||
|
||||
_, err = tx.ExecContext(ctx, `DELETE FROM usage_logs WHERE id = 1`)
|
||||
require.NoError(t, err)
|
||||
state = readGroupUsageRollupTestStateTx(t, ctx, tx)
|
||||
require.Equal(t, "2020-01-03", state.buildDirtyFrom.String)
|
||||
}
|
||||
|
||||
// 计算阶段对状态行只持 FOR KEY SHARE:迟到写入与窗口内删除都不等待它。
|
||||
func TestGroupUsageRollupBuildKeyShareDoesNotBlockLateWrites(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
schema := createGroupUsageRollupTriggerTestSchema(t, ctx, false)
|
||||
seedTx := beginGroupUsageRollupTriggerTestTx(t, ctx, schema)
|
||||
_, err := seedTx.ExecContext(ctx, `
|
||||
INSERT INTO groups (id) VALUES (10);
|
||||
INSERT INTO users (id) VALUES (1);
|
||||
INSERT INTO usage_logs (id, user_id, group_id, actual_cost, created_at)
|
||||
VALUES (1, 1, 10, 1, TIMESTAMPTZ '2020-01-08 08:00:00+08');
|
||||
UPDATE usage_group_rollup_state
|
||||
SET closed_before = DATE '2020-01-05',
|
||||
building_until = DATE '2020-01-10'
|
||||
WHERE id = 1;
|
||||
`)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, seedTx.Commit())
|
||||
|
||||
buildTx := beginGroupUsageRollupTriggerTestTx(t, ctx, schema)
|
||||
defer func() { _ = buildTx.Rollback() }()
|
||||
var stateID int16
|
||||
require.NoError(t, buildTx.QueryRowContext(ctx, `
|
||||
SELECT id FROM usage_group_rollup_state WHERE id = 1 FOR KEY SHARE
|
||||
`).Scan(&stateID))
|
||||
|
||||
for _, statement := range []string{
|
||||
`INSERT INTO usage_logs (id, user_id, group_id, actual_cost, created_at)
|
||||
VALUES (2, 1, 10, 1, TIMESTAMPTZ '2020-01-07 08:00:00+08')`,
|
||||
`DELETE FROM usage_logs WHERE id = 1`,
|
||||
} {
|
||||
writeTx := beginGroupUsageRollupTriggerTestTx(t, ctx, schema)
|
||||
require.NoError(t, setGroupUsageRollupTriggerTimeZone(ctx, writeTx, "Asia/Shanghai"))
|
||||
var writePID int
|
||||
require.NoError(t, writeTx.QueryRowContext(ctx, "SELECT pg_backend_pid()").Scan(&writePID))
|
||||
result := make(chan error, 1)
|
||||
go func(statement string) {
|
||||
_, execErr := writeTx.ExecContext(ctx, statement)
|
||||
result <- execErr
|
||||
}(statement)
|
||||
blocked, err := waitForGroupUsageRollupStateLock(ctx, writePID, result)
|
||||
require.NoError(t, err)
|
||||
require.False(t, blocked, "计算阶段不得阻塞: %s", statement)
|
||||
require.NoError(t, writeTx.Commit())
|
||||
}
|
||||
|
||||
require.NoError(t, buildTx.Commit())
|
||||
var dirtyFrom string
|
||||
require.NoError(t, integrationDB.QueryRowContext(ctx, fmt.Sprintf(
|
||||
"SELECT build_dirty_from::text FROM %s.usage_group_rollup_state WHERE id = 1",
|
||||
pq.QuoteIdentifier(schema),
|
||||
)).Scan(&dirtyFrom))
|
||||
require.Equal(t, "2020-01-07", dirtyFrom)
|
||||
}
|
||||
|
||||
func TestGroupUsageRollupSyncSkipsWhileAnotherBuildHoldsLock(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||
defer cancel()
|
||||
useGroupUsageRepositoryTestTimezone(t, "Asia/Shanghai")
|
||||
schema := createGroupUsageRollupTriggerTestSchema(t, ctx, false)
|
||||
db := openGroupUsageRollupSchemaDB(t, schema, "Asia/Shanghai")
|
||||
todayStart := time.Date(2026, 8, 13, 16, 0, 0, 0, time.UTC)
|
||||
|
||||
holder, err := integrationDB.Conn(ctx)
|
||||
require.NoError(t, err)
|
||||
defer func() { _ = holder.Close() }()
|
||||
var locked bool
|
||||
require.NoError(t, holder.QueryRowContext(ctx, groupUsageRollupBuildLockSQL).Scan(&locked))
|
||||
require.True(t, locked)
|
||||
defer func() { _, _ = holder.ExecContext(context.Background(), groupUsageRollupBuildUnlockSQL) }()
|
||||
|
||||
repo := newDashboardAggregationRepositoryWithSQL(db)
|
||||
require.NoError(t, repo.SyncGroupUsageRollups(ctx, todayStart))
|
||||
state := readGroupUsageRollupTestState(t, ctx, db)
|
||||
require.Equal(t, "1970-01-01", state.closedBefore)
|
||||
require.False(t, state.buildingUntil.Valid)
|
||||
}
|
||||
|
||||
// 上一次重建在登记之后中断:下一次同步覆盖遗留登记并发布到今日。
|
||||
func TestGroupUsageRollupSyncRecoversFromInterruptedBuild(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||
defer cancel()
|
||||
useGroupUsageRepositoryTestTimezone(t, "Asia/Shanghai")
|
||||
schema := createGroupUsageRollupTriggerTestSchema(t, ctx, false)
|
||||
db := openGroupUsageRollupSchemaDB(t, schema, "Asia/Shanghai")
|
||||
todayStart := time.Date(2026, 8, 13, 16, 0, 0, 0, time.UTC)
|
||||
|
||||
execGroupUsageRollupSQL(t, ctx, db, `
|
||||
INSERT INTO groups (id) VALUES (10);
|
||||
INSERT INTO users (id) VALUES (1);
|
||||
INSERT INTO usage_logs (id, user_id, group_id, actual_cost, created_at) VALUES
|
||||
(1, 1, 10, 1, TIMESTAMPTZ '2026-08-11 09:00:00+08'),
|
||||
(2, 1, 10, 2, TIMESTAMPTZ '2026-08-12 09:00:00+08'),
|
||||
(3, 1, 10, 4, TIMESTAMPTZ '2026-08-13 09:00:00+08');
|
||||
INSERT INTO usage_group_daily_rollups (bucket_date, group_id, actual_cost) VALUES
|
||||
(DATE '2026-08-11', 10, 1),
|
||||
(DATE '2026-08-12', 10, 999);
|
||||
UPDATE usage_group_rollup_state
|
||||
SET closed_before = DATE '2026-08-12',
|
||||
retained_from = TIMESTAMPTZ '2026-08-11 09:00:00+08',
|
||||
timezone_name = 'Asia/Shanghai',
|
||||
building_until = DATE '2026-08-14',
|
||||
build_dirty_from = DATE '2026-08-13'
|
||||
WHERE id = 1;
|
||||
`)
|
||||
|
||||
repo := newDashboardAggregationRepositoryWithSQL(db)
|
||||
require.NoError(t, repo.SyncGroupUsageRollups(ctx, todayStart))
|
||||
|
||||
state := readGroupUsageRollupTestState(t, ctx, db)
|
||||
require.Equal(t, "2026-08-14", state.closedBefore)
|
||||
require.False(t, state.buildingUntil.Valid)
|
||||
require.False(t, state.buildDirtyFrom.Valid)
|
||||
requireGroupUsageRollupsMatchUsageLogs(t, ctx, db, "Asia/Shanghai", state.retainedFrom, todayStart)
|
||||
}
|
||||
|
||||
type groupUsageRollupTestState struct {
|
||||
closedBefore string
|
||||
retainedFrom time.Time
|
||||
expiredBefore time.Time
|
||||
buildingUntil sql.NullString
|
||||
buildDirtyFrom sql.NullString
|
||||
}
|
||||
|
||||
const groupUsageRollupTestStateQuery = `
|
||||
SELECT closed_before::text, retained_from, expired_before, building_until::text, build_dirty_from::text
|
||||
FROM usage_group_rollup_state
|
||||
WHERE id = 1
|
||||
`
|
||||
|
||||
func readGroupUsageRollupTestState(t *testing.T, ctx context.Context, q sqlQueryer) groupUsageRollupTestState {
|
||||
t.Helper()
|
||||
var state groupUsageRollupTestState
|
||||
require.NoError(t, scanSingleRow(ctx, q, groupUsageRollupTestStateQuery, nil,
|
||||
&state.closedBefore, &state.retainedFrom, &state.expiredBefore, &state.buildingUntil, &state.buildDirtyFrom))
|
||||
return state
|
||||
}
|
||||
|
||||
func readGroupUsageRollupTestStateTx(t *testing.T, ctx context.Context, tx *sql.Tx) groupUsageRollupTestState {
|
||||
t.Helper()
|
||||
return readGroupUsageRollupTestState(t, ctx, tx)
|
||||
}
|
||||
|
||||
// openGroupUsageRollupSchemaDB 打开一个 search_path 指向 schema 的连接池,供仓储以 *sql.DB 方式运行。
|
||||
func openGroupUsageRollupSchemaDB(t *testing.T, schema, timezoneName string) *sql.DB {
|
||||
t.Helper()
|
||||
dsn, err := url.Parse(integrationDSN)
|
||||
require.NoError(t, err)
|
||||
query := dsn.Query()
|
||||
query.Set("search_path", schema)
|
||||
query.Set("TimeZone", timezoneName)
|
||||
dsn.RawQuery = query.Encode()
|
||||
db, err := sql.Open("postgres", dsn.String())
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { _ = db.Close() })
|
||||
require.NoError(t, db.PingContext(context.Background()))
|
||||
return db
|
||||
}
|
||||
|
||||
func execGroupUsageRollupSQL(t *testing.T, ctx context.Context, db *sql.DB, query string) {
|
||||
t.Helper()
|
||||
_, err := db.ExecContext(ctx, query)
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
// waitForBlockedGroupUsageRollupStatement 等待某个后端在执行包含 fragment 的语句时进入锁等待。
|
||||
func waitForBlockedGroupUsageRollupStatement(t *testing.T, ctx context.Context, fragment string) {
|
||||
t.Helper()
|
||||
ticker := time.NewTicker(10 * time.Millisecond)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
var blocked bool
|
||||
require.NoError(t, integrationDB.QueryRowContext(ctx, `
|
||||
SELECT EXISTS (
|
||||
SELECT 1
|
||||
FROM pg_stat_activity
|
||||
WHERE wait_event_type = 'Lock'
|
||||
AND position($1 in query) > 0
|
||||
)
|
||||
`, fragment).Scan(&blocked))
|
||||
if blocked {
|
||||
return
|
||||
}
|
||||
select {
|
||||
case <-ticker.C:
|
||||
case <-ctx.Done():
|
||||
t.Fatalf("等待语句进入锁等待超时: %s", fragment)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// requireGroupUsageRollupsMatchUsageLogs 断言 [retainedFrom 所在日, todayStart) 的日桶与 usage_logs 明细逐日一致。
|
||||
func requireGroupUsageRollupsMatchUsageLogs(t *testing.T, ctx context.Context, db *sql.DB, timezoneName string, retainedFrom, todayStart time.Time) {
|
||||
t.Helper()
|
||||
expected := collectGroupUsageRollupBuckets(t, ctx, db, `
|
||||
SELECT (created_at AT TIME ZONE $3::text)::date::text, group_id, SUM(actual_cost)::float8
|
||||
FROM usage_logs
|
||||
WHERE group_id IS NOT NULL
|
||||
AND created_at >= $1
|
||||
AND created_at < $2
|
||||
GROUP BY 1, 2
|
||||
`, retainedFrom, todayStart, timezoneName)
|
||||
actual := collectGroupUsageRollupBuckets(t, ctx, db, `
|
||||
SELECT bucket_date::text, group_id, actual_cost::float8
|
||||
FROM usage_group_daily_rollups
|
||||
WHERE bucket_date >= ($1::timestamptz AT TIME ZONE $3::text)::date
|
||||
AND bucket_date < ($2::timestamptz AT TIME ZONE $3::text)::date
|
||||
`, retainedFrom, todayStart, timezoneName)
|
||||
require.Equal(t, expected, actual)
|
||||
}
|
||||
|
||||
func collectGroupUsageRollupBuckets(t *testing.T, ctx context.Context, db *sql.DB, query string, args ...any) map[string]float64 {
|
||||
t.Helper()
|
||||
rows, err := db.QueryContext(ctx, query, args...)
|
||||
require.NoError(t, err)
|
||||
defer func() { _ = rows.Close() }()
|
||||
buckets := make(map[string]float64)
|
||||
for rows.Next() {
|
||||
var bucketDate string
|
||||
var groupID int64
|
||||
var cost float64
|
||||
require.NoError(t, rows.Scan(&bucketDate, &groupID, &cost))
|
||||
buckets[fmt.Sprintf("%s/%d", bucketDate, groupID)] = cost
|
||||
}
|
||||
require.NoError(t, rows.Err())
|
||||
return buckets
|
||||
}
|
||||
|
||||
// groupUsageSummaryByGroup 返回 group_id → [total, today, yesterday]。
|
||||
func groupUsageSummaryByGroup(t *testing.T, ctx context.Context, db *sql.DB, todayStart time.Time) map[int64][3]float64 {
|
||||
t.Helper()
|
||||
result, err := newUsageLogRepositoryWithSQL(nil, db).GetAllGroupUsageSummary(ctx, todayStart)
|
||||
require.NoError(t, err)
|
||||
summary := make(map[int64][3]float64, len(result))
|
||||
for _, row := range result {
|
||||
summary[row.GroupID] = [3]float64{row.TotalCost, row.TodayCost, row.YesterdayCost}
|
||||
}
|
||||
return summary
|
||||
}
|
||||
|
||||
// 重建进行中的大批量删除:脏日期已覆盖的行不写状态行,状态行在事务内只更新一次。
|
||||
func TestGroupUsageRollupBulkDeleteDuringBuildWritesStateOnce(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
schema := createGroupUsageRollupTriggerTestSchema(t, ctx, false)
|
||||
tx := beginGroupUsageRollupTriggerTestTx(t, ctx, schema)
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
require.NoError(t, setGroupUsageRollupTriggerTimeZone(ctx, tx, "Asia/Shanghai"))
|
||||
|
||||
_, err := tx.ExecContext(ctx, `
|
||||
INSERT INTO groups (id) VALUES (10);
|
||||
INSERT INTO users (id) VALUES (1);
|
||||
INSERT INTO usage_logs (id, user_id, group_id, actual_cost, created_at)
|
||||
SELECT n, 1, 10, 1, TIMESTAMPTZ '2020-01-15 08:00:00+08' + n * INTERVAL '1 second'
|
||||
FROM generate_series(1, 2000) AS n;
|
||||
UPDATE usage_group_rollup_state
|
||||
SET closed_before = DATE '2020-01-10',
|
||||
building_until = DATE '2020-02-01'
|
||||
WHERE id = 1;
|
||||
`)
|
||||
require.NoError(t, err)
|
||||
|
||||
var updatesBefore int64
|
||||
require.NoError(t, tx.QueryRowContext(ctx, `
|
||||
SELECT n_tup_upd FROM pg_stat_xact_user_tables
|
||||
WHERE schemaname = current_schema() AND relname = 'usage_group_rollup_state'
|
||||
`).Scan(&updatesBefore))
|
||||
|
||||
_, err = tx.ExecContext(ctx, `DELETE FROM usage_logs`)
|
||||
require.NoError(t, err)
|
||||
|
||||
var updatesAfter int64
|
||||
require.NoError(t, tx.QueryRowContext(ctx, `
|
||||
SELECT n_tup_upd FROM pg_stat_xact_user_tables
|
||||
WHERE schemaname = current_schema() AND relname = 'usage_group_rollup_state'
|
||||
`).Scan(&updatesAfter))
|
||||
require.Equal(t, int64(1), updatesAfter-updatesBefore)
|
||||
|
||||
state := readGroupUsageRollupTestStateTx(t, ctx, tx)
|
||||
require.Equal(t, "2020-01-10", state.closedBefore)
|
||||
require.Equal(t, "2020-01-15", state.buildDirtyFrom.String)
|
||||
}
|
||||
|
||||
// 应用侧失效的起点早于保留下界时,从保留下界所在日开始失效。
|
||||
func TestGroupUsageRollupInvalidateAtStartsFromExpiredFloor(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
schema := createGroupUsageRollupTriggerTestSchema(t, ctx, false)
|
||||
tx := beginGroupUsageRollupTriggerTestTx(t, ctx, schema)
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
|
||||
_, err := tx.ExecContext(ctx, `
|
||||
UPDATE usage_group_rollup_state
|
||||
SET closed_before = DATE '2020-03-01',
|
||||
expired_before = TIMESTAMPTZ '2020-02-01 00:00:00+08'
|
||||
WHERE id = 1;
|
||||
SELECT invalidate_group_usage_rollups_at(TIMESTAMPTZ '2020-01-10 08:00:00+08', 'Asia/Shanghai');
|
||||
`)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "2020-02-01", readGroupUsageRollupTestStateTx(t, ctx, tx).closedBefore)
|
||||
|
||||
_, err = tx.ExecContext(ctx, `
|
||||
SELECT invalidate_group_usage_rollups_at(TIMESTAMPTZ '2020-02-10 08:00:00+08', 'Asia/Shanghai')
|
||||
`)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "2020-02-01", readGroupUsageRollupTestStateTx(t, ctx, tx).closedBefore)
|
||||
}
|
||||
|
||||
// 夏令时在零点跳变的日期(America/Santiago 2026-09-06 没有 00:00):从该日续建时不覆盖前一天的日桶。
|
||||
func TestGroupUsageRollupSyncKeepsPreviousDayBucketAcrossMidnightDSTGap(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||
defer cancel()
|
||||
useGroupUsageRepositoryTestTimezone(t, "America/Santiago")
|
||||
schema := createGroupUsageRollupTriggerTestSchema(t, ctx, false)
|
||||
db := openGroupUsageRollupSchemaDB(t, schema, "America/Santiago")
|
||||
santiago, err := time.LoadLocation("America/Santiago")
|
||||
require.NoError(t, err)
|
||||
todayStart := time.Date(2026, 9, 8, 0, 0, 0, 0, santiago)
|
||||
|
||||
execGroupUsageRollupSQL(t, ctx, db, `
|
||||
INSERT INTO groups (id) VALUES (10);
|
||||
INSERT INTO users (id) VALUES (1);
|
||||
INSERT INTO usage_logs (id, user_id, group_id, actual_cost, created_at) VALUES
|
||||
(1, 1, 10, 1, TIMESTAMPTZ '2026-09-06 02:30:00+00'),
|
||||
(2, 1, 10, 2, TIMESTAMPTZ '2026-09-06 03:30:00+00'),
|
||||
(3, 1, 10, 4, TIMESTAMPTZ '2026-09-06 05:00:00+00'),
|
||||
(4, 1, 10, 8, TIMESTAMPTZ '2026-09-07 13:00:00+00');
|
||||
INSERT INTO usage_group_daily_rollups (bucket_date, group_id, actual_cost)
|
||||
VALUES (DATE '2026-09-05', 10, 3);
|
||||
UPDATE usage_group_rollup_state
|
||||
SET closed_before = DATE '2026-09-06',
|
||||
retained_from = TIMESTAMPTZ '2026-09-06 02:30:00+00',
|
||||
timezone_name = 'America/Santiago'
|
||||
WHERE id = 1;
|
||||
`)
|
||||
|
||||
repo := newDashboardAggregationRepositoryWithSQL(db)
|
||||
require.NoError(t, repo.SyncGroupUsageRollups(ctx, todayStart))
|
||||
|
||||
state := readGroupUsageRollupTestState(t, ctx, db)
|
||||
require.Equal(t, "2026-09-08", state.closedBefore)
|
||||
requireGroupUsageRollupsMatchUsageLogs(t, ctx, db, "America/Santiago", state.retainedFrom, todayStart)
|
||||
var previousDay float64
|
||||
require.NoError(t, db.QueryRowContext(ctx, `
|
||||
SELECT actual_cost::float8 FROM usage_group_daily_rollups
|
||||
WHERE bucket_date = DATE '2026-09-05' AND group_id = 10
|
||||
`).Scan(&previousDay))
|
||||
require.InDelta(t, 3, previousDay, 1e-9)
|
||||
}
|
||||
|
||||
// 有长读者持有 usage_logs 的 ACCESS SHARE 时,删除分区在锁等待超时后跳过;
|
||||
// 过期记录由按行删除清理,清理整体成功,分组日汇总保持一致。
|
||||
func TestGroupUsageRollupRetentionCleanupSkipsPartitionDropOnLockTimeout(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
|
||||
defer cancel()
|
||||
useGroupUsageRepositoryTestTimezone(t, "Asia/Shanghai")
|
||||
schema := createGroupUsageRollupTriggerTestSchema(t, ctx, true)
|
||||
db := openGroupUsageRollupSchemaDB(t, schema, "Asia/Shanghai")
|
||||
todayStart := time.Date(2026, 8, 9, 16, 0, 0, 0, time.UTC)
|
||||
|
||||
execGroupUsageRollupSQL(t, ctx, db, `
|
||||
CREATE TABLE usage_logs_202605 PARTITION OF usage_logs
|
||||
FOR VALUES FROM ('2026-05-01') TO ('2026-06-01');
|
||||
INSERT INTO groups (id) VALUES (10);
|
||||
INSERT INTO users (id) VALUES (1);
|
||||
INSERT INTO usage_logs (id, user_id, group_id, actual_cost, created_at) VALUES
|
||||
(1, 1, 10, 1, TIMESTAMPTZ '2026-05-10 10:00:00+08'),
|
||||
(2, 1, 10, 2, TIMESTAMPTZ '2026-07-20 10:00:00+08'),
|
||||
(3, 1, 10, 4, TIMESTAMPTZ '2026-08-05 10:00:00+08');
|
||||
`)
|
||||
repo := newDashboardAggregationRepositoryWithSQL(db)
|
||||
repo.clock = func() time.Time { return todayStart.Add(10 * time.Hour) }
|
||||
require.NoError(t, repo.SyncGroupUsageRollups(ctx, todayStart))
|
||||
|
||||
reader, err := db.BeginTx(ctx, nil)
|
||||
require.NoError(t, err)
|
||||
defer func() { _ = reader.Rollback() }()
|
||||
var count int
|
||||
require.NoError(t, reader.QueryRowContext(ctx, "SELECT COUNT(*) FROM usage_logs").Scan(&count))
|
||||
require.Equal(t, 3, count)
|
||||
|
||||
shanghai, err := time.LoadLocation("Asia/Shanghai")
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, repo.CleanupUsageLogs(ctx, time.Date(2026, 7, 1, 0, 0, 0, 0, shanghai)))
|
||||
require.NoError(t, reader.Rollback())
|
||||
|
||||
var partitionExists bool
|
||||
require.NoError(t, db.QueryRowContext(ctx, "SELECT to_regclass('usage_logs_202605') IS NOT NULL").Scan(&partitionExists))
|
||||
require.True(t, partitionExists)
|
||||
require.NoError(t, db.QueryRowContext(ctx, "SELECT COUNT(*) FROM usage_logs").Scan(&count))
|
||||
require.Equal(t, 2, count)
|
||||
|
||||
state := readGroupUsageRollupTestState(t, ctx, db)
|
||||
require.Equal(t, "2026-08-10", state.closedBefore)
|
||||
requireGroupUsageRollupsMatchUsageLogs(t, ctx, db, "Asia/Shanghai", state.retainedFrom, todayStart)
|
||||
summary := groupUsageSummaryByGroup(t, ctx, db, todayStart)
|
||||
require.InDelta(t, 6, summary[10][0], 1e-9)
|
||||
}
|
||||
@@ -451,6 +451,7 @@ func createGroupUsageRollupTriggerTestSchema(t *testing.T, ctx context.Context,
|
||||
for _, migrationName := range []string{
|
||||
"222_group_usage_daily_rollups.sql",
|
||||
"223_group_usage_rollup_timezone.sql",
|
||||
"251_group_usage_rollup_nonblocking_build.sql",
|
||||
} {
|
||||
migrationSQL, readErr := migrations.FS.ReadFile(migrationName)
|
||||
require.NoError(t, readErr)
|
||||
|
||||
@@ -63,8 +63,6 @@ const (
|
||||
// 上游域名被解析到 443 不可达的 IP 时(DNS 污染/路由异常),单个账号就要卡满
|
||||
// 内核超时;而多账号故障转移是串行的,一次请求会阻塞数分钟且不写中间错误。
|
||||
defaultUpstreamDialTimeout = 10 * time.Second
|
||||
// defaultUpstreamDialKeepAlive: TCP keepalive 探测间隔,与 Go 默认值保持一致
|
||||
defaultUpstreamDialKeepAlive = 30 * time.Second
|
||||
// defaultUpstreamTLSHandshakeTimeout: TLS 握手超时(10秒)
|
||||
// 与建连超时同量级,避免 TCP 已连通但对端不推进握手时无限等待
|
||||
defaultUpstreamTLSHandshakeTimeout = 10 * time.Second
|
||||
@@ -1365,8 +1363,14 @@ func defaultPoolSettings(cfg *config.Config) poolSettings {
|
||||
// 建连没有任何超时上限,只能等内核 TCP 重传耗尽(Linux 约 130 秒)。
|
||||
func newUpstreamDialer() *net.Dialer {
|
||||
return &net.Dialer{
|
||||
Timeout: defaultUpstreamDialTimeout,
|
||||
KeepAlive: defaultUpstreamDialKeepAlive,
|
||||
Timeout: defaultUpstreamDialTimeout,
|
||||
KeepAliveConfig: net.KeepAliveConfig{
|
||||
Enable: true,
|
||||
Idle: upstreamKeepAliveIdle,
|
||||
Interval: upstreamKeepAliveInterval,
|
||||
Count: upstreamKeepAliveCount,
|
||||
},
|
||||
Control: upstreamDialControl,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -30,7 +30,7 @@ func TestNewUpstreamDialerHasBoundedTimeout(t *testing.T) {
|
||||
|
||||
require.Greater(t, dialer.Timeout, time.Duration(0), "建连超时必须有上限")
|
||||
require.Equal(t, defaultUpstreamDialTimeout, dialer.Timeout)
|
||||
require.Equal(t, defaultUpstreamDialKeepAlive, dialer.KeepAlive)
|
||||
require.Equal(t, net.KeepAliveConfig{Enable: true, Idle: 15 * time.Second, Interval: 5 * time.Second, Count: 3}, dialer.KeepAliveConfig)
|
||||
}
|
||||
|
||||
// 建连超时对 HTTP 代理同样生效:Transport.Proxy 走的仍是 DialContext,
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
package repository
|
||||
|
||||
import "time"
|
||||
|
||||
// TCP keep-alive of upstream connections (newUpstreamDialer). A connection
|
||||
// whose peer stops answering is aborted upstreamTCPUserTimeout after its last
|
||||
// received packet: idle 15 s, then 3 probes 5 s apart. With the previous
|
||||
// KeepAlive of 30 s and Go's default interval 15 s and count 9, the same case
|
||||
// took 165 s.
|
||||
//
|
||||
// TCP_USER_TIMEOUT (Linux only, see upstreamDialControl) is set to
|
||||
// idle + interval * count, as Cloudflare's "When TCP sockets refuse to die"
|
||||
// (2019) recommends when both are used: once it is set the kernel aborts on it
|
||||
// rather than on the probe count, so a larger value would add probes and a
|
||||
// smaller one would cut them. It also bounds request data the peer never
|
||||
// acknowledges, where keep-alive does not run. gRPC proposal A18 likewise sets
|
||||
// it only on Linux.
|
||||
const (
|
||||
upstreamKeepAliveIdle = 15 * time.Second
|
||||
upstreamKeepAliveInterval = 5 * time.Second
|
||||
upstreamKeepAliveCount = 3
|
||||
upstreamTCPUserTimeout = upstreamKeepAliveIdle + upstreamKeepAliveInterval*upstreamKeepAliveCount
|
||||
)
|
||||
@@ -0,0 +1,28 @@
|
||||
//go:build linux
|
||||
|
||||
package repository
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
// tcpUserTimeout is TCP_USER_TIMEOUT from Linux include/uapi/linux/tcp.h; the
|
||||
// standard library's syscall package does not define it on linux/amd64.
|
||||
const tcpUserTimeout = 0x12
|
||||
|
||||
// upstreamDialControl sets TCP_USER_TIMEOUT on each upstream socket
|
||||
// before it connects. A failure is logged and the dial goes on without the
|
||||
// option, like the standard library does for the keep-alive options.
|
||||
func upstreamDialControl(network, _ string, raw syscall.RawConn) error {
|
||||
var sockErr error
|
||||
if err := raw.Control(func(fd uintptr) {
|
||||
sockErr = syscall.SetsockoptInt(int(fd), syscall.IPPROTO_TCP, tcpUserTimeout, int(upstreamTCPUserTimeout.Milliseconds()))
|
||||
}); err != nil {
|
||||
sockErr = err
|
||||
}
|
||||
if sockErr != nil {
|
||||
slog.Warn("upstream_tcp_user_timeout_not_set", "network", network, "error", sockErr)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
//go:build linux
|
||||
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"syscall"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// TCP_USER_TIMEOUT in Linux include/uapi/linux/tcp.h.
|
||||
const testTCPUserTimeoutOpt = 0x12
|
||||
|
||||
// A socket dialed by the upstream dialer carries the keep-alive configuration
|
||||
// and TCP_USER_TIMEOUT, read back from the kernel.
|
||||
func TestUpstreamDialerSetsKeepAliveAndUserTimeoutOnTheSocket(t *testing.T) {
|
||||
listener, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { _ = listener.Close() })
|
||||
accepted := make(chan net.Conn, 1)
|
||||
go func() {
|
||||
server, err := listener.Accept()
|
||||
if err != nil {
|
||||
close(accepted)
|
||||
return
|
||||
}
|
||||
accepted <- server
|
||||
}()
|
||||
|
||||
conn, err := newUpstreamDialer().DialContext(context.Background(), "tcp", listener.Addr().String())
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { _ = conn.Close() })
|
||||
if server, ok := <-accepted; ok {
|
||||
t.Cleanup(func() { _ = server.Close() })
|
||||
}
|
||||
tcpConn, ok := conn.(*net.TCPConn)
|
||||
require.True(t, ok, "%T", conn)
|
||||
raw, err := tcpConn.SyscallConn()
|
||||
require.NoError(t, err)
|
||||
|
||||
got := map[string]int{}
|
||||
var readErr error
|
||||
require.NoError(t, raw.Control(func(fd uintptr) {
|
||||
for _, opt := range []struct {
|
||||
name string
|
||||
level, which int
|
||||
}{
|
||||
{"SO_KEEPALIVE", syscall.SOL_SOCKET, syscall.SO_KEEPALIVE},
|
||||
{"TCP_KEEPIDLE", syscall.IPPROTO_TCP, syscall.TCP_KEEPIDLE},
|
||||
{"TCP_KEEPINTVL", syscall.IPPROTO_TCP, syscall.TCP_KEEPINTVL},
|
||||
{"TCP_KEEPCNT", syscall.IPPROTO_TCP, syscall.TCP_KEEPCNT},
|
||||
{"TCP_USER_TIMEOUT", syscall.IPPROTO_TCP, testTCPUserTimeoutOpt},
|
||||
} {
|
||||
value, err := syscall.GetsockoptInt(int(fd), opt.level, opt.which)
|
||||
if err != nil {
|
||||
readErr = err
|
||||
return
|
||||
}
|
||||
got[opt.name] = value
|
||||
}
|
||||
}))
|
||||
require.NoError(t, readErr)
|
||||
require.Equal(t, map[string]int{
|
||||
"SO_KEEPALIVE": 1,
|
||||
"TCP_KEEPIDLE": 15,
|
||||
"TCP_KEEPINTVL": 5,
|
||||
"TCP_KEEPCNT": 3,
|
||||
"TCP_USER_TIMEOUT": 30000,
|
||||
}, got)
|
||||
}
|
||||
|
||||
// A socket option the kernel refuses must not fail the dial: TCP_USER_TIMEOUT
|
||||
// does not apply to a UDP socket, so setting it there returns an error.
|
||||
func TestUpstreamDialerIgnoresUserTimeoutFailure(t *testing.T) {
|
||||
packetConn, err := net.ListenPacket("udp", "127.0.0.1:0")
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { _ = packetConn.Close() })
|
||||
|
||||
conn, err := newUpstreamDialer().DialContext(context.Background(), "udp", packetConn.LocalAddr().String())
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, conn.Close())
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
//go:build !linux
|
||||
|
||||
package repository
|
||||
|
||||
import "syscall"
|
||||
|
||||
// upstreamDialControl is nil off Linux: TCP_USER_TIMEOUT is a Linux socket
|
||||
// option, and the keep-alive configuration alone bounds idle connections.
|
||||
var upstreamDialControl func(network, address string, c syscall.RawConn) error
|
||||
@@ -36,6 +36,7 @@ const (
|
||||
|
||||
var (
|
||||
integrationDB *sql.DB
|
||||
integrationDSN string
|
||||
integrationEntClient *dbent.Client
|
||||
integrationRedis *redisclient.Client
|
||||
|
||||
@@ -91,6 +92,7 @@ func TestMain(m *testing.M) {
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
integrationDSN = dsn
|
||||
integrationDB, err = openSQLWithRetry(ctx, dsn, 30*time.Second)
|
||||
if err != nil {
|
||||
log.Printf("failed to open sql db: %v", err)
|
||||
|
||||
@@ -58,6 +58,7 @@ func TestMigrationsRunner_IsIdempotent_AndSchemaIsUpToDate(t *testing.T) {
|
||||
// groups: OpenAI Live 与 Fast 强制策略都默认关闭,管理员显式开启后才生效。
|
||||
requireColumn(t, tx, "groups", "allow_live", "boolean", 0, false)
|
||||
requireColumn(t, tx, "groups", "force_openai_fast", "boolean", 0, false)
|
||||
requireColumn(t, tx, "groups", "force_openai_ultrafast", "boolean", 0, false)
|
||||
requireColumn(t, tx, "groups", "free_openai_fast", "boolean", 0, false)
|
||||
|
||||
// api_keys: key length should be 128
|
||||
|
||||
@@ -8,8 +8,10 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"runtime/debug"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
@@ -17,6 +19,7 @@ import (
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/redis/go-redis/v9"
|
||||
"github.com/tidwall/gjson"
|
||||
"golang.org/x/sync/singleflight"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -35,7 +38,7 @@ const (
|
||||
// 账号精简记录(sched:meta:<id>)的修订号:全局修订号与按平台划分的修订号(前缀后接平台名)。
|
||||
// 改写精简记录后写入所涉平台的修订号;删除记录、改写平台为空或平台发生变化的记录、写入出错时写入全局修订号。
|
||||
// 取值都是新的随机串,读侧只比较是否相等,键丢失后重建也不会与旧取值相同;
|
||||
// Redis 回滚恢复出缓存记录过的旧取值时,由最长复用时长兜底。
|
||||
// Redis 回滚恢复出缓存记录过的旧取值时,由进程内快照缓存的直接复用时长与宽限期兜底。
|
||||
schedulerAccountMetaRevisionKey = "sched:meta:rev"
|
||||
schedulerAccountMetaPlatformRevisionPrefix = "sched:meta:rev:"
|
||||
|
||||
@@ -47,12 +50,20 @@ const (
|
||||
// 替代立即 DEL,让正在读取旧版本的 reader 有足够时间完成 ZRANGE。
|
||||
snapshotGraceTTLSeconds = 60
|
||||
|
||||
// schedulerSnapshotCacheMaxAge 是进程内快照缓存条目的最长复用时长,
|
||||
// 限定了未推进修订号的精简记录改写在本进程的最长可见延迟,与 outbox_lag_rebuild_seconds 默认 10 秒的陈旧容忍度相同。
|
||||
// schedulerSnapshotCacheMaxAge 是进程内快照缓存条目的直接复用时长,与 outbox_lag_rebuild_seconds 默认 10 秒的陈旧容忍度相同。
|
||||
// 未推进修订号的精简记录改写在本进程的可见延迟不超过该时长与 schedulerSnapshotCacheStaleGrace 之和(另加一次加载耗时)。
|
||||
schedulerSnapshotCacheMaxAge = 10 * time.Second
|
||||
// schedulerSnapshotCacheStaleGrace:条目超过直接复用时长、但 (active, 修订号) 仍与 Redis 一致时,
|
||||
// 在该宽限期内继续返回该条目,同时触发一次后台加载;超过宽限期后调用方等待加载结果。
|
||||
schedulerSnapshotCacheStaleGrace = 20 * time.Second
|
||||
// schedulerSnapshotCacheEvictAge:写入条目时,加载时间早于该时长的其它条目一并清除,
|
||||
// 已退休分组的条目不会长期驻留。
|
||||
schedulerSnapshotCacheEvictAge = 10 * schedulerSnapshotCacheMaxAge
|
||||
// schedulerLastUsedCacheMaxAge 是条目内 last_used 读取结果的复用时长;本进程写入 last_used 后该结果立即失效。
|
||||
schedulerLastUsedCacheMaxAge = 200 * time.Millisecond
|
||||
// schedulerSharedLoadTimeout 是合并加载(快照条目、last_used)的上下文时限,约束取连接与重试;
|
||||
// 单次套接字读取另受 Redis 客户端读超时约束。合并加载不随单个调用方取消。
|
||||
schedulerSharedLoadTimeout = 10 * time.Second
|
||||
|
||||
schedulerAccountMetaRevisionBytes = 16
|
||||
schedulerAccountMetaRevisionWriteTimeout = 3 * time.Second
|
||||
@@ -250,6 +261,10 @@ type schedulerCache struct {
|
||||
|
||||
snapshotMu sync.RWMutex
|
||||
snapshotEntries map[string]*schedulerSnapshotEntry
|
||||
// snapshotLoads 合并同一 bucket、同一组 (active, 修订号) 的条目加载。
|
||||
snapshotLoads singleflight.Group
|
||||
// lastUsedGeneration 在本进程每次写入 last_used 后递增,条目内缓存的 last_used 读取结果随之失效。
|
||||
lastUsedGeneration atomic.Uint64
|
||||
|
||||
// globalRevisionPending 与 globalRevisionWriting 合并写入出错后的后台全局修订号写入,见 scheduleGlobalAccountMetaRevision。
|
||||
globalRevisionPending atomic.Bool
|
||||
@@ -258,14 +273,38 @@ type schedulerCache struct {
|
||||
|
||||
// schedulerSnapshotEntry 是一个 bucket 的已解码快照。
|
||||
// revisions 依次是全局修订号与该 bucket 成员可能涉及的各平台修订号(见 schedulerSnapshotTagKeys)。
|
||||
// accounts 是按快照顺序排列的母本,发布后只读,指针不外泄;
|
||||
// accounts 是按快照顺序排列的母本,发布后只读,指针不外泄;母本可以同时被多个条目引用。
|
||||
// ids、payloads、lastUsedKeys 与 accounts 一一对齐,payloads 是解码出母本的精简记录原文。
|
||||
// 每次读取都按值复制出本次请求独占的副本再套用 last_used。
|
||||
type schedulerSnapshotEntry struct {
|
||||
active string
|
||||
revisions []string
|
||||
loadedAt time.Time
|
||||
ids []string
|
||||
accounts []*service.Account
|
||||
payloads []string
|
||||
lastUsedKeys []string
|
||||
|
||||
lastUsed atomic.Pointer[schedulerLastUsedValues]
|
||||
lastUsedLoads singleflight.Group
|
||||
// refreshing 在宽限期内的后台加载进行期间为 true,同一条目同时只发起一次后台加载。
|
||||
refreshing atomic.Bool
|
||||
}
|
||||
|
||||
// schedulerLastUsedValues 是条目的一次 last_used 读取结果,与条目的 accounts 一一对齐。
|
||||
// nil 表示沿用母本的 LastUsedAt;非 nil 的时间晚于母本,由各次读取共享,不得原地修改。
|
||||
type schedulerLastUsedValues struct {
|
||||
fetchedAt time.Time
|
||||
generation uint64
|
||||
values []*time.Time
|
||||
}
|
||||
|
||||
func (v *schedulerLastUsedValues) freshAt(now time.Time, generation uint64) bool {
|
||||
if v == nil || v.generation != generation {
|
||||
return false
|
||||
}
|
||||
age := now.Sub(v.fetchedAt)
|
||||
return age >= 0 && age < schedulerLastUsedCacheMaxAge
|
||||
}
|
||||
|
||||
func NewSchedulerCache(rdb *redis.Client) service.SchedulerCache {
|
||||
@@ -288,60 +327,141 @@ func newSchedulerCacheWithChunkSizes(rdb *redis.Client, mgetChunkSize, writeChun
|
||||
}
|
||||
}
|
||||
|
||||
// GetSnapshot 读取 bucket 的激活快照。解码后的精简记录按 bucket 常驻进程内存,
|
||||
// 只有 ready、active 版本、全局修订号与该 bucket 所涉平台的修订号都与 Redis 一致且未超过最长复用时长时才复用;
|
||||
// 否则重新从 Redis 加载。last_used 每次都从 Redis 读取。
|
||||
// 返回的账号对象由本次调用独占,可以修改其顶层字段;map、切片底层数组与指针指向的值与其它调用共享,不得原地修改。
|
||||
// GetSnapshot 读取 bucket 的激活快照,语义与返回账号的使用约束同 GetSnapshotValues。
|
||||
func (c *schedulerCache) GetSnapshot(ctx context.Context, bucket service.SchedulerBucket) ([]*service.Account, bool, error) {
|
||||
values, hit, err := c.GetSnapshotValues(ctx, bucket)
|
||||
if err != nil || !hit {
|
||||
return nil, false, err
|
||||
}
|
||||
accounts := make([]*service.Account, len(values))
|
||||
for i := range values {
|
||||
accounts[i] = &values[i]
|
||||
}
|
||||
return accounts, true, nil
|
||||
}
|
||||
|
||||
// GetSnapshotValues 读取 bucket 的激活快照。解码后的精简记录按 bucket 常驻进程内存:
|
||||
// ready、active 版本、全局修订号与该 bucket 所涉平台的修订号都与 Redis 一致且未超过直接复用时长时直接复用;
|
||||
// (active, 修订号) 一致但超过直接复用时长的条目在宽限期内继续返回,同时触发一次后台加载;其余情况等待加载结果。
|
||||
// 同一 bucket、同一组 (active, 修订号) 的并发加载合并为一次;加载时精简记录原文未变、
|
||||
// 且预解析结果对应当前运行时模型映射版本的账号沿用已解码的母本。
|
||||
// last_used 读取结果在条目内复用 schedulerLastUsedCacheMaxAge。
|
||||
// 返回的切片与其中的账号由本次调用独占,可以修改账号的顶层字段;map、切片底层数组与指针指向的值与其它调用共享,不得原地修改。
|
||||
func (c *schedulerCache) GetSnapshotValues(ctx context.Context, bucket service.SchedulerBucket) ([]service.Account, bool, error) {
|
||||
entry, err := c.snapshotEntry(ctx, bucket)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
if entry == nil {
|
||||
return nil, false, nil
|
||||
}
|
||||
accounts, err := c.snapshotAccountsFromEntry(ctx, entry)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
return accounts, true, nil
|
||||
}
|
||||
|
||||
// snapshotEntry 返回 bucket 当前可用的条目;nil 表示快照未命中。
|
||||
func (c *schedulerCache) snapshotEntry(ctx context.Context, bucket service.SchedulerBucket) (*schedulerSnapshotEntry, error) {
|
||||
bucketKey := bucket.String()
|
||||
tagKeys := schedulerSnapshotTagKeys(bucket)
|
||||
tags, err := c.rdb.MGet(ctx, tagKeys...).Result()
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
return nil, err
|
||||
}
|
||||
if len(tags) != len(tagKeys) {
|
||||
return nil, false, fmt.Errorf("unexpected scheduler snapshot tag count: got %d, want %d", len(tags), len(tagKeys))
|
||||
return nil, fmt.Errorf("unexpected scheduler snapshot tag count: got %d, want %d", len(tags), len(tagKeys))
|
||||
}
|
||||
readyVal, err := schedulerCacheOptionalString(tags[0])
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
return nil, err
|
||||
}
|
||||
activeVal, err := schedulerCacheOptionalString(tags[1])
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
return nil, err
|
||||
}
|
||||
// 修订号缺失(nil)按空字符串比较:它是一个独立取值,不会与任何写入过的随机修订号相等。
|
||||
revisions := make([]string, 0, len(tags)-2)
|
||||
for _, tag := range tags[2:] {
|
||||
revision, err := schedulerCacheOptionalString(tag)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
return nil, err
|
||||
}
|
||||
revisions = append(revisions, revision)
|
||||
}
|
||||
if readyVal != "1" || activeVal == "" {
|
||||
c.dropSnapshotEntry(bucketKey)
|
||||
return nil, false, nil
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
now := c.now()
|
||||
if entry := c.lookupSnapshotEntry(bucketKey); entry != nil && entry.matches(activeVal, revisions, now) {
|
||||
accounts, err := c.snapshotAccountsFromEntry(ctx, entry)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
if entry := c.lookupSnapshotEntry(bucketKey); entry != nil && entry.sameVersion(activeVal, revisions) {
|
||||
age := now.Sub(entry.loadedAt)
|
||||
if age >= 0 && age < schedulerSnapshotCacheMaxAge {
|
||||
return entry, nil
|
||||
}
|
||||
if age >= 0 && age < schedulerSnapshotCacheMaxAge+schedulerSnapshotCacheStaleGrace {
|
||||
if entry.refreshing.CompareAndSwap(false, true) {
|
||||
results := c.loadSnapshotEntryShared(ctx, bucket, bucketKey, activeVal, revisions, now)
|
||||
go func() {
|
||||
if result := <-results; result.Err != nil {
|
||||
slog.Warn("scheduler snapshot background reload failed", "bucket", bucketKey, "error", result.Err)
|
||||
}
|
||||
entry.refreshing.Store(false)
|
||||
}()
|
||||
}
|
||||
return entry, nil
|
||||
}
|
||||
return accounts, true, nil
|
||||
}
|
||||
|
||||
ids, err := c.rdb.ZRange(ctx, schedulerSnapshotKey(bucket, activeVal), 0, -1).Result()
|
||||
select {
|
||||
case result := <-c.loadSnapshotEntryShared(ctx, bucket, bucketKey, activeVal, revisions, now):
|
||||
if result.Err != nil {
|
||||
return nil, result.Err
|
||||
}
|
||||
entry, _ := result.Val.(*schedulerSnapshotEntry)
|
||||
return entry, nil
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
}
|
||||
|
||||
// loadSnapshotEntryShared 发起或加入 bucket 在给定 (active, 修订号) 下的条目加载,结果的 Val 为 nil 表示快照未命中。
|
||||
// 加载使用与调用方取消解耦、时限为 schedulerSharedLoadTimeout 的上下文。
|
||||
func (c *schedulerCache) loadSnapshotEntryShared(ctx context.Context, bucket service.SchedulerBucket, bucketKey, active string, revisions []string, now time.Time) <-chan singleflight.Result {
|
||||
key := bucketKey + "\x00" + active + "\x00" + strings.Join(revisions, "\x00")
|
||||
loadCtx := context.WithoutCancel(ctx)
|
||||
return c.snapshotLoads.DoChan(key, recoverSchedulerSharedLoad("scheduler snapshot load", func() (any, error) {
|
||||
ctx, cancel := context.WithTimeout(loadCtx, schedulerSharedLoadTimeout)
|
||||
defer cancel()
|
||||
entry, err := c.loadSnapshotEntry(ctx, bucket, bucketKey, active, revisions, now)
|
||||
if err != nil || entry == nil {
|
||||
return nil, err
|
||||
}
|
||||
return entry, nil
|
||||
}))
|
||||
}
|
||||
|
||||
// loadSnapshotEntry 从 Redis 加载条目并写入进程内缓存,返回 nil 表示快照未命中。
|
||||
// 条目记录的是加载前读到的 (active, 修订号) 与当时的时钟 now:精简记录读取晚于这组取值,
|
||||
// 之后若再有改写,修订号或 active 必然不同,或在直接复用时长与宽限期之和后不再返回。
|
||||
// 进程内已有同一 (active, 修订号) 且未过期的条目时直接返回它。
|
||||
func (c *schedulerCache) loadSnapshotEntry(ctx context.Context, bucket service.SchedulerBucket, bucketKey, active string, revisions []string, now time.Time) (*schedulerSnapshotEntry, error) {
|
||||
previous := c.lookupSnapshotEntry(bucketKey)
|
||||
if previous != nil && previous.matches(active, revisions, c.now()) {
|
||||
return previous, nil
|
||||
}
|
||||
|
||||
ids, err := c.rdb.ZRange(ctx, schedulerSnapshotKey(bucket, active), 0, -1).Result()
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
return nil, err
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
// 空快照视为缓存未命中,触发数据库回退查询
|
||||
// 这解决了新分组创建后立即绑定账号时的竞态条件问题
|
||||
c.dropSnapshotEntry(bucketKey)
|
||||
return nil, false, nil
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
keys := make([]string, 0, len(ids))
|
||||
@@ -352,74 +472,156 @@ func (c *schedulerCache) GetSnapshot(ctx context.Context, bucket service.Schedul
|
||||
}
|
||||
values, err := c.mgetChunked(ctx, keys)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
return nil, err
|
||||
}
|
||||
if len(values) != len(ids) {
|
||||
return nil, fmt.Errorf("unexpected scheduler account metadata count: got %d, want %d", len(values), len(ids))
|
||||
}
|
||||
|
||||
masters := make([]*service.Account, 0, len(values))
|
||||
for _, val := range values {
|
||||
reusable := previous.masterIndex()
|
||||
masters := make([]*service.Account, len(values))
|
||||
payloads := make([]string, len(values))
|
||||
for i, val := range values {
|
||||
if val == nil {
|
||||
c.dropSnapshotEntry(bucketKey)
|
||||
return nil, false, nil
|
||||
return nil, nil
|
||||
}
|
||||
account, err := decodeCachedAccount(val)
|
||||
payload, err := schedulerCachePayload(val)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
return nil, err
|
||||
}
|
||||
masters = append(masters, account)
|
||||
}
|
||||
// 母本发布进缓存前由本 goroutine 完成预处理,发布后只读。
|
||||
for _, master := range masters {
|
||||
master.PrepareSharedSnapshot()
|
||||
if j, ok := reusable[ids[i]]; ok && previous.payloads[j] == payload && previous.accounts[j].SharedSnapshotCurrent() {
|
||||
masters[i] = previous.accounts[j]
|
||||
payloads[i] = previous.payloads[j]
|
||||
continue
|
||||
}
|
||||
account, err := decodeCachedAccountPayload(payload)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// 母本发布进缓存前由本 goroutine 完成预处理,发布后只读。
|
||||
account.PrepareSharedSnapshot()
|
||||
masters[i] = account
|
||||
payloads[i] = payload
|
||||
}
|
||||
|
||||
// 条目记录的是加载前读到的 (active, 修订号) 与当时的时钟:精简记录读取晚于这组取值,
|
||||
// 之后若再有改写,修订号或 active 必然不同,或在最长复用时长后过期。
|
||||
entry := &schedulerSnapshotEntry{
|
||||
active: activeVal,
|
||||
active: active,
|
||||
revisions: revisions,
|
||||
loadedAt: now,
|
||||
ids: ids,
|
||||
accounts: masters,
|
||||
payloads: payloads,
|
||||
lastUsedKeys: lastUsedKeys,
|
||||
}
|
||||
c.storeSnapshotEntry(bucketKey, entry)
|
||||
return entry, nil
|
||||
}
|
||||
|
||||
accounts, err := c.snapshotAccountsFromEntry(ctx, entry)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
return accounts, true, nil
|
||||
func (e *schedulerSnapshotEntry) sameVersion(active string, revisions []string) bool {
|
||||
return e.active == active && slices.Equal(e.revisions, revisions)
|
||||
}
|
||||
|
||||
func (e *schedulerSnapshotEntry) matches(active string, revisions []string, now time.Time) bool {
|
||||
if e.active != active || !slices.Equal(e.revisions, revisions) {
|
||||
if !e.sameVersion(active, revisions) {
|
||||
return false
|
||||
}
|
||||
age := now.Sub(e.loadedAt)
|
||||
return age >= 0 && age < schedulerSnapshotCacheMaxAge
|
||||
}
|
||||
|
||||
// snapshotAccountsFromEntry 读取最新 last_used,并为本次调用一次性分配一组母本副本。
|
||||
func (c *schedulerCache) snapshotAccountsFromEntry(ctx context.Context, entry *schedulerSnapshotEntry) ([]*service.Account, error) {
|
||||
lastUsedValues, err := c.mgetChunked(ctx, entry.lastUsedKeys)
|
||||
// masterIndex 返回账号 ID 到母本下标的映射;条目为 nil 或缺少原文时返回 nil。
|
||||
func (e *schedulerSnapshotEntry) masterIndex() map[string]int {
|
||||
if e == nil || len(e.ids) == 0 || len(e.ids) != len(e.accounts) || len(e.ids) != len(e.payloads) {
|
||||
return nil
|
||||
}
|
||||
index := make(map[string]int, len(e.ids))
|
||||
for i, id := range e.ids {
|
||||
index[id] = i
|
||||
}
|
||||
return index
|
||||
}
|
||||
|
||||
// snapshotAccountsFromEntry 为本次调用一次性分配一组母本副本,并套用 last_used。
|
||||
func (c *schedulerCache) snapshotAccountsFromEntry(ctx context.Context, entry *schedulerSnapshotEntry) ([]service.Account, error) {
|
||||
lastUsed, err := c.entryLastUsed(ctx, entry)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(lastUsedValues) != len(entry.accounts) {
|
||||
return nil, fmt.Errorf("unexpected scheduler last_used value count: got %d, want %d", len(lastUsedValues), len(entry.accounts))
|
||||
}
|
||||
slab := make([]service.Account, len(entry.accounts))
|
||||
accounts := make([]*service.Account, len(entry.accounts))
|
||||
accounts := make([]service.Account, len(entry.accounts))
|
||||
for i, master := range entry.accounts {
|
||||
slab[i] = *master
|
||||
account := &slab[i]
|
||||
if err := applySchedulerLastUsed(account, lastUsedValues[i]); err != nil {
|
||||
return nil, err
|
||||
accounts[i] = *master
|
||||
if lastUsed[i] != nil {
|
||||
accounts[i].LastUsedAt = lastUsed[i]
|
||||
}
|
||||
accounts[i] = account
|
||||
}
|
||||
return accounts, nil
|
||||
}
|
||||
|
||||
// entryLastUsed 返回条目的 last_used 读取结果:结果未超过 schedulerLastUsedCacheMaxAge 且本进程此后未写入 last_used 时直接复用,
|
||||
// 否则等待一次合并后的读取。
|
||||
func (c *schedulerCache) entryLastUsed(ctx context.Context, entry *schedulerSnapshotEntry) ([]*time.Time, error) {
|
||||
generation := c.lastUsedGeneration.Load()
|
||||
if current := entry.lastUsed.Load(); current.freshAt(c.now(), generation) {
|
||||
return current.values, nil
|
||||
}
|
||||
loadCtx := context.WithoutCancel(ctx)
|
||||
results := entry.lastUsedLoads.DoChan(strconv.FormatUint(generation, 10), recoverSchedulerSharedLoad("scheduler last_used load", func() (any, error) {
|
||||
fetchedAt := c.now()
|
||||
if current := entry.lastUsed.Load(); current.freshAt(fetchedAt, generation) {
|
||||
return current, nil
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(loadCtx, schedulerSharedLoadTimeout)
|
||||
defer cancel()
|
||||
raw, err := c.mgetChunked(ctx, entry.lastUsedKeys)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(raw) != len(entry.accounts) {
|
||||
return nil, fmt.Errorf("unexpected scheduler last_used value count: got %d, want %d", len(raw), len(entry.accounts))
|
||||
}
|
||||
values := make([]*time.Time, len(raw))
|
||||
for i, value := range raw {
|
||||
lastUsedAt, err := parseSchedulerLastUsed(value)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if lastUsedAt != nil && (entry.accounts[i].LastUsedAt == nil || lastUsedAt.After(*entry.accounts[i].LastUsedAt)) {
|
||||
values[i] = lastUsedAt
|
||||
}
|
||||
}
|
||||
loaded := &schedulerLastUsedValues{fetchedAt: fetchedAt, generation: generation, values: values}
|
||||
entry.lastUsed.Store(loaded)
|
||||
return loaded, nil
|
||||
}))
|
||||
select {
|
||||
case result := <-results:
|
||||
if result.Err != nil {
|
||||
return nil, result.Err
|
||||
}
|
||||
loaded, _ := result.Val.(*schedulerLastUsedValues)
|
||||
if loaded == nil {
|
||||
return nil, errors.New("scheduler last_used load returned no values")
|
||||
}
|
||||
return loaded.values, nil
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
}
|
||||
|
||||
// recoverSchedulerSharedLoad 包装合并加载:加载 panic 时记录堆栈并转成错误交给全部等待方。
|
||||
func recoverSchedulerSharedLoad(name string, load func() (any, error)) func() (any, error) {
|
||||
return func() (result any, err error) {
|
||||
defer func() {
|
||||
if recovered := recover(); recovered != nil {
|
||||
slog.Error("scheduler shared load panicked", "load", name, "panic", recovered, "stack", string(debug.Stack()))
|
||||
result, err = nil, fmt.Errorf("%s panicked: %v", name, recovered)
|
||||
}
|
||||
}()
|
||||
return load()
|
||||
}
|
||||
}
|
||||
|
||||
func (c *schedulerCache) lookupSnapshotEntry(bucketKey string) *schedulerSnapshotEntry {
|
||||
c.snapshotMu.RLock()
|
||||
defer c.snapshotMu.RUnlock()
|
||||
@@ -846,6 +1048,8 @@ func (c *schedulerCache) UpdateLastUsed(ctx context.Context, updates map[int64]t
|
||||
pipe.Set(ctx, schedulerAccountMetaRevisionKey, newSchedulerAccountMetaRevision(), 0)
|
||||
}
|
||||
_, err := pipe.Exec(ctx)
|
||||
// 写入结束(含部分失败)后才推进本进程的代际:此后发起的 last_used 读取都排在写入之后。
|
||||
c.lastUsedGeneration.Add(1)
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -930,9 +1134,24 @@ func schedulerLastUsedMillis(value time.Time) (int64, error) {
|
||||
}
|
||||
|
||||
func applySchedulerLastUsed(account *service.Account, value any) error {
|
||||
if account == nil || value == nil {
|
||||
if account == nil {
|
||||
return nil
|
||||
}
|
||||
lastUsedAt, err := parseSchedulerLastUsed(value)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if lastUsedAt != nil && (account.LastUsedAt == nil || lastUsedAt.After(*account.LastUsedAt)) {
|
||||
account.LastUsedAt = lastUsedAt
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// parseSchedulerLastUsed 解析 last_used 侧键的毫秒时间戳;键不存在(nil)时返回 nil。
|
||||
func parseSchedulerLastUsed(value any) (*time.Time, error) {
|
||||
if value == nil {
|
||||
return nil, nil
|
||||
}
|
||||
var raw string
|
||||
switch typed := value.(type) {
|
||||
case string:
|
||||
@@ -940,31 +1159,38 @@ func applySchedulerLastUsed(account *service.Account, value any) error {
|
||||
case []byte:
|
||||
raw = string(typed)
|
||||
default:
|
||||
return fmt.Errorf("unexpected last_used cache type: %T", value)
|
||||
return nil, fmt.Errorf("unexpected last_used cache type: %T", value)
|
||||
}
|
||||
millis, err := strconv.ParseInt(raw, 10, 64)
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid last_used cache value %q: %w", raw, err)
|
||||
return nil, fmt.Errorf("invalid last_used cache value %q: %w", raw, err)
|
||||
}
|
||||
lastUsedAt := time.UnixMilli(millis).UTC()
|
||||
if account.LastUsedAt == nil || lastUsedAt.After(*account.LastUsedAt) {
|
||||
account.LastUsedAt = ptrTime(lastUsedAt)
|
||||
}
|
||||
return nil
|
||||
return ptrTime(time.UnixMilli(millis).UTC()), nil
|
||||
}
|
||||
|
||||
func decodeCachedAccount(val any) (*service.Account, error) {
|
||||
var payload []byte
|
||||
payload, err := schedulerCachePayload(val)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return decodeCachedAccountPayload(payload)
|
||||
}
|
||||
|
||||
// schedulerCachePayload 取出 Redis 返回的账号记录原文。
|
||||
func schedulerCachePayload(val any) (string, error) {
|
||||
switch raw := val.(type) {
|
||||
case string:
|
||||
payload = []byte(raw)
|
||||
return raw, nil
|
||||
case []byte:
|
||||
payload = raw
|
||||
return string(raw), nil
|
||||
default:
|
||||
return nil, fmt.Errorf("unexpected account cache type: %T", val)
|
||||
return "", fmt.Errorf("unexpected account cache type: %T", val)
|
||||
}
|
||||
}
|
||||
|
||||
func decodeCachedAccountPayload(payload string) (*service.Account, error) {
|
||||
var account service.Account
|
||||
if err := json.Unmarshal(payload, &account); err != nil {
|
||||
if err := json.Unmarshal([]byte(payload), &account); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &account, nil
|
||||
@@ -975,7 +1201,7 @@ func decodeCachedAccount(val any) (*service.Account, error) {
|
||||
// 与最后一批精简记录同一次往返发出,且排在全部精简记录写入之后。
|
||||
// 精简记录用 SET ... GET 写入并取回旧值:旧值的平台与新平台不同时,旧平台 bucket 中可能仍缓存着该账号,
|
||||
// 全部写入完成后另行写入全局修订号。该检测尽力而为(客户端在 pipeline 内部重试时取回的可能已是本次写入的值),
|
||||
// 漏检由进程内快照缓存的最长复用时长兜底。
|
||||
// 漏检由进程内快照缓存的直接复用时长与宽限期兜底。
|
||||
// 任一块执行出错时,此前已执行的块与出错的块都可能已有精简记录生效,返回时启动后台写入全局修订号。
|
||||
func (c *schedulerCache) writeAccountIDs(ctx context.Context, accounts []service.Account) ([]int64, error) {
|
||||
if len(accounts) == 0 {
|
||||
@@ -1102,7 +1328,7 @@ func (c *schedulerCache) scheduleGlobalAccountMetaRevision(ctx context.Context)
|
||||
}
|
||||
|
||||
// advanceGlobalAccountMetaRevision 单独写入新的全局修订号,使所有 bucket 的进程内快照失效。
|
||||
// 不受调用方取消影响;失败只记录日志,由进程内快照缓存的最长复用时长兜底。
|
||||
// 不受调用方取消影响;失败只记录日志,由进程内快照缓存的直接复用时长与宽限期兜底。
|
||||
func (c *schedulerCache) advanceGlobalAccountMetaRevision(ctx context.Context) {
|
||||
writeCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), schedulerAccountMetaRevisionWriteTimeout)
|
||||
defer cancel()
|
||||
@@ -1135,21 +1361,29 @@ func (c *schedulerCache) mgetChunked(ctx context.Context, keys []string) ([]any,
|
||||
return []any{}, nil
|
||||
}
|
||||
|
||||
out := make([]any, 0, len(keys))
|
||||
chunkSize := c.mgetChunkSize
|
||||
if chunkSize <= 0 {
|
||||
chunkSize = defaultSchedulerSnapshotMGetChunkSize
|
||||
}
|
||||
if len(keys) <= chunkSize {
|
||||
return c.rdb.MGet(ctx, keys...).Result()
|
||||
}
|
||||
// 多个分块的 MGET 放在同一个 pipeline 里,一次往返发出。
|
||||
pipe := c.rdb.Pipeline()
|
||||
cmds := make([]*redis.SliceCmd, 0, (len(keys)+chunkSize-1)/chunkSize)
|
||||
for start := 0; start < len(keys); start += chunkSize {
|
||||
end := start + chunkSize
|
||||
if end > len(keys) {
|
||||
end = len(keys)
|
||||
}
|
||||
part, err := c.rdb.MGet(ctx, keys[start:end]...).Result()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, part...)
|
||||
cmds = append(cmds, pipe.MGet(ctx, keys[start:end]...))
|
||||
}
|
||||
if _, err := pipe.Exec(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make([]any, 0, len(keys))
|
||||
for _, cmd := range cmds {
|
||||
out = append(out, cmd.Val()...)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -1249,6 +1483,11 @@ func filterSchedulerCredentials(credentials map[string]any) map[string]any {
|
||||
// Candidate-list admission evaluates the account override before hydrating
|
||||
// the full account. Dropping it silently falls back to the platform threshold.
|
||||
keys := []string{"model_mapping", "compact_model_mapping", "api_key", "project_id", "oauth_type", "plan_type", "account_scheduling_threshold",
|
||||
// OpenAI 端点能力集必须进投影:候选过滤按 SupportsOpenAIEndpointCapability 判
|
||||
// capability_mismatch,而 Seedance 分支直接读该键、不走「未配置即放行」。
|
||||
// 裁掉后 Seedance 账号在选号阶段必然被剔除,表现为 /v1/models 能列出模型、
|
||||
// 建任务恒定 503 seedance_no_eligible_account。
|
||||
"openai_capabilities",
|
||||
// Gemini 显式缓存的候选过滤(GeminiExplicitCacheExclusions)读本投影判定账号是否支持显式缓存:
|
||||
// 官方地址、Vertex 认证方式与上游网关的显式缓存声明。缺这几个键时只能按类型粗筛,
|
||||
// 不支持的账号要逐个选中后才被剔除。
|
||||
@@ -1317,6 +1556,8 @@ func filterSchedulerExtra(extra map[string]any) map[string]any {
|
||||
// 走网关报 no available accounts"。
|
||||
"openai_passthrough",
|
||||
"openai_oauth_passthrough",
|
||||
// 透传账号显式开启按模型筛选后,候选过滤同样依赖本投影里的开关判定白名单。
|
||||
"openai_passthrough_model_filter",
|
||||
// 生图尺寸档位在候选过滤阶段按本投影判定,裁掉后受限账号会接到不允许的档位。
|
||||
service.AccountExtraOpenAIImageSizeTiers,
|
||||
"codex_fingerprint_mode",
|
||||
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/xai"
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/alicebob/miniredis/v2"
|
||||
"github.com/redis/go-redis/v9"
|
||||
@@ -219,8 +220,10 @@ func memoEntryCount(cache *schedulerCache) int {
|
||||
return len(cache.snapshotEntries)
|
||||
}
|
||||
|
||||
func TestSchedulerCacheSnapshotMemoSecondReadOnlyFetchesTagsAndLastUsed(t *testing.T) {
|
||||
func TestSchedulerCacheSnapshotMemoRepeatReadsFetchTagsAndExpiredLastUsed(t *testing.T) {
|
||||
cache, _, recorder := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize)
|
||||
clock := &memoTestClock{now: time.Date(2026, 10, 20, 8, 0, 0, 0, time.UTC)}
|
||||
cache.now = clock.Now
|
||||
bucket := memoTestBucket(101)
|
||||
memoPublish(t, cache, bucket, memoTestAccount(1, "a"), memoTestAccount(2, "b"), memoTestAccount(3, "c"))
|
||||
|
||||
@@ -228,9 +231,17 @@ func TestSchedulerCacheSnapshotMemoSecondReadOnlyFetchesTagsAndLastUsed(t *testi
|
||||
first := memoRead(t, cache, bucket)
|
||||
require.Equal(t, 1, recorder.countPrefix("zrange "))
|
||||
require.Equal(t, 1, recorder.countPrefix("mget "+schedulerAccountMetaPrefix))
|
||||
require.Equal(t, 1, recorder.countPrefix("mget "+schedulerAccountLastUsedPrefix))
|
||||
|
||||
recorder.reset()
|
||||
second := memoRead(t, cache, bucket)
|
||||
require.Equal(t, []string{
|
||||
"mget " + schedulerBucketKey(schedulerReadyPrefix, bucket),
|
||||
}, recorder.recorded(), "last_used read within its max age is reused")
|
||||
|
||||
clock.Advance(schedulerLastUsedCacheMaxAge)
|
||||
recorder.reset()
|
||||
memoRead(t, cache, bucket)
|
||||
require.Equal(t, []string{
|
||||
"mget " + schedulerBucketKey(schedulerReadyPrefix, bucket),
|
||||
"mget " + schedulerLastUsedKey("1"),
|
||||
@@ -248,6 +259,8 @@ func TestSchedulerCacheSnapshotMemoSecondReadOnlyFetchesTagsAndLastUsed(t *testi
|
||||
func TestSchedulerCacheSnapshotMemoLastUsedIsFreshAndCopiesAreIndependent(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
cache, _, recorder := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize)
|
||||
clock := &memoTestClock{now: time.Date(2026, 10, 20, 8, 0, 0, 0, time.UTC)}
|
||||
cache.now = clock.Now
|
||||
bucket := memoTestBucket(102)
|
||||
embedded := time.Now().UTC().Truncate(time.Millisecond).Add(-time.Hour)
|
||||
account := memoTestAccount(11, "a")
|
||||
@@ -272,8 +285,9 @@ func TestSchedulerCacheSnapshotMemoLastUsedIsFreshAndCopiesAreIndependent(t *tes
|
||||
second[0].Credentials = map[string]any{"model_mapping": map[string]any{"claude-sonnet": "replaced"}}
|
||||
require.Equal(t, "replaced", second[0].GetMappedModel("claude-sonnet"))
|
||||
|
||||
// 删除 last_used 侧键(不改精简记录):若母本曾被套用 last_used,这里会读到 latest。
|
||||
// 删除 last_used 侧键(不改精简记录)并越过 last_used 复用时长:若母本曾被套用 last_used,这里会读到 latest。
|
||||
require.NoError(t, cache.rdb.Del(ctx, schedulerLastUsedKey("11")).Err())
|
||||
clock.Advance(schedulerLastUsedCacheMaxAge)
|
||||
recorder.reset()
|
||||
third := memoRead(t, cache, bucket)
|
||||
require.Zero(t, recorder.countPrefix("zrange "))
|
||||
@@ -660,6 +674,8 @@ func memoReadExpectHit(t *testing.T, cache *schedulerCache, recorder *schedulerC
|
||||
func TestSchedulerCacheSnapshotMemoPlatformRevisionScopesInvalidation(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
cache, _, recorder := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize)
|
||||
clock := &memoTestClock{now: time.Date(2026, 10, 20, 8, 0, 0, 0, time.UTC)}
|
||||
cache.now = clock.Now
|
||||
geminiSingle := service.SchedulerBucket{GroupID: 201, Platform: service.PlatformGemini, Mode: service.SchedulerModeSingle}
|
||||
gemini := memoTestAccountOn(service.PlatformGemini, 211, "gemini")
|
||||
memoPublish(t, cache, geminiSingle, gemini)
|
||||
@@ -672,7 +688,6 @@ func TestSchedulerCacheSnapshotMemoPlatformRevisionScopesInvalidation(t *testing
|
||||
memoRead(t, cache, geminiSingle)
|
||||
require.Equal(t, []string{
|
||||
"mget " + schedulerBucketKey(schedulerReadyPrefix, geminiSingle),
|
||||
"mget " + schedulerLastUsedKey("211"),
|
||||
}, recorder.recorded(), "an Anthropic account write must not invalidate a Gemini bucket")
|
||||
|
||||
gemini.Name = "gemini-renamed"
|
||||
@@ -844,8 +859,248 @@ func TestSchedulerCacheSnapshotMemoMaxAgeBoundsUnversionedWrites(t *testing.T) {
|
||||
clock.Advance(schedulerSnapshotCacheMaxAge - time.Millisecond)
|
||||
require.Equal(t, "old", memoRead(t, cache, bucket)[0].Name)
|
||||
|
||||
// 超过直接复用时长:本次仍返回旧条目,同时由后台加载刷新。
|
||||
clock.Advance(time.Millisecond)
|
||||
require.Equal(t, "old", memoRead(t, cache, bucket)[0].Name)
|
||||
require.Eventually(t, func() bool {
|
||||
accounts, hit, err := cache.GetSnapshot(ctx, bucket)
|
||||
return err == nil && hit && accounts[0].Name == "new"
|
||||
}, time.Second, 5*time.Millisecond)
|
||||
}
|
||||
|
||||
func TestSchedulerCacheSnapshotMemoStaleGraceIsBounded(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
cache, _, recorder := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize)
|
||||
clock := &memoTestClock{now: time.Date(2026, 10, 20, 8, 0, 0, 0, time.UTC)}
|
||||
cache.now = clock.Now
|
||||
bucket := memoTestBucket(127)
|
||||
memoPublish(t, cache, bucket, memoTestAccount(152, "old"))
|
||||
require.Equal(t, "old", memoRead(t, cache, bucket)[0].Name)
|
||||
|
||||
_, metaPayload, err := marshalSchedulerCacheAccount(memoTestAccount(152, "new"))
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, cache.rdb.Set(ctx, schedulerAccountMetaKey("152"), metaPayload, 0).Err())
|
||||
|
||||
// 超过直接复用时长与宽限期之和后,读取等待加载结果。
|
||||
clock.Advance(schedulerSnapshotCacheMaxAge + schedulerSnapshotCacheStaleGrace)
|
||||
recorder.reset()
|
||||
require.Equal(t, "new", memoRead(t, cache, bucket)[0].Name)
|
||||
require.Equal(t, 1, recorder.countPrefix("zrange "))
|
||||
}
|
||||
|
||||
func TestSchedulerCacheSnapshotMemoVersionChangeWaitsForReload(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
cache, _, _ := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize)
|
||||
clock := &memoTestClock{now: time.Date(2026, 10, 20, 8, 0, 0, 0, time.UTC)}
|
||||
cache.now = clock.Now
|
||||
bucket := memoTestBucket(128)
|
||||
account := memoTestAccount(153, "old")
|
||||
memoPublish(t, cache, bucket, account)
|
||||
require.Equal(t, "old", memoRead(t, cache, bucket)[0].Name)
|
||||
|
||||
// 条目已超过直接复用时长;修订号变化后不走宽限期,本次读取即看到新值。
|
||||
clock.Advance(schedulerSnapshotCacheMaxAge)
|
||||
account.Name = "new"
|
||||
require.NoError(t, cache.SetAccount(ctx, &account))
|
||||
require.Equal(t, "new", memoRead(t, cache, bucket)[0].Name)
|
||||
}
|
||||
|
||||
// blockingZRangeHook 让 ZRANGE 停在 release 关闭之前。
|
||||
type blockingZRangeHook struct {
|
||||
release chan struct{}
|
||||
}
|
||||
|
||||
func (h *blockingZRangeHook) DialHook(next redis.DialHook) redis.DialHook { return next }
|
||||
|
||||
func (h *blockingZRangeHook) ProcessHook(next redis.ProcessHook) redis.ProcessHook {
|
||||
return func(ctx context.Context, cmd redis.Cmder) error {
|
||||
if strings.EqualFold(cmd.Name(), "zrange") {
|
||||
<-h.release
|
||||
}
|
||||
return next(ctx, cmd)
|
||||
}
|
||||
}
|
||||
|
||||
func (h *blockingZRangeHook) ProcessPipelineHook(next redis.ProcessPipelineHook) redis.ProcessPipelineHook {
|
||||
return next
|
||||
}
|
||||
|
||||
func TestSchedulerCacheSnapshotMemoConcurrentLoadsAreCoalesced(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
cache, _, recorder := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize)
|
||||
bucket := memoTestBucket(129)
|
||||
memoPublish(t, cache, bucket, memoTestAccount(154, "a"), memoTestAccount(155, "b"))
|
||||
hook := &blockingZRangeHook{release: make(chan struct{})}
|
||||
cache.rdb.AddHook(hook)
|
||||
recorder.reset()
|
||||
|
||||
const readers = 16
|
||||
results := make(chan error, readers)
|
||||
for i := 0; i < readers; i++ {
|
||||
go func() {
|
||||
accounts, hit, err := cache.GetSnapshot(ctx, bucket)
|
||||
if err == nil && (!hit || len(accounts) != 2) {
|
||||
err = fmt.Errorf("hit=%v accounts=%d", hit, len(accounts))
|
||||
}
|
||||
results <- err
|
||||
}()
|
||||
}
|
||||
readyKey := "mget " + schedulerBucketKey(schedulerReadyPrefix, bucket)
|
||||
require.Eventually(t, func() bool { return recorder.countPrefix(readyKey) == readers }, time.Second, time.Millisecond)
|
||||
close(hook.release)
|
||||
for i := 0; i < readers; i++ {
|
||||
require.NoError(t, <-results)
|
||||
}
|
||||
require.Equal(t, 1, recorder.countPrefix("zrange "))
|
||||
require.Equal(t, 1, recorder.countPrefix("mget "+schedulerAccountMetaPrefix))
|
||||
}
|
||||
|
||||
func TestSchedulerCacheSnapshotMemoCanceledWaiterDoesNotAbortSharedLoad(t *testing.T) {
|
||||
cache, _, recorder := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize)
|
||||
bucket := memoTestBucket(130)
|
||||
memoPublish(t, cache, bucket, memoTestAccount(156, "a"))
|
||||
hook := &blockingZRangeHook{release: make(chan struct{})}
|
||||
cache.rdb.AddHook(hook)
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
done := make(chan error, 1)
|
||||
go func() {
|
||||
_, _, err := cache.GetSnapshot(ctx, bucket)
|
||||
done <- err
|
||||
}()
|
||||
require.Eventually(t, func() bool { return recorder.countPrefix("zrange ") == 1 }, time.Second, time.Millisecond)
|
||||
cancel()
|
||||
require.ErrorIs(t, <-done, context.Canceled)
|
||||
|
||||
close(hook.release)
|
||||
require.Eventually(t, func() bool { return memoEntryCount(cache) == 1 }, time.Second, time.Millisecond)
|
||||
require.Equal(t, []int64{156}, memoIDs(memoRead(t, cache, bucket)))
|
||||
}
|
||||
|
||||
func TestSchedulerCacheSnapshotMemoReloadReusesUnchangedMasters(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
cache, _, _ := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize)
|
||||
bucket := memoTestBucket(131)
|
||||
changed := memoTestAccount(158, "b")
|
||||
memoPublish(t, cache, bucket, memoTestAccount(157, "a"), changed, memoTestAccount(159, "c"))
|
||||
memoRead(t, cache, bucket)
|
||||
before := cache.lookupSnapshotEntry(bucket.String())
|
||||
require.NotNil(t, before)
|
||||
|
||||
changed.Name = "b2"
|
||||
require.NoError(t, cache.SetAccount(ctx, &changed))
|
||||
got := memoRead(t, cache, bucket)
|
||||
require.Equal(t, "b2", got[1].Name)
|
||||
after := cache.lookupSnapshotEntry(bucket.String())
|
||||
require.NotSame(t, before, after)
|
||||
require.Same(t, before.accounts[0], after.accounts[0])
|
||||
require.NotSame(t, before.accounts[1], after.accounts[1])
|
||||
require.Same(t, before.accounts[2], after.accounts[2])
|
||||
require.Equal(t, "b", before.accounts[1].Name, "reload must not modify the previous master")
|
||||
}
|
||||
|
||||
// 服务层按该方法签名探测值切片读取。
|
||||
var _ interface {
|
||||
GetSnapshotValues(ctx context.Context, bucket service.SchedulerBucket) ([]service.Account, bool, error)
|
||||
} = (*schedulerCache)(nil)
|
||||
|
||||
func TestSchedulerCacheSnapshotMemoReloadRedecodesMastersAfterRuntimeMappingChange(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
cache, _, _ := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize)
|
||||
bucket := memoTestBucket(134)
|
||||
changed := memoTestAccount(167, "b")
|
||||
memoPublish(t, cache, bucket, memoTestAccount(166, "a"), changed)
|
||||
memoRead(t, cache, bucket)
|
||||
before := cache.lookupSnapshotEntry(bucket.String())
|
||||
require.True(t, before.accounts[0].SharedSnapshotCurrent())
|
||||
|
||||
xai.SetRuntimeModelMappingOptions(xai.RuntimeModelMappingOptions())
|
||||
require.False(t, before.accounts[0].SharedSnapshotCurrent())
|
||||
changed.Name = "b2"
|
||||
require.NoError(t, cache.SetAccount(ctx, &changed))
|
||||
memoRead(t, cache, bucket)
|
||||
after := cache.lookupSnapshotEntry(bucket.String())
|
||||
require.NotSame(t, before.accounts[0], after.accounts[0], "a master prepared under an older runtime mapping version is decoded again")
|
||||
require.True(t, after.accounts[0].SharedSnapshotCurrent())
|
||||
}
|
||||
|
||||
func TestSchedulerCacheSnapshotMemoStaleEntryStartsOneBackgroundReload(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
cache, _, recorder := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize)
|
||||
clock := &memoTestClock{now: time.Date(2026, 10, 20, 8, 0, 0, 0, time.UTC)}
|
||||
cache.now = clock.Now
|
||||
bucket := memoTestBucket(135)
|
||||
memoPublish(t, cache, bucket, memoTestAccount(168, "old"))
|
||||
require.Equal(t, "old", memoRead(t, cache, bucket)[0].Name)
|
||||
stale := cache.lookupSnapshotEntry(bucket.String())
|
||||
|
||||
_, metaPayload, err := marshalSchedulerCacheAccount(memoTestAccount(168, "new"))
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, cache.rdb.Set(ctx, schedulerAccountMetaKey("168"), metaPayload, 0).Err())
|
||||
hook := &blockingZRangeHook{release: make(chan struct{})}
|
||||
cache.rdb.AddHook(hook)
|
||||
clock.Advance(schedulerSnapshotCacheMaxAge)
|
||||
recorder.reset()
|
||||
|
||||
for i := 0; i < 5; i++ {
|
||||
require.Equal(t, "old", memoRead(t, cache, bucket)[0].Name)
|
||||
}
|
||||
require.True(t, stale.refreshing.Load())
|
||||
require.Eventually(t, func() bool { return recorder.countPrefix("zrange ") == 1 }, time.Second, time.Millisecond)
|
||||
close(hook.release)
|
||||
require.Eventually(t, func() bool { return !stale.refreshing.Load() }, time.Second, time.Millisecond)
|
||||
require.Equal(t, "new", memoRead(t, cache, bucket)[0].Name)
|
||||
require.Equal(t, 1, recorder.countPrefix("zrange "))
|
||||
}
|
||||
|
||||
func TestSchedulerCacheSnapshotMemoLastUsedWriteInvalidatesLocalCache(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
cache, _, recorder := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize)
|
||||
clock := &memoTestClock{now: time.Date(2026, 10, 20, 8, 0, 0, 0, time.UTC)}
|
||||
cache.now = clock.Now
|
||||
bucket := memoTestBucket(132)
|
||||
memoPublish(t, cache, bucket, memoTestAccount(160, "a"))
|
||||
require.Nil(t, memoRead(t, cache, bucket)[0].LastUsedAt)
|
||||
|
||||
// 其它进程写入的 last_used 在复用时长内不可见。
|
||||
usedAt := time.Date(2026, 10, 20, 7, 0, 0, 0, time.UTC)
|
||||
require.NoError(t, cache.rdb.Set(ctx, schedulerLastUsedKey("160"), strconv.FormatInt(usedAt.UnixMilli(), 10), 0).Err())
|
||||
require.Nil(t, memoRead(t, cache, bucket)[0].LastUsedAt)
|
||||
|
||||
// 本进程写入 last_used 后立即可见。
|
||||
later := usedAt.Add(time.Minute)
|
||||
require.NoError(t, cache.UpdateLastUsed(ctx, map[int64]time.Time{160: later}))
|
||||
recorder.reset()
|
||||
got := memoRead(t, cache, bucket)
|
||||
require.Equal(t, later, *got[0].LastUsedAt)
|
||||
require.Equal(t, 1, recorder.countPrefix("mget "+schedulerAccountLastUsedPrefix))
|
||||
require.Zero(t, recorder.countPrefix("zrange "))
|
||||
}
|
||||
|
||||
func TestSchedulerCacheSnapshotMemoChunkedMGetUsesOnePipeline(t *testing.T) {
|
||||
mr := miniredis.RunT(t)
|
||||
rdb := redis.NewClient(&redis.Options{Addr: mr.Addr()})
|
||||
t.Cleanup(func() { _ = rdb.Close() })
|
||||
recorder := &schedulerCacheCommandRecorder{}
|
||||
rdb.AddHook(recorder)
|
||||
cache, ok := newSchedulerCacheWithChunkSizes(rdb, 2, defaultSchedulerSnapshotWriteChunkSize).(*schedulerCache)
|
||||
require.True(t, ok)
|
||||
bucket := memoTestBucket(133)
|
||||
accounts := make([]service.Account, 0, 5)
|
||||
for id := int64(161); id <= 165; id++ {
|
||||
accounts = append(accounts, memoTestAccount(id, strconv.FormatInt(id, 10)))
|
||||
}
|
||||
memoPublish(t, cache, bucket, accounts...)
|
||||
|
||||
recorder.reset()
|
||||
got := memoRead(t, cache, bucket)
|
||||
require.Equal(t, []int64{161, 162, 163, 164, 165}, memoIDs(got))
|
||||
batches := recorder.pipelineBatches()
|
||||
require.Len(t, batches, 2, "metadata and last_used each travel in one pipeline")
|
||||
for _, batch := range batches {
|
||||
require.Len(t, batch, 3)
|
||||
}
|
||||
require.Equal(t, 3, recorder.countPrefix("mget "+schedulerAccountMetaPrefix))
|
||||
}
|
||||
|
||||
func TestSchedulerCacheSnapshotMemoEvictsLongIdleEntries(t *testing.T) {
|
||||
|
||||
@@ -1180,6 +1180,33 @@ func TestBuildSchedulerMetadataAccount_KeepsOpenAIPassthroughForModelGate(t *tes
|
||||
}
|
||||
}
|
||||
|
||||
// 透传账号显式开启"按模型筛选"后,候选过滤同样读的是本投影;裁掉
|
||||
// openai_passthrough_model_filter 会让账号在选号阶段退回"透传放行全部模型",
|
||||
// 而模型列表等读完整账号的路径仍按白名单收窄,两边口径分裂。
|
||||
func TestBuildSchedulerMetadataAccount_KeepsOpenAIPassthroughModelFilter(t *testing.T) {
|
||||
account := service.Account{
|
||||
ID: 8748,
|
||||
Platform: service.PlatformOpenAI,
|
||||
Type: service.AccountTypeAPIKey,
|
||||
Credentials: map[string]any{
|
||||
"model_mapping": map[string]any{"qwen3.8-max": "qwen3.8-max"},
|
||||
"api_key": "drop-me",
|
||||
},
|
||||
Extra: map[string]any{"openai_passthrough": true, "openai_passthrough_model_filter": true},
|
||||
}
|
||||
require.False(t, account.IsModelSupported("gpt-6.1-sol"), "前置条件:开启筛选的透传账号应拒绝白名单外模型")
|
||||
|
||||
payload, err := json.Marshal(buildSchedulerMetadataAccount(account))
|
||||
require.NoError(t, err)
|
||||
var restored service.Account
|
||||
require.NoError(t, json.Unmarshal(payload, &restored))
|
||||
|
||||
require.Equal(t, true, restored.Extra["openai_passthrough_model_filter"])
|
||||
require.True(t, restored.IsOpenAIPassthroughModelFilterEnabled())
|
||||
require.False(t, restored.IsModelSupported("gpt-6.1-sol"))
|
||||
require.True(t, restored.IsModelSupported("qwen3.8-max"))
|
||||
}
|
||||
|
||||
// 调度投影必须保留账号的 RPM 配置。
|
||||
//
|
||||
// 候选过滤走 ListSchedulableAccounts,读的是 buildSchedulerMetadataAccount 产出的精简投影;
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
//go:build unit
|
||||
|
||||
package repository
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// buildSchedulerMetadataAccount 是调度候选的唯一投影出口,openAIAccountSkipReason
|
||||
// 按 SupportsOpenAIEndpointCapability 判 capability_mismatch。Seedance 分支直接读
|
||||
// credentials.openai_capabilities 且不走「未配置即放行」,所以该键一旦被裁掉,
|
||||
// Seedance 账号在选号阶段必然被剔除,而 /v1/models 走 DB 全量仍会列出模型。
|
||||
func TestSchedulerMetadataKeepsOpenAICapabilities(t *testing.T) {
|
||||
account := service.Account{
|
||||
ID: 1,
|
||||
Platform: service.PlatformOpenAI,
|
||||
Type: service.AccountTypeAPIKey,
|
||||
Credentials: map[string]any{
|
||||
"api_key": "sk-test",
|
||||
"base_url": "https://relay.example.com/api/v3",
|
||||
"openai_capabilities": []string{"seedance"},
|
||||
},
|
||||
}
|
||||
|
||||
projected := buildSchedulerMetadataAccount(account)
|
||||
|
||||
require.Equal(t, []string{"seedance"}, projected.Credentials["openai_capabilities"])
|
||||
require.Equal(t, "https://relay.example.com/api/v3", projected.Credentials["base_url"])
|
||||
require.True(t, projected.SupportsOpenAIEndpointCapability(service.OpenAIEndpointCapabilitySeedance))
|
||||
}
|
||||
|
||||
func TestSchedulerMetadataDropsUnlistedCredentials(t *testing.T) {
|
||||
account := service.Account{
|
||||
ID: 2,
|
||||
Platform: service.PlatformOpenAI,
|
||||
Type: service.AccountTypeAPIKey,
|
||||
Credentials: map[string]any{
|
||||
"api_key": "sk-test",
|
||||
"base_url": "https://relay.example.com/api/v3",
|
||||
"openai_capabilities": []string{"seedance"},
|
||||
"model_mapping": map[string]string{"seedance-2-5": "doubao-seedance-2-5-260628"},
|
||||
"unlisted_secret": "drop-me",
|
||||
},
|
||||
}
|
||||
|
||||
projected := buildSchedulerMetadataAccount(account)
|
||||
|
||||
require.Equal(t, map[string]string{"seedance-2-5": "doubao-seedance-2-5-260628"}, projected.Credentials["model_mapping"])
|
||||
require.NotContains(t, projected.Credentials, "unlisted_secret")
|
||||
}
|
||||
Loaded 100 of 340 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user