mirror of
https://github.com/Wei-Shaw/sub2api.git
synced 2026-12-04 15:50:18 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
eb413d9b39 | ||
|
|
c589c121ec | ||
|
|
3f99496496 | ||
|
|
4f621a5a10 | ||
|
|
2f39007e86 | ||
|
|
9ac8925fe9 | ||
|
|
6ba762f3bf | ||
|
|
bfceebe029 | ||
|
|
82302dbfca | ||
|
|
af6a5c3d0c | ||
|
|
cd412f6c09 | ||
|
|
a562e77638 | ||
|
|
c7ae3a36e4 | ||
|
|
a2cd083dce | ||
|
|
4e694a3745 | ||
|
|
c3f1b4bc75 | ||
|
|
332f45f858 | ||
|
|
8baebfee07 | ||
|
|
44ac31a891 | ||
|
|
547c35acf5 | ||
|
|
d07f63ddf8 | ||
|
|
f7ec8b3cee | ||
|
|
484625a239 | ||
|
|
57ddb49706 | ||
|
|
d63c48cf62 | ||
|
|
49ef0328a5 | ||
|
|
7a09fbf167 | ||
|
|
ec68ce4f87 | ||
|
|
5720d10c38 | ||
|
|
725b235f97 | ||
|
|
f8c9792d7b | ||
|
|
d35839def7 | ||
|
|
6be2403d7a | ||
|
|
08fdfa61d8 | ||
|
|
c7af427fb8 | ||
|
|
c2acc48d5d | ||
|
|
470dba8363 | ||
|
|
874e1b337a | ||
|
|
9172ba8b95 | ||
|
|
708d833d6b | ||
|
|
806534e5ca | ||
|
|
9c72aca60c | ||
|
|
4644600eb1 | ||
|
|
acec49eaaf | ||
|
|
39b0022a6f | ||
|
|
6db1e10ef0 | ||
|
|
e7bf4232cf | ||
|
|
2ecf932f87 | ||
|
|
800ebceb0f | ||
|
|
b55a546fa5 | ||
|
|
da03c58cf2 | ||
|
|
f4b6acf2f9 | ||
|
|
ad6c1ba138 | ||
|
|
e4a0116fd2 | ||
|
|
0a30b2e5b2 | ||
|
|
8c3de07b8e | ||
|
|
38f0461163 | ||
|
|
8cbd513c27 | ||
|
|
db62b187dc | ||
|
|
cff176dfd7 | ||
|
|
5746b50e8b | ||
|
|
4b43302f59 | ||
|
|
2c922cf496 | ||
|
|
6744f02164 | ||
|
|
524e8df850 | ||
|
|
57a990fafa | ||
|
|
7e0edb310f | ||
|
|
76ddf1e782 | ||
|
|
7aceae8025 | ||
|
|
9b3717b55e | ||
|
|
542d678dee | ||
|
|
11c58d92d0 | ||
|
|
3fcd1c15b9 | ||
|
|
272b331868 | ||
|
|
ca39c9c097 | ||
|
|
aede013903 | ||
|
|
667902572f | ||
|
|
ff06dab68d | ||
|
|
29f6ae68a6 | ||
|
|
6d345a4ec0 | ||
|
|
4f41f253f4 | ||
|
|
905893ca9e | ||
|
|
989a491859 | ||
|
|
ce7940a900 | ||
|
|
380ab13810 | ||
|
|
24b70236d5 | ||
|
|
aa25d20690 | ||
|
|
edba3eb7eb | ||
|
|
ec0e489ab7 | ||
|
|
ce3a27912e | ||
|
|
622ad49022 | ||
|
|
a64db2860b | ||
|
|
ea2df1442b | ||
|
|
97b70cca2a | ||
|
|
6bc40957cf | ||
|
|
51455623ce | ||
|
|
4bd5fa6480 | ||
|
|
4cfeeb2396 | ||
|
|
c101515d0a | ||
|
|
63cfafbac3 | ||
|
|
15aec090c2 | ||
|
|
a08eb02ff8 | ||
|
|
9f1ec1f69e | ||
|
|
b88a4f4cf9 | ||
|
|
4c953d9252 | ||
|
|
debe9e3e21 | ||
|
|
d036368c8e | ||
|
|
b7b5321a6a | ||
|
|
2d597faf60 | ||
|
|
252e394f5c | ||
|
|
cdbfa172e3 | ||
|
|
120f4eeac8 | ||
|
|
5e68375f0c | ||
|
|
a07fa27e29 | ||
|
|
0e8cb91137 | ||
|
|
ade6442b58 | ||
|
|
988569acde | ||
|
|
e7bf40dedf | ||
|
|
8a8f1c135e | ||
|
|
35eaa252b3 | ||
|
|
9e7647ec90 | ||
|
|
6c55134201 | ||
|
|
1d746382e9 | ||
|
|
a4d580691f | ||
|
|
8ff16c5cc0 | ||
|
|
2934284844 | ||
|
|
1a55e82973 | ||
|
|
71436d44cc | ||
|
|
9e63d8b986 | ||
|
|
d6f167622d | ||
|
|
0dba88681b | ||
|
|
385e07ca85 | ||
|
|
8aa5c2a4ba | ||
|
|
c678e772af | ||
|
|
ebc32f90fb | ||
|
|
7613baf97c | ||
|
|
33472b553a | ||
|
|
337e33bda5 | ||
|
|
d762d5fa8a | ||
|
|
9f6e0f76ba | ||
|
|
6ddd0fe8d4 | ||
|
|
f84d1d3eb2 | ||
|
|
b20c5d0e78 | ||
|
|
c5b12503bb | ||
|
|
7d32ba27f7 | ||
|
|
799aee99fd | ||
|
|
79f84cb2aa | ||
|
|
56e27df2d7 | ||
|
|
cbde784ed0 | ||
|
|
e7f32da0a8 | ||
|
|
c15bfc71cf | ||
|
|
638b48c876 | ||
|
|
bf88f07f46 | ||
|
|
ed3317d02b | ||
|
|
854b16dfe8 | ||
|
|
ee99ee1e23 | ||
|
|
e141954afc | ||
|
|
8a1ca956fd | ||
|
|
2c09c5cc29 | ||
|
|
7e563855f0 | ||
|
|
0e35d49c99 | ||
|
|
5620cd6bac | ||
|
|
04aa0974a8 | ||
|
|
e93012e94e | ||
|
|
b089e60895 | ||
|
|
a1c77909ed | ||
|
|
de1967bee3 | ||
|
|
0f64666b67 | ||
|
|
069e75c47e | ||
|
|
d6585a2cad | ||
|
|
50eb7befec | ||
|
|
527c37ac26 | ||
|
|
c1b4041f35 | ||
|
|
5c69258b3f | ||
|
|
ef3649aafe | ||
|
|
2eb3170504 | ||
|
|
bc1a717083 | ||
|
|
cd73d7975e | ||
|
|
df3c428142 | ||
|
|
58b026c0b1 | ||
|
|
a622eca4f9 | ||
|
|
f53641e53c | ||
|
|
e40a84edac | ||
|
|
1e8f5f3c39 | ||
|
|
80ba2fca9a | ||
|
|
f34df0e313 | ||
|
|
cc08bc0f17 | ||
|
|
6a8fca6b4e | ||
|
|
d29660bfd7 | ||
|
|
8185695197 | ||
|
|
02dea61bdb | ||
|
|
a55ef06db7 | ||
|
|
c85fd1c873 | ||
|
|
40fda7a702 | ||
|
|
c8c1e7e649 |
No files matched your search
@@ -6,6 +6,8 @@ Each build uses GoReleaser OSS in snapshot mode with the selected release versio
|
||||
|
||||
Go caches are isolated by target and refreshed on each source commit, with fallback to the preceding target cache. Save uses the original restore key, even if a build hook changes `go.sum`. Matrix jobs upload uniquely named artifacts. The publishing job extracts only the regular Linux binary from each verified archive and restores its executable permission before constructing Docker contexts. QEMU remains limited to runtime-image instructions. DockerHub images are omitted when its credentials are absent; GHCR is always retained. Simple mode still publishes only the amd64 GHCR image and the simple release description.
|
||||
|
||||
A tag push is rejected in `prepare`, before anything is built or published, unless `backend/cmd/server/VERSION` at the tagged commit already equals the tag version: commit the VERSION bump first, then tag that commit. Source builds of the tag (`go build`, GitHub source archives, Docker builds without `.git`) embed that file. To re-release an older tag created before this rule, run the workflow manually with `allow_version_mismatch=true`; it then emits a warning and builds with the tag version.
|
||||
|
||||
All build jobs use the commit resolved by `prepare`, including a manual release's selected tag. Helper scripts come from the workflow revision and are passed as a run-local artifact, so older application tags do not need to contain the new scripts. The workflow serializes release runs to prevent simultaneous updates to moving image tags.
|
||||
|
||||
## Validate without publication
|
||||
@@ -17,7 +19,7 @@ gh workflow run release.yml --ref <branch> \
|
||||
-f tag=<branch> -f dry_run=true -f simple_release=false
|
||||
```
|
||||
|
||||
A dry run builds all selected archives and both runtime images, verifies artifact provenance and produces the final checksum file. It exports images locally as OCI archives instead of pushing them. It skips registry logins, GitHub Release publication, DockerHub description updates, Telegram notifications and VERSION synchronization. Test the simple path separately with `simple_release=true`.
|
||||
A dry run builds all selected archives and both runtime images, verifies artifact provenance and produces the final checksum file. It exports images locally as OCI archives instead of pushing them. It skips registry logins, GitHub Release publication, DockerHub description updates, and Telegram notifications. Test the simple path separately with `simple_release=true`.
|
||||
|
||||
Dry-run artifacts are available in the Actions run, including `release-dry-run-report`. Compare job start/end times, GoReleaser's build duration and cache restore results. Do not present an initial cold-cache run as a warmed-cache benchmark; publishing network time is not measured by dry runs.
|
||||
|
||||
|
||||
@@ -63,6 +63,15 @@ def plan(args):
|
||||
tagged_sha = subprocess.check_output(['git', 'rev-parse', '--verify', f'refs/tags/{tag}^{{commit}}'], text=True).strip()
|
||||
if sha != tagged_sha:
|
||||
raise ValueError('checkout does not match the selected release tag')
|
||||
committed = VERSION_FILE.read_text().strip()
|
||||
if committed != version:
|
||||
# Source builds of the tag (go build, archives, Docker builds without .git)
|
||||
# embed this file, so the tagged commit itself must carry the new version.
|
||||
message = (f'{VERSION_FILE} at {tag} is {committed!r}, expected {version!r}; '
|
||||
'commit the VERSION bump first, then tag that commit')
|
||||
if not args.allow_version_mismatch:
|
||||
raise ValueError(message)
|
||||
print(f'::warning::{message}')
|
||||
if not VERSION_RE.fullmatch(version):
|
||||
raise ValueError('invalid VERSION')
|
||||
VERSION_FILE.write_text(version + '\n')
|
||||
@@ -161,6 +170,7 @@ def main():
|
||||
p.add_argument('--ref', required=True)
|
||||
p.add_argument('--simple', action='store_true')
|
||||
p.add_argument('--dry-run', action='store_true')
|
||||
p.add_argument('--allow-version-mismatch', action='store_true')
|
||||
p.set_defaults(run=plan)
|
||||
p = commands.add_parser('config')
|
||||
p.add_argument('mode', choices=['build', 'publish'])
|
||||
|
||||
@@ -121,8 +121,24 @@ class ReleaseMatrixTest(unittest.TestCase):
|
||||
self.assertEqual(binary.read_bytes(), b'fixture')
|
||||
self.assertEqual(binary.stat().st_mode & 0o777, 0o755)
|
||||
|
||||
def test_tag_push_requires_committed_version_to_match_tag(self):
|
||||
release.VERSION_FILE.write_text('9.8.6\n')
|
||||
args = argparse.Namespace(ref='v9.8.7', dry_run=False, simple=False, allow_version_mismatch=False)
|
||||
with patch.object(subprocess, 'check_output', return_value='a' * 40 + '\n'):
|
||||
with self.assertRaisesRegex(ValueError, "is '9.8.6', expected '9.8.7'"):
|
||||
release.plan(args)
|
||||
|
||||
def test_manual_release_of_older_tag_warns_and_uses_tag_version(self):
|
||||
release.VERSION_FILE.write_text('9.8.6\n')
|
||||
args = argparse.Namespace(ref='v9.8.7', dry_run=False, simple=False, allow_version_mismatch=True)
|
||||
with patch.dict(os.environ, {'GITHUB_OUTPUT': 'outputs'}), patch.object(subprocess, 'check_output', return_value='a' * 40 + '\n'):
|
||||
release.plan(args)
|
||||
output = dict(line.split('=', 1) for line in Path('outputs').read_text().splitlines())
|
||||
self.assertEqual(output['version'], '9.8.7')
|
||||
self.assertEqual(release.VERSION_FILE.read_text(), '9.8.7\n')
|
||||
|
||||
def test_plan_requires_a_tag_for_publication(self):
|
||||
args = argparse.Namespace(ref='main', dry_run=False, simple=False)
|
||||
args = argparse.Namespace(ref='main', dry_run=False, simple=False, allow_version_mismatch=False)
|
||||
with patch.object(subprocess, 'check_output', return_value='a' * 40 + '\n'):
|
||||
with self.assertRaisesRegex(ValueError, 'version tag'):
|
||||
release.plan(args)
|
||||
|
||||
@@ -20,6 +20,11 @@ on:
|
||||
required: false
|
||||
type: boolean
|
||||
default: false
|
||||
allow_version_mismatch:
|
||||
description: 'Re-release an older tag whose committed VERSION predates the tag (builds with the tag version)'
|
||||
required: false
|
||||
type: boolean
|
||||
default: false
|
||||
|
||||
concurrency:
|
||||
group: release-${{ github.repository }}
|
||||
@@ -64,10 +69,14 @@ jobs:
|
||||
id: plan
|
||||
env:
|
||||
REQUESTED_REF: ${{ inputs.tag || github.ref_name }}
|
||||
ALLOW_VERSION_MISMATCH: ${{ github.event_name == 'workflow_dispatch' && inputs.allow_version_mismatch == true }}
|
||||
run: |
|
||||
args=(--ref "$REQUESTED_REF")
|
||||
if [[ "$SIMPLE_RELEASE" == true ]]; then args+=(--simple); fi
|
||||
if [[ "$DRY_RUN" == true ]]; then args+=(--dry-run); fi
|
||||
# The tagged commit must already carry the release VERSION. Only an explicit
|
||||
# manual re-release of an older tag may bypass this.
|
||||
if [[ "$ALLOW_VERSION_MISMATCH" == true ]]; then args+=(--allow-version-mismatch); fi
|
||||
python "$RUNNER_TEMP/release-tools/release_matrix.py" plan "${args[@]}"
|
||||
- uses: actions/upload-artifact@v7
|
||||
with:
|
||||
@@ -374,35 +383,3 @@ jobs:
|
||||
parse_mode: "Markdown",
|
||||
disable_web_page_preview: true
|
||||
}')"
|
||||
|
||||
sync-version-file:
|
||||
needs: [prepare, release]
|
||||
if: ${{ needs.release.result == 'success' && needs.prepare.outputs.dry_run != 'true' }}
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
env:
|
||||
RELEASE_VERSION: ${{ needs.prepare.outputs.version }}
|
||||
steps:
|
||||
- name: Checkout default branch
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ github.event.repository.default_branch }}
|
||||
|
||||
- name: Sync VERSION file to released tag
|
||||
run: |
|
||||
VERSION="$RELEASE_VERSION"
|
||||
|
||||
CURRENT_VERSION=$(tr -d '\r\n' < backend/cmd/server/VERSION || true)
|
||||
if [ "$CURRENT_VERSION" = "$VERSION" ]; then
|
||||
echo "VERSION file already matches $VERSION"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
echo "$VERSION" > backend/cmd/server/VERSION
|
||||
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
|
||||
git add backend/cmd/server/VERSION
|
||||
git commit -m "chore: sync VERSION to ${VERSION} [skip ci]"
|
||||
git push origin HEAD:${{ github.event.repository.default_branch }}
|
||||
@@ -133,8 +133,8 @@ Please read the following carefully before using this project:
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://www.axisnow.io/"><img src="assets/partners/logos/axisnow.jpg" alt="AxisNow" width="150"></a></td>
|
||||
<td>Thanks to AxisNow for sponsoring this project! <a href="https://www.axisnow.io/">AxisNow</a> protects and accelerates websites and APIs, delivering an optimal access experience across mainland China and globally, while extending acceleration and security capabilities to native/mobile apps through client SDKs — <strong>self-hosted private-deployment CDN</strong> | <strong>subscription-based DDoS-protected CDN</strong> | <strong>autonomous, flexibly composable CDN network</strong>.</td>
|
||||
<td width="180"><a href="https://www.axisnow.io/zh/docs/guide/sub2api"><img src="assets/partners/logos/axisnow.jpg" alt="AxisNow" width="150"></a></td>
|
||||
<td>Protect and accelerate your Sub2API with AxisNow<br>Optimized routes for users in mainland China, WAF and rate limiting to protect your API entry point, and support for self-hosted or subscription CDN edge nodes. <a href="https://www.axisnow.io/zh/docs/guide/sub2api">View the Sub2API integration guide →</a></td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
@@ -162,11 +162,6 @@ Please read the following carefully before using this project:
|
||||
<td>🔑 Buying AI accounts at top prices | Gemini · Claude · GPT | Main and alt accounts all welcome, any channel wanted | Pay-per-usage supported | Seeking first-hand resources from major providers, I'll bring the KEY.<br>WeChat: Liuyou-zawd | Telegram: <a href="https://t.me/AACC8888888">AACC8888888</a></td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://niuproxy.com/?utm_source=sub2api&utm_medium=sub2api&ref=sub2api"><img src="assets/partners/logos/NiuProxy.jpg" alt="NiuProxy" width="150"></a></td>
|
||||
<td><a href="https://niuproxy.com/?utm_source=sub2api&utm_medium=sub2api&ref=sub2api">NiuProxy</a> provides affordable global proxy solutions for web scraping, AI agents, automation, and data collection. With residential proxies starting at $0.35/GB across 190+ countries and regions, NiuProxy offers flexible plans and HTTP(S)/SOCKS5 support.<br>🎁 Use code PAY2 for 10% OFF your recharge!</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://soleapi.com/r/sub2api"><img src="assets/partners/logos/soleapi.png" alt="SoleAPI" width="150"></a></td>
|
||||
<td>Thanks to <a href="https://soleapi.com/r/sub2api">SoleAPI</a> for supporting this project! SoleAPI is an AI model gateway for developers and enterprises: one API key gives you access to 30+ leading models including Claude, GPT and Gemini. It is natively compatible with the OpenAI and Anthropic protocols, so Claude Code, Codex, Cursor and your existing SDKs work by simply changing the Base URL. Requests are routed in real time by latency and upstream health, with millisecond-level automatic failover to backup channels, 99.99% service availability and 24/7 technical support. Every call lands on a single bill with per-request token and cost breakdowns you can inspect at any time. Sign up through this project's <a href="https://soleapi.com/r/sub2api">referral link</a> to receive free trial credits, and earn ongoing cashback by inviting friends who top up!</td>
|
||||
|
||||
+2
-7
@@ -136,8 +136,8 @@
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://www.axisnow.io/"><img src="assets/partners/logos/axisnow.jpg" alt="AxisNow" width="150"></a></td>
|
||||
<td>感谢 AxisNow 赞助了本项目!<a href="https://www.axisnow.io/">AxisNow</a> 保护并加速网站与 API,兼顾中国大陆及全球的访问体验,并通过客户端 SDK,将加速与安全能力延伸至原生/移动 App — <strong>自建私有部署 CDN</strong>|<strong>订阅式高防 CDN</strong>|<strong>自主可控、灵活组合的 CDN 网络</strong>。</td>
|
||||
<td width="180"><a href="https://www.axisnow.io/zh/docs/guide/sub2api"><img src="assets/partners/logos/axisnow.jpg" alt="AxisNow" width="150"></a></td>
|
||||
<td>使用 AxisNow 保护并加速你的 Sub2API<br>为中国大陆用户提供优化线路,通过 WAF 和速率控制保护 API 入口,支持自建或订阅 CDN 边缘节点。<a href="https://www.axisnow.io/zh/docs/guide/sub2api">查看 Sub2API 接入教程 →</a></td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
@@ -165,11 +165,6 @@
|
||||
<td>🔑 高价收 AI 账号|Gemini · Claude · GPT|大小号通收,各种渠道都要|支持按量跑付|寻一手大厂资源,我上 KEY 。<br>微信:Liuyou-zawd|TG:<a href="https://t.me/AACC8888888">AACC8888888</a></td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://niuproxy.com/?utm_source=sub2api&utm_medium=sub2api&ref=sub2api"><img src="assets/partners/logos/NiuProxy.jpg" alt="NiuProxy" width="150"></a></td>
|
||||
<td><a href="https://niuproxy.com/?utm_source=sub2api&utm_medium=sub2api&ref=sub2api">NiuProxy</a> 为网页抓取、AI 智能体、自动化和数据采集提供高性价比的全球代理解决方案。住宅代理低至 $0.35/GB,覆盖 190+ 个国家和地区,套餐灵活,支持 HTTP(S)/SOCKS5 协议。<br>🎁 使用优惠码 PAY2 充值立享 9 折优惠!</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://soleapi.com/r/sub2api"><img src="assets/partners/logos/soleapi.png" alt="SoleAPI" width="150"></a></td>
|
||||
<td>感谢 <a href="https://soleapi.com/r/sub2api">SoleAPI</a> 对本项目的支持!SoleAPI 是面向开发者与企业的 AI 模型网关:一个 API Key 即可调用 Claude、GPT、Gemini 等 30+ 主流模型。原生兼容 OpenAI 与 Anthropic 协议,Claude Code、Codex、Cursor 及现有 SDK 只需修改 Base URL 即可接入。请求按延迟与上游健康度实时路由,毫秒级自动切换至备用通道,服务可用性达 99.99%,并提供 7×24 小时技术支持。所有调用统一账单结算,每次请求的 token 与费用明细随时可查。通过本项目的<a href="https://soleapi.com/r/sub2api">推荐链接</a>注册即可获得免费试用额度,邀请好友充值还可持续获得返现!</td>
|
||||
|
||||
+2
-7
@@ -135,8 +135,8 @@
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://www.axisnow.io/"><img src="assets/partners/logos/axisnow.jpg" alt="AxisNow" width="150"></a></td>
|
||||
<td>AxisNow のご支援に感謝します!<a href="https://www.axisnow.io/">AxisNow</a> はウェブサイトと API を保護・高速化し、中国本土および世界中で快適なアクセス体験を実現します。クライアント SDK により、ネイティブ/モバイルアプリにも高速化・セキュリティ機能を拡張できます — <strong>自社構築・プライベートデプロイ CDN</strong>|<strong>サブスクリプション型高防御 CDN</strong>|<strong>自律制御で柔軟に組み合わせられる CDN ネットワーク</strong>。</td>
|
||||
<td width="180"><a href="https://www.axisnow.io/zh/docs/guide/sub2api"><img src="assets/partners/logos/axisnow.jpg" alt="AxisNow" width="150"></a></td>
|
||||
<td>AxisNow で Sub2API を保護・高速化<br>中国本土のユーザー向けに最適化された回線を提供し、WAF とレート制御で API の入口を保護します。自社構築またはサブスクリプションの CDN エッジノードに対応しています。<a href="https://www.axisnow.io/zh/docs/guide/sub2api">Sub2API 導入ガイドを見る →</a></td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
@@ -164,11 +164,6 @@
|
||||
<td>🔑 AI アカウント高価買取|Gemini · Claude · GPT|メイン・サブアカウントすべて買取、チャネル問わず歓迎|従量制での支払いに対応|大手の一次リソースを求めています、KEY は私が用意します。<br>WeChat:Liuyou-zawd|Telegram:<a href="https://t.me/AACC8888888">AACC8888888</a></td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://niuproxy.com/?utm_source=sub2api&utm_medium=sub2api&ref=sub2api"><img src="assets/partners/logos/NiuProxy.jpg" alt="NiuProxy" width="150"></a></td>
|
||||
<td><a href="https://niuproxy.com/?utm_source=sub2api&utm_medium=sub2api&ref=sub2api">NiuProxy</a> は、Web スクレイピング、AI エージェント、自動化、データ収集向けに、手頃な価格のグローバルプロキシソリューションを提供します。住宅プロキシは $0.35/GB から、190 以上の国と地域をカバーし、柔軟なプランと HTTP(S)/SOCKS5 に対応しています。<br>🎁 コード PAY2 でチャージが 10% オフ!</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://soleapi.com/r/sub2api"><img src="assets/partners/logos/soleapi.png" alt="SoleAPI" width="150"></a></td>
|
||||
<td><a href="https://soleapi.com/r/sub2api">SoleAPI</a> 様、本プロジェクトへのご支援ありがとうございます!SoleAPI は開発者と企業向けの AI モデルゲートウェイです。1 つの API キーで Claude、GPT、Gemini をはじめとする 30 以上の主要モデルを利用できます。OpenAI と Anthropic のプロトコルにネイティブ対応しているため、Claude Code、Codex、Cursor や既存の SDK も Base URL を変更するだけで動作します。リクエストはレイテンシと上流の稼働状況に応じてリアルタイムにルーティングされ、ミリ秒単位でバックアップチャネルへ自動フェイルオーバーします。サービス可用性は 99.99%、24 時間 365 日の技術サポートも提供しています。すべての呼び出しは 1 つの請求書にまとめられ、リクエストごとの token 数と費用の内訳をいつでも確認できます。本プロジェクトの<a href="https://soleapi.com/r/sub2api">紹介リンク</a>から登録すると無料トライアルクレジットを受け取れ、友人を招待してチャージしてもらうと継続的にキャッシュバックを獲得できます!</td>
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 10 KiB |
@@ -1 +1 @@
|
||||
0.2.25
|
||||
0.2.27
|
||||
+1
-1
@@ -55,7 +55,7 @@ require (
|
||||
github.com/zeromicro/go-zero v1.9.4
|
||||
go.uber.org/zap v1.24.0
|
||||
golang.org/x/crypto v0.58.0
|
||||
golang.org/x/image v0.41.0
|
||||
golang.org/x/image v0.45.0
|
||||
golang.org/x/mod v0.41.0
|
||||
golang.org/x/net v0.62.0
|
||||
golang.org/x/sync v0.24.0
|
||||
|
||||
@@ -591,6 +591,8 @@ golang.org/x/exp v0.0.0-20251023183803-a4bb9ffd2546 h1:mgKeJMpvi0yx/sU5GsxQ7p6s2
|
||||
golang.org/x/exp v0.0.0-20251023183803-a4bb9ffd2546/go.mod h1:j/pmGrbnkbPtQfxEe5D0VQhZC6qKbfKifgD0oM7sR70=
|
||||
golang.org/x/image v0.41.0 h1:8wS72eGJMJaBxK6okTzd4WaXumUlTVlb753MlsSvTCo=
|
||||
golang.org/x/image v0.41.0/go.mod h1:uIc348UZMSvS5Z65CVZ7iDPaNobNFEPeJ4kbqTOszmA=
|
||||
golang.org/x/image v0.45.0 h1:FMb1nTbH5H9vF55SriQHgFw5GnNL9Jg6L25BwXKzhB0=
|
||||
golang.org/x/image v0.45.0/go.mod h1:n62x/7RqlwXDvGsSU4u6IUTUf6KghUZ9Bt7cG/T9Fx4=
|
||||
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
|
||||
golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
|
||||
golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
|
||||
|
||||
@@ -115,9 +115,19 @@ type Config struct {
|
||||
SimpleModeKeyRateLimitEnabled bool `mapstructure:"simple_mode_key_rate_limit_enabled" yaml:"simple_mode_key_rate_limit_enabled"`
|
||||
}
|
||||
|
||||
// SimpleModeConfig controls startup behavior in simple mode.
|
||||
// SimpleModeConfig controls optional behavior in simple mode.
|
||||
type SimpleModeConfig struct {
|
||||
AutoCreateDefaultGroups bool `mapstructure:"auto_create_default_groups" yaml:"auto_create_default_groups"`
|
||||
GroupIsolation bool `mapstructure:"group_isolation" yaml:"group_isolation"`
|
||||
}
|
||||
|
||||
// UsesSharedSimpleModePool reports whether scheduling may ignore account group bindings.
|
||||
func (c *Config) UsesSharedSimpleModePool() bool {
|
||||
return c != nil && c.RunMode == RunModeSimple && !c.SimpleMode.GroupIsolation
|
||||
}
|
||||
|
||||
func (c *Config) SimpleModeGroupIsolationEnabled() bool {
|
||||
return c != nil && c.RunMode == RunModeSimple && c.SimpleMode.GroupIsolation
|
||||
}
|
||||
|
||||
// MCPConfig fixes the public resource URL used by OAuth discovery and tokens.
|
||||
@@ -1179,6 +1189,9 @@ type GatewayConfig struct {
|
||||
LogUpstreamErrorBody bool `mapstructure:"log_upstream_error_body"`
|
||||
// 上游错误响应体记录最大字节数(超过会截断)
|
||||
LogUpstreamErrorBodyMaxBytes int `mapstructure:"log_upstream_error_body_max_bytes"`
|
||||
// RetryAfterMaxSeconds 限制下发给客户端的 Retry-After 秒数(默认 300):
|
||||
// 上游或账号池给出的恢复时间可能长达数小时,客户端按原值冷却会长时间挂起。
|
||||
RetryAfterMaxSeconds int `mapstructure:"retry_after_max_seconds"`
|
||||
|
||||
// API-key 账号在客户端未提供 anthropic-beta 时,是否按需自动补齐(默认关闭以保持兼容)
|
||||
InjectBetaForAPIKey bool `mapstructure:"inject_beta_for_apikey"`
|
||||
@@ -1287,15 +1300,17 @@ type GatewayOpenAIHTTP2Config struct {
|
||||
}
|
||||
|
||||
// GatewayOpenAIProxyStreamCircuitConfig controls the bounded, in-process
|
||||
// proxy-ID circuit used for incomplete OpenAI Responses SSE streams.
|
||||
// account+proxy circuit used for incomplete OpenAI Responses SSE streams.
|
||||
// Entries are scoped to the account that owned the stream, so one account
|
||||
// cannot quarantine other accounts that share the same egress proxy.
|
||||
type GatewayOpenAIProxyStreamCircuitConfig struct {
|
||||
// Disabled: 完全关闭代理断流熔断(默认开启)。
|
||||
// Disabled: 完全关闭账号+代理断流熔断(默认开启)。
|
||||
Disabled bool `mapstructure:"disabled"`
|
||||
// FailureThreshold: 统计窗口内多少次断流后隔离代理。
|
||||
// FailureThreshold: 统计窗口内多少次断流后隔离该账号在该代理上的熔断项。
|
||||
FailureThreshold int `mapstructure:"failure_threshold"`
|
||||
// WindowSeconds: 断流统计窗口(秒)。
|
||||
WindowSeconds int `mapstructure:"window_seconds"`
|
||||
// TTLSeconds: 代理隔离持续时间(秒)。
|
||||
// TTLSeconds: 熔断项隔离持续时间(秒)。
|
||||
TTLSeconds int `mapstructure:"ttl_seconds"`
|
||||
}
|
||||
|
||||
@@ -1386,7 +1401,9 @@ type GatewayOpenAIWSConfig struct {
|
||||
ClientReadLimitBytes int64 `mapstructure:"client_read_limit_bytes"`
|
||||
// HTTPBridgeEnabled: 首包过大时,保持客户端 WS,改用 HTTP Responses 上游。
|
||||
HTTPBridgeEnabled bool `mapstructure:"http_bridge_enabled"`
|
||||
// HTTPBridgeThresholdBytes: 触发 HTTP bridge 的入站 WS payload 阈值。
|
||||
// HTTPBridgeThresholdBytes caps the first-message size from which a WebSocket session is
|
||||
// bridged to HTTP. Zero (the default) follows the limit announced by the upstream handshake
|
||||
// (x-codex-websocket-max-message-bytes) and falls back to 15 MiB until one is known.
|
||||
HTTPBridgeThresholdBytes int64 `mapstructure:"http_bridge_threshold_bytes"`
|
||||
|
||||
// Feature 开关:v2 优先于 v1
|
||||
@@ -2134,6 +2151,7 @@ func setDefaults() {
|
||||
viper.SetDefault("run_mode", RunModeStandard)
|
||||
viper.SetDefault("gateway.min_output_tokens", 128)
|
||||
viper.SetDefault("simple_mode.auto_create_default_groups", true)
|
||||
viper.SetDefault("simple_mode.group_isolation", false)
|
||||
viper.SetDefault("simple_mode_key_rate_limit_enabled", false)
|
||||
|
||||
// Server
|
||||
@@ -2526,6 +2544,7 @@ func setDefaults() {
|
||||
viper.SetDefault("gateway.openai_high_effort_first_output_timeout_seconds", 0)
|
||||
viper.SetDefault("gateway.log_upstream_error_body", true)
|
||||
viper.SetDefault("gateway.log_upstream_error_body_max_bytes", 2048)
|
||||
viper.SetDefault("gateway.retry_after_max_seconds", 300)
|
||||
viper.SetDefault("gateway.inject_beta_for_apikey", false)
|
||||
viper.SetDefault("gateway.failover_on_400", false)
|
||||
viper.SetDefault("gateway.max_account_switches", 10)
|
||||
@@ -2555,7 +2574,7 @@ func setDefaults() {
|
||||
viper.SetDefault("gateway.openai_ws.prewarm_generate_enabled", false)
|
||||
viper.SetDefault("gateway.openai_ws.client_read_limit_bytes", 64*1024*1024)
|
||||
viper.SetDefault("gateway.openai_ws.http_bridge_enabled", true)
|
||||
viper.SetDefault("gateway.openai_ws.http_bridge_threshold_bytes", 15*1024*1024)
|
||||
viper.SetDefault("gateway.openai_ws.http_bridge_threshold_bytes", 0)
|
||||
viper.SetDefault("gateway.openai_ws.responses_websockets", false)
|
||||
viper.SetDefault("gateway.openai_ws.responses_websockets_v2", true)
|
||||
viper.SetDefault("gateway.openai_ws.max_conns_per_account", 128)
|
||||
@@ -3652,9 +3671,6 @@ func (c *Config) Validate() error {
|
||||
if c.Gateway.OpenAIWS.HTTPBridgeThresholdBytes < 0 {
|
||||
return fmt.Errorf("gateway.openai_ws.http_bridge_threshold_bytes must be non-negative")
|
||||
}
|
||||
if c.Gateway.OpenAIWS.HTTPBridgeEnabled && c.Gateway.OpenAIWS.HTTPBridgeThresholdBytes == 0 {
|
||||
return fmt.Errorf("gateway.openai_ws.http_bridge_threshold_bytes must be positive when http_bridge_enabled is true")
|
||||
}
|
||||
if c.Gateway.OpenAIWS.FallbackCooldownSeconds < 0 {
|
||||
return fmt.Errorf("gateway.openai_ws.fallback_cooldown_seconds must be non-negative")
|
||||
}
|
||||
|
||||
@@ -219,6 +219,32 @@ func TestLoadSimpleModeKeyRateLimitEnabledFromEnvironment(t *testing.T) {
|
||||
require.True(t, cfg.SimpleModeKeyRateLimitEnabled)
|
||||
}
|
||||
|
||||
func TestLoadSimpleModeGroupIsolation(t *testing.T) {
|
||||
for _, tt := range []struct {
|
||||
name, mode, yaml, env string
|
||||
shared, isolated bool
|
||||
}{
|
||||
{"default", RunModeSimple, "", "", true, false},
|
||||
{"yaml with empty env", RunModeSimple, "simple_mode:\n group_isolation: true\n", "", false, true},
|
||||
{"env opt-in", RunModeSimple, "", "true", false, true},
|
||||
{"explicit opt-out", RunModeSimple, "simple_mode:\n group_isolation: true\n", "false", true, false},
|
||||
{"standard", RunModeStandard, "", "true", false, false},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
resetViperWithJWTSecret(t)
|
||||
path := filepath.Join(t.TempDir(), "config.yaml")
|
||||
require.NoError(t, os.WriteFile(path, []byte(tt.yaml), 0o600))
|
||||
t.Setenv("CONFIG_FILE", path)
|
||||
t.Setenv("RUN_MODE", tt.mode)
|
||||
t.Setenv("SIMPLE_MODE_GROUP_ISOLATION", tt.env)
|
||||
cfg, err := Load()
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, tt.shared, cfg.UsesSharedSimpleModePool())
|
||||
require.Equal(t, tt.isolated, cfg.SimpleModeGroupIsolationEnabled())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadRedisUsernameFromEnvironment(t *testing.T) {
|
||||
resetViperWithJWTSecret(t)
|
||||
t.Setenv("REDIS_USERNAME", "app-user")
|
||||
@@ -646,8 +672,8 @@ func TestLoadDefaultOpenAIWSConfig(t *testing.T) {
|
||||
if !cfg.Gateway.OpenAIWS.HTTPBridgeEnabled {
|
||||
t.Fatalf("Gateway.OpenAIWS.HTTPBridgeEnabled = false, want true")
|
||||
}
|
||||
if cfg.Gateway.OpenAIWS.HTTPBridgeThresholdBytes != 15*1024*1024 {
|
||||
t.Fatalf("Gateway.OpenAIWS.HTTPBridgeThresholdBytes = %d, want %d", cfg.Gateway.OpenAIWS.HTTPBridgeThresholdBytes, 15*1024*1024)
|
||||
if cfg.Gateway.OpenAIWS.HTTPBridgeThresholdBytes != 0 {
|
||||
t.Fatalf("Gateway.OpenAIWS.HTTPBridgeThresholdBytes = %d, want 0 (follow upstream)", cfg.Gateway.OpenAIWS.HTTPBridgeThresholdBytes)
|
||||
}
|
||||
if cfg.Gateway.OpenAIWS.RetryBackoffInitialMS != 120 {
|
||||
t.Fatalf("Gateway.OpenAIWS.RetryBackoffInitialMS = %d, want 120", cfg.Gateway.OpenAIWS.RetryBackoffInitialMS)
|
||||
|
||||
@@ -12,4 +12,11 @@ type GroupCodexModelsManifestConfig struct {
|
||||
// usable or all upstream fetches fail: fall back to the scheduler loop
|
||||
// (true) or return the upstream error / 503 (false, default).
|
||||
FallbackToScheduler bool `json:"fallback_to_scheduler,omitempty"`
|
||||
// KeepHiddenAutoModes keeps Codex automatic modes (codex-auto-*) that the
|
||||
// upstream manifest already hides from the picker, byte-for-byte, instead
|
||||
// of removing them when the group model list does not select them. Codex
|
||||
// then reviews approvals with its dedicated reviewer model, and an
|
||||
// otherwise untouched upstream manifest keeps the upstream ETag. It applies
|
||||
// to manifests fetched from upstream, with or without pinned accounts.
|
||||
KeepHiddenAutoModes bool `json:"keep_hidden_auto_modes,omitempty"`
|
||||
}
|
||||
@@ -588,6 +588,23 @@ func (s *stubAdminService) CheckMixedChannelRisk(ctx context.Context, currentAcc
|
||||
return s.checkMixedErr
|
||||
}
|
||||
|
||||
func matchesProxyFilters(proxy service.Proxy, protocol, status, search string) bool {
|
||||
if protocol != "" && proxy.Protocol != protocol {
|
||||
return false
|
||||
}
|
||||
if status != "" && proxy.Status != status {
|
||||
return false
|
||||
}
|
||||
if search != "" {
|
||||
name := strings.ToLower(proxy.Name)
|
||||
host := strings.ToLower(proxy.Host)
|
||||
if !strings.Contains(name, search) && !strings.Contains(host, search) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (s *stubAdminService) ListProxies(ctx context.Context, page, pageSize int, protocol, status, search string, sortBy, sortOrder string) ([]service.Proxy, int64, error) {
|
||||
s.lastListProxies.protocol = protocol
|
||||
s.lastListProxies.status = status
|
||||
@@ -598,26 +615,24 @@ func (s *stubAdminService) ListProxies(ctx context.Context, page, pageSize int,
|
||||
search = strings.TrimSpace(strings.ToLower(search))
|
||||
filtered := make([]service.Proxy, 0, len(s.proxies))
|
||||
for _, proxy := range s.proxies {
|
||||
if protocol != "" && proxy.Protocol != protocol {
|
||||
if !matchesProxyFilters(proxy, protocol, status, search) {
|
||||
continue
|
||||
}
|
||||
if status != "" && proxy.Status != status {
|
||||
continue
|
||||
}
|
||||
if search != "" {
|
||||
name := strings.ToLower(proxy.Name)
|
||||
host := strings.ToLower(proxy.Host)
|
||||
if !strings.Contains(name, search) && !strings.Contains(host, search) {
|
||||
continue
|
||||
}
|
||||
}
|
||||
filtered = append(filtered, proxy)
|
||||
}
|
||||
return filtered, int64(len(filtered)), nil
|
||||
}
|
||||
|
||||
func (s *stubAdminService) ListProxiesWithAccountCount(ctx context.Context, page, pageSize int, protocol, status, search string, sortBy, sortOrder string) ([]service.ProxyWithAccountCount, int64, error) {
|
||||
return s.proxyCounts, int64(len(s.proxyCounts)), nil
|
||||
search = strings.TrimSpace(strings.ToLower(search))
|
||||
filtered := make([]service.ProxyWithAccountCount, 0, len(s.proxyCounts))
|
||||
for _, item := range s.proxyCounts {
|
||||
if !matchesProxyFilters(item.Proxy, protocol, status, search) {
|
||||
continue
|
||||
}
|
||||
filtered = append(filtered, item)
|
||||
}
|
||||
return filtered, int64(len(filtered)), nil
|
||||
}
|
||||
|
||||
func (s *stubAdminService) GetAllProxies(ctx context.Context) ([]service.Proxy, error) {
|
||||
|
||||
@@ -646,16 +646,6 @@ func (h *ChannelHandler) GetModelDefaultPricing(c *gin.Context) {
|
||||
})
|
||||
}
|
||||
|
||||
// platformLiteLLMProvider maps a channel platform name to the corresponding
|
||||
// LiteLLM provider string used as the key in the pricing catalog (platform list).
|
||||
func platformLiteLLMProvider(platform string) (string, bool) {
|
||||
spec, ok := domain.LookupPlatform(platform)
|
||||
if !ok || spec.LiteLLMProvider == "" {
|
||||
return "", false
|
||||
}
|
||||
return spec.LiteLLMProvider, true
|
||||
}
|
||||
|
||||
// SyncPricingModels 返回 LiteLLM 定价目录中指定平台的最新模型列表
|
||||
// GET /api/v1/admin/channels/pricing/sync-models?platform=anthropic
|
||||
func (h *ChannelHandler) SyncPricingModels(c *gin.Context) {
|
||||
@@ -666,14 +656,14 @@ func (h *ChannelHandler) SyncPricingModels(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
provider, ok := platformLiteLLMProvider(platform)
|
||||
if !ok {
|
||||
spec, ok := domain.LookupPlatform(platform)
|
||||
if !ok || spec.LiteLLMProvider == "" {
|
||||
response.ErrorFrom(c, infraerrors.BadRequest("UNSUPPORTED_PLATFORM",
|
||||
fmt.Sprintf("unsupported platform: %s", platform)).
|
||||
WithMetadata(map[string]string{"param": "platform"}))
|
||||
return
|
||||
}
|
||||
|
||||
models := h.pricingService.ListModelNamesByProvider(provider)
|
||||
models := h.pricingService.ListModelNamesForPlatform(spec)
|
||||
response.Success(c, gin.H{"models": models})
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
//go:build unit
|
||||
|
||||
package admin
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
type moderationAccountsHandlerSettingRepo struct {
|
||||
service.SettingRepository
|
||||
mu sync.Mutex
|
||||
values map[string]string
|
||||
}
|
||||
|
||||
func (r *moderationAccountsHandlerSettingRepo) GetValue(_ context.Context, key string) (string, error) {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
v, ok := r.values[key]
|
||||
if !ok {
|
||||
return "", service.ErrSettingNotFound
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
func (r *moderationAccountsHandlerSettingRepo) GetMultiple(_ context.Context, keys []string) (map[string]string, error) {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
out := make(map[string]string, len(keys))
|
||||
for _, k := range keys {
|
||||
if v, ok := r.values[k]; ok {
|
||||
out[k] = v
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (r *moderationAccountsHandlerSettingRepo) Set(_ context.Context, key, value string) error {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
r.values[key] = value
|
||||
return nil
|
||||
}
|
||||
|
||||
type moderationAccountsHandlerStubRepo struct {
|
||||
service.ContentModerationRepository
|
||||
accounts []service.ContentModerationExcludedAccount
|
||||
lastFilter service.ContentModerationAccountSearchFilter
|
||||
}
|
||||
|
||||
func (r *moderationAccountsHandlerStubRepo) SearchModerationAccounts(
|
||||
_ context.Context,
|
||||
filter service.ContentModerationAccountSearchFilter,
|
||||
) ([]service.ContentModerationExcludedAccount, error) {
|
||||
r.lastFilter = filter
|
||||
return r.accounts, nil
|
||||
}
|
||||
|
||||
func (r *moderationAccountsHandlerStubRepo) ListModerationAccountsByIDs(
|
||||
_ context.Context,
|
||||
ids []int64,
|
||||
) ([]service.ContentModerationExcludedAccount, error) {
|
||||
byID := make(map[int64]service.ContentModerationExcludedAccount, len(r.accounts))
|
||||
for _, item := range r.accounts {
|
||||
byID[item.ID] = item
|
||||
}
|
||||
out := make([]service.ContentModerationExcludedAccount, 0, len(ids))
|
||||
for _, id := range ids {
|
||||
if item, ok := byID[id]; ok {
|
||||
out = append(out, item)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func TestContentModerationHandler_ExcludedAccountsConfigAndSearch(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
settingRepo := &moderationAccountsHandlerSettingRepo{values: map[string]string{}}
|
||||
modRepo := &moderationAccountsHandlerStubRepo{
|
||||
accounts: []service.ContentModerationExcludedAccount{
|
||||
{ID: 12, Name: "Claude-OAuth-A", Platform: "anthropic", Type: "oauth"},
|
||||
{ID: 35, Name: "OpenAI-Key-B", Platform: "openai", Type: "apikey"},
|
||||
},
|
||||
}
|
||||
svc := service.NewContentModerationService(settingRepo, modRepo, nil, nil, nil, nil, nil, nil)
|
||||
h := NewContentModerationHandler(svc)
|
||||
|
||||
router := gin.New()
|
||||
router.GET("/config", h.GetConfig)
|
||||
router.PUT("/config", h.UpdateConfig)
|
||||
router.GET("/accounts/search", h.SearchAccounts)
|
||||
|
||||
// 1. 按所选分组模糊搜索账户(OAuth + API Key)
|
||||
recSearch := httptest.NewRecorder()
|
||||
reqSearch := httptest.NewRequest(http.MethodGet, "/accounts/search?search=key&group_ids=3,8&limit=15", nil)
|
||||
router.ServeHTTP(recSearch, reqSearch)
|
||||
require.Equal(t, http.StatusOK, recSearch.Code)
|
||||
require.Equal(t, "key", modRepo.lastFilter.Search)
|
||||
require.False(t, modRepo.lastFilter.AllGroups)
|
||||
require.Equal(t, []int64{3, 8}, modRepo.lastFilter.GroupIDs)
|
||||
require.Equal(t, 15, modRepo.lastFilter.Limit)
|
||||
|
||||
// 非法 group_ids 返回 400
|
||||
recBad := httptest.NewRecorder()
|
||||
router.ServeHTTP(recBad, httptest.NewRequest(http.MethodGet, "/accounts/search?group_ids=abc", nil))
|
||||
require.Equal(t, http.StatusBadRequest, recBad.Code)
|
||||
|
||||
// 2. 更新配置写入 excluded_account_ids 并验证 GET /config 正确回显详情
|
||||
payload, err := json.Marshal(map[string]any{
|
||||
"excluded_account_ids": []int64{12, 35},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
recUpdate := httptest.NewRecorder()
|
||||
reqUpdate := httptest.NewRequest(http.MethodPut, "/config", bytes.NewReader(payload))
|
||||
reqUpdate.Header.Set("Content-Type", "application/json")
|
||||
router.ServeHTTP(recUpdate, reqUpdate)
|
||||
require.Equal(t, http.StatusOK, recUpdate.Code)
|
||||
|
||||
recGet := httptest.NewRecorder()
|
||||
router.ServeHTTP(recGet, httptest.NewRequest(http.MethodGet, "/config", nil))
|
||||
require.Equal(t, http.StatusOK, recGet.Code)
|
||||
|
||||
var resp struct {
|
||||
Data service.ContentModerationConfigView `json:"data"`
|
||||
}
|
||||
require.NoError(t, json.Unmarshal(recGet.Body.Bytes(), &resp))
|
||||
require.Equal(t, []int64{12, 35}, resp.Data.ExcludedAccountIDs)
|
||||
require.Len(t, resp.Data.ExcludedAccounts, 2)
|
||||
require.Equal(t, "Claude-OAuth-A", resp.Data.ExcludedAccounts[0].Name)
|
||||
require.Equal(t, "OpenAI-Key-B", resp.Data.ExcludedAccounts[1].Name)
|
||||
}
|
||||
@@ -37,6 +37,7 @@ type contentModerationConfigRequest struct {
|
||||
SampleRate *int `json:"sample_rate"`
|
||||
AllGroups *bool `json:"all_groups"`
|
||||
GroupIDs *[]int64 `json:"group_ids"`
|
||||
ExcludedAccountIDs *[]int64 `json:"excluded_account_ids"`
|
||||
RecordNonHits *bool `json:"record_non_hits"`
|
||||
Thresholds *map[string]float64 `json:"thresholds"`
|
||||
WorkerCount *int `json:"worker_count"`
|
||||
@@ -106,6 +107,7 @@ func (h *ContentModerationHandler) UpdateConfig(c *gin.Context) {
|
||||
SampleRate: req.SampleRate,
|
||||
AllGroups: req.AllGroups,
|
||||
GroupIDs: req.GroupIDs,
|
||||
ExcludedAccountIDs: req.ExcludedAccountIDs,
|
||||
RecordNonHits: req.RecordNonHits,
|
||||
Thresholds: req.Thresholds,
|
||||
WorkerCount: req.WorkerCount,
|
||||
@@ -248,6 +250,45 @@ func (h *ContentModerationHandler) ClearFlaggedHashes(c *gin.Context) {
|
||||
response.Success(c, result)
|
||||
}
|
||||
|
||||
func (h *ContentModerationHandler) SearchAccounts(c *gin.Context) {
|
||||
allGroups := strings.EqualFold(strings.TrimSpace(c.Query("all_groups")), "true") || strings.TrimSpace(c.Query("all_groups")) == "1"
|
||||
var groupIDs []int64
|
||||
for _, rawVal := range c.QueryArray("group_ids") {
|
||||
for _, part := range strings.Split(rawVal, ",") {
|
||||
part = strings.TrimSpace(part)
|
||||
if part == "" {
|
||||
continue
|
||||
}
|
||||
id, err := strconv.ParseInt(part, 10, 64)
|
||||
if err != nil || id <= 0 {
|
||||
response.BadRequest(c, "Invalid group_ids")
|
||||
return
|
||||
}
|
||||
groupIDs = append(groupIDs, id)
|
||||
}
|
||||
}
|
||||
limit := 20
|
||||
if rawLimit := strings.TrimSpace(c.Query("limit")); rawLimit != "" {
|
||||
parsedLimit, err := strconv.Atoi(rawLimit)
|
||||
if err != nil || parsedLimit <= 0 {
|
||||
response.BadRequest(c, "Invalid limit")
|
||||
return
|
||||
}
|
||||
limit = parsedLimit
|
||||
}
|
||||
items, err := h.service.SearchAccounts(c.Request.Context(), service.ContentModerationAccountSearchFilter{
|
||||
Search: strings.TrimSpace(c.Query("search")),
|
||||
AllGroups: allGroups,
|
||||
GroupIDs: groupIDs,
|
||||
Limit: limit,
|
||||
})
|
||||
if err != nil {
|
||||
response.ErrorFrom(c, err)
|
||||
return
|
||||
}
|
||||
response.Success(c, items)
|
||||
}
|
||||
|
||||
func parseContentModerationDate(raw string) (time.Time, bool, error) {
|
||||
raw = strings.TrimSpace(raw)
|
||||
if raw == "" {
|
||||
|
||||
@@ -547,7 +547,8 @@ func (h *SettingHandler) TestWebSearchEmulation(c *gin.Context) {
|
||||
|
||||
result, err := service.TestWebSearch(c.Request.Context(), req.Query)
|
||||
if err != nil {
|
||||
response.ErrorFrom(c, err)
|
||||
// Like the SMTP test, return the cause so the admin can fix the provider config.
|
||||
response.BadRequest(c, "Web search test failed: "+err.Error())
|
||||
return
|
||||
}
|
||||
response.Success(c, result)
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
//go:build unit
|
||||
|
||||
package admin
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestTestWebSearchEmulationReturnsFailureCause(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
service.SetWebSearchManager(nil)
|
||||
t.Cleanup(func() { service.SetWebSearchManager(nil) })
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/api/v1/admin/settings/web-search-emulation/test", bytes.NewBufferString(`{"query":"golang"}`))
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
|
||||
(&SettingHandler{}).TestWebSearchEmulation(c)
|
||||
|
||||
require.Equal(t, http.StatusBadRequest, rec.Code)
|
||||
var body struct {
|
||||
Message string `json:"message"`
|
||||
}
|
||||
require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &body))
|
||||
require.Contains(t, body.Message, "Web search test failed")
|
||||
require.Contains(t, body.Message, "save config first", "the admin must see why the test failed, not a generic internal error")
|
||||
}
|
||||
@@ -47,6 +47,11 @@ func (h *BatchImageHandler) Submit(c *gin.Context) {
|
||||
}
|
||||
got, err := h.service.Submit(c.Request.Context(), owner, req, c.GetHeader("Idempotency-Key"))
|
||||
if err != nil {
|
||||
var modBlocked *accountModerationBlockedError
|
||||
if errors.As(err, &modBlocked) && h.openAI != nil {
|
||||
h.openAI.openAISecurityAuditError(c, modBlocked.decision)
|
||||
return
|
||||
}
|
||||
batchImageError(c, err)
|
||||
return
|
||||
}
|
||||
@@ -88,6 +93,12 @@ func (h *BatchImageHandler) checkSecurityAuditBeforeSubmit(c *gin.Context, req *
|
||||
h.openAI.openAISecurityAuditError(c, decision)
|
||||
return false
|
||||
}
|
||||
c.Request = c.Request.WithContext(service.WithAccountModerationHook(c.Request.Context(), func(accountID int64) error {
|
||||
if dec := checkSelectedAccountModeration(c, accountID); dec != nil && !dec.AllowNextStage {
|
||||
return &accountModerationBlockedError{decision: dec}
|
||||
}
|
||||
return nil
|
||||
}))
|
||||
return true
|
||||
}
|
||||
|
||||
|
||||
@@ -116,6 +116,17 @@ func bindRequestedReasoningEffort(c *gin.Context, body []byte, model string) {
|
||||
c.Request = c.Request.WithContext(service.WithRequestedReasoningEffort(c.Request.Context(), *effort))
|
||||
}
|
||||
|
||||
func bindRequestedReasoningEffortWithFields(c *gin.Context, body []byte, model, reasoningEffort, reasoningEffortTop, outputConfigEffort string) {
|
||||
if c == nil || c.Request == nil {
|
||||
return
|
||||
}
|
||||
effort := service.CanonicalRequestedReasoningEffortWithFields(body, reasoningEffort, reasoningEffortTop, outputConfigEffort, model)
|
||||
if effort == nil {
|
||||
return
|
||||
}
|
||||
c.Request = c.Request.WithContext(service.WithRequestedReasoningEffort(c.Request.Context(), *effort))
|
||||
}
|
||||
|
||||
func stampOpenAIRequestedReasoningEffort(result *service.OpenAIForwardResult, c *gin.Context) {
|
||||
if result == nil || result.RequestedReasoningEffort != nil {
|
||||
return
|
||||
@@ -142,6 +153,20 @@ func applyOpenAIReasoningEffortPolicyForRequest(c *gin.Context, apiKey *service.
|
||||
return service.ApplyOpenAIReasoningEffortPolicy(body, maxEffort, mappings, overLimit)
|
||||
}
|
||||
|
||||
func applyOpenAIReasoningEffortPolicyForRequestWithFields(
|
||||
c *gin.Context,
|
||||
apiKey *service.APIKey,
|
||||
body []byte,
|
||||
model, reasoningEffort, reasoningEffortTop, outputConfigEffort string,
|
||||
) ([]byte, bool, error) {
|
||||
bindRequestedReasoningEffortWithFields(c, body, strings.TrimSpace(model), reasoningEffort, reasoningEffortTop, outputConfigEffort)
|
||||
maxEffort, mappings, overLimit, ok := openAIReasoningEffortPolicyForRequest(c, apiKey)
|
||||
if !ok {
|
||||
return body, false, nil
|
||||
}
|
||||
return service.ApplyOpenAIReasoningEffortPolicy(body, maxEffort, mappings, overLimit)
|
||||
}
|
||||
|
||||
func respondOpenAIReasoningEffortPolicyError(c *gin.Context, err error, write func(*gin.Context, int, string, string)) {
|
||||
if c == nil || err == nil || write == nil {
|
||||
return
|
||||
|
||||
@@ -0,0 +1,225 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/securityaudit"
|
||||
middleware2 "github.com/Wei-Shaw/sub2api/internal/server/middleware"
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/gin-gonic/gin"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
const pendingAccountModerationContextKey = "sub2api.content_moderation.pending_account"
|
||||
|
||||
type pendingAccountModeration struct {
|
||||
mu sync.Mutex
|
||||
svc *service.ContentModerationService
|
||||
reqLog *zap.Logger
|
||||
input service.ContentModerationCheckInput
|
||||
checkedNonExcl bool
|
||||
cachedDecision *securityaudit.Decision
|
||||
}
|
||||
|
||||
type accountModerationBlockedError struct {
|
||||
decision *securityaudit.Decision
|
||||
}
|
||||
|
||||
func (e *accountModerationBlockedError) Error() string {
|
||||
if e == nil || e.decision == nil || e.decision.ClientMessage == "" {
|
||||
return "Request blocked by content policy"
|
||||
}
|
||||
return e.decision.ClientMessage
|
||||
}
|
||||
|
||||
func boundAccountIDFromGinContext(c *gin.Context) int64 {
|
||||
if c == nil {
|
||||
return 0
|
||||
}
|
||||
if v, ok := c.Get(opsAccountIDKey); ok {
|
||||
if id, valid := v.(int64); valid && id > 0 {
|
||||
return id
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func deferAccountModerationIfNeeded(
|
||||
c *gin.Context,
|
||||
reqLog *zap.Logger,
|
||||
svc *service.ContentModerationService,
|
||||
input service.ContentModerationCheckInput,
|
||||
) bool {
|
||||
if c == nil || c.Request == nil || svc == nil || input.AccountID > 0 {
|
||||
return false
|
||||
}
|
||||
if !svc.ShouldDeferForAccountExclusion(c.Request.Context(), input) {
|
||||
return false
|
||||
}
|
||||
clonedInput := input
|
||||
if input.GroupID != nil {
|
||||
gid := *input.GroupID
|
||||
clonedInput.GroupID = &gid
|
||||
}
|
||||
// 复制切片以防止调用方(如异步生图提交阶段)清空外层缓冲引用。
|
||||
clonedInput.Body = append([]byte(nil), input.Body...)
|
||||
c.Set(pendingAccountModerationContextKey, &pendingAccountModeration{
|
||||
svc: svc,
|
||||
reqLog: reqLog,
|
||||
input: clonedInput,
|
||||
})
|
||||
return true
|
||||
}
|
||||
|
||||
// resetWSRetryAccountModeration 在 WebSocket 后续轮次因故障切换以新 turn 1 重放时,
|
||||
// 按当前重放载荷重建待审上下文并清空旧轮次缓存;若当前无排除账户则立即同步审计。
|
||||
func resetWSRetryAccountModeration(
|
||||
c *gin.Context,
|
||||
reqLog *zap.Logger,
|
||||
svc *service.ContentModerationService,
|
||||
apiKey *service.APIKey,
|
||||
subject middleware2.AuthSubject,
|
||||
protocol string,
|
||||
model string,
|
||||
payload []byte,
|
||||
) *securityaudit.Decision {
|
||||
if c == nil || c.Request == nil {
|
||||
return nil
|
||||
}
|
||||
if c.Keys != nil {
|
||||
delete(c.Keys, pendingAccountModerationContextKey)
|
||||
delete(c.Keys, securityAuditWSDedupeContextKey)
|
||||
delete(c.Keys, opsAccountIDKey)
|
||||
}
|
||||
if svc == nil {
|
||||
return nil
|
||||
}
|
||||
input := buildContentModerationInput(c, apiKey, subject, protocol, model, payload)
|
||||
if trimmedModel := strings.TrimSpace(model); trimmedModel != "" {
|
||||
input.Model = trimmedModel
|
||||
}
|
||||
input.AccountID = 0
|
||||
if deferAccountModerationIfNeeded(c, reqLog, svc, input) {
|
||||
return nil
|
||||
}
|
||||
legacyDecision := runContentModerationWithInput(c.Request.Context(), reqLog, svc, input)
|
||||
if legacyDecision == nil || !legacyDecision.Blocked {
|
||||
return nil
|
||||
}
|
||||
return &securityaudit.Decision{
|
||||
Kind: securityaudit.DecisionBlock,
|
||||
HTTPStatus: contentModerationStatus(legacyDecision),
|
||||
ErrorCode: "content_policy_violation",
|
||||
ClientMessage: legacyDecision.Message,
|
||||
AllowNextStage: false,
|
||||
Legacy: &securityaudit.LegacyDecision{
|
||||
Allowed: legacyDecision.Allowed,
|
||||
Blocked: legacyDecision.Blocked,
|
||||
Flagged: legacyDecision.Flagged,
|
||||
Message: legacyDecision.Message,
|
||||
StatusCode: legacyDecision.StatusCode,
|
||||
ErrorCode: "content_policy_violation",
|
||||
Action: legacyDecision.Action,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func checkSelectedAccountModeration(c *gin.Context, accountID int64) *securityaudit.Decision {
|
||||
if c == nil || c.Request == nil || accountID <= 0 {
|
||||
return nil
|
||||
}
|
||||
raw, exists := c.Get(pendingAccountModerationContextKey)
|
||||
if !exists || raw == nil {
|
||||
return nil
|
||||
}
|
||||
pending, ok := raw.(*pendingAccountModeration)
|
||||
if !ok || pending == nil || pending.svc == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
ctx := c.Request.Context()
|
||||
// 选定账户命中内存排除集:全局最优先直接忽略(O(1) 内存查找,0 数据库/Redis 查询)。
|
||||
if pending.svc.IsAccountExcluded(ctx, accountID) {
|
||||
return nil
|
||||
}
|
||||
|
||||
pending.mu.Lock()
|
||||
defer pending.mu.Unlock()
|
||||
if pending.checkedNonExcl {
|
||||
return pending.cachedDecision
|
||||
}
|
||||
|
||||
checkInput := pending.input
|
||||
checkInput.AccountID = accountID
|
||||
legacyDecision := runContentModerationWithInput(ctx, pending.reqLog, pending.svc, checkInput)
|
||||
pending.checkedNonExcl = true
|
||||
if legacyDecision == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
decision := securityaudit.Decision{
|
||||
Kind: securityaudit.DecisionAllow,
|
||||
HTTPStatus: http.StatusOK,
|
||||
AllowNextStage: true,
|
||||
Legacy: &securityaudit.LegacyDecision{
|
||||
Allowed: legacyDecision.Allowed,
|
||||
Blocked: legacyDecision.Blocked,
|
||||
Flagged: legacyDecision.Flagged,
|
||||
Message: legacyDecision.Message,
|
||||
StatusCode: legacyDecision.StatusCode,
|
||||
ErrorCode: "content_policy_violation",
|
||||
Action: legacyDecision.Action,
|
||||
},
|
||||
}
|
||||
if legacyDecision.Blocked {
|
||||
decision.Kind = securityaudit.DecisionBlock
|
||||
decision.HTTPStatus = contentModerationStatus(legacyDecision)
|
||||
decision.ErrorCode = "content_policy_violation"
|
||||
decision.ClientMessage = legacyDecision.Message
|
||||
decision.AllowNextStage = false
|
||||
}
|
||||
pending.cachedDecision = &decision
|
||||
if !decision.AllowNextStage {
|
||||
return &decision
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func selectionReleaseFunc(selection *service.AccountSelectionResult) func() {
|
||||
if selection != nil && selection.Acquired {
|
||||
return selection.ReleaseFunc
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func webSearchSecurityAuditError(c *gin.Context, decision *securityaudit.Decision) {
|
||||
if securityAuditStreamCommitted(c) {
|
||||
writeGenericSecurityAuditSSEError(c, securityAuditStatus(decision), securityAuditErrorCode(decision), securityAuditErrorCode(decision), securityAuditMessage(decision))
|
||||
return
|
||||
}
|
||||
c.JSON(securityAuditStatus(decision), gin.H{"error": gin.H{
|
||||
"type": securityAuditErrorCode(decision),
|
||||
"message": securityAuditMessage(decision),
|
||||
}})
|
||||
}
|
||||
|
||||
func rejectSelectedAccountIfModerated(
|
||||
c *gin.Context,
|
||||
accountID int64,
|
||||
releaseFunc func(),
|
||||
writeErr func(*gin.Context, *securityaudit.Decision),
|
||||
) bool {
|
||||
decision := checkSelectedAccountModeration(c, accountID)
|
||||
if decision == nil || decision.AllowNextStage {
|
||||
return false
|
||||
}
|
||||
if releaseFunc != nil {
|
||||
releaseFunc()
|
||||
}
|
||||
if writeErr != nil {
|
||||
writeErr(c, decision)
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,251 @@
|
||||
//go:build unit
|
||||
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/securityaudit"
|
||||
middleware2 "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 stubBlockingPromptEngine struct{}
|
||||
|
||||
func (stubBlockingPromptEngine) EffectiveMode() securityaudit.Mode {
|
||||
return securityaudit.ModeBlocking
|
||||
}
|
||||
|
||||
func (stubBlockingPromptEngine) Enqueue(context.Context, securityaudit.Request) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (stubBlockingPromptEngine) Evaluate(context.Context, securityaudit.Request) (*securityaudit.PromptDecision, error) {
|
||||
return &securityaudit.PromptDecision{
|
||||
Kind: securityaudit.DecisionBlock,
|
||||
ErrorCode: securityaudit.ErrorCodeBlocked,
|
||||
AllowNextStage: false,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func newDeferredModerationTestSuite(t *testing.T, upstreamCounter *atomic.Int32) (*service.ContentModerationService, *securityaudit.Coordinator) {
|
||||
t.Helper()
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
if upstreamCounter != nil {
|
||||
upstreamCounter.Add(1)
|
||||
}
|
||||
_, _ = w.Write([]byte(`{"model":"omni-moderation-latest","results":[{"flagged":false,"category_scores":{"violence":0.10}}]}`))
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
|
||||
groupID := int64(7)
|
||||
rawCfg, err := json.Marshal(map[string]any{
|
||||
"enabled": true,
|
||||
"mode": "pre_block",
|
||||
"base_url": server.URL,
|
||||
"api_keys": []string{"sk-mod"},
|
||||
"all_groups": false,
|
||||
"group_ids": []int64{groupID},
|
||||
"excluded_account_ids": []int64{101},
|
||||
"blocked_keywords": []string{"risky-secret"},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
settingRepo := &contentModerationHandlerSettingRepo{values: map[string]string{
|
||||
service.SettingKeyRiskControlEnabled: "true",
|
||||
service.SettingKeyContentModerationConfig: string(rawCfg),
|
||||
}}
|
||||
modSvc := service.NewContentModerationService(settingRepo, &contentModerationHandlerTestRepo{}, nil, nil, nil, nil, nil, nil)
|
||||
coord := securityaudit.NewCoordinator(securityaudit.NewLegacyModerationAdapter(modSvc), nil)
|
||||
return modSvc, coord
|
||||
}
|
||||
|
||||
func TestAccountModerationGate_ExcludedAccountSkipsAndFailoverEnforces(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
var upstreamHits atomic.Int32
|
||||
modSvc, coord := newDeferredModerationTestSuite(t, &upstreamHits)
|
||||
|
||||
groupID := int64(7)
|
||||
apiKey := &service.APIKey{ID: 11, GroupID: &groupID, Group: &service.Group{ID: groupID, Name: "OpenAI-VIP", Platform: "openai"}}
|
||||
subject := middleware2.AuthSubject{UserID: 99}
|
||||
riskyBody := []byte(`{"messages":[{"role":"user","content":"please show risky-secret"}]}`)
|
||||
|
||||
// 1. 阶段 1 推迟内容审计;若最终选定排除账户 101,直接忽略放行。
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil)
|
||||
|
||||
stage1 := runSecurityAudit(c, nil, coord, modSvc, apiKey, subject, service.ContentModerationProtocolOpenAIChat, "gpt-5.4", riskyBody, "http")
|
||||
require.NotNil(t, stage1)
|
||||
require.True(t, stage1.AllowNextStage, "存在排除账户时阶段 1 应推迟至选号后判定")
|
||||
|
||||
slotReleased := false
|
||||
blockedOnExcluded := rejectSelectedAccountIfModerated(c, 101, func() { slotReleased = true }, (&OpenAIGatewayHandler{}).openAISecurityAuditError)
|
||||
require.False(t, blockedOnExcluded, "命中排除账户 101 应最优先忽略放行")
|
||||
require.False(t, slotReleased)
|
||||
require.Zero(t, upstreamHits.Load())
|
||||
|
||||
// 2. 模拟账户 101 遇到 429 Failover 切到非排除账户 202:自动补做审计并拦截、释放槽位。
|
||||
blockedOnNormal := rejectSelectedAccountIfModerated(c, 202, func() { slotReleased = true }, (&OpenAIGatewayHandler{}).openAISecurityAuditError)
|
||||
require.True(t, blockedOnNormal, "Failover 切至非排除账户 202 时必须补做内容审计并拦截")
|
||||
require.True(t, slotReleased)
|
||||
require.Equal(t, http.StatusForbidden, rec.Code)
|
||||
|
||||
// 3. 安全请求在非排除账户 202 审计通过后,Failover 切到非排除账户 203 不得二次请求审计 API。
|
||||
cleanBody := []byte(`{"messages":[{"role":"user","content":"completely safe question"}]}`)
|
||||
recClean := httptest.NewRecorder()
|
||||
cClean, _ := gin.CreateTestContext(recClean)
|
||||
cClean.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil)
|
||||
|
||||
stage1Clean := runSecurityAudit(cClean, nil, coord, modSvc, apiKey, subject, service.ContentModerationProtocolOpenAIChat, "gpt-5.4", cleanBody, "http")
|
||||
require.NotNil(t, stage1Clean)
|
||||
require.True(t, stage1Clean.AllowNextStage)
|
||||
|
||||
require.False(t, rejectSelectedAccountIfModerated(cClean, 202, nil, nil))
|
||||
require.Equal(t, int32(1), upstreamHits.Load())
|
||||
require.False(t, rejectSelectedAccountIfModerated(cClean, 203, nil, nil))
|
||||
require.Equal(t, int32(1), upstreamHits.Load(), "同一请求 Failover 至其他非排除账户应复用已通过审计结果")
|
||||
}
|
||||
|
||||
func TestAccountModerationGate_WSSubsequentTurnAndPromptAuditOrder(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
modSvc, coord := newDeferredModerationTestSuite(t, nil)
|
||||
|
||||
groupID := int64(7)
|
||||
apiKey := &service.APIKey{ID: 11, GroupID: &groupID, Group: &service.Group{ID: groupID, Platform: "openai"}}
|
||||
subject := middleware2.AuthSubject{UserID: 99}
|
||||
riskyPayload := []byte(`{"model":"gpt-5.4","input":"risky-secret"}`)
|
||||
|
||||
// WebSocket 后续轮次:绑定排除账户 101 时直接放行;绑定普通账户 202 时拦截。
|
||||
cWS, _ := gin.CreateTestContext(httptest.NewRecorder())
|
||||
cWS.Request = httptest.NewRequest(http.MethodGet, "/v1/responses", nil)
|
||||
cWS.Set(securityAuditWSTurnContextKey, 2)
|
||||
setOpsSelectedAccount(cWS, 101, "openai")
|
||||
|
||||
dExcluded := runSecurityAudit(cWS, nil, coord, modSvc, apiKey, subject, service.ContentModerationProtocolOpenAIResponses, "gpt-5.4", riskyPayload, "subsequent_turn")
|
||||
require.NotNil(t, dExcluded)
|
||||
require.True(t, dExcluded.AllowNextStage)
|
||||
|
||||
cWSNormal, _ := gin.CreateTestContext(httptest.NewRecorder())
|
||||
cWSNormal.Request = httptest.NewRequest(http.MethodGet, "/v1/responses", nil)
|
||||
cWSNormal.Set(securityAuditWSTurnContextKey, 2)
|
||||
setOpsSelectedAccount(cWSNormal, 202, "openai")
|
||||
|
||||
dNormal := runSecurityAudit(cWSNormal, nil, coord, modSvc, apiKey, subject, service.ContentModerationProtocolOpenAIResponses, "gpt-5.4", riskyPayload, "subsequent_turn")
|
||||
require.NotNil(t, dNormal)
|
||||
require.False(t, dNormal.AllowNextStage)
|
||||
|
||||
// PromptAudit 开启阻塞时,即使配置了排除账户,PromptAudit 仍在选号前立即拦截。
|
||||
blockingCoord := securityaudit.NewCoordinator(securityaudit.NewLegacyModerationAdapter(modSvc), stubBlockingPromptEngine{})
|
||||
cPrompt, _ := gin.CreateTestContext(httptest.NewRecorder())
|
||||
cPrompt.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil)
|
||||
dPrompt := runSecurityAudit(cPrompt, nil, blockingCoord, modSvc, apiKey, subject, service.ContentModerationProtocolOpenAIResponses, "gpt-5.4", []byte(`{"input":"safe"}`), "http")
|
||||
require.NotNil(t, dPrompt)
|
||||
require.False(t, dPrompt.AllowNextStage)
|
||||
require.Equal(t, securityaudit.ErrorCodeBlocked, dPrompt.ErrorCode)
|
||||
}
|
||||
|
||||
func TestAccountModerationGate_WSRetryRebuildsPendingForCurrentTurn(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
modSvc, coord := newDeferredModerationTestSuite(t, nil)
|
||||
|
||||
groupID := int64(7)
|
||||
apiKey := &service.APIKey{ID: 11, GroupID: &groupID, Group: &service.Group{ID: groupID, Platform: "openai"}}
|
||||
subject := middleware2.AuthSubject{UserID: 99}
|
||||
|
||||
c, _ := gin.CreateTestContext(httptest.NewRecorder())
|
||||
c.Request = httptest.NewRequest(http.MethodGet, "/v1/responses", nil)
|
||||
|
||||
// Turn 1: 安全输入进入并选中排除账户 101,pending 记录的是首轮安全输入。
|
||||
turn1Safe := []byte(`{"type":"response.create","model":"gpt-5.4","input":"hello safe world"}`)
|
||||
d1 := runSecurityAudit(c, nil, coord, modSvc, apiKey, subject, service.ContentModerationProtocolOpenAIResponses, "gpt-5.4", turn1Safe, "first_turn")
|
||||
require.NotNil(t, d1)
|
||||
require.True(t, d1.AllowNextStage)
|
||||
require.Nil(t, checkSelectedAccountModeration(c, 101))
|
||||
setOpsSelectedAccount(c, 101, "openai")
|
||||
|
||||
// Turn 2: 违规输入在排除账户 101 的 BeforeRequest 中按排除账户放行。
|
||||
c.Set(securityAuditWSTurnContextKey, 2)
|
||||
turn2Risky := []byte(`{"type":"response.create","model":"gpt-5.4","input":"please expose risky-secret"}`)
|
||||
d2 := runSecurityAudit(c, nil, coord, modSvc, apiKey, subject, service.ContentModerationProtocolOpenAIResponses, "gpt-5.4", turn2Risky, "subsequent_turn")
|
||||
require.NotNil(t, d2)
|
||||
require.True(t, d2.AllowNextStage)
|
||||
|
||||
// Turn 2 在上游遇到 429 触发当前轮换号重放,切换到普通账户 202:必须审计第 2 轮违规输入并拦截。
|
||||
retryImmediate := resetWSRetryAccountModeration(c, nil, modSvc, apiKey, subject, service.ContentModerationProtocolOpenAIResponses, "gpt-5.4", turn2Risky)
|
||||
require.Nil(t, retryImmediate, "存在排除账户时应重建待审上下文供新选号判定")
|
||||
|
||||
wsBlocked := checkSelectedAccountModeration(c, 202)
|
||||
require.NotNil(t, wsBlocked, "换号至普通账户 202 时必须按第 2 轮载荷拦截,不能误用首轮安全载荷")
|
||||
require.False(t, wsBlocked.AllowNextStage)
|
||||
require.Equal(t, "content_policy_violation", wsBlocked.ErrorCode)
|
||||
}
|
||||
|
||||
func TestSecurityAuditErrors_StreamingCommittedEmitsSSEEventsInsteadOfRawJSON(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
legacyBlock := &securityaudit.Decision{
|
||||
Kind: securityaudit.DecisionBlock,
|
||||
HTTPStatus: http.StatusForbidden,
|
||||
ErrorCode: "content_policy_violation",
|
||||
ClientMessage: "内容审计拦截测试",
|
||||
AllowNextStage: false,
|
||||
Legacy: &securityaudit.LegacyDecision{
|
||||
Allowed: false,
|
||||
Blocked: true,
|
||||
StatusCode: http.StatusForbidden,
|
||||
ErrorCode: "content_policy_violation",
|
||||
Message: "内容审计拦截测试",
|
||||
},
|
||||
}
|
||||
|
||||
// 1. OpenAI /v1/responses 已发出 SSE 心跳后延迟拦截:输出合法的 response.failed 终止帧。
|
||||
recResp := httptest.NewRecorder()
|
||||
cResp, _ := gin.CreateTestContext(recResp)
|
||||
cResp.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil)
|
||||
cResp.Header("Content-Type", "text/event-stream")
|
||||
cResp.Status(http.StatusOK)
|
||||
_, _ = cResp.Writer.WriteString(": ping\n\n")
|
||||
cResp.Writer.Flush()
|
||||
|
||||
(&OpenAIGatewayHandler{}).openAISecurityAuditError(cResp, legacyBlock)
|
||||
respOut := recResp.Body.String()
|
||||
require.Contains(t, respOut, ": ping\n\n")
|
||||
require.Contains(t, respOut, "event: response.failed\n")
|
||||
require.Contains(t, respOut, "内容审计拦截测试")
|
||||
|
||||
// 2. OpenAI /v1/chat/completions 已发出 SSE 心跳后延迟拦截:输出 event: error SSE 帧。
|
||||
recCC := httptest.NewRecorder()
|
||||
cCC, _ := gin.CreateTestContext(recCC)
|
||||
cCC.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil)
|
||||
cCC.Header("Content-Type", "text/event-stream")
|
||||
cCC.Status(http.StatusOK)
|
||||
_, _ = cCC.Writer.WriteString(": ping\n\n")
|
||||
cCC.Writer.Flush()
|
||||
|
||||
(&OpenAIGatewayHandler{}).openAISecurityAuditError(cCC, legacyBlock)
|
||||
ccOut := recCC.Body.String()
|
||||
require.Contains(t, ccOut, ": ping\n\nevent: error\ndata: ")
|
||||
require.Contains(t, ccOut, "content_policy_violation")
|
||||
|
||||
// 3. Anthropic /v1/messages 已发出 SSE 心跳后延迟拦截:输出 SSE data 帧而非裸 JSON。
|
||||
recAnth := httptest.NewRecorder()
|
||||
cAnth, _ := gin.CreateTestContext(recAnth)
|
||||
cAnth.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil)
|
||||
cAnth.Header("Content-Type", "text/event-stream")
|
||||
cAnth.Status(http.StatusOK)
|
||||
_, _ = cAnth.Writer.WriteString(": ping\n\n")
|
||||
cAnth.Writer.Flush()
|
||||
|
||||
(&GatewayHandler{}).anthropicSecurityAuditError(cAnth, legacyBlock)
|
||||
anthOut := recAnth.Body.String()
|
||||
require.Contains(t, anthOut, ": ping\n\ndata: {\"type\":\"error\"")
|
||||
require.Contains(t, anthOut, "内容审计拦截测试")
|
||||
}
|
||||
@@ -38,14 +38,14 @@ func clientRequestedUsageFields(c *gin.Context, mapping service.ChannelMappingRe
|
||||
return mapping.ToUsageFields(clientRequestedModel(c, fallbackModel), upstreamModel)
|
||||
}
|
||||
|
||||
func runContentModeration(c *gin.Context, reqLog *zap.Logger, svc *service.ContentModerationService, apiKey *service.APIKey, subject middleware2.AuthSubject, protocol string, model string, body []byte) *service.ContentModerationDecision {
|
||||
if svc == nil || c == nil || c.Request == nil {
|
||||
func runContentModerationWithInput(ctx context.Context, reqLog *zap.Logger, svc *service.ContentModerationService, input service.ContentModerationCheckInput) *service.ContentModerationDecision {
|
||||
if svc == nil || ctx == nil {
|
||||
return nil
|
||||
}
|
||||
input := buildContentModerationInput(c, apiKey, subject, protocol, model, body)
|
||||
if reqLog != nil {
|
||||
reqLog.Info("content_moderation.gateway_check_start",
|
||||
reqLog.Debug("content_moderation.gateway_check_start",
|
||||
zap.String("request_id", input.RequestID),
|
||||
zap.Int64("account_id", input.AccountID),
|
||||
zap.Int64("user_id", input.UserID),
|
||||
zap.Int64("api_key_id", input.APIKeyID),
|
||||
zap.String("api_key_name", input.APIKeyName),
|
||||
@@ -55,10 +55,10 @@ func runContentModeration(c *gin.Context, reqLog *zap.Logger, svc *service.Conte
|
||||
zap.String("provider", input.Provider),
|
||||
zap.String("protocol", input.Protocol),
|
||||
zap.String("model", input.Model),
|
||||
zap.Int("body_bytes", len(body)),
|
||||
zap.Int("body_bytes", len(input.Body)),
|
||||
)
|
||||
}
|
||||
decision, err := svc.Check(c.Request.Context(), input)
|
||||
decision, err := svc.Check(ctx, input)
|
||||
if err != nil {
|
||||
if reqLog != nil {
|
||||
reqLog.Warn("content_moderation.check_failed", zap.Error(err))
|
||||
@@ -66,8 +66,13 @@ func runContentModeration(c *gin.Context, reqLog *zap.Logger, svc *service.Conte
|
||||
return nil
|
||||
}
|
||||
if reqLog != nil && decision != nil {
|
||||
reqLog.Info("content_moderation.gateway_check_done",
|
||||
logFn := reqLog.Debug
|
||||
if decision.Blocked || decision.Flagged {
|
||||
logFn = reqLog.Info
|
||||
}
|
||||
logFn("content_moderation.gateway_check_done",
|
||||
zap.String("request_id", input.RequestID),
|
||||
zap.Int64("account_id", input.AccountID),
|
||||
zap.Bool("allowed", decision.Allowed),
|
||||
zap.Bool("blocked", decision.Blocked),
|
||||
zap.Bool("flagged", decision.Flagged),
|
||||
|
||||
@@ -17,6 +17,7 @@ func TestGroupMapperRoundTripsCodexModelsManifestConfig(t *testing.T) {
|
||||
Enabled: true,
|
||||
AccountIDs: []int64{101, 202},
|
||||
FallbackToScheduler: true,
|
||||
KeepHiddenAutoModes: true,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -27,6 +28,7 @@ func TestGroupMapperRoundTripsCodexModelsManifestConfig(t *testing.T) {
|
||||
Enabled bool `json:"enabled"`
|
||||
AccountIDs []int64 `json:"account_ids"`
|
||||
FallbackToScheduler bool `json:"fallback_to_scheduler"`
|
||||
KeepHiddenAutoModes bool `json:"keep_hidden_auto_modes"`
|
||||
} `json:"codex_models_manifest_config"`
|
||||
}
|
||||
require.NoError(t, json.Unmarshal(adminJSON, &adminEnvelope))
|
||||
@@ -34,6 +36,7 @@ func TestGroupMapperRoundTripsCodexModelsManifestConfig(t *testing.T) {
|
||||
require.True(t, adminEnvelope.CodexModelsManifestConfig.Enabled)
|
||||
require.Equal(t, []int64{101, 202}, adminEnvelope.CodexModelsManifestConfig.AccountIDs)
|
||||
require.True(t, adminEnvelope.CodexModelsManifestConfig.FallbackToScheduler)
|
||||
require.True(t, adminEnvelope.CodexModelsManifestConfig.KeepHiddenAutoModes)
|
||||
|
||||
userJSON, err := json.Marshal(GroupFromService(group))
|
||||
require.NoError(t, err)
|
||||
|
||||
@@ -55,6 +55,13 @@ const (
|
||||
// 语义上等同于「无可用账号」:候选账号都不满足分组的利润约束。
|
||||
const profitVetoExhaustedMessage = "No available accounts: all candidates rejected by group profit control"
|
||||
|
||||
func appendUpstreamRetryAfterField(fields []zap.Field, failoverErr *service.UpstreamFailoverError) []zap.Field {
|
||||
if failoverErr != nil && failoverErr.UpstreamRetryAfter > 0 {
|
||||
return append(fields, zap.Duration("upstream_retry_after", failoverErr.UpstreamRetryAfter))
|
||||
}
|
||||
return fields
|
||||
}
|
||||
|
||||
func sameAccountRetryDelayFor(failoverErr *service.UpstreamFailoverError, retryCount int) time.Duration {
|
||||
if failoverErr == nil {
|
||||
return sameAccountRetryDelay
|
||||
@@ -76,6 +83,19 @@ func sameAccountRetryDelayFor(failoverErr *service.UpstreamFailoverError, retryC
|
||||
return delay
|
||||
}
|
||||
|
||||
// wsSameAccountRetryAllowed preserves the WebSocket retry contract: an OAuth
|
||||
// 429 deadline or a request-scoped transient failure may use the existing
|
||||
// retry budget. The caller checks that the current turn can be replayed.
|
||||
func wsSameAccountRetryAllowed(account *service.Account, failoverErr *service.UpstreamFailoverError, retryCount int) bool {
|
||||
if account == nil || failoverErr == nil {
|
||||
return false
|
||||
}
|
||||
if (failoverErr.StatusCode != http.StatusTooManyRequests || failoverErr.SameAccountRetryDeadline.IsZero()) && !failoverErr.RequestScopedTransient {
|
||||
return false
|
||||
}
|
||||
return sameAccountRetryAllowed(failoverErr, retryCount, effectiveSameAccountRetryLimit(failoverErr, account))
|
||||
}
|
||||
|
||||
func sameAccountRetryAllowed(failoverErr *service.UpstreamFailoverError, retryCount, retryLimit int) bool {
|
||||
if failoverErr == nil || !failoverErr.RetryableOnSameAccount {
|
||||
return false
|
||||
@@ -220,13 +240,14 @@ func (s *FailoverState) HandleFailoverError(
|
||||
if sameAccountRetry {
|
||||
s.SameAccountRetryCount[accountID]++
|
||||
retryDelay := sameAccountRetryDelayFor(failoverErr, s.SameAccountRetryCount[accountID])
|
||||
logger.FromContext(ctx).Warn("gateway.failover_same_account_retry",
|
||||
retryFields := appendUpstreamRetryAfterField([]zap.Field{
|
||||
zap.Int64("account_id", accountID),
|
||||
zap.Int("upstream_status", failoverErr.StatusCode),
|
||||
zap.Int("same_account_retry_count", s.SameAccountRetryCount[accountID]),
|
||||
zap.Int("same_account_retry_max", retryLimit),
|
||||
zap.Duration("retry_delay", retryDelay),
|
||||
)
|
||||
}, failoverErr)
|
||||
logger.FromContext(ctx).Warn("gateway.failover_same_account_retry", retryFields...)
|
||||
if !sleepWithContext(ctx, retryDelay) {
|
||||
return FailoverCanceled
|
||||
}
|
||||
@@ -248,12 +269,13 @@ func (s *FailoverState) HandleFailoverError(
|
||||
|
||||
// 递增切换计数
|
||||
s.SwitchCount++
|
||||
logger.FromContext(ctx).Warn("gateway.failover_switch_account",
|
||||
switchFields := appendUpstreamRetryAfterField([]zap.Field{
|
||||
zap.Int64("account_id", accountID),
|
||||
zap.Int("upstream_status", failoverErr.StatusCode),
|
||||
zap.Int("switch_count", s.SwitchCount),
|
||||
zap.Int("max_switches", s.MaxSwitches),
|
||||
)
|
||||
}, failoverErr)
|
||||
logger.FromContext(ctx).Warn("gateway.failover_switch_account", switchFields...)
|
||||
|
||||
// Antigravity 平台换号线性递增延时
|
||||
if platform == service.PlatformAntigravity {
|
||||
|
||||
@@ -1040,3 +1040,31 @@ func TestFailoverClientGone(t *testing.T) {
|
||||
require.False(t, failoverClientGone(nil))
|
||||
})
|
||||
}
|
||||
|
||||
func TestWSSameAccountRetryRetainsBoundedRequestScopedCapacityRetry(t *testing.T) {
|
||||
account := &service.Account{Type: service.AccountTypeAPIKey, Credentials: map[string]any{"pool_mode": true, "pool_mode_retry_count": float64(1)}}
|
||||
failure := &service.UpstreamFailoverError{
|
||||
StatusCode: http.StatusServiceUnavailable, RetryableOnSameAccount: true, RequestScopedTransient: true,
|
||||
}
|
||||
t.Run("first attempt may retry", func(t *testing.T) {
|
||||
require.True(t, wsSameAccountRetryAllowed(account, failure, 0))
|
||||
})
|
||||
t.Run("configured limit still applies", func(t *testing.T) {
|
||||
require.False(t, wsSameAccountRetryAllowed(account, failure, 1))
|
||||
})
|
||||
t.Run("non-transient 503 cannot retry", func(t *testing.T) {
|
||||
other := *failure
|
||||
other.RequestScopedTransient = false
|
||||
require.False(t, wsSameAccountRetryAllowed(account, &other, 0))
|
||||
})
|
||||
t.Run("explicit zero disables capacity retry", func(t *testing.T) {
|
||||
disabled := &service.Account{Type: service.AccountTypeAPIKey, Credentials: map[string]any{"pool_mode": true, "pool_mode_retry_count": float64(0)}}
|
||||
require.False(t, wsSameAccountRetryAllowed(disabled, failure, 0))
|
||||
})
|
||||
t.Run("OAuth 429 with deadline still retries", func(t *testing.T) {
|
||||
rateLimit := &service.UpstreamFailoverError{
|
||||
StatusCode: http.StatusTooManyRequests, RetryableOnSameAccount: true, SameAccountRetryDeadline: time.Now().Add(time.Minute),
|
||||
}
|
||||
require.True(t, wsSameAccountRetryAllowed(account, rateLimit, 0))
|
||||
})
|
||||
}
|
||||
@@ -392,6 +392,9 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
|
||||
}
|
||||
}
|
||||
account := selection.Account
|
||||
if rejectSelectedAccountIfModerated(c, account.ID, selectionReleaseFunc(selection), h.anthropicSecurityAuditError) {
|
||||
return
|
||||
}
|
||||
setOpsSelectedAccount(c, account.ID, account.Platform)
|
||||
|
||||
// 检查请求拦截(预热请求、SUGGESTION MODE等)
|
||||
@@ -728,6 +731,9 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
|
||||
}
|
||||
}
|
||||
account := selection.Account
|
||||
if rejectSelectedAccountIfModerated(c, account.ID, selectionReleaseFunc(selection), h.anthropicSecurityAuditError) {
|
||||
return
|
||||
}
|
||||
setOpsSelectedAccount(c, account.ID, account.Platform)
|
||||
|
||||
// [DEBUG-STICKY] 打印账号选择结果
|
||||
|
||||
@@ -238,6 +238,9 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) {
|
||||
}
|
||||
}
|
||||
account := selection.Account
|
||||
if rejectSelectedAccountIfModerated(c, account.ID, selectionReleaseFunc(selection), h.openAISecurityAuditError) {
|
||||
return
|
||||
}
|
||||
setOpsSelectedAccount(c, account.ID, account.Platform)
|
||||
|
||||
// 4. Acquire account concurrency slot
|
||||
@@ -427,7 +430,7 @@ func (h *GatewayHandler) handleCCFailoverExhausted(c *gin.Context, lastErr *serv
|
||||
return
|
||||
}
|
||||
if lastErr != nil {
|
||||
copyFailoverRetryAfter(c, lastErr.ResponseHeaders)
|
||||
applyRateLimitRetryAfter(c, lastErr, h.cfg)
|
||||
}
|
||||
if lastErr != nil && lastErr.IsCredentialFailure() {
|
||||
status, message := credentialFailoverClientResponse(lastErr)
|
||||
|
||||
@@ -238,6 +238,9 @@ func (h *GatewayHandler) Responses(c *gin.Context) {
|
||||
}
|
||||
}
|
||||
account := selection.Account
|
||||
if rejectSelectedAccountIfModerated(c, account.ID, selectionReleaseFunc(selection), h.responsesSecurityAuditError) {
|
||||
return
|
||||
}
|
||||
setOpsSelectedAccount(c, account.ID, account.Platform)
|
||||
|
||||
// 4. Acquire account concurrency slot
|
||||
@@ -412,7 +415,7 @@ func (h *GatewayHandler) responsesErrorResponse(c *gin.Context, status int, code
|
||||
// handleResponsesFailoverExhausted writes a failover-exhausted error in Responses format.
|
||||
func (h *GatewayHandler) handleResponsesFailoverExhausted(c *gin.Context, lastErr *service.UpstreamFailoverError, streamStarted bool) {
|
||||
if lastErr != nil {
|
||||
copyFailoverRetryAfter(c, lastErr.ResponseHeaders)
|
||||
applyRateLimitRetryAfter(c, lastErr, h.cfg)
|
||||
}
|
||||
statusCode := http.StatusBadGateway
|
||||
if lastErr != nil && lastErr.StatusCode > 0 {
|
||||
|
||||
@@ -234,12 +234,77 @@ func (h *ConcurrencyHelper) TryAcquireUserSlot(ctx context.Context, userID int64
|
||||
return result.ReleaseFunc, true, nil
|
||||
}
|
||||
|
||||
func (h *ConcurrencyHelper) TryAcquireUserSlotForAPIKey(ctx context.Context, userID int64, maxConcurrency int, apiKeyID int64) (func(), bool, error) {
|
||||
// AcquireUserSlotForAPIKeyWithWait acquires a user concurrency slot for a
|
||||
// connection that cannot carry SSE pings, such as a WebSocket turn. Like the
|
||||
// HTTP path, it waits in the bounded per-user queue for up to timeout instead
|
||||
// of failing as soon as the user is at the limit.
|
||||
//
|
||||
// It returns *WaitQueueFullError when the queue is full, *ConcurrencyError when
|
||||
// the wait times out, and the context error when ctx ends first.
|
||||
func (h *ConcurrencyHelper) AcquireUserSlotForAPIKeyWithWait(ctx context.Context, userID int64, maxConcurrency int, apiKeyID int64, timeout time.Duration) (func(), error) {
|
||||
releaseFunc, acquired, err := h.TryAcquireUserSlot(ctx, userID, maxConcurrency)
|
||||
if err != nil || !acquired {
|
||||
return releaseFunc, acquired, err
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if acquired {
|
||||
return h.withAPIKeySlot(ctx, apiKeyID, releaseFunc), nil
|
||||
}
|
||||
|
||||
queueLimit := service.CalculateMaxWait(maxConcurrency) - maxConcurrency
|
||||
if queueLimit < 1 {
|
||||
queueLimit = 1
|
||||
}
|
||||
canWait, err := h.IncrementWaitCount(ctx, userID, queueLimit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !canWait {
|
||||
return nil, &WaitQueueFullError{SlotType: "user"}
|
||||
}
|
||||
defer h.DecrementWaitCount(ctx, userID)
|
||||
|
||||
releaseFunc, err = h.waitForUserSlot(ctx, userID, maxConcurrency, timeout)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return h.withAPIKeySlot(ctx, apiKeyID, releaseFunc), nil
|
||||
}
|
||||
|
||||
// waitForUserSlot polls for a user slot with the same backoff as
|
||||
// waitForSlotWithPingTimeout, without writing anything to the client.
|
||||
func (h *ConcurrencyHelper) waitForUserSlot(ctx context.Context, userID int64, maxConcurrency int, timeout time.Duration) (func(), error) {
|
||||
waitCtx, cancel := context.WithTimeout(ctx, timeout)
|
||||
defer cancel()
|
||||
|
||||
backoff := initialBackoff
|
||||
timer := time.NewTimer(backoff)
|
||||
defer timer.Stop()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-waitCtx.Done():
|
||||
if parentErr := ctx.Err(); parentErr != nil {
|
||||
return nil, parentErr
|
||||
}
|
||||
return nil, &ConcurrencyError{SlotType: "user", IsTimeout: true}
|
||||
case <-timer.C:
|
||||
result, err := h.concurrencyService.AcquireUserSlot(waitCtx, userID, maxConcurrency)
|
||||
if err != nil {
|
||||
if parentErr := ctx.Err(); parentErr != nil {
|
||||
return nil, parentErr
|
||||
}
|
||||
if waitCtx.Err() != nil {
|
||||
return nil, &ConcurrencyError{SlotType: "user", IsTimeout: true}
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if result.Acquired {
|
||||
return result.ReleaseFunc, nil
|
||||
}
|
||||
backoff = nextBackoff(backoff)
|
||||
timer.Reset(backoff)
|
||||
}
|
||||
}
|
||||
return h.withAPIKeySlot(ctx, apiKeyID, releaseFunc), true, nil
|
||||
}
|
||||
|
||||
// AcquireOpenAIWSIngressLease bounds the whole client WebSocket lifecycle,
|
||||
|
||||
@@ -319,26 +319,6 @@ func TestAcquireUserSlotWithWait_TracksAPIKeySlot(t *testing.T) {
|
||||
require.Equal(t, 1, cache.apiKeyReleaseCalls)
|
||||
}
|
||||
|
||||
func TestTryAcquireUserSlotForAPIKey_TracksAPIKeySlot(t *testing.T) {
|
||||
cache := &helperConcurrencyCacheStub{
|
||||
userSeq: []bool{true},
|
||||
}
|
||||
concurrency := service.NewConcurrencyService(cache)
|
||||
helper := NewConcurrencyHelper(concurrency, SSEPingFormatNone, 5*time.Millisecond)
|
||||
|
||||
release, acquired, err := helper.TryAcquireUserSlotForAPIKey(context.Background(), 202, 3, 77)
|
||||
require.NoError(t, err)
|
||||
require.True(t, acquired)
|
||||
require.NotNil(t, release)
|
||||
require.Equal(t, 1, cache.apiKeyTrackCalls)
|
||||
require.Equal(t, []int64{77}, cache.apiKeyTrackIDs)
|
||||
|
||||
release()
|
||||
|
||||
require.Equal(t, 1, cache.userReleaseCalls)
|
||||
require.Equal(t, 1, cache.apiKeyReleaseCalls)
|
||||
}
|
||||
|
||||
func TestAcquireUserSlotWithWait_WaitSuccessDecrementsBeforeReturn(t *testing.T) {
|
||||
cache := &helperConcurrencyCacheStub{
|
||||
userSeq: []bool{false, true},
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestAcquireUserSlotForAPIKeyWithWait_ImmediateAcquireSkipsWaitQueue(t *testing.T) {
|
||||
cache := &helperConcurrencyCacheStub{userSeq: []bool{true}}
|
||||
helper := NewConcurrencyHelper(service.NewConcurrencyService(cache), SSEPingFormatNone, time.Second)
|
||||
|
||||
release, err := helper.AcquireUserSlotForAPIKeyWithWait(context.Background(), 7, 3, 42, time.Second)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, release)
|
||||
release()
|
||||
|
||||
require.Equal(t, 1, cache.userAcquireCalls)
|
||||
require.Zero(t, cache.waitIncrementCalls)
|
||||
require.Zero(t, cache.waitDecrementCalls)
|
||||
require.Equal(t, 1, cache.userReleaseCalls)
|
||||
require.Equal(t, []int64{42}, cache.apiKeyTrackIDs)
|
||||
require.Equal(t, 1, cache.apiKeyReleaseCalls)
|
||||
}
|
||||
|
||||
func TestAcquireUserSlotForAPIKeyWithWait_WaitsForFreedSlot(t *testing.T) {
|
||||
cache := &helperConcurrencyCacheStub{
|
||||
userSeq: []bool{false, false, true},
|
||||
waitAllowed: true,
|
||||
}
|
||||
helper := NewConcurrencyHelper(service.NewConcurrencyService(cache), SSEPingFormatNone, time.Second)
|
||||
|
||||
release, err := helper.AcquireUserSlotForAPIKeyWithWait(context.Background(), 7, 3, 42, 2*time.Second)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, release)
|
||||
|
||||
require.Equal(t, 3, cache.userAcquireCalls)
|
||||
require.Equal(t, 1, cache.waitIncrementCalls)
|
||||
require.Equal(t, 1, cache.waitDecrementCalls, "the queue entry is released once the slot is acquired")
|
||||
require.Equal(t, service.CalculateMaxWait(3)-3, cache.waitMaxWait)
|
||||
|
||||
release()
|
||||
require.Equal(t, 1, cache.userReleaseCalls)
|
||||
require.Equal(t, []int64{42}, cache.apiKeyTrackIDs)
|
||||
require.Equal(t, 1, cache.apiKeyReleaseCalls)
|
||||
}
|
||||
|
||||
func TestAcquireUserSlotForAPIKeyWithWait_TimesOut(t *testing.T) {
|
||||
cache := &helperConcurrencyCacheStub{waitAllowed: true}
|
||||
helper := NewConcurrencyHelper(service.NewConcurrencyService(cache), SSEPingFormatNone, time.Second)
|
||||
|
||||
start := time.Now()
|
||||
release, err := helper.AcquireUserSlotForAPIKeyWithWait(context.Background(), 7, 3, 42, 250*time.Millisecond)
|
||||
require.Nil(t, release)
|
||||
var concurrencyErr *ConcurrencyError
|
||||
require.ErrorAs(t, err, &concurrencyErr)
|
||||
require.True(t, concurrencyErr.IsTimeout)
|
||||
require.Equal(t, "user", concurrencyErr.SlotType)
|
||||
require.Less(t, time.Since(start), 2*time.Second)
|
||||
|
||||
require.GreaterOrEqual(t, cache.userAcquireCalls, 2, "the slot is retried while waiting")
|
||||
require.Equal(t, 1, cache.waitDecrementCalls)
|
||||
require.Zero(t, cache.userReleaseCalls)
|
||||
require.Empty(t, cache.apiKeyTrackIDs)
|
||||
}
|
||||
|
||||
func TestAcquireUserSlotForAPIKeyWithWait_QueueFull(t *testing.T) {
|
||||
cache := &helperConcurrencyCacheStub{waitAllowed: false}
|
||||
helper := NewConcurrencyHelper(service.NewConcurrencyService(cache), SSEPingFormatNone, time.Second)
|
||||
|
||||
release, err := helper.AcquireUserSlotForAPIKeyWithWait(context.Background(), 7, 3, 42, time.Second)
|
||||
require.Nil(t, release)
|
||||
var queueFullErr *WaitQueueFullError
|
||||
require.ErrorAs(t, err, &queueFullErr)
|
||||
require.Equal(t, "user", queueFullErr.SlotType)
|
||||
|
||||
require.Equal(t, 1, cache.userAcquireCalls, "a full queue fails without polling")
|
||||
require.Equal(t, 1, cache.waitIncrementCalls)
|
||||
require.Zero(t, cache.waitDecrementCalls)
|
||||
}
|
||||
|
||||
func TestAcquireUserSlotForAPIKeyWithWait_StopsWhenContextEnds(t *testing.T) {
|
||||
cache := &helperConcurrencyCacheStub{waitAllowed: true}
|
||||
helper := NewConcurrencyHelper(service.NewConcurrencyService(cache), SSEPingFormatNone, time.Second)
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
time.AfterFunc(150*time.Millisecond, cancel)
|
||||
|
||||
start := time.Now()
|
||||
release, err := helper.AcquireUserSlotForAPIKeyWithWait(ctx, 7, 3, 42, 10*time.Second)
|
||||
require.Nil(t, release)
|
||||
require.True(t, errors.Is(err, context.Canceled), "got %v", err)
|
||||
require.Less(t, time.Since(start), 2*time.Second)
|
||||
require.Equal(t, 1, cache.waitDecrementCalls)
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"unsafe"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/gin-gonic/gin"
|
||||
@@ -13,11 +14,74 @@ type inflightReservationEstimator interface {
|
||||
EstimateInflightReservation(ctx context.Context, apiKey *service.APIKey, req service.InflightEstimateRequest) (float64, bool)
|
||||
}
|
||||
|
||||
// requestMaxOutputTokens 从请求体中提取输出 token 上限(兼容 Anthropic / OpenAI Chat / Responses / Gemini)。
|
||||
// requestMaxOutputTokens 从请求体中提取输出 token 上限(兼容 Anthropic / OpenAI Chat / Responses / Gemini),
|
||||
// 单遍零拷贝遍历顶层键,保持 max_tokens → max_completion_tokens → max_output_tokens → generationConfig.maxOutputTokens → generation_config.max_output_tokens 优先级。
|
||||
func requestMaxOutputTokens(body []byte) int {
|
||||
for _, path := range []string{"max_tokens", "max_completion_tokens", "max_output_tokens", "generationConfig.maxOutputTokens", "generation_config.max_output_tokens"} {
|
||||
if v := gjson.GetBytes(body, path); v.Exists() && v.Type == gjson.Number && v.Int() > 0 {
|
||||
return int(v.Int())
|
||||
if len(body) == 0 {
|
||||
return 0
|
||||
}
|
||||
const (
|
||||
maxTokensBit uint8 = 1 << iota
|
||||
maxCompletionTokensBit
|
||||
maxOutputTokensBit
|
||||
genConfigCamelBit
|
||||
genConfigSnakeBit
|
||||
allMaxTokenBits = maxTokensBit | maxCompletionTokensBit | maxOutputTokensBit | genConfigCamelBit | genConfigSnakeBit
|
||||
)
|
||||
var seen uint8
|
||||
var vals [5]int
|
||||
root := gjson.Parse(unsafe.String(unsafe.SliceData(body), len(body)))
|
||||
if !root.IsObject() {
|
||||
return 0
|
||||
}
|
||||
root.ForEach(func(key, value gjson.Result) bool {
|
||||
switch key.Str {
|
||||
case "max_tokens":
|
||||
if seen&maxTokensBit == 0 {
|
||||
seen |= maxTokensBit
|
||||
if value.Type == gjson.Number && value.Int() > 0 {
|
||||
vals[0] = int(value.Int())
|
||||
return false
|
||||
}
|
||||
}
|
||||
case "max_completion_tokens":
|
||||
if seen&maxCompletionTokensBit == 0 {
|
||||
seen |= maxCompletionTokensBit
|
||||
if value.Type == gjson.Number && value.Int() > 0 {
|
||||
vals[1] = int(value.Int())
|
||||
}
|
||||
}
|
||||
case "max_output_tokens":
|
||||
if seen&maxOutputTokensBit == 0 {
|
||||
seen |= maxOutputTokensBit
|
||||
if value.Type == gjson.Number && value.Int() > 0 {
|
||||
vals[2] = int(value.Int())
|
||||
}
|
||||
}
|
||||
case "generationConfig":
|
||||
if seen&genConfigCamelBit == 0 {
|
||||
if v := value.Get("maxOutputTokens"); v.Exists() {
|
||||
seen |= genConfigCamelBit
|
||||
if v.Type == gjson.Number && v.Int() > 0 {
|
||||
vals[3] = int(v.Int())
|
||||
}
|
||||
}
|
||||
}
|
||||
case "generation_config":
|
||||
if seen&genConfigSnakeBit == 0 {
|
||||
if v := value.Get("max_output_tokens"); v.Exists() {
|
||||
seen |= genConfigSnakeBit
|
||||
if v.Type == gjson.Number && v.Int() > 0 {
|
||||
vals[4] = int(v.Int())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return seen != allMaxTokenBits
|
||||
})
|
||||
for _, v := range vals {
|
||||
if v > 0 {
|
||||
return v
|
||||
}
|
||||
}
|
||||
return 0
|
||||
|
||||
@@ -527,7 +527,9 @@ func TestGatewayCodexModels_GeneratedManifestUsesFinalBodyETag(t *testing.T) {
|
||||
second := httptest.NewRecorder()
|
||||
secondContext, _ := gin.CreateTestContext(second)
|
||||
secondContext.Request = httptest.NewRequest(http.MethodGet, "/models?client_version=0.147.0", nil)
|
||||
secondContext.Request.Header.Set("If-None-Match", "W/"+etag)
|
||||
// The generated ETag is weak; its strong form must still revalidate.
|
||||
require.True(t, strings.HasPrefix(etag, "W/"))
|
||||
secondContext.Request.Header.Set("If-None-Match", strings.TrimPrefix(etag, "W/"))
|
||||
secondContext.Set(string(middleware2.ContextKeyAPIKey), &service.APIKey{Group: group})
|
||||
h.CodexModels(secondContext)
|
||||
|
||||
|
||||
@@ -161,6 +161,9 @@ func (h *GatewayHandler) SystemOne(c *gin.Context) {
|
||||
}
|
||||
}
|
||||
account := selection.Account
|
||||
if rejectSelectedAccountIfModerated(c, account.ID, selectionReleaseFunc(selection), h.anthropicSecurityAuditError) {
|
||||
return
|
||||
}
|
||||
|
||||
accountRelease := selection.ReleaseFunc
|
||||
if !selection.Acquired {
|
||||
|
||||
@@ -175,6 +175,10 @@ func (h *GatewayHandler) WebSearch(c *gin.Context) {
|
||||
break
|
||||
}
|
||||
|
||||
if rejectSelectedAccountIfModerated(c, selected.Account.ID, selectionReleaseFunc(selected), webSearchSecurityAuditError) {
|
||||
return
|
||||
}
|
||||
|
||||
release, acquireOK, acquireErr := h.acquireWebSearchAccountSlot(c, selected)
|
||||
if !acquireOK {
|
||||
// First hop: surface concurrency errors; later hops try another account.
|
||||
|
||||
@@ -194,6 +194,9 @@ func (h *GatewayHandler) GeminiCachedContentsCreate(c *gin.Context) {
|
||||
ttlRejectedLimit = max(ttlRejectedLimit, account.GeminiExplicitCacheUpstreamMaxTTL())
|
||||
continue
|
||||
}
|
||||
if rejectSelectedAccountIfModerated(c, account.ID, selectionReleaseFunc(selection), googleSecurityAuditError) {
|
||||
return
|
||||
}
|
||||
accountReleaseFunc, ok := h.acquireGeminiCachedContentAccountSlot(c, reqLog, geminiConcurrency, selection)
|
||||
if !ok {
|
||||
return
|
||||
|
||||
@@ -87,11 +87,15 @@ func TestAppendUpstreamGeminiModelsPreservesMetadata(t *testing.T) {
|
||||
// Exercise the real handler's native-upstream branch, including scope fallback.
|
||||
type geminiMixedModelsUpstream struct {
|
||||
service.HTTPUpstream
|
||||
status int
|
||||
body string
|
||||
status int
|
||||
body string
|
||||
lastReq *http.Request
|
||||
calls int
|
||||
}
|
||||
|
||||
func (u *geminiMixedModelsUpstream) Do(_ *http.Request, _ string, _ int64, _ int) (*http.Response, error) {
|
||||
func (u *geminiMixedModelsUpstream) Do(req *http.Request, _ string, _ int64, _ int) (*http.Response, error) {
|
||||
u.lastReq = req
|
||||
u.calls++
|
||||
return &http.Response{StatusCode: u.status, Header: http.Header{"Content-Type": {"application/json"}, "X-Request-Id": {"native-id"}}, Body: io.NopCloser(strings.NewReader(u.body))}, nil
|
||||
}
|
||||
func TestGeminiNativeModelsMergesNativeUpstream(t *testing.T) {
|
||||
@@ -240,3 +244,122 @@ func TestGeminiNativeModelsUnmappedAccountKeepsUpstream(t *testing.T) {
|
||||
require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
|
||||
require.Equal(t, 2, f.upstream.calls)
|
||||
}
|
||||
|
||||
func TestGeminiV1BetaListModels_PaginationQueryForwarding(t *testing.T) {
|
||||
newHandler := func(upstream *geminiMixedModelsUpstream, allowlist service.GroupModelAllowlist, includeMixedAG bool) (*GatewayHandler, *service.APIKey) {
|
||||
id := int64(48)
|
||||
accounts := []service.Account{
|
||||
{ID: 1, Platform: service.PlatformGemini, Type: service.AccountTypeAPIKey, Credentials: map[string]any{"api_key": "upstream-key"}},
|
||||
}
|
||||
if includeMixedAG {
|
||||
accounts = append(accounts, service.Account{
|
||||
ID: 2,
|
||||
Platform: service.PlatformAntigravity,
|
||||
Extra: map[string]any{"mixed_scheduling": true},
|
||||
Credentials: map[string]any{"model_mapping": map[string]any{"gemini-synced-custom": "gemini-3.8-flash-high"}},
|
||||
})
|
||||
}
|
||||
repo := &geminiAllowlistAccountRepoStub{gatewayModelsAccountRepoStub: gatewayModelsAccountRepoStub{byGroup: map[int64][]service.Account{id: accounts}}}
|
||||
h := &GatewayHandler{geminiCompatService: service.NewGeminiMessagesCompatService(repo, nil, nil, nil, nil, nil, upstream, nil, &config.Config{})}
|
||||
key := &service.APIKey{GroupID: &id, Group: &service.Group{ID: id, Platform: service.PlatformGemini, ModelAllowlist: allowlist}}
|
||||
return h, key
|
||||
}
|
||||
|
||||
t.Run("allowlists pageSize and pageToken and drops key and unknown params", func(t *testing.T) {
|
||||
upstream := &geminiMixedModelsUpstream{
|
||||
status: http.StatusOK,
|
||||
body: `{"models":[{"name":"models/gemini-page-2"}]}`,
|
||||
}
|
||||
h, key := newHandler(upstream, service.GroupModelAllowlist{}, true)
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
c.Request = httptest.NewRequest(http.MethodGet, "/v1beta/models?pageSize=1000&pageToken=abc%2B%2F%3D%3D&key=sk-client-secret&alt=json&foo=bar", nil)
|
||||
c.Set(string(middleware.ContextKeyAPIKey), key)
|
||||
|
||||
h.GeminiV1BetaListModels(c)
|
||||
require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
|
||||
require.NotNil(t, upstream.lastReq)
|
||||
gotQuery := upstream.lastReq.URL.Query()
|
||||
require.Equal(t, "1000", gotQuery.Get("pageSize"))
|
||||
require.Equal(t, "abc+/==", gotQuery.Get("pageToken"))
|
||||
require.Empty(t, gotQuery.Get("key"))
|
||||
require.Empty(t, gotQuery.Get("alt"))
|
||||
require.Empty(t, gotQuery.Get("foo"))
|
||||
require.Len(t, gotQuery, 2)
|
||||
// 后续分页不重复附加混合分组的 Antigravity 模型。
|
||||
require.Contains(t, rec.Body.String(), "models/gemini-page-2")
|
||||
require.NotContains(t, rec.Body.String(), "models/gemini-synced-custom")
|
||||
})
|
||||
|
||||
t.Run("pageSize zero succeeds and omits pageSize upstream", func(t *testing.T) {
|
||||
upstream := &geminiMixedModelsUpstream{
|
||||
status: http.StatusOK,
|
||||
body: `{"models":[{"name":"models/gemini-page-1"}],"nextPageToken":"tok-2"}`,
|
||||
}
|
||||
h, key := newHandler(upstream, service.GroupModelAllowlist{}, true)
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
c.Request = httptest.NewRequest(http.MethodGet, "/v1beta/models?pageSize=0", nil)
|
||||
c.Set(string(middleware.ContextKeyAPIKey), key)
|
||||
|
||||
h.GeminiV1BetaListModels(c)
|
||||
require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
|
||||
require.NotNil(t, upstream.lastReq)
|
||||
require.Empty(t, upstream.lastReq.URL.RawQuery)
|
||||
// 首页仍附加混合分组的 Antigravity 模型并保留 nextPageToken。
|
||||
require.Contains(t, rec.Body.String(), "models/gemini-synced-custom")
|
||||
require.Contains(t, rec.Body.String(), `"nextPageToken":"tok-2"`)
|
||||
})
|
||||
|
||||
t.Run("invalid pagination params return 400 without hitting upstream", func(t *testing.T) {
|
||||
for _, target := range []string{
|
||||
"/v1beta/models?pageSize=-1",
|
||||
"/v1beta/models?pageSize=abc",
|
||||
"/v1beta/models?pageToken=bad%0Atoken",
|
||||
"/v1beta/models?pageToken=" + strings.Repeat("x", 4097),
|
||||
} {
|
||||
upstream := &geminiMixedModelsUpstream{status: http.StatusOK, body: `{"models":[]}`}
|
||||
h, key := newHandler(upstream, service.GroupModelAllowlist{}, false)
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
c.Request = httptest.NewRequest(http.MethodGet, target, nil)
|
||||
c.Set(string(middleware.ContextKeyAPIKey), key)
|
||||
|
||||
h.GeminiV1BetaListModels(c)
|
||||
require.Equal(t, http.StatusBadRequest, rec.Code, target)
|
||||
require.Zero(t, upstream.calls, target)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("allowlist dropping all models on a page keeps empty array and nextPageToken", func(t *testing.T) {
|
||||
upstream := &geminiMixedModelsUpstream{
|
||||
status: http.StatusOK,
|
||||
body: `{"models":[{"name":"models/gemini-blocked"}],"nextPageToken":"tok-2"}`,
|
||||
}
|
||||
h, key := newHandler(upstream, service.GroupModelAllowlist{Enabled: true, Models: []string{"gemini-allowed"}}, false)
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
c.Request = httptest.NewRequest(http.MethodGet, "/v1beta/models?pageSize=1", nil)
|
||||
c.Set(string(middleware.ContextKeyAPIKey), key)
|
||||
|
||||
h.GeminiV1BetaListModels(c)
|
||||
require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
|
||||
require.JSONEq(t, `{"models":[],"nextPageToken":"tok-2"}`, rec.Body.String())
|
||||
})
|
||||
|
||||
t.Run("upstream error passes through untouched when allowlist is enabled", func(t *testing.T) {
|
||||
upstream := &geminiMixedModelsUpstream{
|
||||
status: http.StatusBadRequest,
|
||||
body: `{"error":{"code":400,"message":"Invalid page token","status":"INVALID_ARGUMENT"}}`,
|
||||
}
|
||||
h, key := newHandler(upstream, service.GroupModelAllowlist{Enabled: true, Models: []string{"gemini-allowed"}}, false)
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
c.Request = httptest.NewRequest(http.MethodGet, "/v1beta/models?pageToken=expired", nil)
|
||||
c.Set(string(middleware.ContextKeyAPIKey), key)
|
||||
|
||||
h.GeminiV1BetaListModels(c)
|
||||
require.Equal(t, http.StatusBadRequest, rec.Code, rec.Body.String())
|
||||
require.JSONEq(t, upstream.body, rec.Body.String())
|
||||
})
|
||||
}
|
||||
@@ -48,6 +48,12 @@ func (h *GatewayHandler) GeminiV1BetaListModels(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
listQuery, err := service.ParseGeminiListModelsQuery(c.Query("pageSize"), c.Query("pageToken"))
|
||||
if err != nil {
|
||||
googleError(c, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// 分组级模型白名单开启时过滤 models[].name(名字形如 models/xxx)。
|
||||
filterGeminiModels := func(models []gemini.Model) []gemini.Model {
|
||||
if apiKey.Group == nil || !apiKey.Group.ModelAllowlistEnabled() {
|
||||
@@ -106,7 +112,7 @@ func (h *GatewayHandler) GeminiV1BetaListModels(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
res, err := h.geminiCompatService.ForwardListModels(c.Request.Context(), account)
|
||||
res, err := h.geminiCompatService.ForwardListModelsWithQuery(c.Request.Context(), account, listQuery)
|
||||
if err != nil {
|
||||
googleError(c, http.StatusBadGateway, err.Error())
|
||||
return
|
||||
@@ -115,13 +121,14 @@ func (h *GatewayHandler) GeminiV1BetaListModels(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gemini.ModelsListResponse{Models: filterGeminiModels(mergeGeminiModelLists(gemini.DefaultModels(), agModels))})
|
||||
return
|
||||
}
|
||||
if res.StatusCode == http.StatusOK && len(agModels) > 0 {
|
||||
// 仅在首页附加混合分组内的 Antigravity 模型,避免后续分页重复追加。
|
||||
if res.StatusCode == http.StatusOK && len(agModels) > 0 && listQuery.PageToken == "" {
|
||||
if merged, ok := appendUpstreamGeminiModels(res.Body, agModels); ok {
|
||||
res.Body = merged
|
||||
}
|
||||
}
|
||||
|
||||
if apiKey.Group != nil && apiKey.Group.ModelAllowlistEnabled() {
|
||||
if res.StatusCode == http.StatusOK && apiKey.Group != nil && apiKey.Group.ModelAllowlistEnabled() {
|
||||
if filtered, dropped, ok := filterUpstreamGeminiModelsBody(res.Body, apiKey.Group.ModelAllowlist); ok && dropped {
|
||||
// 只在确有条目被过滤时替换响应体;全命中或解析失败时保持原始响应,
|
||||
// 统一经 writeUpstreamResponse 写出(保留全部上游响应头)。
|
||||
@@ -637,6 +644,9 @@ func (h *GatewayHandler) GeminiV1BetaModels(c *gin.Context) {
|
||||
}
|
||||
}
|
||||
account := selection.Account
|
||||
if rejectSelectedAccountIfModerated(c, account.ID, selectionReleaseFunc(selection), googleSecurityAuditError) {
|
||||
return
|
||||
}
|
||||
setOpsSelectedAccount(c, account.ID, account.Platform)
|
||||
|
||||
// 检测账号切换:如果粘性会话绑定的账号与当前选择的账号不同,清除 thoughtSignature
|
||||
|
||||
@@ -279,6 +279,9 @@ func (h *OpenAIGatewayHandler) GrokVoice(c *gin.Context, endpoint string) {
|
||||
return
|
||||
}
|
||||
account := selection.Account
|
||||
if rejectSelectedAccountIfModerated(c, account.ID, selectionReleaseFunc(selection), h.openAISecurityAuditError) {
|
||||
return
|
||||
}
|
||||
var started bool
|
||||
release, status := h.acquireResponsesAccountSlot(c, apiKey.GroupID, "", selection, false, &started, reqLog)
|
||||
if status == openAISlotAcquireProfitVetoed {
|
||||
|
||||
@@ -357,6 +357,9 @@ func (h *OpenAIGatewayHandler) handleGrokMedia(c *gin.Context, endpoint service.
|
||||
if failoverClientGone(c) {
|
||||
return
|
||||
}
|
||||
if rejectSelectedAccountIfModerated(c, account.ID, selectionReleaseFunc(selection), h.openAISecurityAuditError) {
|
||||
return
|
||||
}
|
||||
sessionHash = ensureOpenAIPoolModeSessionHash(sessionHash, account)
|
||||
setOpsSelectedAccount(c, account.ID, account.Platform)
|
||||
|
||||
|
||||
@@ -32,6 +32,10 @@ type noAccountErrorClassification struct {
|
||||
ErrType string
|
||||
Message string
|
||||
ModelNotFound bool // true when this is a 404 model_not_found classification
|
||||
// RetryAfterSeconds carries the earliest recovery time the gateway could
|
||||
// determine for a temporary availability failure. Zero means unknown; no
|
||||
// Retry-After header is emitted in that case.
|
||||
RetryAfterSeconds int
|
||||
}
|
||||
|
||||
var selectionModelRateLimitedPattern = regexp.MustCompile(`(?:model_rate_limited|rate_limited)=(\d+)`)
|
||||
@@ -68,9 +72,10 @@ func classifySelectionFailureError(err error, fallback noAccountErrorClassificat
|
||||
return fallback
|
||||
}
|
||||
return noAccountErrorClassification{
|
||||
Status: http.StatusTooManyRequests,
|
||||
ErrType: "rate_limit_error",
|
||||
Message: "All available accounts are currently rate-limited. Please retry later.",
|
||||
Status: http.StatusTooManyRequests,
|
||||
ErrType: "rate_limit_error",
|
||||
Message: "All available accounts are currently rate-limited. Please retry later.",
|
||||
RetryAfterSeconds: fallback.RetryAfterSeconds,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -134,6 +139,7 @@ func classifyNoAccountError(
|
||||
ModelNotFound: true,
|
||||
}
|
||||
}
|
||||
fallback.RetryAfterSeconds = result.RetryAfterSeconds
|
||||
return fallback
|
||||
}
|
||||
|
||||
@@ -153,12 +159,26 @@ func classifyNoAccountErrorFromGin(
|
||||
ctx = c.Request.Context()
|
||||
}
|
||||
classification := classifyNoAccountError(ctx, diag, apiKey, routingModel, displayModel, platform)
|
||||
classification.applyRetryAfter(c)
|
||||
if classification.ModelNotFound {
|
||||
service.MarkOpsClientBusinessLimited(c, service.OpsClientBusinessLimitedReasonLocalModelConfiguration)
|
||||
}
|
||||
return classification
|
||||
}
|
||||
|
||||
// applyRetryAfter publishes the scheduler-derived recovery hint for temporary
|
||||
// availability failures. It never adds the header to a 404 model_not_found or
|
||||
// when the recovery time is unknown.
|
||||
func (classification noAccountErrorClassification) applyRetryAfter(c *gin.Context) {
|
||||
if c == nil || classification.RetryAfterSeconds <= 0 {
|
||||
return
|
||||
}
|
||||
switch classification.Status {
|
||||
case http.StatusTooManyRequests, http.StatusServiceUnavailable, 529:
|
||||
c.Header("Retry-After", strconv.Itoa(classification.RetryAfterSeconds))
|
||||
}
|
||||
}
|
||||
|
||||
func classifyOpenAICompatibleNoAccountErrorFromGin(
|
||||
c *gin.Context,
|
||||
diag service.ModelAvailabilityDiagnoser,
|
||||
|
||||
@@ -322,3 +322,84 @@ func TestGPT55RetirementEmptyListingDoesNotUseDefaults(t *testing.T) {
|
||||
require.Empty(t, modelListingSource(service.PlatformOpenAI, []string{}, []string{"gpt-5.5"}))
|
||||
require.Equal(t, []string{"gpt-5.5"}, modelListingSource(service.PlatformOpenAI, nil, []string{"gpt-5.5"}))
|
||||
}
|
||||
|
||||
// The scheduler publishes the earliest cooldown among model-capable accounts;
|
||||
// the classifier must turn it into Retry-After on both the 503 fallback and the
|
||||
// 429 rate-limit verdict.
|
||||
func TestClassifyNoAccountError_RateLimitedPoolCarriesRetryAfter(t *testing.T) {
|
||||
c := newTestGinContextWithRequest()
|
||||
fd := &fakeDiagnoser{resp: service.ModelAvailabilityDiagnosis{
|
||||
HasAccountsInPool: true,
|
||||
HasModelSupport: true,
|
||||
RetryAfterSeconds: 59,
|
||||
}}
|
||||
apiKey := &service.APIKey{GroupID: ptrInt64(7)}
|
||||
|
||||
cls := classifyNoAccountErrorFromGin(c, fd, apiKey, "gpt-5.6-sol", "gpt-5.6-sol", service.PlatformOpenAI)
|
||||
require.Equal(t, http.StatusServiceUnavailable, cls.Status)
|
||||
require.Equal(t, 59, cls.RetryAfterSeconds)
|
||||
require.Equal(t, "59", c.Writer.Header().Get("Retry-After"))
|
||||
|
||||
cls = classifySelectionFailureError(
|
||||
fmt.Errorf("no available OpenAI accounts supporting model: gpt-5.6-sol (pool=3, filtered: model_rate_limited=3)"),
|
||||
cls,
|
||||
)
|
||||
require.Equal(t, http.StatusTooManyRequests, cls.Status)
|
||||
require.Equal(t, "rate_limit_error", cls.ErrType)
|
||||
require.Equal(t, 59, cls.RetryAfterSeconds, "the 429 upgrade must keep the recovery hint")
|
||||
require.Equal(t, "59", c.Writer.Header().Get("Retry-After"))
|
||||
}
|
||||
|
||||
func TestClassifyNoAccountError_UnknownRecoveryOmitsRetryAfter(t *testing.T) {
|
||||
c := newTestGinContextWithRequest()
|
||||
fd := &fakeDiagnoser{resp: service.ModelAvailabilityDiagnosis{HasAccountsInPool: true, HasModelSupport: true}}
|
||||
apiKey := &service.APIKey{GroupID: ptrInt64(7)}
|
||||
|
||||
cls := classifyNoAccountErrorFromGin(c, fd, apiKey, "gpt-5", "gpt-5", service.PlatformOpenAI)
|
||||
|
||||
require.Equal(t, http.StatusServiceUnavailable, cls.Status)
|
||||
require.Zero(t, cls.RetryAfterSeconds)
|
||||
require.Empty(t, c.Writer.Header().Get("Retry-After"),
|
||||
"an unknown recovery time must not be invented")
|
||||
}
|
||||
|
||||
func TestClassifyNoAccountError_ModelNotFoundOmitsRetryAfter(t *testing.T) {
|
||||
c := newTestGinContextWithRequest()
|
||||
fd := &fakeDiagnoser{resp: service.ModelAvailabilityDiagnosis{
|
||||
HasAccountsInPool: true,
|
||||
HasModelSupport: false,
|
||||
RetryAfterSeconds: 59,
|
||||
}}
|
||||
apiKey := &service.APIKey{GroupID: ptrInt64(7)}
|
||||
|
||||
cls := classifyNoAccountErrorFromGin(c, fd, apiKey, "gpt-5.9-unknown", "gpt-5.9-unknown", service.PlatformOpenAI)
|
||||
|
||||
require.Equal(t, http.StatusNotFound, cls.Status)
|
||||
require.True(t, cls.ModelNotFound)
|
||||
require.Zero(t, cls.RetryAfterSeconds)
|
||||
require.Empty(t, c.Writer.Header().Get("Retry-After"),
|
||||
"a permanent model configuration error has no recovery time")
|
||||
}
|
||||
|
||||
// The scheduler now appends a model-cooldown reason breakdown to the legacy
|
||||
// summary. The 429 upgrade must keep parsing the aggregate model_rate_limited
|
||||
// count, and the breakdown keys must not be mistaken for it.
|
||||
func TestClassifySelectionFailureError_NewReasonBreakdownStillUpgrades(t *testing.T) {
|
||||
fallback := noAccountErrorClassification{
|
||||
Status: http.StatusServiceUnavailable,
|
||||
ErrType: "api_error",
|
||||
Message: "Service temporarily unavailable",
|
||||
}
|
||||
|
||||
got := classifySelectionFailureError(
|
||||
fmt.Errorf("no available accounts supporting model: gpt-5.6-sol "+
|
||||
"(total=37 eligible=0 excluded=0 unschedulable=0 platform_filtered=0 model_unsupported=0 "+
|
||||
"model_rate_limited=36 model_rate_limited_reasons=other:2,upstream_404_model_not_found:34 profit_threshold=0 "+
|
||||
"profit_invalid_account_rate=0)"),
|
||||
fallback,
|
||||
)
|
||||
|
||||
require.Equal(t, http.StatusTooManyRequests, got.Status)
|
||||
require.Equal(t, "rate_limit_error", got.ErrType)
|
||||
require.False(t, got.ModelNotFound)
|
||||
}
|
||||
@@ -173,6 +173,9 @@ func (h *OpenAIGatewayHandler) AlphaSearch(c *gin.Context) {
|
||||
}
|
||||
|
||||
account := selection.Account
|
||||
if rejectSelectedAccountIfModerated(c, account.ID, selectionReleaseFunc(selection), h.openAISecurityAuditError) {
|
||||
return
|
||||
}
|
||||
setOpsSelectedAccount(c, account.ID, account.Platform)
|
||||
accountRelease, slotResult := h.acquireResponsesAccountSlot(c, apiKey.GroupID, sessionHash, selection, false, &streamStarted, reqLog)
|
||||
if slotResult == openAISlotAcquireProfitVetoed {
|
||||
@@ -220,7 +223,9 @@ func (h *OpenAIGatewayHandler) AlphaSearch(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
h.gatewayService.ReportOpenAIAccountScheduleResult(account, openAIAccountScheduleModel(c, account, requestedModel, false, result), false, nil, err)
|
||||
if failoverErr.Reason != service.OpenAIAlphaSearchRejectedReason {
|
||||
h.gatewayService.ReportOpenAIAccountScheduleResult(account, openAIAccountScheduleModel(c, account, requestedModel, false, result), false, nil, err)
|
||||
}
|
||||
if c.Writer.Size() != writerSizeBeforeForward {
|
||||
h.handleFailoverExhausted(c, failoverErr, true)
|
||||
return
|
||||
@@ -237,13 +242,14 @@ func (h *OpenAIGatewayHandler) AlphaSearch(c *gin.Context) {
|
||||
if sameAccountRetryAllowed(failoverErr, sameAccountRetryCount[account.ID], retryLimit) {
|
||||
sameAccountRetryCount[account.ID]++
|
||||
retryDelay := sameAccountRetryDelayFor(failoverErr, sameAccountRetryCount[account.ID])
|
||||
reqLog.Warn("openai_alpha_search.same_account_retry",
|
||||
retryFields := appendUpstreamRetryAfterField([]zap.Field{
|
||||
zap.Int64("account_id", account.ID),
|
||||
zap.Int("upstream_status", failoverErr.StatusCode),
|
||||
zap.Int("retry_limit", retryLimit),
|
||||
zap.Int("retry_count", sameAccountRetryCount[account.ID]),
|
||||
zap.Duration("retry_delay", retryDelay),
|
||||
)
|
||||
}, failoverErr)
|
||||
reqLog.Warn("openai_alpha_search.same_account_retry", retryFields...)
|
||||
select {
|
||||
case <-c.Request.Context().Done():
|
||||
return
|
||||
@@ -264,11 +270,12 @@ func (h *OpenAIGatewayHandler) AlphaSearch(c *gin.Context) {
|
||||
h.handleFailoverExhausted(c, failoverErr, false)
|
||||
return
|
||||
}
|
||||
reqLog.Warn("openai_alpha_search.upstream_failover_switching",
|
||||
switchFields := appendUpstreamRetryAfterField([]zap.Field{
|
||||
zap.Int64("account_id", account.ID),
|
||||
zap.Int("upstream_status", failoverErr.StatusCode),
|
||||
zap.Int("switch_count", switchCount),
|
||||
)
|
||||
}, failoverErr)
|
||||
reqLog.Warn("openai_alpha_search.upstream_failover_switching", switchFields...)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
"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 alphaSearchUpstream struct {
|
||||
service.HTTPUpstream
|
||||
successAccount int64
|
||||
calls []int64
|
||||
}
|
||||
|
||||
const alphaSearchSuccess = `{"output":"search result"}`
|
||||
|
||||
func alphaSearchRejection(accountID int64) string {
|
||||
return fmt.Sprintf(`{ "error": {"message": "rejected by %d"} }`+"\n", accountID)
|
||||
}
|
||||
|
||||
func (u *alphaSearchUpstream) Do(_ *http.Request, _ string, accountID int64, _ int) (*http.Response, error) {
|
||||
u.calls = append(u.calls, accountID)
|
||||
status, contentType, body := http.StatusBadRequest, "application/problem+json", alphaSearchRejection(accountID)
|
||||
if accountID == u.successAccount {
|
||||
status, contentType, body = http.StatusOK, "application/json", alphaSearchSuccess
|
||||
}
|
||||
return &http.Response{
|
||||
StatusCode: status,
|
||||
Header: http.Header{"Content-Type": {contentType}},
|
||||
Body: io.NopCloser(strings.NewReader(body)),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func TestAlphaSearchBadRequestFailover(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
accountCount int
|
||||
successAccount int64
|
||||
maxSwitches int
|
||||
firstType string
|
||||
wantCalls []int64
|
||||
wantStatus int
|
||||
wantBody string
|
||||
}{
|
||||
{"next account succeeds", 2, 2, 2, service.AccountTypeAPIKey, []int64{1, 2}, http.StatusOK, alphaSearchSuccess},
|
||||
{"single account", 1, 0, 2, service.AccountTypeAPIKey, []int64{1}, http.StatusBadRequest, alphaSearchRejection(1)},
|
||||
{"all accounts reject", 2, 0, 3, service.AccountTypeAPIKey, []int64{1, 2}, http.StatusBadRequest, alphaSearchRejection(2)},
|
||||
{"switch limit", 3, 3, 1, service.AccountTypeAPIKey, []int64{1, 2}, http.StatusBadRequest, alphaSearchRejection(2)},
|
||||
{"oauth passes through", 2, 2, 2, service.AccountTypeOAuth, []int64{1}, http.StatusBadRequest, alphaSearchRejection(1)},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
repo := &openAIWSFailoverHandlerAccountRepoStub{}
|
||||
for i := 1; i <= tc.accountCount; i++ {
|
||||
account := newPinnedCodexAccount(int64(i), service.StatusActive, true, false)
|
||||
account.Concurrency = 0
|
||||
account.Credentials["pool_mode"] = true
|
||||
account.Credentials["pool_mode_retry_status_codes"] = []any{400}
|
||||
repo.accounts = append(repo.accounts, account)
|
||||
}
|
||||
if tc.firstType == service.AccountTypeOAuth {
|
||||
repo.accounts[0].Type = tc.firstType
|
||||
repo.accounts[0].Credentials = map[string]any{"access_token": "oauth-token", "chatgpt_account_id": "chatgpt-account"}
|
||||
}
|
||||
cfg := &config.Config{RunMode: config.RunModeSimple}
|
||||
upstream := &alphaSearchUpstream{successAccount: tc.successAccount}
|
||||
usage := &openAIWSUsageHandlerUsageLogRepoStub{created: make(chan *service.UsageLog, 4)}
|
||||
billing := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil)
|
||||
t.Cleanup(billing.Stop)
|
||||
gateway := service.NewOpenAIGatewayService(repo, usage, nil, nil, nil, nil, nil, cfg,
|
||||
nil, nil, service.NewBillingService(cfg, nil), service.NewRateLimitService(repo, nil, cfg, nil, nil), billing, upstream,
|
||||
&service.DeferredService{}, nil, nil, nil, nil, nil, nil, nil)
|
||||
h := NewOpenAIGatewayHandler(gateway, service.NewConcurrencyService(nil), billing, &service.APIKeyService{}, nil, nil, nil, nil, cfg)
|
||||
h.maxAccountSwitches = tc.maxSwitches
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/v1/alpha/search", strings.NewReader(`{"model":"gpt-5.6-sol","commands":{"search_query":[{"q":"news"}]}}`))
|
||||
group := &service.Group{ID: 42, Platform: service.PlatformOpenAI}
|
||||
c.Set(string(middleware.ContextKeyAPIKey), &service.APIKey{ID: 1, GroupID: &group.ID, Group: group, User: &service.User{ID: 2}})
|
||||
c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: 2})
|
||||
|
||||
h.AlphaSearch(c)
|
||||
|
||||
require.Equal(t, tc.wantCalls, upstream.calls)
|
||||
require.Equal(t, tc.wantStatus, rec.Code)
|
||||
require.Equal(t, tc.wantBody, rec.Body.String())
|
||||
require.Empty(t, repo.rateLimitedIDs)
|
||||
if tc.wantStatus == http.StatusOK {
|
||||
require.Len(t, usage.created, 1)
|
||||
require.Equal(t, tc.successAccount, (<-usage.created).AccountID)
|
||||
require.Equal(t, "application/json", rec.Header().Get("Content-Type"))
|
||||
} else {
|
||||
require.Empty(t, usage.created)
|
||||
require.Equal(t, "application/problem+json", rec.Header().Get("Content-Type"))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,14 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/tidwall/gjson"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
const automationBootstrapPrompt = "Review the project and report any important changes."
|
||||
@@ -82,12 +85,20 @@ func TestNormalizeCodexAutomationBootstrapRejectsUnsafeShapes(t *testing.T) {
|
||||
body: codexAutomationBootstrapBody(t, validOutput, `,"call_id":"call-1"`),
|
||||
},
|
||||
{
|
||||
name: "previous response",
|
||||
body: []byte(`{"model":"gpt-5","previous_response_id":"resp-1","input":[{"type":"function_call_output","namespace":"codex_app","name":"automation_update","output":` + mustJSON(t, validOutput) + `}]}`),
|
||||
name: "ambiguous call context",
|
||||
body: []byte(`{"model":"gpt-5","input":[{"type":"function_call_output","namespace":"codex_app","name":"automation_update","output":` + mustJSON(t, validOutput) + `},{"type":"function_call"}]}`),
|
||||
},
|
||||
{
|
||||
name: "real call context",
|
||||
body: []byte(`{"model":"gpt-5","input":[{"type":"function_call_output","namespace":"codex_app","name":"automation_update","output":` + mustJSON(t, validOutput) + `},{"type":"function_call","call_id":"call-1"}]}`),
|
||||
name: "ambiguous built-in call context",
|
||||
body: []byte(`{"model":"gpt-5","input":[{"type":"function_call_output","namespace":"codex_app","name":"automation_update","output":` + mustJSON(t, validOutput) + `},{"type":"computer_call"}]}`),
|
||||
},
|
||||
{
|
||||
name: "ambiguous tool search call without call id or id",
|
||||
body: []byte(`{"model":"gpt-5","input":[{"type":"function_call_output","namespace":"codex_app","name":"automation_update","output":` + mustJSON(t, validOutput) + `},{"type":"tool_search_call"}]}`),
|
||||
},
|
||||
{
|
||||
name: "non-string previous response id",
|
||||
body: []byte(`{"model":"gpt-5","previous_response_id":null,"input":[{"type":"function_call_output","namespace":"codex_app","name":"automation_update","output":` + mustJSON(t, validOutput) + `}]}`),
|
||||
},
|
||||
{
|
||||
name: "mismatched memory id",
|
||||
@@ -190,16 +201,19 @@ Read the reference index and report changes. Preserve A & B and <tags>
|
||||
}
|
||||
for _, invalid := range []string{
|
||||
strings.Replace(output, "2026-09-09T00:33:34.775Z", "yesterday", 1),
|
||||
strings.Replace(output, "2026-09-09T00:33:34.775Z", " 2026-09-09T00:33:34.775Z ", 1),
|
||||
strings.Replace(output, "2026-09-09T00:33:34.775Z", "<v>2026-09-09T00:33:34.775Z</v>", 1),
|
||||
strings.Replace(output, "<current_time_iso>2026-09-09T00:33:34.775Z</current_time_iso>", "", 1),
|
||||
strings.Replace(output, "Read the reference index and report changes. Preserve A & B and <tags>.", " ", 1),
|
||||
strings.Replace(output, "<instructions>", `<instructions source="other">`, 1),
|
||||
strings.Replace(output, "<instructions>", "<instructions><nested/>", 1),
|
||||
strings.Replace(output, "</instructions>", "", 1),
|
||||
output + "<heartbeat><automation_id>dup</automation_id></heartbeat>",
|
||||
`<heartbeat><automation_id>wiki</automation_id><current_time_iso>2026-09-09T00:33:34.775Z</current_time_iso><instructions>a</heartbeat>OUTSIDE<heartbeat><fake>b</fake></instructions></heartbeat>`,
|
||||
} {
|
||||
require.False(t, validCodexAutomationHeartbeat(invalid))
|
||||
require.False(t, validCodexAutomationHeartbeat(invalid), invalid)
|
||||
}
|
||||
for _, guarded := range [][]byte{
|
||||
codexAutomationBootstrapBody(t, output, `,"call_id":"call-1"`),
|
||||
[]byte(strings.Replace(string(body), `"model":"gpt-5"`, `"model":"gpt-5","previous_response_id":"resp-1"`, 1)),
|
||||
[]byte(strings.Replace(string(body), `"namespace":"codex_app"`, `"namespace":"other"`, 1)),
|
||||
} {
|
||||
unchanged, normalized := normalizeCodexAutomationBootstrap(guarded)
|
||||
@@ -208,6 +222,134 @@ Read the reference index and report changes. Preserve A & B and <tags>
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeCodexAutomationBootstrapHeartbeatLiteralClosingTagAndHistoryVariants(t *testing.T) {
|
||||
// 正文内包含字面量 </instructions> 时仍应按外层边界正确识别。
|
||||
promptWithClosingTag := "<heartbeat>\n" +
|
||||
" <automation_id>prompt-audit</automation_id>\n" +
|
||||
" <current_time_iso>2026-11-22T14:55:28.776Z</current_time_iso>\n" +
|
||||
" <instructions>\n" +
|
||||
"Verify all <instructions>...</instructions> blocks in prompts/ are properly closed.\n" +
|
||||
" </instructions>\n" +
|
||||
"</heartbeat>"
|
||||
got, changed := normalizeCodexAutomationBootstrap(codexAutomationBootstrapBody(t, promptWithClosingTag, ""))
|
||||
require.True(t, changed)
|
||||
require.Equal(t, promptWithClosingTag, gjson.GetBytes(got, "input.0.content.0.text").String())
|
||||
|
||||
// Bootstrap(Automation: ...)格式与历史上下文、托管工具(含无 id 的 web_search_call / x_search_call /
|
||||
// 带 id 的 tool_search_call)共存时也能正常归一化。
|
||||
bootstrapText := codexAutomationBootstrap("wiki", "never", automationBootstrapPrompt)
|
||||
withHistory := []byte(`{"model":"gpt-6.1-sol","previous_response_id":"resp_1","input":[` +
|
||||
`{"type":"function_call","call_id":"call_1","name":"exec","arguments":"{}"},` +
|
||||
`{"type":"function_call_output","call_id":"call_1","output":"ok"},` +
|
||||
`{"type":"web_search_call","status":"completed"},` +
|
||||
`{"type":"x_search_call","id":"xs_1","status":"completed"},` +
|
||||
`{"type":"tool_search_call","id":"ts_1","arguments":{"query":"repo"}},` +
|
||||
`{"type":"function_call_output","namespace":"codex_app","name":"automation_update","output":` + mustJSON(t, bootstrapText) + `}` +
|
||||
`]}`)
|
||||
got, changed = normalizeCodexAutomationBootstrap(withHistory)
|
||||
require.True(t, changed)
|
||||
require.Equal(t, "message", gjson.GetBytes(got, "input.5.type").String())
|
||||
require.Equal(t, "user", gjson.GetBytes(got, "input.5.role").String())
|
||||
require.Equal(t, bootstrapText, gjson.GetBytes(got, "input.5.content.0.text").String())
|
||||
|
||||
// automation_update 与 delegation(create_thread)同帧共存时不得互相死锁。
|
||||
mixedDelegation := []byte(`{"model":"gpt-6.1-sol","input":[` +
|
||||
`{"type":"function_call_output","namespace":"codex_app","name":"create_thread","output":` + mustJSON(t, delegationEnvelope) + `},` +
|
||||
`{"type":"function_call_output","namespace":"codex_app","name":"automation_update","output":"<heartbeat><automation_id>wiki</automation_id></heartbeat>"}` +
|
||||
`]}`)
|
||||
got, changed = normalizeCodexAutomationBootstrap(mixedDelegation)
|
||||
require.True(t, changed)
|
||||
require.Equal(t, "message", gjson.GetBytes(got, "input.1.type").String())
|
||||
got, changed = normalizeCodexDelegationBootstrap(got)
|
||||
require.True(t, changed)
|
||||
require.Equal(t, "message", gjson.GetBytes(got, "input.0.type").String())
|
||||
|
||||
// 未在 untrusted 白名单里的 standalone agent ExternalMessage(如 browser_tabs)
|
||||
// 不得阻断同请求中 automation_update 的归一化。
|
||||
mixedAgent := []byte(`{"model":"gpt-6.1-sol","input":[` +
|
||||
`{"type":"function_call_output","id":"fco_1","namespace":"agent","name":"browser_tabs","output":"<tabs/>"},` +
|
||||
`{"type":"function_call_output","id":"fco_2","namespace":"codex_app","name":"automation_update","output":` + mustJSON(t, promptWithClosingTag) + `}` +
|
||||
`]}`)
|
||||
got, changed = normalizeCodexAutomationBootstrap(mixedAgent)
|
||||
require.True(t, changed)
|
||||
require.Equal(t, "function_call_output", gjson.GetBytes(got, "input.0.type").String())
|
||||
require.Equal(t, "agent", gjson.GetBytes(got, "input.0.namespace").String())
|
||||
require.Equal(t, "message", gjson.GetBytes(got, "input.1.type").String())
|
||||
require.Equal(t, "user", gjson.GetBytes(got, "input.1.role").String())
|
||||
}
|
||||
|
||||
func TestNormalizeCodexAutomationBootstrapHeartbeatWithUnescapedInstructionsAndHistory(t *testing.T) {
|
||||
// 复现 Codex Desktop Windows 定时任务真实载荷:
|
||||
// 1. <instructions> 含未 XML 转义的 PowerShell `&`、`<OrderNo>`、`<单号>` 与 CRLF;
|
||||
// 2. 长对话复用同一线程,包含历史配对的 function_call / function_call_output、
|
||||
// item_reference、web_search_call(无 call_id 仅有 id)与多轮历史 heartbeat。
|
||||
heartbeat1 := "<heartbeat>\r\n" +
|
||||
" <automation_id>automation</automation_id>\r\n" +
|
||||
" <current_time_iso>2026-11-22T14:55:28.776Z</current_time_iso>\r\n" +
|
||||
" <instructions>\r\n" +
|
||||
"每轮仅运行一次:\n" +
|
||||
"& 'C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe' -File 'Run-Monitor.ps1'\n" +
|
||||
"再定位slt<OrderNo>所在行,证据 runs/verified_<单号>.png,支持 <nested/> 标签。\r\n" +
|
||||
" </instructions>\r\n" +
|
||||
"</heartbeat>\r\n"
|
||||
heartbeat2 := "<heartbeat>\r\n" +
|
||||
" <automation_id>automation</automation_id>\r\n" +
|
||||
" <current_time_iso>2026-11-23T04:58:10.100Z</current_time_iso>\r\n" +
|
||||
" <instructions>\r\n" +
|
||||
"第二轮定时检查:a < b && c > d\r\n" +
|
||||
" </instructions>\r\n" +
|
||||
"</heartbeat>\r\n"
|
||||
|
||||
body := []byte(`{` +
|
||||
`"model":"gpt-6.1-sol",` +
|
||||
`"previous_response_id":"resp_hist_1",` +
|
||||
`"metadata":{"large":9007199254740993},` +
|
||||
`"input":[` +
|
||||
`{"type":"message","role":"user","content":"initial"},` +
|
||||
`{"type":"function_call","call_id":"call_1","name":"exec","arguments":"{}"},` +
|
||||
`{"type":"function_call_output","call_id":"call_1","output":"ok"},` +
|
||||
`{"type":"web_search_call","id":"ws_1","status":"completed"},` +
|
||||
`{"type":"item_reference","id":"item_1"},` +
|
||||
`{"type":"function_call_output","id":"fco_1","namespace":"codex_app","name":"automation_update","output":` + mustJSON(t, heartbeat1) + `},` +
|
||||
`{"type":"function_call_output","id":"fco_2","namespace":"codex_app","name":"automation_update","output":` + mustJSON(t, heartbeat2) + `},` +
|
||||
`{"type":"message","role":"user","content":"??"}` +
|
||||
`]}`)
|
||||
|
||||
got, changed := normalizeCodexAutomationBootstrap(body)
|
||||
require.True(t, changed)
|
||||
require.Equal(t, "resp_hist_1", gjson.GetBytes(got, "previous_response_id").String())
|
||||
require.Equal(t, "9007199254740993", gjson.GetBytes(got, "metadata.large").Raw)
|
||||
// 历史调用上下文保持原样
|
||||
require.Equal(t, "call_1", gjson.GetBytes(got, "input.1.call_id").String())
|
||||
require.Equal(t, "call_1", gjson.GetBytes(got, "input.2.call_id").String())
|
||||
require.Equal(t, "ws_1", gjson.GetBytes(got, "input.3.id").String())
|
||||
require.Equal(t, "item_1", gjson.GetBytes(got, "input.4.id").String())
|
||||
// 两轮 heartbeat 均被转为标准 user message,内容原样保留
|
||||
require.Equal(t, "message", gjson.GetBytes(got, "input.5.type").String())
|
||||
require.Equal(t, "user", gjson.GetBytes(got, "input.5.role").String())
|
||||
require.Equal(t, heartbeat1, gjson.GetBytes(got, "input.5.content.0.text").String())
|
||||
require.False(t, gjson.GetBytes(got, "input.5.namespace").Exists())
|
||||
require.Equal(t, "message", gjson.GetBytes(got, "input.6.type").String())
|
||||
require.Equal(t, "user", gjson.GetBytes(got, "input.6.role").String())
|
||||
require.Equal(t, heartbeat2, gjson.GetBytes(got, "input.6.content.0.text").String())
|
||||
require.Equal(t, "??", gjson.GetBytes(got, "input.7.content").String())
|
||||
|
||||
// 幂等
|
||||
again, changedAgain := normalizeCodexAutomationBootstrap(got)
|
||||
require.False(t, changedAgain)
|
||||
require.Equal(t, got, again)
|
||||
|
||||
// 首轮无历史上下文时也能通过 HTTP call_id 校验
|
||||
firstTurn := codexAutomationBootstrapBody(t, heartbeat1, "")
|
||||
firstTurnNormalized, firstChanged := normalizeCodexAutomationBootstrap(firstTurn)
|
||||
require.True(t, firstChanged)
|
||||
h := &OpenAIGatewayHandler{}
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
require.True(t, h.validateFunctionCallOutputRequest(c, firstTurnNormalized, zap.NewNop()))
|
||||
require.False(t, c.Writer.Written())
|
||||
}
|
||||
|
||||
// The byte precheck must stay a necessary condition: an escaped type or tool
|
||||
// name is still a candidate, and a body without either is returned untouched
|
||||
// without the token scan and decode.
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
//go:build unit
|
||||
|
||||
package handler
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
func capacityShedSSEOverloadResponse(retryAfterSec string) *http.Response {
|
||||
stream := fmt.Sprintf(
|
||||
"event: response.created\n"+
|
||||
"data: {\"type\":\"response.created\",\"response\":{\"id\":\"resp_shed\"}}\n\n"+
|
||||
"event: error\n"+
|
||||
"data: {\"type\":\"error\",\"error\":{\"type\":\"service_unavailable_error\",\"code\":\"server_is_overloaded\",\"message\":\"Our servers are currently overloaded. Please try again later.\",\"headers\":{\"retry-after\":%q}}}\n\n",
|
||||
retryAfterSec,
|
||||
)
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: http.Header{"Content-Type": []string{"text/event-stream"}},
|
||||
Body: io.NopCloser(bytes.NewBufferString(stream)),
|
||||
}
|
||||
}
|
||||
|
||||
func capacityShedHTTPOverloadResponse(retryAfterMs string) *http.Response {
|
||||
h := http.Header{"Content-Type": []string{"application/json"}}
|
||||
if retryAfterMs != "" {
|
||||
h.Set("Retry-After-Ms", retryAfterMs)
|
||||
}
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusServiceUnavailable,
|
||||
Header: h,
|
||||
Body: io.NopCloser(bytes.NewBufferString(
|
||||
`{"error":{"type":"service_unavailable_error","code":"server_is_overloaded","message":"Our servers are currently overloaded. Please try again later."}}`,
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenAIGatewayHandlerResponses_LongOverloadRetryAfterSwitchesImmediately(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
upstream := newAstraProCapturedUpstream(capacityShedSSEOverloadResponse("315"), astra200())
|
||||
handler := newOpenAIResponsesFailoverTestHandler(t, upstream)
|
||||
c, rec := newAstraProFailoverContext(t, astraProRequestBody)
|
||||
|
||||
handler.Responses(c)
|
||||
|
||||
_, accountIDs, _ := upstream.snapshot()
|
||||
require.Equal(t, []int64{1, 2}, accountIDs)
|
||||
require.Equal(t, http.StatusOK, rec.Code)
|
||||
require.Equal(t, "completed", gjson.GetBytes(rec.Body.Bytes(), "status").String())
|
||||
}
|
||||
|
||||
func TestOpenAIGatewayHandlerResponses_ShortOverloadRetryAfterRetriesSameAccount(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
upstream := newAstraProCapturedUpstream(capacityShedHTTPOverloadResponse("10"), astra200())
|
||||
handler := newOpenAIResponsesFailoverTestHandler(t, upstream)
|
||||
c, rec := newAstraProFailoverContext(t, astraProRequestBody)
|
||||
|
||||
handler.Responses(c)
|
||||
|
||||
_, accountIDs, _ := upstream.snapshot()
|
||||
require.Equal(t, []int64{1, 1}, accountIDs)
|
||||
require.Equal(t, http.StatusOK, rec.Code)
|
||||
}
|
||||
|
||||
func TestOpenAIGatewayHandlerResponses_AllAccountsLongOverloadFailsFast503(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
upstream := newAstraProCapturedUpstream(
|
||||
capacityShedSSEOverloadResponse("315"),
|
||||
capacityShedSSEOverloadResponse("335"),
|
||||
)
|
||||
handler := newOpenAIResponsesFailoverTestHandler(t, upstream)
|
||||
c, rec := newAstraProFailoverContext(t, astraProRequestBody)
|
||||
|
||||
handler.Responses(c)
|
||||
|
||||
_, accountIDs, _ := upstream.snapshot()
|
||||
require.Equal(t, []int64{1, 2}, accountIDs)
|
||||
require.Equal(t, http.StatusServiceUnavailable, rec.Code)
|
||||
require.Contains(t, gjson.GetBytes(rec.Body.Bytes(), "error.message").String(), "servers are currently overloaded")
|
||||
}
|
||||
@@ -227,6 +227,9 @@ func (h *OpenAIGatewayHandler) ChatCompletions(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
account := selection.Account
|
||||
if rejectSelectedAccountIfModerated(c, account.ID, selectionReleaseFunc(selection), h.openAISecurityAuditError) {
|
||||
return
|
||||
}
|
||||
sessionHash = ensureOpenAIPoolModeSessionHash(sessionHash, account)
|
||||
reqLog.Debug("openai_chat_completions.account_selected", zap.Int64("account_id", account.ID), zap.String("account_name", account.Name))
|
||||
_ = scheduleDecision
|
||||
@@ -356,13 +359,14 @@ func (h *OpenAIGatewayHandler) ChatCompletions(c *gin.Context) {
|
||||
if sameAccountRetryAllowed(failoverErr, sameAccountRetryCount[account.ID], retryLimit) {
|
||||
sameAccountRetryCount[account.ID]++
|
||||
retryDelay := sameAccountRetryDelayFor(failoverErr, sameAccountRetryCount[account.ID])
|
||||
reqLog.Warn("openai_chat_completions.pool_mode_same_account_retry",
|
||||
retryFields := appendUpstreamRetryAfterField([]zap.Field{
|
||||
zap.Int64("account_id", account.ID),
|
||||
zap.Int("upstream_status", failoverErr.StatusCode),
|
||||
zap.Int("retry_limit", retryLimit),
|
||||
zap.Int("retry_count", sameAccountRetryCount[account.ID]),
|
||||
zap.Duration("retry_delay", retryDelay),
|
||||
)
|
||||
}, failoverErr)
|
||||
reqLog.Warn("openai_chat_completions.pool_mode_same_account_retry", retryFields...)
|
||||
select {
|
||||
case <-c.Request.Context().Done():
|
||||
return
|
||||
@@ -383,12 +387,13 @@ func (h *OpenAIGatewayHandler) ChatCompletions(c *gin.Context) {
|
||||
h.handleFailoverExhausted(c, failoverErr, streamStarted)
|
||||
return
|
||||
}
|
||||
reqLog.Warn("openai_chat_completions.upstream_failover_switching",
|
||||
switchFields := appendUpstreamRetryAfterField([]zap.Field{
|
||||
zap.Int64("account_id", account.ID),
|
||||
zap.Int("upstream_status", failoverErr.StatusCode),
|
||||
zap.Int("switch_count", switchCount),
|
||||
zap.Int("max_switches", maxAccountSwitches),
|
||||
)
|
||||
}, failoverErr)
|
||||
reqLog.Warn("openai_chat_completions.upstream_failover_switching", switchFields...)
|
||||
continue
|
||||
}
|
||||
h.gatewayService.ReportOpenAIAccountScheduleResult(account, openAIAccountScheduleModel(c, account, reqModel, false, nil), false, nil, err)
|
||||
|
||||
@@ -53,7 +53,7 @@ func TestCodexCallOutputGateAdmitsEveryRewrite(t *testing.T) {
|
||||
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)
|
||||
_, rewritten := normalizeCodexCallOutputBootstrap(body, isCodexAutomationCandidate, true)
|
||||
if rewritten {
|
||||
rewrites++
|
||||
require.True(t, mayContainCodexCallOutputCandidate(body, "automation_update"), "%s", body)
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestCodexModelsFallsBackToLocalManifestWhenUpstreamCannotServeModels(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
firstStatus int
|
||||
firstBody string
|
||||
}{
|
||||
{name: "upstream 5xx", firstStatus: http.StatusServiceUnavailable},
|
||||
{name: "empty manifest", firstStatus: http.StatusOK, firstBody: `{"models":[]}`},
|
||||
{name: "non JSON body", firstStatus: http.StatusOK, firstBody: `not-json`},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
handler, upstream, groupID := newCodexModelsFailoverTestHandlerWithAccountCount(tc.firstStatus, 1, 3)
|
||||
upstream.firstBody = tc.firstBody
|
||||
|
||||
recorder := performCodexModelsRequest(t, handler, groupID)
|
||||
|
||||
require.Equal(t, http.StatusOK, recorder.Code, recorder.Body.String())
|
||||
require.NotEmpty(t, recorder.Header().Get("ETag"))
|
||||
slugs := codexHandlerManifestSlugs(t, recorder)
|
||||
require.Contains(t, slugs, "gpt-5.6-sol")
|
||||
require.NotContains(t, slugs, "gpt-image-2")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCodexModelsFallsBackToLocalManifestAfterAllCandidatesFail(t *testing.T) {
|
||||
handler, upstream, groupID := newCodexModelsFailoverTestHandler(http.StatusServiceUnavailable)
|
||||
upstream.statuses = map[int64]int{
|
||||
1: http.StatusServiceUnavailable,
|
||||
2: http.StatusServiceUnavailable,
|
||||
}
|
||||
|
||||
recorder := performCodexModelsRequest(t, handler, groupID)
|
||||
|
||||
require.Equal(t, []int64{1, 2}, upstream.calls())
|
||||
require.Equal(t, http.StatusOK, recorder.Code, recorder.Body.String())
|
||||
require.Contains(t, codexHandlerManifestSlugs(t, recorder), "gpt-5.6-sol")
|
||||
}
|
||||
|
||||
func TestCodexModelsFallbackPrefersGroupModelsListConfig(t *testing.T) {
|
||||
handler, upstream, groupID := newCodexModelsFailoverTestHandler(http.StatusServiceUnavailable)
|
||||
upstream.statuses = map[int64]int{
|
||||
1: http.StatusServiceUnavailable,
|
||||
2: http.StatusServiceUnavailable,
|
||||
}
|
||||
group := &service.Group{ID: groupID, Platform: service.PlatformOpenAI}
|
||||
group.ModelAllowlist = service.GroupModelAllowlist{
|
||||
Enabled: true,
|
||||
Models: []string{"gpt-5.6-luna", "gpt-6.2-sol"},
|
||||
}
|
||||
|
||||
recorder := performCodexModelsRequestForGroup(t, handler, group, "")
|
||||
|
||||
require.Equal(t, http.StatusOK, recorder.Code, recorder.Body.String())
|
||||
require.ElementsMatch(t, []string{"gpt-5.6-luna", "gpt-6.2-sol"}, codexHandlerManifestSlugs(t, recorder))
|
||||
}
|
||||
|
||||
func TestCodexModelsUpstreamManifestWinsOverLocalFallback(t *testing.T) {
|
||||
handler, upstream, groupID := newCodexModelsFailoverTestHandlerWithAccountCount(http.StatusOK, 1, 3)
|
||||
upstream.firstBody = `{"models":[{"slug":"upstream-only-model"}]}`
|
||||
|
||||
recorder := performCodexModelsRequest(t, handler, groupID)
|
||||
|
||||
require.Equal(t, http.StatusOK, recorder.Code, recorder.Body.String())
|
||||
require.Equal(t, []string{"upstream-only-model"}, codexHandlerManifestSlugs(t, recorder))
|
||||
}
|
||||
|
||||
func TestCodexModelsFallbackSupportsETagRevalidation(t *testing.T) {
|
||||
handler, upstream, groupID := newCodexModelsFailoverTestHandlerWithAccountCount(http.StatusServiceUnavailable, 1, 3)
|
||||
group := &service.Group{ID: groupID, Platform: service.PlatformOpenAI}
|
||||
|
||||
first := performCodexModelsRequestForGroup(t, handler, group, "")
|
||||
require.Equal(t, http.StatusOK, first.Code, first.Body.String())
|
||||
etag := first.Header().Get("ETag")
|
||||
require.NotEmpty(t, etag)
|
||||
require.NotEmpty(t, upstream.calls())
|
||||
|
||||
second := performCodexModelsRequestForGroup(t, handler, group, etag)
|
||||
require.Equal(t, http.StatusNotModified, second.Code, second.Body.String())
|
||||
require.Empty(t, second.Body.Bytes())
|
||||
}
|
||||
|
||||
func TestCodexModelsKeepsUpstreamErrorWhenLocalFallbackIsEmpty(t *testing.T) {
|
||||
handler, upstream, groupID := newCodexModelsFailoverTestHandlerWithAccountCount(http.StatusServiceUnavailable, 1, 3)
|
||||
group := &service.Group{ID: groupID, Platform: service.PlatformOpenAI}
|
||||
// Dedicated image models are dropped from Codex manifests, so the local
|
||||
// list is empty and the original upstream error must be preserved.
|
||||
group.ModelAllowlist = service.GroupModelAllowlist{Enabled: true, Models: []string{"gpt-image-2"}}
|
||||
|
||||
recorder := performCodexModelsRequestForGroup(t, handler, group, "")
|
||||
|
||||
require.Equal(t, http.StatusBadGateway, recorder.Code, recorder.Body.String())
|
||||
require.NotEmpty(t, upstream.calls())
|
||||
}
|
||||
|
||||
// codexModelsGroupWithoutLocalFallback configures a model list that Codex
|
||||
// cannot advertise (image-generation only). The #5252 local fallback therefore
|
||||
// stays empty and tests can still observe the original upstream error.
|
||||
func codexModelsGroupWithoutLocalFallback(groupID int64) *service.Group {
|
||||
return &service.Group{
|
||||
ID: groupID,
|
||||
Platform: service.PlatformOpenAI,
|
||||
ModelAllowlist: service.GroupModelAllowlist{
|
||||
Enabled: true,
|
||||
Models: []string{"gpt-image-2"},
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"go.uber.org/zap"
|
||||
|
||||
infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors"
|
||||
middleware2 "github.com/Wei-Shaw/sub2api/internal/server/middleware"
|
||||
@@ -20,6 +21,9 @@ import (
|
||||
// when disabled, groups with explicit mappings are generated locally;
|
||||
// otherwise ChatGPT manifests are proxied verbatim and custom API key manifests
|
||||
// receive provider-compatibility normalization plus short-lived caching.
|
||||
// When no upstream can serve /models (missing endpoint, 5xx, or an empty
|
||||
// manifest), a local fallback manifest is generated instead of failing the
|
||||
// request while the group still has a usable local model list (#5252).
|
||||
func (h *OpenAIGatewayHandler) CodexModels(c *gin.Context) {
|
||||
if c.Request.Context().Err() != nil {
|
||||
return
|
||||
@@ -67,7 +71,7 @@ func (h *OpenAIGatewayHandler) CodexModels(c *gin.Context) {
|
||||
if c.Request.Context().Err() != nil {
|
||||
return
|
||||
}
|
||||
writeOpenAIModelsResponse(c, pinnedManifest)
|
||||
h.writeCodexModelsResponse(c, apiKey.Group, pinnedManifest)
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -86,7 +90,7 @@ func (h *OpenAIGatewayHandler) CodexModels(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
if configured {
|
||||
writeOpenAIModelsResponse(c, configuredManifest)
|
||||
h.writeCodexModelsResponse(c, apiKey.Group, configuredManifest)
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -106,6 +110,9 @@ func (h *OpenAIGatewayHandler) CodexModels(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
if lastUpstreamErr != nil {
|
||||
if h.writeLocalCodexModelsFallback(c, apiKey.Group, lastUpstreamErr) {
|
||||
return
|
||||
}
|
||||
h.errorResponse(c, infraerrors.Code(lastUpstreamErr), "upstream_error", infraerrors.Message(lastUpstreamErr))
|
||||
return
|
||||
}
|
||||
@@ -122,15 +129,29 @@ func (h *OpenAIGatewayHandler) CodexModels(c *gin.Context) {
|
||||
if c.Request.Context().Err() != nil {
|
||||
return
|
||||
}
|
||||
if service.IsRetryableCodexModelsManifestError(err) && switchCount < maxAccountSwitches {
|
||||
failedAccountIDs[account.ID] = struct{}{}
|
||||
switchCount++
|
||||
lastUpstreamErr = err
|
||||
continue
|
||||
if service.IsRetryableCodexModelsManifestError(err) {
|
||||
if switchCount < maxAccountSwitches {
|
||||
failedAccountIDs[account.ID] = struct{}{}
|
||||
switchCount++
|
||||
lastUpstreamErr = err
|
||||
continue
|
||||
}
|
||||
// All candidates failed (or the switch budget is exhausted): an
|
||||
// upstream without a usable /models endpoint must not break the
|
||||
// client model picker while the group can describe its models
|
||||
// locally (#5252).
|
||||
if h.writeLocalCodexModelsFallback(c, apiKey.Group, err) {
|
||||
return
|
||||
}
|
||||
}
|
||||
h.errorResponse(c, infraerrors.Code(err), "upstream_error", infraerrors.Message(err))
|
||||
return
|
||||
}
|
||||
// A 2xx manifest with no models is as unusable as a failed request for
|
||||
// Codex clients. Prefer the local catalog when one exists.
|
||||
if service.CodexModelsManifestIsEmpty(manifest.Body) && h.writeLocalCodexModelsFallback(c, apiKey.Group, errors.New("upstream returned an empty models manifest")) {
|
||||
return
|
||||
}
|
||||
if err := h.gatewayService.CompleteAPIKeyCodexModelsManifestForClient(manifest, account); err != nil {
|
||||
h.errorResponse(c, http.StatusInternalServerError, "api_error", "Failed to complete Codex models manifest")
|
||||
return
|
||||
@@ -147,7 +168,48 @@ func (h *OpenAIGatewayHandler) CodexModels(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
writeOpenAIModelsResponse(c, manifest)
|
||||
h.writeCodexModelsResponse(c, apiKey.Group, manifest)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// writeLocalCodexModelsFallback writes a locally generated Codex manifest when
|
||||
// the selected upstreams cannot serve /models. It reports false when the local
|
||||
// model list is empty so the caller can preserve the original upstream error.
|
||||
func (h *OpenAIGatewayHandler) writeLocalCodexModelsFallback(c *gin.Context, group *service.Group, upstreamErr error) bool {
|
||||
if h == nil || h.gatewayService == nil {
|
||||
return false
|
||||
}
|
||||
var groupID int64
|
||||
if group != nil {
|
||||
groupID = group.ID
|
||||
}
|
||||
reqLog := requestLogger(c, "handler.openai_gateway.codex_models", zap.Int64("group_id", groupID))
|
||||
manifest, configured, err := h.gatewayService.BuildLocalCodexModelsFallbackManifest(
|
||||
c.Request.Context(),
|
||||
group,
|
||||
c.GetHeader("If-None-Match"),
|
||||
)
|
||||
if err != nil {
|
||||
reqLog.Warn("openai.codex_models_local_fallback_failed", zap.Error(err), zap.NamedError("upstream_error", upstreamErr))
|
||||
return false
|
||||
}
|
||||
if !configured || manifest == nil {
|
||||
return false
|
||||
}
|
||||
// The client gets a 200, so this is the only signal that the upstream
|
||||
// /models endpoint is unusable for the group.
|
||||
reqLog.Warn("openai.codex_models_local_fallback_served", zap.NamedError("upstream_error", upstreamErr))
|
||||
h.writeCodexModelsResponse(c, group, manifest)
|
||||
return true
|
||||
}
|
||||
|
||||
// writeCodexModelsResponse records the ETag the group's manifest is served with,
|
||||
// so codex.response.metadata events can be translated to it, and writes the
|
||||
// manifest response.
|
||||
func (h *OpenAIGatewayHandler) writeCodexModelsResponse(c *gin.Context, group *service.Group, manifest *service.OpenAIModelsResponse) {
|
||||
if group != nil && h.gatewayService != nil {
|
||||
h.gatewayService.RecordCodexModelsManifestETag(group.ID, manifest)
|
||||
}
|
||||
writeOpenAIModelsResponse(c, manifest)
|
||||
}
|
||||
@@ -534,7 +534,7 @@ func TestCodexModelsReturnsLastUpstreamErrorWhenAccountsAreExhausted(t *testing.
|
||||
1: http.StatusServiceUnavailable,
|
||||
2: http.StatusGatewayTimeout,
|
||||
}
|
||||
recorder := performCodexModelsRequest(t, handler, groupID)
|
||||
recorder := performCodexModelsRequestForGroup(t, handler, codexModelsGroupWithoutLocalFallback(groupID), "")
|
||||
|
||||
if got, want := upstream.calls(), []int64{1, 2}; !equalInt64Slices(got, want) {
|
||||
t.Fatalf("upstream account calls: got %v, want %v", got, want)
|
||||
@@ -555,7 +555,7 @@ func TestCodexModelsHonorsAccountSwitchLimit(t *testing.T) {
|
||||
3: http.StatusGatewayTimeout,
|
||||
4: http.StatusInternalServerError,
|
||||
}
|
||||
recorder := performCodexModelsRequest(t, handler, groupID)
|
||||
recorder := performCodexModelsRequestForGroup(t, handler, codexModelsGroupWithoutLocalFallback(groupID), "")
|
||||
|
||||
if got, want := upstream.calls(), []int64{1, 2, 3}; !equalInt64Slices(got, want) {
|
||||
t.Fatalf("upstream account calls: got %v, want %v", got, want)
|
||||
|
||||
@@ -181,6 +181,9 @@ func (h *OpenAIGatewayHandler) Embeddings(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
account := selection.Account
|
||||
if rejectSelectedAccountIfModerated(c, account.ID, selectionReleaseFunc(selection), h.openAISecurityAuditError) {
|
||||
return
|
||||
}
|
||||
setOpsSelectedAccount(c, account.ID, account.Platform)
|
||||
|
||||
accountReleaseFunc, slotResult := h.acquireResponsesAccountSlot(c, apiKey.GroupID, "", selection, false, &streamStarted, reqLog)
|
||||
@@ -244,12 +247,13 @@ func (h *OpenAIGatewayHandler) Embeddings(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
switchCount++
|
||||
reqLog.Warn("openai_embeddings.upstream_failover_switching",
|
||||
switchFields := appendUpstreamRetryAfterField([]zap.Field{
|
||||
zap.Int64("account_id", account.ID),
|
||||
zap.Int("upstream_status", failoverErr.StatusCode),
|
||||
zap.Int("switch_count", switchCount),
|
||||
zap.Int("max_switches", maxAccountSwitches),
|
||||
)
|
||||
}, failoverErr)
|
||||
reqLog.Warn("openai_embeddings.upstream_failover_switching", switchFields...)
|
||||
continue
|
||||
}
|
||||
h.gatewayService.ReportOpenAIAccountScheduleResult(account, openAIAccountScheduleModel(c, account, reqModel, false, result), false, nil, err)
|
||||
|
||||
@@ -123,6 +123,9 @@ func (h *OpenAIGatewayHandler) ResponsesInputTokens(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
if rejectSelectedAccountIfModerated(c, account.ID, nil, h.openAISecurityAuditError) {
|
||||
return
|
||||
}
|
||||
setOpsSelectedAccount(c, account.ID, account.Platform)
|
||||
if err := h.gatewayService.ForwardResponsesInputTokens(c.Request.Context(), c, account, forwardBody); err != nil {
|
||||
reqLog.Error("openai_input_tokens.forward_failed", zap.Int64("account_id", account.ID), zap.Error(err))
|
||||
@@ -297,6 +300,9 @@ func (h *OpenAIGatewayHandler) CountTokens(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
if rejectSelectedAccountIfModerated(c, account.ID, nil, h.anthropicSecurityAuditError) {
|
||||
return
|
||||
}
|
||||
setOpsSelectedAccount(c, account.ID, account.Platform)
|
||||
forwardBody := mappedBodyForMessages(channelMapping.Mapped, channelMapping.MappedModel)
|
||||
defaultMappedModel := preferredMappedModel
|
||||
|
||||
@@ -277,7 +277,7 @@ func TestFailoverExhaustionRejectsSecretBearingRetryAfter(t *testing.T) {
|
||||
require.NotContains(t, recorder.Body.String(), "must-not-leak")
|
||||
}
|
||||
|
||||
func TestFailoverExhaustionRejectsFarFutureRetryAfterDate(t *testing.T) {
|
||||
func TestFailoverExhaustionCapsFarFutureRetryAfterDate(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
recorder := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(recorder)
|
||||
@@ -291,10 +291,11 @@ func TestFailoverExhaustionRejectsFarFutureRetryAfterDate(t *testing.T) {
|
||||
}, false)
|
||||
|
||||
require.Equal(t, http.StatusTooManyRequests, recorder.Code)
|
||||
require.Empty(t, recorder.Header().Get("Retry-After"))
|
||||
require.Equal(t, "300", recorder.Header().Get("Retry-After"),
|
||||
"absurd upstream windows must be capped instead of forwarded verbatim")
|
||||
}
|
||||
|
||||
func TestFailoverExhaustionAllowsBoundedRetryAfterDate(t *testing.T) {
|
||||
func TestFailoverExhaustionConvertsRetryAfterDateToSeconds(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
recorder := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(recorder)
|
||||
@@ -307,7 +308,8 @@ func TestFailoverExhaustionAllowsBoundedRetryAfterDate(t *testing.T) {
|
||||
}, false)
|
||||
|
||||
require.Equal(t, http.StatusTooManyRequests, recorder.Code)
|
||||
require.Equal(t, retryAfter, recorder.Header().Get("Retry-After"))
|
||||
require.Equal(t, "300", recorder.Header().Get("Retry-After"),
|
||||
"dates are converted to integer seconds and capped")
|
||||
}
|
||||
|
||||
func TestOpsClassificationTreatsCredentialFailureAsAuthNotInference(t *testing.T) {
|
||||
@@ -438,3 +440,38 @@ func TestOpsWebSocketCredentialFailoverExhaustedIsRecorded(t *testing.T) {
|
||||
require.Equal(t, http.StatusServiceUnavailable, job.entry.StatusCode)
|
||||
require.Equal(t, service.GrokCredentialUnavailableClientMessage, job.entry.ErrorMessage)
|
||||
}
|
||||
|
||||
func TestFailoverExhaustionUsesBodyRetryAfterMs(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
recorder := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(recorder)
|
||||
h := &OpenAIGatewayHandler{}
|
||||
|
||||
h.handleFailoverExhausted(c, &service.UpstreamFailoverError{
|
||||
StatusCode: http.StatusTooManyRequests,
|
||||
ResponseBody: []byte(`{"error":{"headers":{"retry-after-ms":"1500"}}}`),
|
||||
}, false)
|
||||
|
||||
require.Equal(t, http.StatusTooManyRequests, recorder.Code)
|
||||
require.Equal(t, "2", recorder.Header().Get("Retry-After"),
|
||||
"body-provided millisecond hints are converted to whole seconds")
|
||||
}
|
||||
|
||||
func TestFailoverExhaustionCapacityShedOmitsRetryAfter(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
recorder := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(recorder)
|
||||
h := &OpenAIGatewayHandler{}
|
||||
|
||||
h.handleFailoverExhausted(c, &service.UpstreamFailoverError{
|
||||
StatusCode: http.StatusTooManyRequests,
|
||||
RequestScopedTransient: true,
|
||||
ResponseHeaders: http.Header{"Retry-After": []string{"480"}},
|
||||
ResponseBody: []byte(`{"error":{"type":"server_error","code":"server_is_overloaded",` +
|
||||
`"message":"Our servers are currently overloaded. Please try again later."}}`),
|
||||
}, false)
|
||||
|
||||
require.NotEmpty(t, recorder.Body.String())
|
||||
require.Empty(t, recorder.Header().Get("Retry-After"),
|
||||
"capacity-shed windows must not be forwarded; clients would sleep through a transient blip")
|
||||
}
|
||||
@@ -16,6 +16,7 @@ import (
|
||||
"sync/atomic"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
"unsafe"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
"github.com/Wei-Shaw/sub2api/internal/domain"
|
||||
@@ -81,7 +82,8 @@ func newOpenAIWSUnsupportedModelSwitchError(model string) error {
|
||||
}
|
||||
|
||||
func shouldReportOpenAIWSProxyAccountFailure(err error) bool {
|
||||
return err != nil && !errors.Is(err, errOpenAIWSUnsupportedModelSwitch) && !service.IsOpenAIWSSessionPreemptedError(err)
|
||||
return err != nil && !errors.Is(err, errOpenAIWSUnsupportedModelSwitch) &&
|
||||
!errors.Is(err, service.ErrResponsesWSBridgeHistoryLimit) && !service.IsOpenAIWSSessionPreemptedError(err)
|
||||
}
|
||||
|
||||
// openAIWSIngressEndedByClient reports whether a finished ingress WebSocket turn
|
||||
@@ -470,55 +472,67 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) {
|
||||
h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", "Failed to parse request body")
|
||||
return
|
||||
}
|
||||
service.MarkOpenAIRequestBodyJSONValidated(c)
|
||||
|
||||
// 使用 gjson 只读提取字段做校验,避免完整 Unmarshal
|
||||
modelResult := gjson.GetBytes(body, "model")
|
||||
if !modelResult.Exists() || modelResult.Type != gjson.String || modelResult.String() == "" {
|
||||
// 单次只读扫描顶层校验与路由字段,避免对大请求体重复调用 gjson.GetBytes。
|
||||
ingressFields := parseOpenAIResponsesIngressFields(body)
|
||||
if !ingressFields.ModelValid {
|
||||
h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", "model is required")
|
||||
return
|
||||
}
|
||||
reqModel := modelResult.String()
|
||||
reqModel := ingressFields.Model
|
||||
ensureCompositeTargetPlatform(c, apiKey, reqModel)
|
||||
if !openAICompatibleTextTargetAllowed(c, apiKey, reqModel) {
|
||||
h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", "Model is not supported by this OpenAI-compatible endpoint for composite groups")
|
||||
return
|
||||
}
|
||||
if cappedBody, changed, err := applyOpenAIReasoningEffortPolicyForRequest(c, apiKey, body); err != nil {
|
||||
ingressBodyChanged := false
|
||||
if cappedBody, changed, err := applyOpenAIReasoningEffortPolicyForRequestWithFields(
|
||||
c, apiKey, body, reqModel,
|
||||
ingressFields.ReasoningEffort, ingressFields.ReasoningEffortTop, ingressFields.OutputConfigEffort,
|
||||
); err != nil {
|
||||
respondOpenAIReasoningEffortPolicyError(c, err, h.errorResponse)
|
||||
return
|
||||
} else if changed {
|
||||
body = cappedBody
|
||||
ingressBodyChanged = true
|
||||
}
|
||||
if normalizedBody, changed := normalizeCodexUntrustedContext(body); changed {
|
||||
body = normalizedBody
|
||||
ingressBodyChanged = true
|
||||
reqLog.Info("openai.codex_untrusted_context_normalized",
|
||||
zap.String("normalization", "call_output_to_user_message"),
|
||||
)
|
||||
}
|
||||
if normalizedBody, changed := normalizeCodexAutomationBootstrap(body); changed {
|
||||
body = normalizedBody
|
||||
ingressBodyChanged = true
|
||||
reqLog.Info("openai.codex_automation_bootstrap_normalized",
|
||||
zap.String("normalization", "call_output_to_user_message"),
|
||||
)
|
||||
}
|
||||
if normalizedBody, changed := normalizeCodexDelegationBootstrap(body); changed {
|
||||
body = normalizedBody
|
||||
ingressBodyChanged = true
|
||||
reqLog.Info("openai.codex_delegation_bootstrap_normalized",
|
||||
zap.String("normalization", "call_output_to_user_message"),
|
||||
)
|
||||
}
|
||||
if ingressBodyChanged {
|
||||
ingressFields = parseOpenAIResponsesIngressFields(body)
|
||||
}
|
||||
|
||||
reqStream, ok := parseOpenAICompatibleStream(body)
|
||||
if !ok {
|
||||
if !ingressFields.StreamValid {
|
||||
h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", invalidStreamFieldTypeMessage)
|
||||
return
|
||||
}
|
||||
if _, err := service.ValidateOpenAIServiceTierField(body); err != nil {
|
||||
reqStream := ingressFields.Stream
|
||||
if _, err := service.ValidateOpenAIServiceTierResult(ingressFields.ServiceTier); err != nil {
|
||||
h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", err.Error())
|
||||
return
|
||||
}
|
||||
reqLog = reqLog.With(zap.String("model", reqModel), zap.Bool("stream", reqStream))
|
||||
previousResponseID := strings.TrimSpace(gjson.GetBytes(body, "previous_response_id").String())
|
||||
previousResponseID := ingressFields.PreviousResponseID
|
||||
if previousResponseID != "" {
|
||||
previousResponseIDKind := service.ClassifyOpenAIPreviousResponseIDKind(previousResponseID)
|
||||
reqLog = reqLog.With(
|
||||
@@ -563,10 +577,10 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
// 使用 IsExplicitImageGenerationIntent 排除被动 image_gen namespace 声明。
|
||||
// 使用 IsExplicitImageGenerationIntentValidated 排除被动 image_gen namespace 声明。
|
||||
// Codex 在所有请求中被动声明 image_gen namespace,宽泛检测会导致禁了生图的
|
||||
// 分组中所有 Codex 请求被 403(#4447),并误占生图并发槽位。
|
||||
imageIntent := service.IsExplicitImageGenerationIntent("/v1/responses", reqModel, body)
|
||||
imageIntent := service.IsExplicitImageGenerationIntentValidated("/v1/responses", reqModel, body)
|
||||
if imageIntent && !service.GroupAllowsImageGeneration(apiKey.Group) {
|
||||
h.errorResponse(c, http.StatusForbidden, "permission_error", service.ImageGenerationPermissionMessage())
|
||||
return
|
||||
@@ -632,7 +646,11 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) {
|
||||
}
|
||||
|
||||
// 余额模式在途预留:防止并发请求在预检时看到同一份余额而集体透支。
|
||||
inflightRelease, err := reserveInflightBalance(c, h.billingCacheService, h.gatewayService, apiKey, subscription, tokenInflightEstimate(reqModel, body))
|
||||
var inflightEstimate service.InflightEstimateRequest
|
||||
if h.billingCacheService != nil && h.billingCacheService.InflightReservationEnabled() {
|
||||
inflightEstimate = tokenInflightEstimate(reqModel, body)
|
||||
}
|
||||
inflightRelease, err := reserveInflightBalance(c, h.billingCacheService, h.gatewayService, apiKey, subscription, inflightEstimate)
|
||||
if err != nil {
|
||||
reqLog.Info("openai.inflight_reservation_rejected", zap.Error(err))
|
||||
status, code, message, retryAfter := billingErrorDetails(err)
|
||||
@@ -685,6 +703,18 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) {
|
||||
pricingCtx, pricingAt := h.gatewayService.WithOpenAIRequestPricingContext(c.Request.Context(), apiKey.GroupID)
|
||||
c.Request = c.Request.WithContext(pricingCtx)
|
||||
|
||||
var (
|
||||
requestPayloadHashComputed bool
|
||||
requestPayloadHashValue string
|
||||
)
|
||||
getRequestPayloadHash := func() string {
|
||||
if !requestPayloadHashComputed {
|
||||
requestPayloadHashValue = service.HashUsageRequestPayload(body)
|
||||
requestPayloadHashComputed = true
|
||||
}
|
||||
return requestPayloadHashValue
|
||||
}
|
||||
|
||||
for {
|
||||
// Streaming Forward intentionally detaches the upstream request so usage can
|
||||
// be drained after a disconnect. Re-check the client context before every
|
||||
@@ -789,6 +819,9 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) {
|
||||
)
|
||||
continue
|
||||
}
|
||||
if rejectSelectedAccountIfModerated(c, account.ID, selectionReleaseFunc(selection), h.openAISecurityAuditError) {
|
||||
return
|
||||
}
|
||||
sessionHash = ensureOpenAIPoolModeSessionHash(sessionHash, account)
|
||||
reqLog.Debug("openai.account_selected", zap.Int64("account_id", account.ID), zap.String("account_name", account.Name))
|
||||
setOpsSelectedAccount(c, account.ID, account.Platform)
|
||||
@@ -828,11 +861,9 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) {
|
||||
if h.handleForwardRequestBodyMemoryOverload(c, err, streamStarted) {
|
||||
return
|
||||
}
|
||||
var cyberBlockBodyHTTP []byte
|
||||
if service.GetOpsCyberPolicy(c) != nil {
|
||||
cyberBlockBodyHTTP = sessionHashBody
|
||||
h.recordCyberPolicyIfMarked(c, apiKey, account, subscription, reqModel, err != nil, sessionHashBody, clientRequestedUsageFields(c, channelMapping, reqModel, ""), getRequestPayloadHash())
|
||||
}
|
||||
h.recordCyberPolicyIfMarked(c, apiKey, account, subscription, reqModel, err != nil, cyberBlockBodyHTTP, clientRequestedUsageFields(c, channelMapping, reqModel, ""), service.HashUsageRequestPayload(body))
|
||||
forwardDurationMs := time.Since(forwardStart).Milliseconds()
|
||||
upstreamLatencyMs, _ := getContextInt64(c, service.OpsUpstreamLatencyMsKey)
|
||||
responseLatencyMs := forwardDurationMs
|
||||
@@ -852,7 +883,7 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) {
|
||||
stampOpenAIRequestedReasoningEffort(res, c)
|
||||
userAgent := c.GetHeader("User-Agent")
|
||||
clientIP := ip.GetClientIP(c)
|
||||
requestPayloadHash := service.HashUsageRequestPayload(body)
|
||||
requestPayloadHash := getRequestPayloadHash()
|
||||
inboundEndpoint := GetInboundEndpoint(c)
|
||||
upstreamEndpoint := resolveOpenAIUpstreamEndpoint(c, account, res)
|
||||
quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey)
|
||||
@@ -950,13 +981,14 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) {
|
||||
if sameAccountRetryAllowed(failoverErr, sameAccountRetryCount[account.ID], retryLimit) {
|
||||
sameAccountRetryCount[account.ID]++
|
||||
retryDelay := sameAccountRetryDelayFor(failoverErr, sameAccountRetryCount[account.ID])
|
||||
reqLog.Warn("openai.pool_mode_same_account_retry",
|
||||
retryFields := appendUpstreamRetryAfterField([]zap.Field{
|
||||
zap.Int64("account_id", account.ID),
|
||||
zap.Int("upstream_status", failoverErr.StatusCode),
|
||||
zap.Int("retry_limit", retryLimit),
|
||||
zap.Int("retry_count", sameAccountRetryCount[account.ID]),
|
||||
zap.Duration("retry_delay", retryDelay),
|
||||
)
|
||||
}, failoverErr)
|
||||
reqLog.Warn("openai.pool_mode_same_account_retry", retryFields...)
|
||||
select {
|
||||
case <-c.Request.Context().Done():
|
||||
return
|
||||
@@ -993,6 +1025,7 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) {
|
||||
} else if account.ProxyID != nil {
|
||||
failoverSwitchFields = append(failoverSwitchFields, zap.Int64p("proxy_id", account.ProxyID))
|
||||
}
|
||||
failoverSwitchFields = appendUpstreamRetryAfterField(failoverSwitchFields, failoverErr)
|
||||
reqLog.Warn("openai.upstream_failover_switching", failoverSwitchFields...)
|
||||
continue
|
||||
}
|
||||
@@ -1391,6 +1424,9 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
account := selection.Account
|
||||
if rejectSelectedAccountIfModerated(c, account.ID, selectionReleaseFunc(selection), h.anthropicSecurityAuditError) {
|
||||
return
|
||||
}
|
||||
sessionHash = ensureOpenAIPoolModeSessionHash(sessionHash, account)
|
||||
reqLog.Debug("openai_messages.account_selected", zap.Int64("account_id", account.ID), zap.String("account_name", account.Name))
|
||||
_ = scheduleDecision
|
||||
@@ -1527,13 +1563,14 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) {
|
||||
if sameAccountRetryAllowed(failoverErr, sameAccountRetryCount[account.ID], retryLimit) {
|
||||
sameAccountRetryCount[account.ID]++
|
||||
retryDelay := sameAccountRetryDelayFor(failoverErr, sameAccountRetryCount[account.ID])
|
||||
reqLog.Warn("openai_messages.pool_mode_same_account_retry",
|
||||
retryFields := appendUpstreamRetryAfterField([]zap.Field{
|
||||
zap.Int64("account_id", account.ID),
|
||||
zap.Int("upstream_status", failoverErr.StatusCode),
|
||||
zap.Int("retry_limit", retryLimit),
|
||||
zap.Int("retry_count", sameAccountRetryCount[account.ID]),
|
||||
zap.Duration("retry_delay", retryDelay),
|
||||
)
|
||||
}, failoverErr)
|
||||
reqLog.Warn("openai_messages.pool_mode_same_account_retry", retryFields...)
|
||||
select {
|
||||
case <-c.Request.Context().Done():
|
||||
return
|
||||
@@ -1554,12 +1591,13 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) {
|
||||
h.handleAnthropicFailoverExhausted(c, failoverErr, streamStarted)
|
||||
return
|
||||
}
|
||||
reqLog.Warn("openai_messages.upstream_failover_switching",
|
||||
switchFields := appendUpstreamRetryAfterField([]zap.Field{
|
||||
zap.Int64("account_id", account.ID),
|
||||
zap.Int("upstream_status", failoverErr.StatusCode),
|
||||
zap.Int("switch_count", switchCount),
|
||||
zap.Int("max_switches", maxAccountSwitches),
|
||||
)
|
||||
}, failoverErr)
|
||||
reqLog.Warn("openai_messages.upstream_failover_switching", switchFields...)
|
||||
continue
|
||||
}
|
||||
if result != nil && result.ClientDisconnect {
|
||||
@@ -1656,7 +1694,7 @@ func (h *OpenAIGatewayHandler) anthropicStreamingAwareError(c *gin.Context, stat
|
||||
// handleAnthropicFailoverExhausted maps upstream failover errors to Anthropic format.
|
||||
func (h *OpenAIGatewayHandler) handleAnthropicFailoverExhausted(c *gin.Context, failoverErr *service.UpstreamFailoverError, streamStarted bool) {
|
||||
if failoverErr != nil {
|
||||
copyFailoverRetryAfter(c, failoverErr.ResponseHeaders)
|
||||
applyRateLimitRetryAfter(c, failoverErr, h.cfg)
|
||||
}
|
||||
if failoverErr != nil && failoverErr.IsCredentialFailure() {
|
||||
status, message := credentialFailoverClientResponse(failoverErr)
|
||||
@@ -1692,7 +1730,99 @@ func (h *OpenAIGatewayHandler) ensureAnthropicErrorResponse(c *gin.Context, stre
|
||||
return true
|
||||
}
|
||||
|
||||
type openAIResponsesIngressFields struct {
|
||||
Model string
|
||||
ModelValid bool
|
||||
Stream bool
|
||||
StreamValid bool
|
||||
ServiceTier gjson.Result
|
||||
PreviousResponseID string
|
||||
ReasoningEffort string
|
||||
ReasoningEffortTop string
|
||||
OutputConfigEffort string
|
||||
}
|
||||
|
||||
// parseOpenAIResponsesIngressFields 单次只读扫描 /v1/responses 顶层入口字段,
|
||||
// 提取出的字符串全部 clone 断开对原始请求体的引用;ServiceTier 仅在本次同步校验期间使用。
|
||||
func parseOpenAIResponsesIngressFields(body []byte) openAIResponsesIngressFields {
|
||||
fields := openAIResponsesIngressFields{StreamValid: true}
|
||||
if len(body) == 0 {
|
||||
return fields
|
||||
}
|
||||
root := gjson.Parse(unsafe.String(unsafe.SliceData(body), len(body)))
|
||||
if !root.IsObject() {
|
||||
return fields
|
||||
}
|
||||
const (
|
||||
seenModel uint8 = 1 << iota
|
||||
seenStream
|
||||
seenServiceTier
|
||||
seenPrevRespID
|
||||
seenReasoning
|
||||
seenReasoningTop
|
||||
seenOutputConfig
|
||||
seenAll = seenModel | seenStream | seenServiceTier | seenPrevRespID |
|
||||
seenReasoning | seenReasoningTop | seenOutputConfig
|
||||
)
|
||||
var seen uint8
|
||||
root.ForEach(func(key, value gjson.Result) bool {
|
||||
switch key.Str {
|
||||
case "model":
|
||||
if seen&seenModel == 0 {
|
||||
seen |= seenModel
|
||||
if value.Type == gjson.String && value.String() != "" {
|
||||
fields.ModelValid = true
|
||||
fields.Model = strings.Clone(value.String())
|
||||
}
|
||||
}
|
||||
case "stream":
|
||||
if seen&seenStream == 0 {
|
||||
seen |= seenStream
|
||||
if value.Type != gjson.True && value.Type != gjson.False {
|
||||
fields.StreamValid = false
|
||||
} else {
|
||||
fields.Stream = value.Bool()
|
||||
}
|
||||
}
|
||||
case "service_tier":
|
||||
if seen&seenServiceTier == 0 {
|
||||
seen |= seenServiceTier
|
||||
fields.ServiceTier = value
|
||||
}
|
||||
case "previous_response_id":
|
||||
if seen&seenPrevRespID == 0 {
|
||||
seen |= seenPrevRespID
|
||||
fields.PreviousResponseID = strings.Clone(strings.TrimSpace(value.String()))
|
||||
}
|
||||
case "reasoning":
|
||||
if seen&seenReasoning == 0 {
|
||||
if effort := value.Get("effort"); effort.Exists() {
|
||||
seen |= seenReasoning
|
||||
fields.ReasoningEffort = strings.Clone(strings.TrimSpace(effort.String()))
|
||||
}
|
||||
}
|
||||
case "reasoning_effort":
|
||||
if seen&seenReasoningTop == 0 {
|
||||
seen |= seenReasoningTop
|
||||
fields.ReasoningEffortTop = strings.Clone(strings.TrimSpace(value.String()))
|
||||
}
|
||||
case "output_config":
|
||||
if seen&seenOutputConfig == 0 {
|
||||
if effort := value.Get("effort"); effort.Exists() {
|
||||
seen |= seenOutputConfig
|
||||
fields.OutputConfigEffort = strings.Clone(strings.TrimSpace(effort.String()))
|
||||
}
|
||||
}
|
||||
}
|
||||
return seen != seenAll
|
||||
})
|
||||
return fields
|
||||
}
|
||||
|
||||
func (h *OpenAIGatewayHandler) validateFunctionCallOutputRequest(c *gin.Context, body []byte, reqLog *zap.Logger) bool {
|
||||
if !bytes.Contains(body, []byte("function_call_output")) && !service.JSONMayEscapePlainASCII(body) {
|
||||
return true
|
||||
}
|
||||
if !gjson.GetBytes(body, `input.#(type=="function_call_output")`).Exists() {
|
||||
return true
|
||||
}
|
||||
@@ -1739,7 +1869,10 @@ func normalizeCodexAutomationBootstrap(body []byte) ([]byte, bool) {
|
||||
if !mayContainCodexCallOutputCandidate(body, "automation_update") {
|
||||
return body, false
|
||||
}
|
||||
return normalizeCodexCallOutputBootstrap(body, isCodexAutomationCandidate, false)
|
||||
// 定时任务复用已有长对话时,会在历史调用上下文之后追加 automation_update heartbeat,
|
||||
// 也可能携带 previous_response_id;它仍是客户端注入的触发消息而非历史工具调用的结果,
|
||||
// 因此允许它与可明确配对的历史上下文共存。
|
||||
return normalizeCodexCallOutputBootstrap(body, isCodexAutomationCandidate, true)
|
||||
}
|
||||
|
||||
// mayContainCodexCallOutputCandidate is a necessary condition for a bootstrap
|
||||
@@ -1796,8 +1929,8 @@ func normalizeCodexCallOutputBootstrap(body []byte, isCandidate func(map[string]
|
||||
|
||||
// Responses built-ins follow the *_call / *_call_output naming convention,
|
||||
// so classify by the wire type shape instead of maintaining an incomplete
|
||||
// allowlist. Delegation may coexist with historical anchors only when their
|
||||
// IDs make them unambiguous; automation retains the bootstrap-only boundary.
|
||||
// allowlist. Delegation and automation may coexist with historical anchors
|
||||
// only when their IDs make them unambiguous.
|
||||
for _, raw := range input {
|
||||
item, ok := raw.(map[string]any)
|
||||
if !ok {
|
||||
@@ -1805,19 +1938,32 @@ func normalizeCodexCallOutputBootstrap(body []byte, isCandidate func(map[string]
|
||||
}
|
||||
typ := stringField(item, "type")
|
||||
if isCandidate(item) {
|
||||
callIDValue, exists := item["call_id"]
|
||||
callID, isString := callIDValue.(string)
|
||||
if exists && (!isString || strings.TrimSpace(callID) != "") {
|
||||
if !hasMissingOrBlankCallID(item) {
|
||||
return body, false
|
||||
}
|
||||
continue
|
||||
}
|
||||
if allowHistoricalContext && isCodexCoexistingStandaloneOutput(item) {
|
||||
continue
|
||||
}
|
||||
if typ == "item_reference" {
|
||||
if allowHistoricalContext && strings.TrimSpace(stringField(item, "id")) != "" {
|
||||
continue
|
||||
}
|
||||
return body, false
|
||||
}
|
||||
if isResponsesServerSideCallType(typ) {
|
||||
if allowHistoricalContext {
|
||||
continue
|
||||
}
|
||||
return body, false
|
||||
}
|
||||
if typ == "tool_search_call" {
|
||||
if allowHistoricalContext && (strings.TrimSpace(stringField(item, "call_id")) != "" || strings.TrimSpace(stringField(item, "id")) != "") {
|
||||
continue
|
||||
}
|
||||
return body, false
|
||||
}
|
||||
if strings.HasSuffix(typ, "_call") || isResponsesCallOutputType(typ) {
|
||||
if allowHistoricalContext && strings.TrimSpace(stringField(item, "call_id")) != "" {
|
||||
continue
|
||||
@@ -1914,6 +2060,48 @@ func isResponsesCallOutputType(typ string) bool {
|
||||
return strings.HasSuffix(typ, "_call_output") || typ == "tool_search_output"
|
||||
}
|
||||
|
||||
// isResponsesServerSideCallType 识别服务端托管的 Responses *_call 历史项。
|
||||
// 这类项不与客户端 *_call_output 配对,协议上不带 call_id(且 store=false 回放可能无 id)。
|
||||
func isResponsesServerSideCallType(typ string) bool {
|
||||
switch typ {
|
||||
case "web_search_call", "x_search_call", "file_search_call", "code_interpreter_call", "image_generation_call", "mcp_call":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func hasMissingOrBlankCallID(item map[string]any) bool {
|
||||
callIDValue, exists := item["call_id"]
|
||||
if !exists {
|
||||
return true
|
||||
}
|
||||
callID, isString := callIDValue.(string)
|
||||
return isString && strings.TrimSpace(callID) == ""
|
||||
}
|
||||
|
||||
// isCodexCoexistingStandaloneOutput 允许同一请求中的合法兄弟 Codex ExternalMessage 共存:
|
||||
// 1. automation_update 与 delegation(create_thread/send_message_to_thread)可共存,避免两步归一化互相死锁;
|
||||
// 2. namespace=="agent" 的 standalone 环境上下文(如 browser_tabs/terminal_info)与 codex_app 任务触发独立,
|
||||
// 不应阻断 automation/delegation 归一化。
|
||||
//
|
||||
// 注意:不放行 codex_app/codex_tui 下畸形的非候选输出,保留原有拒绝语义。
|
||||
func isCodexCoexistingStandaloneOutput(item map[string]any) bool {
|
||||
if !hasMissingOrBlankCallID(item) {
|
||||
return false
|
||||
}
|
||||
if isCodexAutomationCandidate(item) || isCodexDelegationCandidate(item) {
|
||||
return true
|
||||
}
|
||||
if stringField(item, "type") != "function_call_output" ||
|
||||
stringField(item, "namespace") != "agent" ||
|
||||
strings.TrimSpace(stringField(item, "name")) == "" {
|
||||
return false
|
||||
}
|
||||
_, ok := item["output"].(string)
|
||||
return ok
|
||||
}
|
||||
|
||||
func isCodexDelegationCandidate(item map[string]any) bool {
|
||||
if stringField(item, "type") != "function_call_output" ||
|
||||
!isCodexDelegationTool(stringField(item, "namespace"), stringField(item, "name")) {
|
||||
@@ -2008,77 +2196,107 @@ func validCodexAutomationLastRun(value string) bool {
|
||||
return err == nil && runAt.UnixMilli() == epochMillis
|
||||
}
|
||||
|
||||
// validCodexAutomationHeartbeat 校验 Codex Desktop 生成的 <heartbeat> 触发信封。
|
||||
// Codex Desktop 通过字符串拼接写入 <instructions> 正文,不会对用户 prompt 中的
|
||||
// `&`、`<OrderNo>` 等字符做 XML 转义,因此外层标签仍按精确字面量严格校验,
|
||||
// 而 <instructions>...</instructions> 内部作为原始文本提取。
|
||||
func validCodexAutomationHeartbeat(value string) bool {
|
||||
decoder := xml.NewDecoder(strings.NewReader(value))
|
||||
var rootSeen, automationIDSeen bool
|
||||
var childName string
|
||||
var childText bytes.Buffer
|
||||
fields := make(map[string]string)
|
||||
depth := 0
|
||||
rest := strings.TrimSpace(value)
|
||||
if !strings.HasPrefix(rest, "<heartbeat>") || !strings.HasSuffix(rest, "</heartbeat>") {
|
||||
return false
|
||||
}
|
||||
inner := rest[len("<heartbeat>") : len(rest)-len("</heartbeat>")]
|
||||
|
||||
fields := make(map[string]string, 3)
|
||||
for {
|
||||
token, err := decoder.Token()
|
||||
if err == io.EOF {
|
||||
id := fields["automation_id"]
|
||||
timestamp, hasTime := fields["current_time_iso"]
|
||||
instructions, hasInstructions := fields["instructions"]
|
||||
if hasTime != hasInstructions {
|
||||
return false
|
||||
}
|
||||
if hasTime {
|
||||
if _, err := time.Parse(time.RFC3339Nano, timestamp); err != nil || strings.TrimSpace(instructions) == "" {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return rootSeen && automationIDSeen && depth == 0 &&
|
||||
strings.TrimSpace(id) == id && validCodexAutomationID(id)
|
||||
inner = strings.TrimSpace(inner)
|
||||
if inner == "" {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
var tagName, closeTag string
|
||||
switch {
|
||||
case strings.HasPrefix(inner, "<automation_id>"):
|
||||
tagName, closeTag = "automation_id", "</automation_id>"
|
||||
case strings.HasPrefix(inner, "<current_time_iso>"):
|
||||
tagName, closeTag = "current_time_iso", "</current_time_iso>"
|
||||
case strings.HasPrefix(inner, "<instructions>"):
|
||||
tagName, closeTag = "instructions", "</instructions>"
|
||||
default:
|
||||
return false
|
||||
}
|
||||
switch current := token.(type) {
|
||||
case xml.StartElement:
|
||||
depth++
|
||||
if current.Name.Space != "" || len(current.Attr) != 0 || depth > 2 {
|
||||
return false
|
||||
}
|
||||
if depth == 1 {
|
||||
if rootSeen || current.Name.Local != "heartbeat" {
|
||||
return false
|
||||
}
|
||||
rootSeen = true
|
||||
} else {
|
||||
childName = current.Name.Local
|
||||
switch childName {
|
||||
case "automation_id", "current_time_iso", "instructions":
|
||||
default:
|
||||
return false
|
||||
}
|
||||
if _, duplicate := fields[childName]; duplicate {
|
||||
return false
|
||||
}
|
||||
childText.Reset()
|
||||
}
|
||||
case xml.EndElement:
|
||||
if current.Name.Space != "" {
|
||||
return false
|
||||
}
|
||||
if depth == 2 {
|
||||
fields[childName] = childText.String()
|
||||
automationIDSeen = automationIDSeen || childName == "automation_id"
|
||||
}
|
||||
depth--
|
||||
if depth < 0 {
|
||||
return false
|
||||
}
|
||||
case xml.CharData:
|
||||
if depth == 2 {
|
||||
_, _ = childText.Write(current)
|
||||
} else if len(bytes.TrimSpace(current)) != 0 {
|
||||
return false
|
||||
}
|
||||
case xml.Comment, xml.ProcInst, xml.Directive:
|
||||
if _, duplicate := fields[tagName]; duplicate {
|
||||
return false
|
||||
}
|
||||
inner = inner[len("<")+len(tagName)+len(">"):]
|
||||
var end int
|
||||
if tagName == "instructions" {
|
||||
end = findHeartbeatInstructionsEnd(inner, fields)
|
||||
} else {
|
||||
end = strings.Index(inner, closeTag)
|
||||
}
|
||||
if end < 0 {
|
||||
return false
|
||||
}
|
||||
fields[tagName] = inner[:end]
|
||||
inner = inner[end+len(closeTag):]
|
||||
}
|
||||
|
||||
id, hasID := fields["automation_id"]
|
||||
if !hasID || strings.TrimSpace(id) != id || !validCodexAutomationID(id) {
|
||||
return false
|
||||
}
|
||||
timestamp, hasTime := fields["current_time_iso"]
|
||||
instructions, hasInstructions := fields["instructions"]
|
||||
if hasTime != hasInstructions {
|
||||
return false
|
||||
}
|
||||
if hasTime {
|
||||
if strings.TrimSpace(timestamp) != timestamp {
|
||||
return false
|
||||
}
|
||||
if _, err := time.Parse(time.RFC3339Nano, timestamp); err != nil {
|
||||
return false
|
||||
}
|
||||
if strings.TrimSpace(instructions) == "" || strings.Contains(instructions, "</heartbeat>") {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// findHeartbeatInstructionsEnd 寻找与当前 <instructions> 配对的结束标签偏移。
|
||||
// 允许正文内包含字面量 `</instructions>`,仅当其后(跳过空白)紧跟信封结尾或尚未出现的
|
||||
// 合法兄弟标签(`<automation_id>` / `<current_time_iso>`)时才视为结束边界;
|
||||
// 若其后紧跟重复标签,直接返回 -1 拒绝。
|
||||
func findHeartbeatInstructionsEnd(inner string, fields map[string]string) int {
|
||||
const closeTag = "</instructions>"
|
||||
offset := 0
|
||||
for {
|
||||
rel := strings.Index(inner[offset:], closeTag)
|
||||
if rel < 0 {
|
||||
return -1
|
||||
}
|
||||
end := offset + rel
|
||||
after := strings.TrimSpace(inner[end+len(closeTag):])
|
||||
if after == "" {
|
||||
return end
|
||||
}
|
||||
if strings.HasPrefix(after, "<instructions>") {
|
||||
return -1
|
||||
}
|
||||
if strings.HasPrefix(after, "<automation_id>") {
|
||||
if _, seen := fields["automation_id"]; !seen {
|
||||
return end
|
||||
}
|
||||
return -1
|
||||
}
|
||||
if strings.HasPrefix(after, "<current_time_iso>") {
|
||||
if _, seen := fields["current_time_iso"]; !seen {
|
||||
return end
|
||||
}
|
||||
return -1
|
||||
}
|
||||
offset = end + len(closeTag)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2547,6 +2765,8 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) {
|
||||
c.Request = c.Request.WithContext(ctx)
|
||||
}
|
||||
|
||||
clientReadLimit := service.ResolveOpenAIWSClientReadLimitBytes(h.cfg)
|
||||
service.SetOpenAIWSClientMaxMessageBytesHeader(c.Writer.Header(), clientReadLimit)
|
||||
wsConn, err := coderws.Accept(c.Writer, c.Request, &coderws.AcceptOptions{
|
||||
CompressionMode: coderws.CompressionContextTakeover,
|
||||
})
|
||||
@@ -2565,7 +2785,7 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) {
|
||||
defer func() {
|
||||
_ = wsConn.CloseNow()
|
||||
}()
|
||||
wsConn.SetReadLimit(service.ResolveOpenAIWSClientReadLimitBytes(h.cfg))
|
||||
wsConn.SetReadLimit(clientReadLimit)
|
||||
|
||||
firstMessageTimeout := service.ResolveOpenAIWSClientFirstMessageTimeout(h.cfg)
|
||||
msgType, firstMessage, err := service.ReadOpenAIWSClientMessage(
|
||||
@@ -2731,7 +2951,7 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) {
|
||||
// 必须尽早注册,确保任何 early return 都能释放已获取的并发槽位。
|
||||
defer releaseTurnSlots()
|
||||
|
||||
userReleaseFunc, userAcquired, err := h.concurrencyHelper.TryAcquireUserSlotForAPIKey(ctx, subject.UserID, subject.Concurrency, apiKey.ID)
|
||||
userReleaseFunc, userAcquired, err := h.acquireOpenAIWSUserSlot(ctx, subject, apiKey.ID)
|
||||
if err != nil {
|
||||
reqLog.Warn("openai.websocket_user_slot_acquire_failed", zap.Error(err))
|
||||
closeOpenAIClientWS(wsConn, coderws.StatusInternalError, "failed to acquire user concurrency slot")
|
||||
@@ -2746,7 +2966,7 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) {
|
||||
if currentUserRelease != nil {
|
||||
return true
|
||||
}
|
||||
userReleaseFunc, userAcquired, err := h.concurrencyHelper.TryAcquireUserSlotForAPIKey(ctx, subject.UserID, subject.Concurrency, apiKey.ID)
|
||||
userReleaseFunc, userAcquired, err := h.acquireOpenAIWSUserSlot(ctx, subject, apiKey.ID)
|
||||
if err != nil {
|
||||
reqLog.Warn("openai.websocket_user_slot_reacquire_failed", zap.Error(err))
|
||||
closeOpenAIClientWS(wsConn, coderws.StatusInternalError, "failed to acquire user concurrency slot")
|
||||
@@ -2812,11 +3032,7 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) {
|
||||
var oauth429FailoverState service.OpenAIOAuth429FailoverState
|
||||
wsAttemptMessage := append([]byte(nil), firstMessage...)
|
||||
waitForWSSameAccountRetry := func(account *service.Account, failoverErr *service.UpstreamFailoverError) bool {
|
||||
if account == nil || failoverErr == nil || failoverErr.StatusCode != http.StatusTooManyRequests || failoverErr.SameAccountRetryDeadline.IsZero() {
|
||||
return false
|
||||
}
|
||||
retryLimit := effectiveSameAccountRetryLimit(failoverErr, account)
|
||||
if !sameAccountRetryAllowed(failoverErr, sameAccountRetryCount[account.ID], retryLimit) {
|
||||
if account == nil || !wsSameAccountRetryAllowed(account, failoverErr, sameAccountRetryCount[account.ID]) {
|
||||
return false
|
||||
}
|
||||
sameAccountRetryCount[account.ID]++
|
||||
@@ -2861,12 +3077,13 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) {
|
||||
closeOpenAIWSFailoverExhausted(c, wsConn, failoverErr)
|
||||
return false
|
||||
}
|
||||
reqLog.Warn("openai.websocket_upstream_failover_switching",
|
||||
wsSwitchFields := appendUpstreamRetryAfterField([]zap.Field{
|
||||
zap.Int64("account_id", account.ID),
|
||||
zap.Int("upstream_status", failoverErr.StatusCode),
|
||||
zap.Int("switch_count", switchCount),
|
||||
zap.Int("max_switches", maxAccountSwitches),
|
||||
)
|
||||
}, failoverErr)
|
||||
reqLog.Warn("openai.websocket_upstream_failover_switching", wsSwitchFields...)
|
||||
if ctx.Err() != nil {
|
||||
return false
|
||||
}
|
||||
@@ -2893,6 +3110,11 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) {
|
||||
if ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
// Re-evaluated on every selection: a current-turn failover replay clears
|
||||
// previousResponseID because the retry payload already carries the full
|
||||
// input, so it must not be held to the original continuation chain.
|
||||
strictPreviousResponseAffinity := previousResponseID != "" && requestPlatform == service.PlatformOpenAI
|
||||
schedulePreviousResponseCanMove := previousResponseCanMove && !strictPreviousResponseAffinity
|
||||
reqLog.Debug("openai.websocket_account_selecting", zap.Int("excluded_account_count", len(failedAccountIDs)))
|
||||
selection, scheduleDecision, err := h.gatewayService.SelectAccountWithSchedulerForCapability(
|
||||
ctx,
|
||||
@@ -2904,7 +3126,7 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) {
|
||||
requiredTransport,
|
||||
requiredCapability,
|
||||
false,
|
||||
previousResponseCanMove,
|
||||
schedulePreviousResponseCanMove,
|
||||
!imageIntent,
|
||||
requestPlatform,
|
||||
)
|
||||
@@ -2930,6 +3152,19 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) {
|
||||
}
|
||||
|
||||
account := selection.Account
|
||||
if strictPreviousResponseAffinity && !scheduleDecision.StickyPreviousHit {
|
||||
if selection.ReleaseFunc != nil {
|
||||
selection.ReleaseFunc()
|
||||
selection.ReleaseFunc = nil
|
||||
}
|
||||
reqLog.Warn("openai.websocket_previous_response_not_found",
|
||||
zap.Int64("account_id", account.ID),
|
||||
zap.String("schedule_layer", scheduleDecision.Layer),
|
||||
)
|
||||
writePreviousResponseNotFoundWSError(ctx, wsConn)
|
||||
closeOpenAIClientWS(wsConn, coderws.StatusPolicyViolation, "previous_response_not_found")
|
||||
return
|
||||
}
|
||||
accountMaxConcurrency := account.Concurrency
|
||||
if selection.WaitPlan != nil && selection.WaitPlan.MaxConcurrency > 0 {
|
||||
accountMaxConcurrency = selection.WaitPlan.MaxConcurrency
|
||||
@@ -2996,6 +3231,14 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) {
|
||||
}
|
||||
// 准入完成:门并入连接 ctx,turn 级复核与 failover 重选共用。
|
||||
ctx = admissionCtx
|
||||
if wsDecision := checkSelectedAccountModeration(c, account.ID); wsDecision != nil && !wsDecision.AllowNextStage {
|
||||
if accountReleaseFunc != nil {
|
||||
accountReleaseFunc()
|
||||
}
|
||||
writeSecurityAuditWSError(ctx, wsConn, wsDecision)
|
||||
closeOpenAIClientWS(wsConn, securityAuditWSCloseStatus(wsDecision), securityAuditWSCloseReason(wsDecision))
|
||||
return
|
||||
}
|
||||
// Account selection starts a fresh upstream attempt. Clear any model
|
||||
// captured by the previous failover account before credential lookup.
|
||||
setOpsSelectedAccount(c, account.ID, account.Platform)
|
||||
@@ -3167,7 +3410,7 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) {
|
||||
// 防御式清理:避免异常路径下旧槽位覆盖导致泄漏。
|
||||
releaseTurnSlots()
|
||||
// 非首轮 turn 需要重新抢占并发槽位,避免长连接空闲占槽。
|
||||
userReleaseFunc, userAcquired, err := h.concurrencyHelper.TryAcquireUserSlotForAPIKey(ctx, subject.UserID, subject.Concurrency, apiKey.ID)
|
||||
userReleaseFunc, userAcquired, err := h.acquireOpenAIWSUserSlot(ctx, subject, apiKey.ID)
|
||||
if err != nil {
|
||||
return service.NewOpenAIWSClientCloseError(coderws.StatusInternalError, "failed to acquire user concurrency slot", err)
|
||||
}
|
||||
@@ -3300,17 +3543,6 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) {
|
||||
}
|
||||
|
||||
wsFirstMessage := wsAttemptMessage
|
||||
// 切组/会话失配防护:previous_response_id 未在当前分组命中粘连账号(StickyPreviousHit=false),
|
||||
// 说明该会话链不属于本次调度到的账号,原样转发会触发上游会话链鉴权失败(“鉴权失败,请检查 API Key”)。
|
||||
// 故剥离首包里的 previous_response_id,改用首包内 input 重建上下文;带 function_call_output 的
|
||||
// 工具续链无法重建,保持原样。仅作用于首轮首包,后续 turn 的续链由 WS 转发层既有逻辑处理。
|
||||
if previousResponseID != "" && !scheduleDecision.StickyPreviousHit && previousResponseCanMove {
|
||||
wsFirstMessage = service.RemovePreviousResponseIDFromBody(wsFirstMessage)
|
||||
reqLog.Debug("openai.websocket_previous_response_id_stripped_cross_group",
|
||||
zap.Int64("account_id", account.ID),
|
||||
zap.String("schedule_layer", scheduleDecision.Layer),
|
||||
)
|
||||
}
|
||||
|
||||
// WebSocket 首包可能很大,hash 必须在 hooks 外算成字符串,避免 AfterTurn 闭包保活请求体。
|
||||
requestPayloadHash = service.HashUsageRequestPayload(wsFirstMessage)
|
||||
@@ -3341,6 +3573,28 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) {
|
||||
wsAttemptMessage = nextAttemptMessage
|
||||
if retryCurrentTurn {
|
||||
previousResponseID = ""
|
||||
retryModPayload := retryPayload
|
||||
if len(retryModPayload) == 0 {
|
||||
retryModPayload = wsAttemptMessage
|
||||
}
|
||||
retryModModel := strings.TrimSpace(gjson.GetBytes(retryModPayload, "model").String())
|
||||
if retryModModel == "" {
|
||||
retryModModel = reqModel
|
||||
}
|
||||
if retryDecision := resetWSRetryAccountModeration(
|
||||
c,
|
||||
reqLog,
|
||||
h.contentModerationService,
|
||||
apiKey,
|
||||
subject,
|
||||
service.ContentModerationProtocolOpenAIResponses,
|
||||
retryModModel,
|
||||
retryModPayload,
|
||||
); retryDecision != nil && !retryDecision.AllowNextStage {
|
||||
writeSecurityAuditWSError(ctx, wsConn, retryDecision)
|
||||
closeOpenAIClientWS(wsConn, securityAuditWSCloseStatus(retryDecision), securityAuditWSCloseReason(retryDecision))
|
||||
return
|
||||
}
|
||||
reqLog.Warn("openai.websocket_current_turn_failover_retry",
|
||||
zap.Int64("account_id", account.ID),
|
||||
zap.Int("upstream_status", failoverErr.StatusCode),
|
||||
@@ -3366,6 +3620,12 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) {
|
||||
}
|
||||
currentAccountRelease = wrapReleaseOnDone(ctx, accountRelease)
|
||||
}
|
||||
if sameAccDecision := checkSelectedAccountModeration(c, account.ID); sameAccDecision != nil && !sameAccDecision.AllowNextStage {
|
||||
writeSecurityAuditWSError(ctx, wsConn, sameAccDecision)
|
||||
closeOpenAIClientWS(wsConn, securityAuditWSCloseStatus(sameAccDecision), securityAuditWSCloseReason(sameAccDecision))
|
||||
return
|
||||
}
|
||||
setOpsSelectedAccount(c, account.ID, account.Platform)
|
||||
wsFirstMessage = wsAttemptMessage
|
||||
continue
|
||||
}
|
||||
@@ -3640,13 +3900,17 @@ func (h *OpenAIGatewayHandler) handleFailoverExhausted(c *gin.Context, failoverE
|
||||
h.handleFailoverExhaustedSimple(c, http.StatusBadGateway, streamStarted)
|
||||
return
|
||||
}
|
||||
if failoverErr.Reason == service.OpenAIAlphaSearchRejectedReason && !streamStarted {
|
||||
h.gatewayService.WriteAlphaSearchResponse(c, failoverErr.StatusCode, failoverErr.ResponseHeaders, failoverErr.ResponseBody)
|
||||
return
|
||||
}
|
||||
if failoverErr.Reason == service.OpenAIResponsesToolsUnsupportedReason {
|
||||
// No upstream request was sent for this local capability mismatch. Keep
|
||||
// the original client error without attributing it to upstream health.
|
||||
h.handleStreamingAwareError(c, failoverErr.ClientStatusCode, "invalid_request_error", failoverErr.ClientMessage, streamStarted)
|
||||
return
|
||||
}
|
||||
copyFailoverRetryAfter(c, failoverErr.ResponseHeaders)
|
||||
applyRateLimitRetryAfter(c, failoverErr, h.cfg)
|
||||
if failoverErr.IsOpenAIRequestBodyTooLarge() {
|
||||
// An operator-configured passthrough rule wins over the built-in body
|
||||
// limit mapping below. Failover on 413 exists because different
|
||||
@@ -3784,34 +4048,15 @@ func credentialFailoverClientResponse(failoverErr *service.UpstreamFailoverError
|
||||
return http.StatusServiceUnavailable, service.GrokCredentialUnavailableClientMessage
|
||||
}
|
||||
|
||||
func copyFailoverRetryAfter(c *gin.Context, headers http.Header) {
|
||||
if c == nil || headers == nil {
|
||||
// applyRateLimitRetryAfter forwards an upstream rate-limit cooldown hint to the
|
||||
// downstream error response. Only explicit upstream 429s qualify: capacity-shed
|
||||
// and generic 5xx responses advertise long windows that clients would honor by
|
||||
// sleeping through a transient blip (#8560, #8938).
|
||||
func applyRateLimitRetryAfter(c *gin.Context, failoverErr *service.UpstreamFailoverError, cfg *config.Config) {
|
||||
if c == nil || failoverErr == nil || failoverErr.IsOpenAICapacityShed() {
|
||||
return
|
||||
}
|
||||
retryAfter := strings.TrimSpace(headers.Get("Retry-After"))
|
||||
if retryAfter == "" || len(retryAfter) > 128 || strings.ContainsAny(retryAfter, "\r\n") || !isSafeRetryAfter(retryAfter) {
|
||||
return
|
||||
}
|
||||
c.Header("Retry-After", retryAfter)
|
||||
}
|
||||
|
||||
func isSafeRetryAfter(value string) bool {
|
||||
digitsOnly := true
|
||||
for _, char := range value {
|
||||
if char < '0' || char > '9' {
|
||||
digitsOnly = false
|
||||
break
|
||||
}
|
||||
}
|
||||
if digitsOnly {
|
||||
seconds, err := strconv.ParseUint(value, 10, 32)
|
||||
return err == nil && seconds <= uint64((7*24*time.Hour)/time.Second)
|
||||
}
|
||||
retryAt, err := http.ParseTime(value)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return !retryAt.After(time.Now().Add(7 * 24 * time.Hour))
|
||||
service.SetUpstreamRateLimitRetryAfter(c, failoverErr.StatusCode, failoverErr.ResponseHeaders, failoverErr.ResponseBody, cfg)
|
||||
}
|
||||
|
||||
// handleFailoverExhaustedSimple 简化版本,用于没有响应体的情况
|
||||
@@ -4129,6 +4374,35 @@ func blockedModelAllowlistCandidate(group *service.Group, candidates []string) s
|
||||
return ""
|
||||
}
|
||||
|
||||
// openAIWSUserSlotWait bounds how long a WebSocket turn waits for a user
|
||||
// concurrency slot. It is longer than the HTTP wait because a rejected
|
||||
// WebSocket turn costs more: the client has already uploaded the full request,
|
||||
// and repeated rejections move the whole session to HTTP. It stays well below
|
||||
// the default Codex stream idle timeout of five minutes.
|
||||
var openAIWSUserSlotWait = 60 * time.Second
|
||||
|
||||
// acquireOpenAIWSUserSlot waits for a user concurrency slot for a WebSocket
|
||||
// turn instead of rejecting it at once. By the time a turn needs a slot, the
|
||||
// client has already uploaded the full request, and clients such as Codex
|
||||
// switch the session to HTTP after repeated rejections, which then resends the
|
||||
// whole context on every turn.
|
||||
//
|
||||
// acquired is false without an error when the wait timed out, the wait queue
|
||||
// is full or the connection context ended; callers close the connection with
|
||||
// StatusTryAgainLater as before.
|
||||
func (h *OpenAIGatewayHandler) acquireOpenAIWSUserSlot(ctx context.Context, subject middleware2.AuthSubject, apiKeyID int64) (func(), bool, error) {
|
||||
releaseFunc, err := h.concurrencyHelper.AcquireUserSlotForAPIKeyWithWait(ctx, subject.UserID, subject.Concurrency, apiKeyID, openAIWSUserSlotWait)
|
||||
if err == nil {
|
||||
return releaseFunc, true, nil
|
||||
}
|
||||
var concurrencyErr *ConcurrencyError
|
||||
var queueFullErr *WaitQueueFullError
|
||||
if errors.As(err, &concurrencyErr) || errors.As(err, &queueFullErr) || ctx.Err() != nil {
|
||||
return nil, false, nil
|
||||
}
|
||||
return nil, false, err
|
||||
}
|
||||
|
||||
func closeOpenAIClientWS(conn *coderws.Conn, status coderws.StatusCode, reason string) {
|
||||
if conn == nil {
|
||||
return
|
||||
@@ -4219,6 +4493,33 @@ func writeContentModerationWSError(ctx context.Context, conn *coderws.Conn, deci
|
||||
_ = conn.Write(writeCtx, coderws.MessageText, payload)
|
||||
}
|
||||
|
||||
// writePreviousResponseNotFoundWSError sends an error frame telling the client
|
||||
// that previous_response_id could not be resolved to its owning upstream chain.
|
||||
func writePreviousResponseNotFoundWSError(ctx context.Context, conn *coderws.Conn) {
|
||||
if conn == nil {
|
||||
return
|
||||
}
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
payload, err := json.Marshal(gin.H{
|
||||
"event_id": "evt_previous_response_not_found",
|
||||
"type": "error",
|
||||
"status": http.StatusBadRequest,
|
||||
"error": gin.H{
|
||||
"type": "invalid_request_error",
|
||||
"code": "previous_response_not_found",
|
||||
"message": "Previous response not found; reconnect with full input history.",
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
payload = []byte(`{"event_id":"evt_previous_response_not_found","type":"error","status":400,"error":{"type":"invalid_request_error","code":"previous_response_not_found","message":"Previous response not found; reconnect with full input history."}}`)
|
||||
}
|
||||
writeCtx, cancel := context.WithTimeout(ctx, 2*time.Second)
|
||||
defer cancel()
|
||||
_ = conn.Write(writeCtx, coderws.MessageText, payload)
|
||||
}
|
||||
|
||||
// writeCyberSessionBlockedWSError sends an error frame telling the client this
|
||||
// session is blocked by the cyber session block (F5a) before closing.
|
||||
func writeCyberSessionBlockedWSError(ctx context.Context, conn *coderws.Conn) {
|
||||
|
||||
@@ -1132,6 +1132,26 @@ func TestOpenAIResponsesWebSocket_FirstMessageTimeoutUsesConfig(t *testing.T) {
|
||||
}, time.Second, 10*time.Millisecond)
|
||||
}
|
||||
|
||||
func TestOpenAIResponsesWebSocket_AnnouncesClientReadLimit(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
h := newOpenAIHandlerForPreviousResponseIDValidation(t, nil)
|
||||
h.cfg = &config.Config{}
|
||||
h.cfg.Gateway.OpenAIWS.ClientReadLimitBytes = 96 * 1024 * 1024
|
||||
h.cfg.Gateway.OpenAIWS.ClientFirstMessageTimeoutSeconds = 1
|
||||
wsServer := newOpenAIWSHandlerTestServer(t, h, middleware.AuthSubject{UserID: 1, Concurrency: 1})
|
||||
defer wsServer.Close()
|
||||
|
||||
dialCtx, cancelDial := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
clientConn, resp, err := coderws.Dial(dialCtx, "ws"+strings.TrimPrefix(wsServer.URL, "http")+"/openai/v1/responses", nil)
|
||||
cancelDial()
|
||||
require.NoError(t, err)
|
||||
defer func() { _ = clientConn.CloseNow() }()
|
||||
|
||||
require.NotNil(t, resp)
|
||||
require.Equal(t, "100663296", resp.Header.Get("x-codex-websocket-max-message-bytes"))
|
||||
}
|
||||
|
||||
func TestOpenAIResponsesWebSocket_IngressLeaseReleasedOnEarlyReturn(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
cache := &concurrencyCacheMock{
|
||||
@@ -1364,6 +1384,14 @@ func (r *contentModerationHandlerTestRepo) UpdateLogEmailSent(ctx context.Contex
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *contentModerationHandlerTestRepo) SearchModerationAccounts(context.Context, service.ContentModerationAccountSearchFilter) ([]service.ContentModerationExcludedAccount, error) {
|
||||
return []service.ContentModerationExcludedAccount{}, nil
|
||||
}
|
||||
|
||||
func (r *contentModerationHandlerTestRepo) ListModerationAccountsByIDs(context.Context, []int64) ([]service.ContentModerationExcludedAccount, error) {
|
||||
return []service.ContentModerationExcludedAccount{}, nil
|
||||
}
|
||||
|
||||
func TestOpenAIResponsesWebSocket_ContentModerationBlocksFirstFrame(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
|
||||
@@ -0,0 +1,190 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
"github.com/Wei-Shaw/sub2api/internal/server/middleware"
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
coderws "github.com/coder/websocket"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
// newOpenAIWSUserSlotTestServer starts a WebSocket gateway in front of one
|
||||
// upstream account. userSlotFree decides every user slot acquisition attempt;
|
||||
// the account slot is always free. The returned counter reports how many
|
||||
// messages reached the upstream.
|
||||
func newOpenAIWSUserSlotTestServer(t *testing.T, userSlotFree func(attempt int32) bool) (string, *atomic.Int32) {
|
||||
t.Helper()
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
var upstreamMessages atomic.Int32
|
||||
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
conn, err := coderws.Accept(w, r, &coderws.AcceptOptions{CompressionMode: coderws.CompressionContextTakeover})
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer func() { _ = conn.CloseNow() }()
|
||||
for {
|
||||
_, _, err := conn.Read(r.Context())
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
turn := upstreamMessages.Add(1)
|
||||
completed := fmt.Sprintf(`{"type":"response.completed","response":{"id":"resp_slot_wait_%d","model":"gpt-5.1","output":[],"usage":{"input_tokens":1,"output_tokens":1}}}`, turn)
|
||||
if err := conn.Write(r.Context(), coderws.MessageText, []byte(completed)); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}))
|
||||
t.Cleanup(upstream.Close)
|
||||
|
||||
groupID := int64(4301)
|
||||
accounts := []service.Account{{
|
||||
ID: 9951,
|
||||
Name: "openai-ws-slot-wait",
|
||||
Platform: service.PlatformOpenAI,
|
||||
Type: service.AccountTypeAPIKey,
|
||||
Status: service.StatusActive,
|
||||
Schedulable: true,
|
||||
Concurrency: 5,
|
||||
Priority: 1,
|
||||
Credentials: map[string]any{
|
||||
"api_key": "sk-slot-wait",
|
||||
"base_url": upstream.URL,
|
||||
},
|
||||
Extra: map[string]any{
|
||||
"openai_apikey_responses_websockets_v2_enabled": true,
|
||||
"openai_apikey_responses_websockets_v2_mode": service.OpenAIWSIngressModeCtxPool,
|
||||
},
|
||||
}}
|
||||
|
||||
cfg := &config.Config{}
|
||||
cfg.RunMode = config.RunModeSimple
|
||||
cfg.Default.RateMultiplier = 1
|
||||
cfg.Security.URLAllowlist.Enabled = false
|
||||
cfg.Security.URLAllowlist.AllowInsecureHTTP = true
|
||||
cfg.Gateway.OpenAIWS.Enabled = true
|
||||
cfg.Gateway.OpenAIWS.APIKeyEnabled = true
|
||||
cfg.Gateway.OpenAIWS.ResponsesWebsocketsV2 = true
|
||||
cfg.Gateway.OpenAIWS.ModeRouterV2Enabled = true
|
||||
cfg.Gateway.OpenAIWS.DialTimeoutSeconds = 3
|
||||
cfg.Gateway.OpenAIWS.ReadTimeoutSeconds = 3
|
||||
cfg.Gateway.OpenAIWS.WriteTimeoutSeconds = 3
|
||||
|
||||
accountRepo := &openAIWSFailoverHandlerAccountRepoStub{accounts: accounts}
|
||||
rateLimitSvc := service.NewRateLimitService(accountRepo, nil, cfg, nil, nil)
|
||||
billingCacheSvc := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil)
|
||||
t.Cleanup(billingCacheSvc.Stop)
|
||||
gatewaySvc := service.NewOpenAIGatewayService(
|
||||
accountRepo, nil, nil, nil, nil, nil, nil, cfg, nil, nil,
|
||||
service.NewBillingService(cfg, nil), rateLimitSvc, billingCacheSvc, nil,
|
||||
&service.DeferredService{}, nil, nil, nil, nil, nil, nil, nil,
|
||||
)
|
||||
|
||||
var userAttempts atomic.Int32
|
||||
cache := &concurrencyCacheMock{
|
||||
acquireUserSlotFn: func(ctx context.Context, userID int64, maxConcurrency int, requestID string) (bool, error) {
|
||||
return userSlotFree(userAttempts.Add(1)), nil
|
||||
},
|
||||
acquireAccountSlotFn: func(ctx context.Context, accountID int64, maxConcurrency int, requestID string) (bool, error) {
|
||||
return true, nil
|
||||
},
|
||||
}
|
||||
h := &OpenAIGatewayHandler{
|
||||
gatewayService: gatewaySvc,
|
||||
billingCacheService: billingCacheSvc,
|
||||
apiKeyService: &service.APIKeyService{},
|
||||
concurrencyHelper: NewConcurrencyHelper(service.NewConcurrencyService(cache), SSEPingFormatNone, time.Second),
|
||||
maxAccountSwitches: 1,
|
||||
}
|
||||
|
||||
apiKey := &service.APIKey{
|
||||
ID: 1951,
|
||||
GroupID: &groupID,
|
||||
User: &service.User{ID: 1851, Status: service.StatusActive},
|
||||
Group: &service.Group{ID: groupID, Platform: service.PlatformOpenAI, Status: service.StatusActive},
|
||||
}
|
||||
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})
|
||||
c.Next()
|
||||
})
|
||||
router.GET("/openai/v1/responses", h.ResponsesWebSocket)
|
||||
server := httptest.NewServer(router)
|
||||
t.Cleanup(server.Close)
|
||||
|
||||
return "ws" + strings.TrimPrefix(server.URL, "http") + "/openai/v1/responses", &upstreamMessages
|
||||
}
|
||||
|
||||
func dialOpenAIWSUserSlotTestClient(t *testing.T, url string) *coderws.Conn {
|
||||
t.Helper()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
defer cancel()
|
||||
conn, _, err := coderws.Dial(ctx, url, &coderws.DialOptions{CompressionMode: coderws.CompressionContextTakeover})
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { _ = conn.CloseNow() })
|
||||
return conn
|
||||
}
|
||||
|
||||
func writeOpenAIWSUserSlotTestMessage(t *testing.T, conn *coderws.Conn, message string) {
|
||||
t.Helper()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
defer cancel()
|
||||
require.NoError(t, conn.Write(ctx, coderws.MessageText, []byte(message)))
|
||||
}
|
||||
|
||||
func readOpenAIWSUserSlotTestEvent(conn *coderws.Conn) ([]byte, error) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
_, event, err := conn.Read(ctx)
|
||||
return event, err
|
||||
}
|
||||
|
||||
func TestOpenAIResponsesWebSocket_WaitsForUserSlotOnEveryTurn(t *testing.T) {
|
||||
// Attempts 1-2 find the user at the limit, attempt 3 admits the first turn.
|
||||
// The second turn re-acquires its slot: attempt 4 is busy, attempt 5 admits it.
|
||||
url, upstreamMessages := newOpenAIWSUserSlotTestServer(t, func(attempt int32) bool {
|
||||
return attempt == 3 || attempt >= 5
|
||||
})
|
||||
conn := dialOpenAIWSUserSlotTestClient(t, url)
|
||||
|
||||
writeOpenAIWSUserSlotTestMessage(t, conn, `{"type":"response.create","model":"gpt-5.1","input":[{"role":"user","content":"first"}]}`)
|
||||
event, err := readOpenAIWSUserSlotTestEvent(conn)
|
||||
require.NoError(t, err, "a busy user slot must queue the turn instead of closing the connection")
|
||||
require.Equal(t, "response.completed", gjson.GetBytes(event, "type").String())
|
||||
require.Equal(t, "resp_slot_wait_1", gjson.GetBytes(event, "response.id").String())
|
||||
|
||||
writeOpenAIWSUserSlotTestMessage(t, conn, `{"type":"response.create","model":"gpt-5.1","previous_response_id":"resp_slot_wait_1","input":[{"role":"user","content":"second"}]}`)
|
||||
event, err = readOpenAIWSUserSlotTestEvent(conn)
|
||||
require.NoError(t, err, "a later turn must also queue for its slot on the same connection")
|
||||
require.Equal(t, "response.completed", gjson.GetBytes(event, "type").String())
|
||||
require.Equal(t, "resp_slot_wait_2", gjson.GetBytes(event, "response.id").String())
|
||||
|
||||
require.Equal(t, int32(2), upstreamMessages.Load())
|
||||
}
|
||||
|
||||
func TestOpenAIResponsesWebSocket_ClosesWhenUserSlotWaitTimesOut(t *testing.T) {
|
||||
previousWait := openAIWSUserSlotWait
|
||||
openAIWSUserSlotWait = 300 * time.Millisecond
|
||||
t.Cleanup(func() { openAIWSUserSlotWait = previousWait })
|
||||
|
||||
url, upstreamMessages := newOpenAIWSUserSlotTestServer(t, func(int32) bool { return false })
|
||||
conn := dialOpenAIWSUserSlotTestClient(t, url)
|
||||
|
||||
writeOpenAIWSUserSlotTestMessage(t, conn, `{"type":"response.create","model":"gpt-5.1","input":[{"role":"user","content":"first"}]}`)
|
||||
_, err := readOpenAIWSUserSlotTestEvent(conn)
|
||||
require.Equal(t, coderws.StatusTryAgainLater, coderws.CloseStatus(err), "got %v", err)
|
||||
require.ErrorContains(t, err, "too many concurrent requests")
|
||||
require.Zero(t, upstreamMessages.Load(), "a turn without a user slot must not reach the upstream")
|
||||
}
|
||||
@@ -235,6 +235,9 @@ func (h *OpenAIGatewayHandler) Images(c *gin.Context) {
|
||||
)
|
||||
|
||||
account := selection.Account
|
||||
if rejectSelectedAccountIfModerated(c, account.ID, selectionReleaseFunc(selection), h.openAISecurityAuditError) {
|
||||
return
|
||||
}
|
||||
sessionHash = ensureOpenAIPoolModeSessionHash(sessionHash, account)
|
||||
reqLog.Debug("openai.images.account_selected", zap.Int64("account_id", account.ID), zap.String("account_name", account.Name))
|
||||
setOpsSelectedAccount(c, account.ID, account.Platform)
|
||||
@@ -330,13 +333,14 @@ func (h *OpenAIGatewayHandler) Images(c *gin.Context) {
|
||||
if sameAccountRetryAllowed(failoverErr, sameAccountRetryCount[account.ID], retryLimit) {
|
||||
sameAccountRetryCount[account.ID]++
|
||||
retryDelay := sameAccountRetryDelayFor(failoverErr, sameAccountRetryCount[account.ID])
|
||||
reqLog.Warn("openai.images.pool_mode_same_account_retry",
|
||||
retryFields := appendUpstreamRetryAfterField([]zap.Field{
|
||||
zap.Int64("account_id", account.ID),
|
||||
zap.Int("upstream_status", failoverErr.StatusCode),
|
||||
zap.Int("retry_limit", retryLimit),
|
||||
zap.Int("retry_count", sameAccountRetryCount[account.ID]),
|
||||
zap.Duration("retry_delay", retryDelay),
|
||||
)
|
||||
}, failoverErr)
|
||||
reqLog.Warn("openai.images.pool_mode_same_account_retry", retryFields...)
|
||||
select {
|
||||
case <-requestCtx.Done():
|
||||
return
|
||||
@@ -357,12 +361,13 @@ func (h *OpenAIGatewayHandler) Images(c *gin.Context) {
|
||||
h.handleFailoverExhausted(c, failoverErr, streamStarted)
|
||||
return
|
||||
}
|
||||
reqLog.Warn("openai.images.upstream_failover_switching",
|
||||
switchFields := appendUpstreamRetryAfterField([]zap.Field{
|
||||
zap.Int64("account_id", account.ID),
|
||||
zap.Int("upstream_status", failoverErr.StatusCode),
|
||||
zap.Int("switch_count", switchCount),
|
||||
zap.Int("max_switches", maxAccountSwitches),
|
||||
)
|
||||
}, failoverErr)
|
||||
reqLog.Warn("openai.images.upstream_failover_switching", switchFields...)
|
||||
continue
|
||||
}
|
||||
h.gatewayService.ReportOpenAIAccountScheduleResult(account, openAIAccountScheduleModel(c, account, requestModel, false, result), false, nil, err)
|
||||
|
||||
@@ -26,7 +26,10 @@ func TestOpenAIImagesBalanceExhaustionPreservesMachineReadableCause(t *testing.T
|
||||
ClientMessage: service.OpenAIImagesInsufficientBalanceMessage,
|
||||
ResponseHeaders: http.Header{"Retry-After": []string{"23"}, "X-Request-Id": []string{"req-images-balance"}},
|
||||
}, streamStarted)
|
||||
require.Equal(t, "23", recorder.Header().Get("Retry-After"))
|
||||
// A Retry-After on a non-rate-limit upstream failure (502 mapped to 402
|
||||
// here) is intentionally not forwarded: only explicit upstream 429 rate
|
||||
// limits carry a usable cooldown (#8560, #8938).
|
||||
require.Empty(t, recorder.Header().Get("Retry-After"))
|
||||
|
||||
if streamStarted {
|
||||
require.Contains(t, recorder.Body.String(), `"code":"insufficient_balance"`)
|
||||
|
||||
@@ -113,8 +113,19 @@ func (h *OpenAIGatewayHandler) Live(c *gin.Context) {
|
||||
defer userRelease()
|
||||
|
||||
identity := liveCallIdentity(c, apiKey, subject.UserID, subscription)
|
||||
created, err := h.gatewayService.CreateLiveCall(c.Request.Context(), request, identity, subject.Concurrency)
|
||||
liveCtx := service.WithAccountModerationHook(c.Request.Context(), func(accountID int64) error {
|
||||
if d := checkSelectedAccountModeration(c, accountID); d != nil && !d.AllowNextStage {
|
||||
return &accountModerationBlockedError{decision: d}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
created, err := h.gatewayService.CreateLiveCall(liveCtx, request, identity, subject.Concurrency)
|
||||
if err != nil {
|
||||
var modBlocked *accountModerationBlockedError
|
||||
if errors.As(err, &modBlocked) && modBlocked.decision != nil {
|
||||
h.openAISecurityAuditError(c, modBlocked.decision)
|
||||
return
|
||||
}
|
||||
h.writeLiveCreateError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -7,17 +7,33 @@ import (
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
)
|
||||
|
||||
var codexSelectedPageName = regexp.MustCompile(`^codex_apps_selected_page_part_([1-9][0-9]*)_of_([1-9][0-9]*)$`)
|
||||
|
||||
// codexContextTagName is the shape of the context names Codex derives from
|
||||
// its context keys; only such names are safe to embed in a tag.
|
||||
var codexContextTagName = regexp.MustCompile(`^[A-Za-z0-9_]{1,128}$`)
|
||||
|
||||
// mayContainCodexAgentContext is the cheap gate for agent context outputs.
|
||||
// Names are not enumerated: Codex keeps adding context tools, and any agent
|
||||
// namespace output without a call_id is injected context, not a tool result.
|
||||
// The type and namespace are JSON strings, which appear literally unless a
|
||||
// \u escape spells their letters; without either the body cannot match.
|
||||
func mayContainCodexAgentContext(body []byte) bool {
|
||||
if !service.JSONMayEscapePlainASCII(body) &&
|
||||
(!bytes.Contains(body, []byte("function_call_output")) || !bytes.Contains(body, []byte("agent"))) {
|
||||
return false
|
||||
}
|
||||
return service.ResponsesInputHasAgentFunctionCallOutput(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", "terminal_info", "goal_objective", "untrusted_context", "untrusted_content", "ide_context", "proposed_plan",
|
||||
) || !hasUniqueJSONMembers(body) {
|
||||
if !mayContainCodexAgentContext(body) || !hasUniqueJSONMembers(body) {
|
||||
return body, false
|
||||
}
|
||||
var request map[string]json.RawMessage
|
||||
@@ -50,12 +66,12 @@ func normalizeCodexUntrustedContext(body []byte) ([]byte, bool) {
|
||||
}
|
||||
name := readString("name")
|
||||
var output *string
|
||||
if json.Unmarshal(item["output"], &output) != nil || output == nil || !validCodexUntrustedContext(name, *output) {
|
||||
if json.Unmarshal(item["output"], &output) != nil || output == nil {
|
||||
continue
|
||||
}
|
||||
text := "<external_" + name + ">" + *output + "</external_" + name + ">"
|
||||
if validCodexPageContext(name, *output) {
|
||||
text = "<external_" + name + ">\n" + *output + "\n</external_" + name + ">"
|
||||
text, ok := codexUntrustedContextText(name, *output)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
message := map[string]any{
|
||||
"type": "message",
|
||||
@@ -87,9 +103,42 @@ func normalizeCodexUntrustedContext(body []byte) ([]byte, bool) {
|
||||
return encoded, true
|
||||
}
|
||||
|
||||
// codexUntrustedContextText renders an agent context output as user text.
|
||||
// Known context names keep their existing tags and format checks. Any other
|
||||
// name is still context when it comes from the agent namespace, so it is
|
||||
// rendered the way Codex renders context when it does not send it as a tool
|
||||
// output: <external_{name}>. The name is client supplied, so it is only used
|
||||
// as a tag when it has the shape Codex derives names in; anything else falls
|
||||
// back to a generic tag.
|
||||
func codexUntrustedContextText(name, output string) (string, bool) {
|
||||
if !knownCodexUntrustedContextName(name) {
|
||||
tag := "agent_context"
|
||||
if codexContextTagName.MatchString(name) {
|
||||
tag = name
|
||||
}
|
||||
return "<external_" + tag + ">" + output + "</external_" + tag + ">", true
|
||||
}
|
||||
if !validCodexUntrustedContext(name, output) {
|
||||
return "", false
|
||||
}
|
||||
text := "<external_" + name + ">" + output + "</external_" + name + ">"
|
||||
if validCodexPageContext(name, output) {
|
||||
text = "<external_" + name + ">\n" + output + "\n</external_" + name + ">"
|
||||
}
|
||||
return text, true
|
||||
}
|
||||
|
||||
func knownCodexUntrustedContextName(name string) bool {
|
||||
switch name {
|
||||
case "codex_apps_open_page", "browser_info", "browser_tabs", "terminal_info", "goal_objective", "untrusted_context", "untrusted_content", "ide_context", "proposed_plan":
|
||||
return true
|
||||
}
|
||||
return codexSelectedPageName.MatchString(name)
|
||||
}
|
||||
|
||||
func validCodexUntrustedContext(name, output string) bool {
|
||||
switch name {
|
||||
case "browser_info", "terminal_info", "goal_objective", "untrusted_context", "ide_context":
|
||||
case "browser_info", "browser_tabs", "terminal_info", "goal_objective", "untrusted_context", "ide_context":
|
||||
return strings.TrimSpace(output) != ""
|
||||
case "untrusted_content":
|
||||
// Codex's fallback for an unnamed context source can carry any text, including an empty value.
|
||||
|
||||
@@ -3,6 +3,7 @@ package handler
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
@@ -54,7 +55,7 @@ func TestNormalizeCodexPageContextFirstMessage(t *testing.T) {
|
||||
require.Equal(t, got, again)
|
||||
}
|
||||
|
||||
var codexTextContextNamesForTest = []string{"browser_info", "terminal_info", "goal_objective", "untrusted_context", "untrusted_content", "ide_context", "proposed_plan"}
|
||||
var codexTextContextNamesForTest = []string{"browser_info", "browser_tabs", "terminal_info", "goal_objective", "untrusted_context", "untrusted_content", "ide_context", "proposed_plan"}
|
||||
|
||||
func TestNormalizeCodexTerminalInfoIssue8991(t *testing.T) {
|
||||
body := []byte(`{"model":"deepseek-flash","input":[{"type":"function_call_output","namespace":"agent","name":"terminal_info","output":"retest context"}]}`)
|
||||
@@ -89,9 +90,6 @@ func TestNormalizeCodexTerminalInfoBoundaries(t *testing.T) {
|
||||
{"boolean output", "output", false},
|
||||
{"numeric output", "output", 42},
|
||||
{"object output", "output", map[string]any{"text": "context"}},
|
||||
{"name prefix", "name", "terminal_info_extra"},
|
||||
{"name case", "name", "Terminal_info"},
|
||||
{"unknown context", "name", "arbitrary_context"},
|
||||
{"other type", "type", "custom_tool_call_output"},
|
||||
} {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
@@ -126,7 +124,7 @@ func TestNormalizeCodexTerminalInfoPreservesUnrelatedResults(t *testing.T) {
|
||||
body := pageContextRequest(t,
|
||||
pageContextItem("terminal_info", "retest context"),
|
||||
map[string]any{"type": "function_call_output", "namespace": "agent", "name": "terminal_info", "call_id": "call_real", "output": "real result"},
|
||||
pageContextItem("read_file", "unrelated result"))
|
||||
map[string]any{"type": "function_call_output", "name": "read_file", "output": "unrelated result"})
|
||||
got, changed := normalizeCodexUntrustedContext(body)
|
||||
require.True(t, changed)
|
||||
require.Equal(t, "message", gjson.GetBytes(got, "input.0.type").String())
|
||||
@@ -141,6 +139,103 @@ func TestNormalizeCodexTerminalInfoPreservesUnrelatedResults(t *testing.T) {
|
||||
require.Contains(t, w.Body.String(), "function_call_output requires call_id")
|
||||
}
|
||||
|
||||
func TestNormalizeCodexAgentContextUnknownNames(t *testing.T) {
|
||||
const browserTabs = `{"tabs":[{"title":"Example","url":"https://example.com"}]}`
|
||||
longName := strings.Repeat("a", 129)
|
||||
body := pageContextRequest(t,
|
||||
map[string]any{"type": "function_call_output", "namespace": "agent", "name": "browser_tabs", "output": browserTabs},
|
||||
map[string]any{"type": "function_call_output", "namespace": "agent", "name": "some_new_context", "output": "new context"},
|
||||
map[string]any{"type": "function_call_output", "namespace": "agent", "name": "terminal_info_extra", "output": "suffix name"},
|
||||
map[string]any{"type": "function_call_output", "namespace": "agent", "name": "Terminal_info", "output": "case name"},
|
||||
map[string]any{"type": "function_call_output", "namespace": "agent", "name": "bad>name</x", "output": "unsafe name"},
|
||||
map[string]any{"type": "function_call_output", "namespace": "agent", "output": "missing name"},
|
||||
map[string]any{"type": "function_call_output", "namespace": "agent", "name": longName, "output": ""},
|
||||
map[string]any{"role": "user", "content": "hello"},
|
||||
)
|
||||
h := &OpenAIGatewayHandler{}
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
require.False(t, h.validateFunctionCallOutputRequest(c, body, zap.NewNop()))
|
||||
require.Equal(t, 400, w.Code)
|
||||
require.Contains(t, w.Body.String(), "function_call_output requires call_id")
|
||||
|
||||
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())
|
||||
for i, want := range []struct{ tag, output string }{
|
||||
{"browser_tabs", browserTabs},
|
||||
{"some_new_context", "new context"},
|
||||
{"terminal_info_extra", "suffix name"},
|
||||
{"Terminal_info", "case name"},
|
||||
{"agent_context", "unsafe name"},
|
||||
{"agent_context", "missing name"},
|
||||
{"agent_context", ""},
|
||||
} {
|
||||
item := gjson.GetBytes(got, "input").Array()[i]
|
||||
require.Equal(t, "message", item.Get("type").String())
|
||||
require.Equal(t, "user", item.Get("role").String())
|
||||
require.Equal(t, "<external_"+want.tag+">"+want.output+"</external_"+want.tag+">", item.Get("content.0.text").String())
|
||||
require.False(t, item.Get("call_id").Exists())
|
||||
require.False(t, item.Get("id").Exists())
|
||||
}
|
||||
require.Equal(t, "hello", gjson.GetBytes(got, "input.7.content").String())
|
||||
again, changed := normalizeCodexUntrustedContext(got)
|
||||
require.False(t, changed)
|
||||
require.Equal(t, got, again)
|
||||
}
|
||||
|
||||
func TestNormalizeCodexAgentContextEscapedAndBlankCallID(t *testing.T) {
|
||||
for _, body := range []string{
|
||||
`{"input":[{"type":"function_call_output","namespace":"\u0061gent","name":"browser_tabs","output":"tabs"}]}`,
|
||||
`{"input":[{"type":"function_call_output","namespace":"agent","name":"browser_tabs","call_id":" ","output":"tabs"}]}`,
|
||||
} {
|
||||
got, changed := normalizeCodexUntrustedContext([]byte(body))
|
||||
require.True(t, changed)
|
||||
require.Equal(t, "<external_browser_tabs>tabs</external_browser_tabs>", gjson.GetBytes(got, "input.0.content.0.text").String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeCodexAgentContextKeepsToolOutputsRejected(t *testing.T) {
|
||||
for _, testCase := range []struct {
|
||||
name string
|
||||
item map[string]any
|
||||
}{
|
||||
{"no namespace", map[string]any{"type": "function_call_output", "name": "read_file", "output": "file body"}},
|
||||
{"other namespace", map[string]any{"type": "function_call_output", "namespace": "codex_app", "name": "read_file", "output": "file body"}},
|
||||
{"non-string output", map[string]any{"type": "function_call_output", "namespace": "agent", "name": "browser_tabs", "output": []any{map[string]any{"url": "https://example.com"}}}},
|
||||
} {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
body := pageContextRequest(t, testCase.item)
|
||||
got, changed := normalizeCodexUntrustedContext(body)
|
||||
require.False(t, changed)
|
||||
require.Equal(t, body, got)
|
||||
h := &OpenAIGatewayHandler{}
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
require.False(t, h.validateFunctionCallOutputRequest(c, body, zap.NewNop()))
|
||||
require.Equal(t, 400, w.Code)
|
||||
require.Contains(t, w.Body.String(), "function_call_output requires call_id")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeCodexAgentContextLeavesCallIDItems(t *testing.T) {
|
||||
body := []byte(`{"model":"gpt-5","input":[{"type":"function_call_output","namespace":"agent","name":"browser_tabs","call_id":"call_real","output":"tabs"}]}`)
|
||||
got, changed := normalizeCodexUntrustedContext(body)
|
||||
require.False(t, changed)
|
||||
require.Equal(t, body, got)
|
||||
// Items with a call_id keep the original validation path.
|
||||
h := &OpenAIGatewayHandler{}
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
require.False(t, h.validateFunctionCallOutputRequest(c, body, zap.NewNop()))
|
||||
require.Equal(t, 400, w.Code)
|
||||
require.Contains(t, w.Body.String(), "item_reference")
|
||||
}
|
||||
|
||||
func TestNormalizeCodexAdditionalUntrustedContext(t *testing.T) {
|
||||
for _, name := range codexTextContextNamesForTest {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
@@ -209,7 +304,7 @@ func TestNormalizeCodexAdditionalUntrustedContextPreservesRealAndMalformedOutput
|
||||
}
|
||||
// Recognized external context cannot make an unrelated tool result valid.
|
||||
body := pageContextRequest(t, pageContextItem("browser_info", "tab"),
|
||||
pageContextItem("read_file", "result"))
|
||||
map[string]any{"type": "function_call_output", "name": "read_file", "output": "result"})
|
||||
got, changed := normalizeCodexUntrustedContext(body)
|
||||
require.True(t, changed)
|
||||
h := &OpenAIGatewayHandler{}
|
||||
@@ -304,7 +399,7 @@ func TestNormalizeCodexPageContextPreservesHistoryAndToolValidation(t *testing.T
|
||||
require.JSONEq(t, gjson.GetBytes(body, index).Raw, gjson.GetBytes(got, index).Raw)
|
||||
}
|
||||
|
||||
badTool := pageContextItem("read_file", "result")
|
||||
badTool := map[string]any{"type": "function_call_output", "name": "read_file", "output": "result"}
|
||||
body = pageContextRequest(t, pageContextItem("codex_apps_open_page", `{"page_id":null}`), badTool)
|
||||
got, changed = normalizeCodexUntrustedContext(body)
|
||||
require.True(t, changed)
|
||||
@@ -346,7 +441,6 @@ func TestNormalizeCodexPageContextRejectsUnrelatedOrMalformedItems(t *testing.T)
|
||||
{"null call id", "call_id", nil},
|
||||
{"other namespace", "namespace", "codex_app"},
|
||||
{"missing namespace", "namespace", ""},
|
||||
{"other tool", "name", "read_file"},
|
||||
{"other type", "type", "custom_tool_call_output"},
|
||||
{"not JSON", "output", "some text"},
|
||||
{"not snapshot", "output", `{"other":null}`},
|
||||
@@ -373,3 +467,62 @@ func TestNormalizeCodexPageContextRejectsUnrelatedOrMalformedItems(t *testing.T)
|
||||
require.Equal(t, body, string(got))
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeCodexBrowserTabs(t *testing.T) {
|
||||
// Shape sent by the Codex desktop in-app browser: an agent-namespace output
|
||||
// with an item id but no call_id, followed by the user's question.
|
||||
tabs := "<in-app-browser-context source=\"ambient-ui-state\">\nTab 1 (active): https://example.com/\nTab 2: https://example.org/\n</in-app-browser-context>"
|
||||
body := pageContextRequest(t,
|
||||
map[string]any{"type": "function_call_output", "id": "fco_123", "namespace": "agent", "name": "browser_tabs", "output": tabs},
|
||||
map[string]any{"type": "message", "role": "user", "content": []any{map[string]any{"type": "input_text", "text": "How many tabs are open?"}}})
|
||||
h := &OpenAIGatewayHandler{}
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
require.False(t, h.validateFunctionCallOutputRequest(c, body, zap.NewNop()))
|
||||
require.Equal(t, 400, w.Code)
|
||||
|
||||
got, changed := normalizeCodexUntrustedContext(body)
|
||||
require.True(t, changed)
|
||||
require.Equal(t, "message", gjson.GetBytes(got, "input.0.type").String())
|
||||
require.Equal(t, "user", gjson.GetBytes(got, "input.0.role").String())
|
||||
require.Equal(t, "<external_browser_tabs>"+tabs+"</external_browser_tabs>", gjson.GetBytes(got, "input.0.content.0.text").String())
|
||||
require.JSONEq(t, gjson.GetBytes(body, "input.1").Raw, gjson.GetBytes(got, "input.1").Raw)
|
||||
w = httptest.NewRecorder()
|
||||
c, _ = gin.CreateTestContext(w)
|
||||
require.True(t, h.validateFunctionCallOutputRequest(c, got, zap.NewNop()))
|
||||
require.False(t, c.Writer.Written())
|
||||
}
|
||||
|
||||
func TestNormalizeCodexBrowserTabsBoundaries(t *testing.T) {
|
||||
for _, testCase := range []struct {
|
||||
name string
|
||||
key string
|
||||
value any
|
||||
}{
|
||||
{"real call id", "call_id", "call_real"},
|
||||
{"other namespace", "namespace", "browser"},
|
||||
{"empty output", "output", ""},
|
||||
{"blank output", "output", " \n\t"},
|
||||
{"object output", "output", map[string]any{"tabs": 2}},
|
||||
} {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
item := pageContextItem("browser_tabs", "Tab 1: https://example.com/")
|
||||
item[testCase.key] = testCase.value
|
||||
body := pageContextRequest(t, item)
|
||||
got, changed := normalizeCodexUntrustedContext(body)
|
||||
require.False(t, changed)
|
||||
require.Equal(t, body, got)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeCodexBrowserTabsNameVariantsUseOwnTag(t *testing.T) {
|
||||
for _, name := range []string{"browser_tabs_extra", "Browser_tabs"} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
body := pageContextRequest(t, pageContextItem(name, "Tab 1: https://example.com/"))
|
||||
got, changed := normalizeCodexUntrustedContext(body)
|
||||
require.True(t, changed)
|
||||
require.Equal(t, "<external_"+name+">Tab 1: https://example.com/</external_"+name+">", gjson.GetBytes(got, "input.0.content.0.text").String())
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestParseOpenAIResponsesIngressFields(t *testing.T) {
|
||||
body := []byte(`{
|
||||
"model": "gpt-6.2-astra",
|
||||
"stream": true,
|
||||
"service_tier": "fast",
|
||||
"previous_response_id": " resp_abc ",
|
||||
"reasoning": {"effort": " medium "},
|
||||
"reasoning_effort": " high ",
|
||||
"output_config": {"effort": " low "}
|
||||
}`)
|
||||
fields := parseOpenAIResponsesIngressFields(body)
|
||||
require.True(t, fields.ModelValid)
|
||||
require.Equal(t, "gpt-6.2-astra", fields.Model)
|
||||
require.True(t, fields.StreamValid)
|
||||
require.True(t, fields.Stream)
|
||||
require.Equal(t, "resp_abc", fields.PreviousResponseID)
|
||||
require.Equal(t, "medium", fields.ReasoningEffort)
|
||||
require.Equal(t, "high", fields.ReasoningEffortTop)
|
||||
require.Equal(t, "low", fields.OutputConfigEffort)
|
||||
|
||||
tier, err := service.ValidateOpenAIServiceTierResult(fields.ServiceTier)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "priority", tier)
|
||||
|
||||
// Invalid stream type.
|
||||
badStream := parseOpenAIResponsesIngressFields([]byte(`{"model":"gpt-6.2-astra","stream":"true"}`))
|
||||
require.True(t, badStream.ModelValid)
|
||||
require.False(t, badStream.StreamValid)
|
||||
|
||||
// Missing/non-string model.
|
||||
missingModel := parseOpenAIResponsesIngressFields([]byte(`{"stream":false}`))
|
||||
require.False(t, missingModel.ModelValid)
|
||||
require.True(t, missingModel.StreamValid)
|
||||
require.False(t, missingModel.Stream)
|
||||
|
||||
// Escaped keys.
|
||||
escaped := parseOpenAIResponsesIngressFields([]byte(`{"\u006dodel":"gpt-6.2-astra","\u0073tream":true,"service_tier":"invalid"}`))
|
||||
require.True(t, escaped.ModelValid)
|
||||
require.Equal(t, "gpt-6.2-astra", escaped.Model)
|
||||
require.True(t, escaped.StreamValid)
|
||||
require.True(t, escaped.Stream)
|
||||
_, err = service.ValidateOpenAIServiceTierResult(escaped.ServiceTier)
|
||||
require.Error(t, err)
|
||||
|
||||
// Non-object root.
|
||||
arr := parseOpenAIResponsesIngressFields([]byte(`[{"model":"x"}]`))
|
||||
require.False(t, arr.ModelValid)
|
||||
require.True(t, arr.StreamValid)
|
||||
|
||||
// Duplicate parent keys keep scanning until nested effort exists.
|
||||
dupParent := parseOpenAIResponsesIngressFields([]byte(`{"model":"gpt-6.2-astra","reasoning":{},"reasoning":{"effort":"xhigh"},"output_config":null,"output_config":{"effort":"low"}}`))
|
||||
require.Equal(t, "xhigh", dupParent.ReasoningEffort)
|
||||
require.Equal(t, "low", dupParent.OutputConfigEffort)
|
||||
}
|
||||
|
||||
func TestRequestMaxOutputTokensSinglePassPriority(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
body string
|
||||
want int
|
||||
}{
|
||||
{
|
||||
name: "max_tokens wins even when last",
|
||||
body: `{"generation_config":{"max_output_tokens":50},"generationConfig":{"maxOutputTokens":40},"max_output_tokens":30,"max_completion_tokens":20,"max_tokens":10}`,
|
||||
want: 10,
|
||||
},
|
||||
{
|
||||
name: "max_completion_tokens wins when max_tokens absent or non-positive",
|
||||
body: `{"max_tokens":0,"max_output_tokens":30,"max_completion_tokens":20}`,
|
||||
want: 20,
|
||||
},
|
||||
{
|
||||
name: "max_output_tokens wins over generationConfig",
|
||||
body: `{"generationConfig":{"maxOutputTokens":40},"max_output_tokens":30}`,
|
||||
want: 30,
|
||||
},
|
||||
{
|
||||
name: "generationConfig camelCase wins over snake_case",
|
||||
body: `{"generation_config":{"max_output_tokens":50},"generationConfig":{"maxOutputTokens":40}}`,
|
||||
want: 40,
|
||||
},
|
||||
{
|
||||
name: "generation_config snake_case fallback",
|
||||
body: `{"generation_config":{"max_output_tokens":50}}`,
|
||||
want: 50,
|
||||
},
|
||||
{
|
||||
name: "absent or non-object returns zero",
|
||||
body: `[{"max_tokens":10}]`,
|
||||
want: 0,
|
||||
},
|
||||
{
|
||||
name: "duplicate parent keys keep scanning for nested maxOutputTokens",
|
||||
body: `{"generationConfig":null,"generationConfig":{"maxOutputTokens":40},"generation_config":{"max_output_tokens":50}}`,
|
||||
want: 40,
|
||||
},
|
||||
{
|
||||
name: "duplicate snake_case parent keys keep scanning for nested max_output_tokens",
|
||||
body: `{"generation_config":{},"generation_config":{"max_output_tokens":55}}`,
|
||||
want: 55,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
require.Equal(t, tc.want, requestMaxOutputTokens([]byte(tc.body)))
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/tlsfingerprint"
|
||||
"github.com/Wei-Shaw/sub2api/internal/server/middleware"
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
coderws "github.com/coder/websocket"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
type wsReplayFailoverUpstream struct {
|
||||
mu sync.Mutex
|
||||
calls map[int64]int
|
||||
bodies map[int64][][]byte
|
||||
}
|
||||
|
||||
func (u *wsReplayFailoverUpstream) Do(req *http.Request, proxyURL string, accountID int64, accountConcurrency int) (*http.Response, error) {
|
||||
u.mu.Lock()
|
||||
defer u.mu.Unlock()
|
||||
body, _ := io.ReadAll(req.Body)
|
||||
u.calls[accountID]++
|
||||
u.bodies[accountID] = append(u.bodies[accountID], body)
|
||||
n := u.calls[accountID]
|
||||
sse := func(id string) *http.Response {
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: http.Header{"Content-Type": []string{"text/event-stream"}},
|
||||
Body: io.NopCloser(strings.NewReader(
|
||||
"data: {\"type\":\"response.completed\",\"response\":{\"id\":\"" + id + "\",\"output\":[{\"id\":\"msg_" + id + "\",\"type\":\"message\",\"role\":\"assistant\",\"content\":[{\"type\":\"output_text\",\"text\":\"ok-" + id + "\"}]}],\"usage\":{\"input_tokens\":1,\"output_tokens\":1}}}\n\n",
|
||||
)),
|
||||
}
|
||||
}
|
||||
if accountID == 9921 {
|
||||
switch n {
|
||||
case 1:
|
||||
return sse("resp_f1_seed"), nil
|
||||
case 2:
|
||||
return sse("resp_f1_turn1"), nil
|
||||
default:
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusTooManyRequests,
|
||||
Header: http.Header{"Content-Type": []string{"application/json"}, "Retry-After": []string{"600"}},
|
||||
Body: io.NopCloser(strings.NewReader(`{"error":{"type":"usage_limit_reached","message":"The usage limit has been reached"}}`)),
|
||||
}, nil
|
||||
}
|
||||
}
|
||||
return sse("resp_f1_replayed"), nil
|
||||
}
|
||||
|
||||
func (u *wsReplayFailoverUpstream) DoWithTLS(req *http.Request, proxyURL string, accountID int64, accountConcurrency int, profile *tlsfingerprint.Profile) (*http.Response, error) {
|
||||
return u.Do(req, proxyURL, accountID, accountConcurrency)
|
||||
}
|
||||
|
||||
func TestOpenAIResponsesWebSocket_CurrentTurnReplayAfterContinuationIsNotRejected(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
upstream := &wsReplayFailoverUpstream{calls: map[int64]int{}, bodies: map[int64][][]byte{}}
|
||||
|
||||
groupID := int64(4291)
|
||||
accounts := []service.Account{
|
||||
{
|
||||
ID: 9921, Name: "f1-apikey", Platform: service.PlatformOpenAI, Type: service.AccountTypeAPIKey,
|
||||
Status: service.StatusActive, Schedulable: true, Concurrency: 2, Priority: 0,
|
||||
Credentials: map[string]any{"api_key": "sk-a", "base_url": "http://127.0.0.1:1"},
|
||||
Extra: map[string]any{
|
||||
"openai_apikey_responses_websockets_v2_enabled": true,
|
||||
"openai_apikey_responses_websockets_v2_mode": service.OpenAIWSIngressModeHTTPBridge,
|
||||
},
|
||||
},
|
||||
{
|
||||
ID: 9922, Name: "f1-oauth", Platform: service.PlatformOpenAI, Type: service.AccountTypeOAuth,
|
||||
Status: service.StatusActive, Schedulable: true, Concurrency: 2, Priority: 5,
|
||||
Credentials: map[string]any{"access_token": "tok", "chatgpt_account_id": "acct"},
|
||||
Extra: map[string]any{
|
||||
"openai_oauth_responses_websockets_v2_enabled": true,
|
||||
"openai_oauth_responses_websockets_v2_mode": service.OpenAIWSIngressModeHTTPBridge,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
cfg := &config.Config{}
|
||||
cfg.RunMode = config.RunModeSimple
|
||||
cfg.Default.RateMultiplier = 1
|
||||
cfg.Security.URLAllowlist.Enabled = false
|
||||
cfg.Security.URLAllowlist.AllowInsecureHTTP = true
|
||||
cfg.Gateway.OpenAIWS.Enabled = true
|
||||
cfg.Gateway.OpenAIWS.OAuthEnabled = true
|
||||
cfg.Gateway.OpenAIWS.APIKeyEnabled = true
|
||||
cfg.Gateway.OpenAIWS.ResponsesWebsocketsV2 = true
|
||||
cfg.Gateway.OpenAIWS.ModeRouterV2Enabled = true
|
||||
cfg.Gateway.OpenAIWS.DialTimeoutSeconds = 3
|
||||
cfg.Gateway.OpenAIWS.ReadTimeoutSeconds = 3
|
||||
cfg.Gateway.OpenAIWS.WriteTimeoutSeconds = 3
|
||||
cfg.Gateway.MaxAccountSwitches = 2
|
||||
|
||||
accountRepo := &openAIWSFailoverHandlerAccountRepoStub{accounts: accounts}
|
||||
rateLimitSvc := service.NewRateLimitService(accountRepo, nil, cfg, nil, nil)
|
||||
billingCacheSvc := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil)
|
||||
t.Cleanup(billingCacheSvc.Stop)
|
||||
gatewaySvc := service.NewOpenAIGatewayService(
|
||||
accountRepo, nil, nil, nil, nil, nil, nil, cfg, nil, nil,
|
||||
service.NewBillingService(cfg, nil), rateLimitSvc, billingCacheSvc,
|
||||
upstream, &service.DeferredService{},
|
||||
nil, nil, nil, nil, nil, nil, nil,
|
||||
)
|
||||
cache := &concurrencyCacheMock{
|
||||
acquireUserSlotFn: func(ctx context.Context, userID int64, maxConcurrency int, requestID string) (bool, error) {
|
||||
return true, nil
|
||||
},
|
||||
acquireAccountSlotFn: func(ctx context.Context, accountID int64, maxConcurrency int, requestID string) (bool, error) {
|
||||
return true, nil
|
||||
},
|
||||
}
|
||||
h := &OpenAIGatewayHandler{
|
||||
gatewayService: gatewaySvc,
|
||||
billingCacheService: billingCacheSvc,
|
||||
apiKeyService: &service.APIKeyService{},
|
||||
concurrencyHelper: NewConcurrencyHelper(service.NewConcurrencyService(cache), SSEPingFormatNone, time.Second),
|
||||
maxAccountSwitches: 2,
|
||||
}
|
||||
apiKey := &service.APIKey{
|
||||
ID: 1891, GroupID: &groupID,
|
||||
User: &service.User{ID: 1791, Status: service.StatusActive},
|
||||
Group: &service.Group{ID: groupID, Platform: service.PlatformOpenAI, Status: service.StatusActive},
|
||||
}
|
||||
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})
|
||||
c.Next()
|
||||
})
|
||||
router.GET("/openai/v1/responses", h.ResponsesWebSocket)
|
||||
srv := httptest.NewServer(router)
|
||||
defer srv.Close()
|
||||
wsURL := "ws" + strings.TrimPrefix(srv.URL, "http") + "/openai/v1/responses"
|
||||
|
||||
dial := func() *coderws.Conn {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
defer cancel()
|
||||
c, _, err := coderws.Dial(ctx, wsURL, nil)
|
||||
require.NoError(t, err)
|
||||
return c
|
||||
}
|
||||
write := func(c *coderws.Conn, s string) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
defer cancel()
|
||||
require.NoError(t, c.Write(ctx, coderws.MessageText, []byte(s)))
|
||||
}
|
||||
readUntilTerminal := func(c *coderws.Conn) ([]byte, error) {
|
||||
for {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
_, msg, err := c.Read(ctx)
|
||||
cancel()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
switch gjson.GetBytes(msg, "type").String() {
|
||||
case "response.completed", "error", "response.failed":
|
||||
return msg, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Seed connection binds resp_f1_seed to the API-key account 9921.
|
||||
c1 := dial()
|
||||
write(c1, `{"type":"response.create","model":"gpt-5.1","input":[{"type":"message","role":"user","content":"seed"}]}`)
|
||||
msg, err := readUntilTerminal(c1)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "resp_f1_seed", gjson.GetBytes(msg, "response.id").String(), string(msg))
|
||||
require.NoError(t, c1.Close(coderws.StatusNormalClosure, "done"))
|
||||
|
||||
// Continuation connection: first frame continues resp_f1_seed (sticky hit 9921).
|
||||
c2 := dial()
|
||||
defer func() { _ = c2.CloseNow() }()
|
||||
write(c2, `{"type":"response.create","model":"gpt-5.1","previous_response_id":"resp_f1_seed","input":[{"type":"message","role":"user","content":"turn1"}]}`)
|
||||
msg, err = readUntilTerminal(c2)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "resp_f1_turn1", gjson.GetBytes(msg, "response.id").String(), string(msg))
|
||||
|
||||
// Turn 2 fails on 9921 with 429 -> current-turn failover replay on 9922.
|
||||
write(c2, `{"type":"response.create","model":"gpt-5.1","previous_response_id":"resp_f1_turn1","input":[{"type":"message","role":"user","content":"turn2"}]}`)
|
||||
msg, err = readUntilTerminal(c2)
|
||||
require.NoError(t, err, "connection closed instead of replaying on replacement account")
|
||||
require.Equal(t, "response.completed", gjson.GetBytes(msg, "type").String(), string(msg))
|
||||
require.Equal(t, "resp_f1_replayed", gjson.GetBytes(msg, "response.id").String())
|
||||
|
||||
upstream.mu.Lock()
|
||||
defer upstream.mu.Unlock()
|
||||
require.Len(t, upstream.bodies[9922], 1)
|
||||
require.False(t, gjson.GetBytes(upstream.bodies[9922][0], "previous_response_id").Exists())
|
||||
}
|
||||
@@ -0,0 +1,336 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
"github.com/Wei-Shaw/sub2api/internal/server/middleware"
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
coderws "github.com/coder/websocket"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
func TestOpenAIResponsesWebSocket_FirstFrameStickyMissFailsLoudlyWithPreviousResponseNotFound(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
var upstreamHits atomic.Int32
|
||||
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
upstreamHits.Add(1)
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
}))
|
||||
defer upstream.Close()
|
||||
|
||||
groupID := int64(4211)
|
||||
accounts := []service.Account{
|
||||
{
|
||||
ID: 9911,
|
||||
Name: "openai-ws-sticky-miss-acct",
|
||||
Platform: service.PlatformOpenAI,
|
||||
Type: service.AccountTypeAPIKey,
|
||||
Status: service.StatusActive,
|
||||
Schedulable: true,
|
||||
Concurrency: 2,
|
||||
Priority: 1,
|
||||
Credentials: map[string]any{
|
||||
"api_key": "sk-first",
|
||||
"base_url": upstream.URL,
|
||||
},
|
||||
Extra: map[string]any{
|
||||
"openai_apikey_responses_websockets_v2_enabled": true,
|
||||
"openai_apikey_responses_websockets_v2_mode": service.OpenAIWSIngressModeCtxPool,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
cfg := &config.Config{}
|
||||
cfg.RunMode = config.RunModeSimple
|
||||
cfg.Default.RateMultiplier = 1
|
||||
cfg.Security.URLAllowlist.Enabled = false
|
||||
cfg.Security.URLAllowlist.AllowInsecureHTTP = true
|
||||
cfg.Gateway.OpenAIWS.Enabled = true
|
||||
cfg.Gateway.OpenAIWS.APIKeyEnabled = true
|
||||
cfg.Gateway.OpenAIWS.ResponsesWebsocketsV2 = true
|
||||
cfg.Gateway.OpenAIWS.ModeRouterV2Enabled = true
|
||||
cfg.Gateway.OpenAIWS.DialTimeoutSeconds = 3
|
||||
cfg.Gateway.OpenAIWS.ReadTimeoutSeconds = 3
|
||||
cfg.Gateway.OpenAIWS.WriteTimeoutSeconds = 3
|
||||
cfg.Gateway.MaxAccountSwitches = 2
|
||||
|
||||
accountRepo := &openAIWSFailoverHandlerAccountRepoStub{accounts: accounts}
|
||||
rateLimitSvc := service.NewRateLimitService(accountRepo, nil, cfg, nil, nil)
|
||||
billingCacheSvc := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil)
|
||||
t.Cleanup(billingCacheSvc.Stop)
|
||||
gatewaySvc := service.NewOpenAIGatewayService(
|
||||
accountRepo,
|
||||
nil, nil, nil, nil, nil, nil,
|
||||
cfg,
|
||||
nil, nil,
|
||||
service.NewBillingService(cfg, nil),
|
||||
rateLimitSvc,
|
||||
billingCacheSvc,
|
||||
nil,
|
||||
&service.DeferredService{},
|
||||
nil, nil, nil, nil, nil, nil, nil,
|
||||
)
|
||||
|
||||
cache := &concurrencyCacheMock{
|
||||
acquireUserSlotFn: func(ctx context.Context, userID int64, maxConcurrency int, requestID string) (bool, error) {
|
||||
return true, nil
|
||||
},
|
||||
acquireAccountSlotFn: func(ctx context.Context, accountID int64, maxConcurrency int, requestID string) (bool, error) {
|
||||
return true, nil
|
||||
},
|
||||
}
|
||||
h := &OpenAIGatewayHandler{
|
||||
gatewayService: gatewaySvc,
|
||||
billingCacheService: billingCacheSvc,
|
||||
apiKeyService: &service.APIKeyService{},
|
||||
concurrencyHelper: NewConcurrencyHelper(service.NewConcurrencyService(cache), SSEPingFormatNone, time.Second),
|
||||
maxAccountSwitches: 2,
|
||||
}
|
||||
|
||||
apiKey := &service.APIKey{
|
||||
ID: 1811,
|
||||
GroupID: &groupID,
|
||||
User: &service.User{ID: 1711, Status: service.StatusActive},
|
||||
Group: &service.Group{ID: groupID, Platform: service.PlatformOpenAI, Status: service.StatusActive},
|
||||
}
|
||||
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})
|
||||
c.Next()
|
||||
})
|
||||
handlerDone := make(chan struct{})
|
||||
router.GET("/openai/v1/responses", func(c *gin.Context) {
|
||||
h.ResponsesWebSocket(c)
|
||||
close(handlerDone)
|
||||
})
|
||||
handlerServer := httptest.NewServer(router)
|
||||
defer handlerServer.Close()
|
||||
|
||||
dialCtx, cancelDial := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
clientConn, _, err := coderws.Dial(
|
||||
dialCtx,
|
||||
"ws"+strings.TrimPrefix(handlerServer.URL, "http")+"/openai/v1/responses",
|
||||
&coderws.DialOptions{CompressionMode: coderws.CompressionContextTakeover},
|
||||
)
|
||||
cancelDial()
|
||||
require.NoError(t, err)
|
||||
defer func() { _ = clientConn.CloseNow() }()
|
||||
|
||||
writeCtx, cancelWrite := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
err = clientConn.Write(writeCtx, coderws.MessageText, []byte(
|
||||
`{"type":"response.create","model":"gpt-5.1","previous_response_id":"resp_expired_or_unknown_1","input":[{"type":"message","role":"user","content":"What was the marker?"}]}`,
|
||||
))
|
||||
cancelWrite()
|
||||
require.NoError(t, err)
|
||||
|
||||
readCtx, cancelRead := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
msgType, rawEvent, err := clientConn.Read(readCtx)
|
||||
cancelRead()
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, coderws.MessageText, msgType)
|
||||
require.Equal(t, "error", gjson.GetBytes(rawEvent, "type").String())
|
||||
require.Equal(t, "invalid_request_error", gjson.GetBytes(rawEvent, "error.type").String())
|
||||
require.Equal(t, "previous_response_not_found", gjson.GetBytes(rawEvent, "error.code").String())
|
||||
|
||||
readCloseCtx, cancelReadClose := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
_, _, closeReadErr := clientConn.Read(readCloseCtx)
|
||||
cancelReadClose()
|
||||
require.Error(t, closeReadErr)
|
||||
var closeErr coderws.CloseError
|
||||
require.ErrorAs(t, closeReadErr, &closeErr)
|
||||
require.Equal(t, coderws.StatusPolicyViolation, closeErr.Code)
|
||||
require.Equal(t, "previous_response_not_found", closeErr.Reason)
|
||||
|
||||
select {
|
||||
case <-handlerDone:
|
||||
case <-time.After(3 * time.Second):
|
||||
t.Fatal("handler did not finish after sticky-miss previous_response_not_found")
|
||||
}
|
||||
|
||||
require.Equal(t, int32(0), upstreamHits.Load(), "sticky-miss delta must never strip previous_response_id and hit upstream")
|
||||
}
|
||||
|
||||
func TestOpenAIResponsesWebSocket_FirstFrameStickyHitContinuesWithPreviousResponseID(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
receivedCh := make(chan []byte, 4)
|
||||
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
conn, err := coderws.Accept(w, r, &coderws.AcceptOptions{CompressionMode: coderws.CompressionContextTakeover})
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer func() { _ = conn.CloseNow() }()
|
||||
|
||||
for i := 0; i < 2; i++ {
|
||||
readCtx, cancelRead := context.WithTimeout(r.Context(), 3*time.Second)
|
||||
_, payload, readErr := conn.Read(readCtx)
|
||||
cancelRead()
|
||||
if readErr != nil {
|
||||
return
|
||||
}
|
||||
receivedCh <- append([]byte(nil), payload...)
|
||||
respID := "resp_ws_sticky_turn_1"
|
||||
if i == 1 {
|
||||
respID = "resp_ws_sticky_turn_2"
|
||||
}
|
||||
writeCtx, cancelWrite := context.WithTimeout(r.Context(), 3*time.Second)
|
||||
_ = conn.Write(writeCtx, coderws.MessageText, []byte(`{"type":"response.completed","response":{"id":"`+respID+`","model":"gpt-5.1","usage":{"input_tokens":5,"output_tokens":2}}}`))
|
||||
cancelWrite()
|
||||
}
|
||||
}))
|
||||
defer upstream.Close()
|
||||
|
||||
groupID := int64(4212)
|
||||
accounts := []service.Account{
|
||||
{
|
||||
ID: 9912,
|
||||
Name: "openai-ws-sticky-hit-acct",
|
||||
Platform: service.PlatformOpenAI,
|
||||
Type: service.AccountTypeAPIKey,
|
||||
Status: service.StatusActive,
|
||||
Schedulable: true,
|
||||
Concurrency: 2,
|
||||
Priority: 1,
|
||||
Credentials: map[string]any{
|
||||
"api_key": "sk-first",
|
||||
"base_url": upstream.URL,
|
||||
},
|
||||
Extra: map[string]any{
|
||||
"openai_apikey_responses_websockets_v2_enabled": true,
|
||||
"openai_apikey_responses_websockets_v2_mode": service.OpenAIWSIngressModeCtxPool,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
cfg := &config.Config{}
|
||||
cfg.RunMode = config.RunModeSimple
|
||||
cfg.Default.RateMultiplier = 1
|
||||
cfg.Security.URLAllowlist.Enabled = false
|
||||
cfg.Security.URLAllowlist.AllowInsecureHTTP = true
|
||||
cfg.Gateway.OpenAIWS.Enabled = true
|
||||
cfg.Gateway.OpenAIWS.APIKeyEnabled = true
|
||||
cfg.Gateway.OpenAIWS.ResponsesWebsocketsV2 = true
|
||||
cfg.Gateway.OpenAIWS.ModeRouterV2Enabled = true
|
||||
cfg.Gateway.OpenAIWS.DialTimeoutSeconds = 3
|
||||
cfg.Gateway.OpenAIWS.ReadTimeoutSeconds = 3
|
||||
cfg.Gateway.OpenAIWS.WriteTimeoutSeconds = 3
|
||||
cfg.Gateway.MaxAccountSwitches = 2
|
||||
|
||||
accountRepo := &openAIWSFailoverHandlerAccountRepoStub{accounts: accounts}
|
||||
rateLimitSvc := service.NewRateLimitService(accountRepo, nil, cfg, nil, nil)
|
||||
billingCacheSvc := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil)
|
||||
t.Cleanup(billingCacheSvc.Stop)
|
||||
gatewaySvc := service.NewOpenAIGatewayService(
|
||||
accountRepo,
|
||||
nil, nil, nil, nil, nil, nil,
|
||||
cfg,
|
||||
nil, nil,
|
||||
service.NewBillingService(cfg, nil),
|
||||
rateLimitSvc,
|
||||
billingCacheSvc,
|
||||
nil,
|
||||
&service.DeferredService{},
|
||||
nil, nil, nil, nil, nil, nil, nil,
|
||||
)
|
||||
|
||||
cache := &concurrencyCacheMock{
|
||||
acquireUserSlotFn: func(ctx context.Context, userID int64, maxConcurrency int, requestID string) (bool, error) {
|
||||
return true, nil
|
||||
},
|
||||
acquireAccountSlotFn: func(ctx context.Context, accountID int64, maxConcurrency int, requestID string) (bool, error) {
|
||||
return true, nil
|
||||
},
|
||||
}
|
||||
h := &OpenAIGatewayHandler{
|
||||
gatewayService: gatewaySvc,
|
||||
billingCacheService: billingCacheSvc,
|
||||
apiKeyService: &service.APIKeyService{},
|
||||
concurrencyHelper: NewConcurrencyHelper(service.NewConcurrencyService(cache), SSEPingFormatNone, time.Second),
|
||||
maxAccountSwitches: 2,
|
||||
}
|
||||
|
||||
apiKey := &service.APIKey{
|
||||
ID: 1812,
|
||||
GroupID: &groupID,
|
||||
User: &service.User{ID: 1712, Status: service.StatusActive},
|
||||
Group: &service.Group{ID: groupID, Platform: service.PlatformOpenAI, Status: service.StatusActive},
|
||||
}
|
||||
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})
|
||||
c.Next()
|
||||
})
|
||||
router.GET("/openai/v1/responses", h.ResponsesWebSocket)
|
||||
handlerServer := httptest.NewServer(router)
|
||||
defer handlerServer.Close()
|
||||
|
||||
dial := func() *coderws.Conn {
|
||||
dialCtx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
defer cancel()
|
||||
conn, _, err := coderws.Dial(
|
||||
dialCtx,
|
||||
"ws"+strings.TrimPrefix(handlerServer.URL, "http")+"/openai/v1/responses",
|
||||
&coderws.DialOptions{CompressionMode: coderws.CompressionContextTakeover},
|
||||
)
|
||||
require.NoError(t, err)
|
||||
return conn
|
||||
}
|
||||
|
||||
// Socket A: seed turn 1 so sticky response -> account + conn is bound.
|
||||
connA := dial()
|
||||
writeCtx, cancelWrite := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
require.NoError(t, connA.Write(writeCtx, coderws.MessageText, []byte(
|
||||
`{"type":"response.create","model":"gpt-5.1","store":false,"input":[{"type":"message","role":"user","content":"Remember PLUM"}]}`,
|
||||
)))
|
||||
cancelWrite()
|
||||
readCtx, cancelRead := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
_, msgA, err := connA.Read(readCtx)
|
||||
cancelRead()
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "resp_ws_sticky_turn_1", gjson.GetBytes(msgA, "response.id").String())
|
||||
require.NoError(t, connA.Close(coderws.StatusNormalClosure, "done"))
|
||||
|
||||
// Socket B: reconnect with valid bound previous_response_id.
|
||||
connB := dial()
|
||||
defer func() { _ = connB.CloseNow() }()
|
||||
writeCtx2, cancelWrite2 := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
require.NoError(t, connB.Write(writeCtx2, coderws.MessageText, []byte(
|
||||
`{"type":"response.create","model":"gpt-5.1","store":false,"previous_response_id":"resp_ws_sticky_turn_1","input":[{"type":"message","role":"user","content":"Which word?"}]}`,
|
||||
)))
|
||||
cancelWrite2()
|
||||
readCtx2, cancelRead2 := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
_, msgB, err := connB.Read(readCtx2)
|
||||
cancelRead2()
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "response.completed", gjson.GetBytes(msgB, "type").String())
|
||||
require.Equal(t, "resp_ws_sticky_turn_2", gjson.GetBytes(msgB, "response.id").String())
|
||||
|
||||
<-receivedCh
|
||||
secondUpstreamPayload := <-receivedCh
|
||||
require.Equal(t, "resp_ws_sticky_turn_1", gjson.GetBytes(secondUpstreamPayload, "previous_response_id").String())
|
||||
}
|
||||
|
||||
func TestOpenAIResponsesWebSocket_GrokFirstFramePreviousResponseIDNotRejectedByOpenAIStickyCheck(t *testing.T) {
|
||||
got := runOpenAIResponsesWebSocketUsageLogCase(t, openAIResponsesWSUsageLogCase{
|
||||
firstPayload: `{"type":"response.create","model":"public-alias","previous_response_id":"resp_grok_prev_1","input":[{"type":"message","role":"user","content":"full history"}]}`,
|
||||
group: compositeWSGroup("public-alias"),
|
||||
accountPlatform: service.PlatformGrok,
|
||||
ingressMode: service.OpenAIWSIngressModeCtxPool,
|
||||
compositeResolver: compositeWSResolver(service.PlatformGrok, service.CompositeRouteEndpointResponses, "grok-4.3"),
|
||||
})
|
||||
require.Len(t, got.upstreamPayloads, 1)
|
||||
require.Equal(t, "grok-4.3", gjson.GetBytes(got.upstreamPayloads[0], "model").String())
|
||||
require.Equal(t, "response.completed", gjson.GetBytes(got.clientEvents[0], "type").String())
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
//go:build unit
|
||||
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
"github.com/Wei-Shaw/sub2api/internal/server/middleware"
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
coderws "github.com/coder/websocket"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
func TestOpenAIResponsesWebSocket_FirstFrameContinuationPinsBoundAccountInStickyWeightedMode(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
service.EnableOpenAIAdvancedSchedulerStickyWeightedForTest(t)
|
||||
|
||||
var preferredHits atomic.Int32
|
||||
boundReceivedCh := make(chan []byte, 4)
|
||||
|
||||
preferredUpstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
preferredHits.Add(1)
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
}))
|
||||
defer preferredUpstream.Close()
|
||||
|
||||
boundUpstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
conn, err := coderws.Accept(w, r, &coderws.AcceptOptions{CompressionMode: coderws.CompressionContextTakeover})
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer func() { _ = conn.CloseNow() }()
|
||||
|
||||
for i := 0; i < 2; i++ {
|
||||
readCtx, cancelRead := context.WithTimeout(r.Context(), 3*time.Second)
|
||||
_, payload, readErr := conn.Read(readCtx)
|
||||
cancelRead()
|
||||
if readErr != nil {
|
||||
return
|
||||
}
|
||||
boundReceivedCh <- append([]byte(nil), payload...)
|
||||
respID := "resp_ws_weighted_turn_1"
|
||||
if i == 1 {
|
||||
respID = "resp_ws_weighted_turn_2"
|
||||
}
|
||||
writeCtx, cancelWrite := context.WithTimeout(r.Context(), 3*time.Second)
|
||||
_ = conn.Write(writeCtx, coderws.MessageText, []byte(`{"type":"response.completed","response":{"id":"`+respID+`","model":"gpt-5.1","usage":{"input_tokens":5,"output_tokens":2}}}`))
|
||||
cancelWrite()
|
||||
}
|
||||
}))
|
||||
defer boundUpstream.Close()
|
||||
|
||||
groupID := int64(4213)
|
||||
// Account 9913 starts schedulable=false during turn 1 so turn 1 binds to 9914 (Priority 100).
|
||||
// Before turn 2 reconnects, 9913 (higher priority 0) becomes schedulable. With sticky-weighted
|
||||
// mode and LBTopK=1, a movable continuation would pick 9913 (StickyPreviousHit=false) and fail;
|
||||
// pinning continuation scheduling (previousResponseCanMove=false) keeps turn 2 on 9914.
|
||||
accounts := []service.Account{
|
||||
{
|
||||
ID: 9913,
|
||||
Name: "openai-ws-higher-priority",
|
||||
Platform: service.PlatformOpenAI,
|
||||
Type: service.AccountTypeAPIKey,
|
||||
Status: service.StatusActive,
|
||||
Schedulable: false,
|
||||
Concurrency: 2,
|
||||
Priority: 0,
|
||||
Credentials: map[string]any{
|
||||
"api_key": "sk-preferred",
|
||||
"base_url": preferredUpstream.URL,
|
||||
},
|
||||
Extra: map[string]any{
|
||||
"openai_apikey_responses_websockets_v2_enabled": true,
|
||||
"openai_apikey_responses_websockets_v2_mode": service.OpenAIWSIngressModeCtxPool,
|
||||
},
|
||||
},
|
||||
{
|
||||
ID: 9914,
|
||||
Name: "openai-ws-bound-owner",
|
||||
Platform: service.PlatformOpenAI,
|
||||
Type: service.AccountTypeAPIKey,
|
||||
Status: service.StatusActive,
|
||||
Schedulable: true,
|
||||
Concurrency: 2,
|
||||
Priority: 100,
|
||||
Credentials: map[string]any{
|
||||
"api_key": "sk-bound",
|
||||
"base_url": boundUpstream.URL,
|
||||
},
|
||||
Extra: map[string]any{
|
||||
"openai_apikey_responses_websockets_v2_enabled": true,
|
||||
"openai_apikey_responses_websockets_v2_mode": service.OpenAIWSIngressModeCtxPool,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
cfg := &config.Config{}
|
||||
cfg.RunMode = config.RunModeSimple
|
||||
cfg.Default.RateMultiplier = 1
|
||||
cfg.Security.URLAllowlist.Enabled = false
|
||||
cfg.Security.URLAllowlist.AllowInsecureHTTP = true
|
||||
cfg.Gateway.OpenAIWS.Enabled = true
|
||||
cfg.Gateway.OpenAIWS.APIKeyEnabled = true
|
||||
cfg.Gateway.OpenAIWS.ResponsesWebsocketsV2 = true
|
||||
cfg.Gateway.OpenAIWS.ModeRouterV2Enabled = true
|
||||
cfg.Gateway.OpenAIWS.LBTopK = 1
|
||||
cfg.Gateway.OpenAIWS.SchedulerScoreWeights.Priority = 1
|
||||
cfg.Gateway.OpenAIWS.DialTimeoutSeconds = 3
|
||||
cfg.Gateway.OpenAIWS.ReadTimeoutSeconds = 3
|
||||
cfg.Gateway.OpenAIWS.WriteTimeoutSeconds = 3
|
||||
cfg.Gateway.MaxAccountSwitches = 2
|
||||
|
||||
accountRepo := &openAIWSFailoverHandlerAccountRepoStub{accounts: accounts}
|
||||
rateLimitSvc := service.NewRateLimitService(accountRepo, nil, cfg, nil, nil)
|
||||
billingCacheSvc := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil)
|
||||
t.Cleanup(billingCacheSvc.Stop)
|
||||
gatewaySvc := service.NewOpenAIGatewayService(
|
||||
accountRepo,
|
||||
nil, nil, nil, nil, nil, nil,
|
||||
cfg,
|
||||
nil, nil,
|
||||
service.NewBillingService(cfg, nil),
|
||||
rateLimitSvc,
|
||||
billingCacheSvc,
|
||||
nil,
|
||||
&service.DeferredService{},
|
||||
nil, nil, nil, nil, nil, nil, nil,
|
||||
)
|
||||
|
||||
cache := &concurrencyCacheMock{
|
||||
acquireUserSlotFn: func(ctx context.Context, userID int64, maxConcurrency int, requestID string) (bool, error) {
|
||||
return true, nil
|
||||
},
|
||||
acquireAccountSlotFn: func(ctx context.Context, accountID int64, maxConcurrency int, requestID string) (bool, error) {
|
||||
return true, nil
|
||||
},
|
||||
}
|
||||
h := &OpenAIGatewayHandler{
|
||||
gatewayService: gatewaySvc,
|
||||
billingCacheService: billingCacheSvc,
|
||||
apiKeyService: &service.APIKeyService{},
|
||||
concurrencyHelper: NewConcurrencyHelper(service.NewConcurrencyService(cache), SSEPingFormatNone, time.Second),
|
||||
maxAccountSwitches: 2,
|
||||
}
|
||||
|
||||
apiKey := &service.APIKey{
|
||||
ID: 1813,
|
||||
GroupID: &groupID,
|
||||
User: &service.User{ID: 1713, Status: service.StatusActive},
|
||||
Group: &service.Group{ID: groupID, Platform: service.PlatformOpenAI, Status: service.StatusActive},
|
||||
}
|
||||
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})
|
||||
c.Next()
|
||||
})
|
||||
router.GET("/openai/v1/responses", h.ResponsesWebSocket)
|
||||
handlerServer := httptest.NewServer(router)
|
||||
defer handlerServer.Close()
|
||||
|
||||
dial := func() *coderws.Conn {
|
||||
dialCtx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
defer cancel()
|
||||
conn, _, err := coderws.Dial(
|
||||
dialCtx,
|
||||
"ws"+strings.TrimPrefix(handlerServer.URL, "http")+"/openai/v1/responses",
|
||||
&coderws.DialOptions{CompressionMode: coderws.CompressionContextTakeover},
|
||||
)
|
||||
require.NoError(t, err)
|
||||
return conn
|
||||
}
|
||||
|
||||
// Socket A binds resp_ws_weighted_turn_1 to account 9914.
|
||||
connA := dial()
|
||||
writeCtx, cancelWrite := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
require.NoError(t, connA.Write(writeCtx, coderws.MessageText, []byte(
|
||||
`{"type":"response.create","model":"gpt-5.1","store":false,"input":[{"type":"message","role":"user","content":"Remember PLUM"}]}`,
|
||||
)))
|
||||
cancelWrite()
|
||||
readCtx, cancelRead := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
_, msgA, err := connA.Read(readCtx)
|
||||
cancelRead()
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "resp_ws_weighted_turn_1", gjson.GetBytes(msgA, "response.id").String())
|
||||
require.NoError(t, connA.Close(coderws.StatusNormalClosure, "done"))
|
||||
|
||||
// Make higher-priority account 9913 schedulable before reconnecting on Socket B.
|
||||
accountRepo.accounts[0].Schedulable = true
|
||||
|
||||
connB := dial()
|
||||
defer func() { _ = connB.CloseNow() }()
|
||||
writeCtx2, cancelWrite2 := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
require.NoError(t, connB.Write(writeCtx2, coderws.MessageText, []byte(
|
||||
`{"type":"response.create","model":"gpt-5.1","store":false,"previous_response_id":"resp_ws_weighted_turn_1","input":[{"type":"message","role":"user","content":"Which word?"}]}`,
|
||||
)))
|
||||
cancelWrite2()
|
||||
readCtx2, cancelRead2 := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
_, msgB, err := connB.Read(readCtx2)
|
||||
cancelRead2()
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "response.completed", gjson.GetBytes(msgB, "type").String())
|
||||
require.Equal(t, "resp_ws_weighted_turn_2", gjson.GetBytes(msgB, "response.id").String())
|
||||
require.Equal(t, int32(0), preferredHits.Load(), "bound continuation must pin to owning account rather than drifting to higher-priority account")
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package handler
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -14,20 +15,71 @@ import (
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func securityAuditStreamCommitted(c *gin.Context) bool {
|
||||
if service.StopOpenAICompactSSEKeepaliveCommitted(c) {
|
||||
return true
|
||||
}
|
||||
return c != nil && c.Writer != nil && c.Writer.Written()
|
||||
}
|
||||
|
||||
func writeGenericSecurityAuditSSEError(c *gin.Context, status int, errType, code, message string) {
|
||||
if c == nil || c.Writer == nil {
|
||||
return
|
||||
}
|
||||
service.MarkOpsStreamError(c, errType, message, status)
|
||||
if inboundIsResponses(c) {
|
||||
if writeResponsesFailedSSE(c, errType, code, message) {
|
||||
return
|
||||
}
|
||||
}
|
||||
flusher, ok := c.Writer.(http.Flusher)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
errObj := gin.H{"type": errType, "message": message}
|
||||
if code != "" {
|
||||
errObj["code"] = code
|
||||
}
|
||||
payload, err := json.Marshal(gin.H{"error": errObj})
|
||||
if err != nil {
|
||||
payload = []byte(`{"error":{"type":"content_policy_violation","message":"Request blocked by content policy"}}`)
|
||||
}
|
||||
_, _ = fmt.Fprintf(c.Writer, "event: error\ndata: %s\n\n", payload)
|
||||
flusher.Flush()
|
||||
}
|
||||
|
||||
func (h *OpenAIGatewayHandler) openAISecurityAuditError(c *gin.Context, decision *securityaudit.Decision) {
|
||||
if decision == nil {
|
||||
return
|
||||
}
|
||||
status := securityAuditStatus(decision)
|
||||
code := securityAuditErrorCode(decision)
|
||||
msg := securityAuditMessage(decision)
|
||||
if securityAuditStreamCommitted(c) {
|
||||
errType := code
|
||||
if decision.Legacy == nil || !decision.Legacy.Blocked {
|
||||
errType = "api_error"
|
||||
if decision.Kind == securityaudit.DecisionBlock {
|
||||
errType = "permission_error"
|
||||
}
|
||||
}
|
||||
if h != nil {
|
||||
h.handleStreamingAwareErrorWithCode(c, status, errType, code, msg, true, false)
|
||||
return
|
||||
}
|
||||
writeGenericSecurityAuditSSEError(c, status, errType, code, msg)
|
||||
return
|
||||
}
|
||||
if decision.Legacy != nil && decision.Legacy.Blocked {
|
||||
h.errorResponse(c, securityAuditStatus(decision), securityAuditErrorCode(decision), securityAuditMessage(decision))
|
||||
h.errorResponse(c, status, code, msg)
|
||||
return
|
||||
}
|
||||
errType := "api_error"
|
||||
if decision.Kind == securityaudit.DecisionBlock {
|
||||
errType = "permission_error"
|
||||
}
|
||||
c.JSON(securityAuditStatus(decision), gin.H{"error": gin.H{
|
||||
"type": errType, "code": securityAuditErrorCode(decision), "message": securityAuditMessage(decision),
|
||||
c.JSON(status, gin.H{"error": gin.H{
|
||||
"type": errType, "code": code, "message": msg,
|
||||
}})
|
||||
}
|
||||
|
||||
@@ -35,16 +87,34 @@ func (h *GatewayHandler) openAISecurityAuditError(c *gin.Context, decision *secu
|
||||
if decision == nil {
|
||||
return
|
||||
}
|
||||
status := securityAuditStatus(decision)
|
||||
code := securityAuditErrorCode(decision)
|
||||
msg := securityAuditMessage(decision)
|
||||
if securityAuditStreamCommitted(c) {
|
||||
errType := code
|
||||
if decision.Legacy == nil || !decision.Legacy.Blocked {
|
||||
errType = "api_error"
|
||||
if decision.Kind == securityaudit.DecisionBlock {
|
||||
errType = "permission_error"
|
||||
}
|
||||
}
|
||||
if h != nil {
|
||||
h.handleStreamingAwareErrorWithCode(c, status, errType, code, msg, true)
|
||||
return
|
||||
}
|
||||
writeGenericSecurityAuditSSEError(c, status, errType, code, msg)
|
||||
return
|
||||
}
|
||||
if decision.Legacy != nil && decision.Legacy.Blocked {
|
||||
h.chatCompletionsErrorResponse(c, securityAuditStatus(decision), securityAuditErrorCode(decision), securityAuditMessage(decision))
|
||||
h.chatCompletionsErrorResponse(c, status, code, msg)
|
||||
return
|
||||
}
|
||||
errType := "api_error"
|
||||
if decision.Kind == securityaudit.DecisionBlock {
|
||||
errType = "permission_error"
|
||||
}
|
||||
c.JSON(securityAuditStatus(decision), gin.H{"error": gin.H{
|
||||
"type": errType, "code": securityAuditErrorCode(decision), "message": securityAuditMessage(decision),
|
||||
c.JSON(status, gin.H{"error": gin.H{
|
||||
"type": errType, "code": code, "message": msg,
|
||||
}})
|
||||
}
|
||||
|
||||
@@ -52,12 +122,26 @@ func (h *GatewayHandler) responsesSecurityAuditError(c *gin.Context, decision *s
|
||||
if decision == nil {
|
||||
return
|
||||
}
|
||||
if decision.Legacy != nil && decision.Legacy.Blocked {
|
||||
h.responsesErrorResponse(c, securityAuditStatus(decision), securityAuditErrorCode(decision), securityAuditMessage(decision))
|
||||
status := securityAuditStatus(decision)
|
||||
code := securityAuditErrorCode(decision)
|
||||
msg := securityAuditMessage(decision)
|
||||
if securityAuditStreamCommitted(c) {
|
||||
errType := code
|
||||
if decision.Legacy == nil || !decision.Legacy.Blocked {
|
||||
errType = "api_error"
|
||||
}
|
||||
service.MarkOpsStreamError(c, errType, msg, status)
|
||||
if !writeResponsesFailedSSE(c, errType, code, msg) {
|
||||
writeGenericSecurityAuditSSEError(c, status, errType, code, msg)
|
||||
}
|
||||
return
|
||||
}
|
||||
c.JSON(securityAuditStatus(decision), gin.H{"error": gin.H{
|
||||
"type": "api_error", "code": securityAuditErrorCode(decision), "message": securityAuditMessage(decision),
|
||||
if decision.Legacy != nil && decision.Legacy.Blocked {
|
||||
h.responsesErrorResponse(c, status, code, msg)
|
||||
return
|
||||
}
|
||||
c.JSON(status, gin.H{"error": gin.H{
|
||||
"type": "api_error", "code": code, "message": msg,
|
||||
}})
|
||||
}
|
||||
|
||||
@@ -65,16 +149,34 @@ func (h *GatewayHandler) anthropicSecurityAuditError(c *gin.Context, decision *s
|
||||
if decision == nil {
|
||||
return
|
||||
}
|
||||
status := securityAuditStatus(decision)
|
||||
code := securityAuditErrorCode(decision)
|
||||
msg := securityAuditMessage(decision)
|
||||
if securityAuditStreamCommitted(c) {
|
||||
errType := code
|
||||
if decision.Legacy == nil || !decision.Legacy.Blocked {
|
||||
errType = "api_error"
|
||||
if decision.Kind == securityaudit.DecisionBlock {
|
||||
errType = "permission_error"
|
||||
}
|
||||
}
|
||||
if h != nil {
|
||||
h.handleStreamingAwareErrorWithCode(c, status, errType, code, msg, true)
|
||||
return
|
||||
}
|
||||
writeGenericSecurityAuditSSEError(c, status, errType, code, msg)
|
||||
return
|
||||
}
|
||||
if decision.Legacy != nil && decision.Legacy.Blocked {
|
||||
h.errorResponse(c, securityAuditStatus(decision), securityAuditErrorCode(decision), securityAuditMessage(decision))
|
||||
h.errorResponse(c, status, code, msg)
|
||||
return
|
||||
}
|
||||
errType := "api_error"
|
||||
if decision.Kind == securityaudit.DecisionBlock {
|
||||
errType = "permission_error"
|
||||
}
|
||||
c.JSON(securityAuditStatus(decision), gin.H{"type": "error", "error": gin.H{
|
||||
"type": errType, "code": securityAuditErrorCode(decision), "message": securityAuditMessage(decision),
|
||||
c.JSON(status, gin.H{"type": "error", "error": gin.H{
|
||||
"type": errType, "code": code, "message": msg,
|
||||
}})
|
||||
}
|
||||
|
||||
@@ -82,16 +184,30 @@ func (h *OpenAIGatewayHandler) anthropicSecurityAuditError(c *gin.Context, decis
|
||||
if decision == nil {
|
||||
return
|
||||
}
|
||||
status := securityAuditStatus(decision)
|
||||
code := securityAuditErrorCode(decision)
|
||||
msg := securityAuditMessage(decision)
|
||||
if securityAuditStreamCommitted(c) {
|
||||
errType := code
|
||||
if decision.Legacy == nil || !decision.Legacy.Blocked {
|
||||
errType = "api_error"
|
||||
if decision.Kind == securityaudit.DecisionBlock {
|
||||
errType = "permission_error"
|
||||
}
|
||||
}
|
||||
h.anthropicStreamingAwareError(c, status, errType, msg, true)
|
||||
return
|
||||
}
|
||||
if decision.Legacy != nil && decision.Legacy.Blocked {
|
||||
h.anthropicErrorResponse(c, securityAuditStatus(decision), securityAuditErrorCode(decision), securityAuditMessage(decision))
|
||||
h.anthropicErrorResponse(c, status, code, msg)
|
||||
return
|
||||
}
|
||||
errType := "api_error"
|
||||
if decision.Kind == securityaudit.DecisionBlock {
|
||||
errType = "permission_error"
|
||||
}
|
||||
c.JSON(securityAuditStatus(decision), gin.H{"type": "error", "error": gin.H{
|
||||
"type": errType, "code": securityAuditErrorCode(decision), "message": securityAuditMessage(decision),
|
||||
c.JSON(status, gin.H{"type": "error", "error": gin.H{
|
||||
"type": errType, "code": code, "message": msg,
|
||||
}})
|
||||
}
|
||||
|
||||
@@ -99,16 +215,36 @@ func googleSecurityAuditError(c *gin.Context, decision *securityaudit.Decision)
|
||||
if decision == nil {
|
||||
return
|
||||
}
|
||||
status := securityAuditStatus(decision)
|
||||
code := securityAuditErrorCode(decision)
|
||||
msg := securityAuditMessage(decision)
|
||||
if securityAuditStreamCommitted(c) {
|
||||
service.MarkOpsStreamError(c, code, msg, status)
|
||||
if flusher, ok := c.Writer.(http.Flusher); ok {
|
||||
googleStatus := googleapi.HTTPStatusToGoogleStatus(status)
|
||||
payload, err := json.Marshal(gin.H{
|
||||
"error": gin.H{
|
||||
"code": status,
|
||||
"message": msg,
|
||||
"status": googleStatus,
|
||||
},
|
||||
})
|
||||
if err == nil {
|
||||
_, _ = fmt.Fprintf(c.Writer, "data: %s\n\n", payload)
|
||||
flusher.Flush()
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
if decision.Legacy != nil && decision.Legacy.Blocked {
|
||||
googleErrorWithType(c, securityAuditStatus(decision), securityAuditErrorCode(decision), "", securityAuditMessage(decision))
|
||||
googleErrorWithType(c, status, code, "", msg)
|
||||
return
|
||||
}
|
||||
errType := "api_error"
|
||||
if decision.Kind == securityaudit.DecisionBlock {
|
||||
errType = "permission_error"
|
||||
}
|
||||
service.SetOpsLocalErrorType(c, errType, securityAuditErrorCode(decision))
|
||||
status := securityAuditStatus(decision)
|
||||
service.SetOpsLocalErrorType(c, errType, code)
|
||||
googleStatus := googleapi.HTTPStatusToGoogleStatus(status)
|
||||
if status == http.StatusServiceUnavailable {
|
||||
googleStatus = "UNAVAILABLE"
|
||||
@@ -118,10 +254,11 @@ func googleSecurityAuditError(c *gin.Context, decision *securityaudit.Decision)
|
||||
requestID = contentModerationRequestID(c.Request.Context())
|
||||
}
|
||||
c.JSON(status, gin.H{"error": gin.H{
|
||||
"code": status, "message": securityAuditMessage(decision), "status": googleStatus,
|
||||
"code": status, "message": msg, "status": googleStatus,
|
||||
"details": []gin.H{{
|
||||
"@type": "type.googleapis.com/google.rpc.ErrorInfo",
|
||||
"reason": securityAuditErrorCode(decision), "domain": "sub2api.securityaudit",
|
||||
"@type": "type.googleapis.com/google.rpc.ErrorInfo",
|
||||
"reason": code,
|
||||
"domain": "sub2api.securityaudit",
|
||||
"metadata": gin.H{"request_id": requestID},
|
||||
}},
|
||||
}})
|
||||
|
||||
@@ -75,8 +75,19 @@ func runSecurityAudit(c *gin.Context, reqLog *zap.Logger, coordinator *securitya
|
||||
return nil
|
||||
}
|
||||
}
|
||||
legacyInput := buildContentModerationInput(c, apiKey, subject, protocol, model, body)
|
||||
if strings.TrimSpace(stage) == "subsequent_turn" {
|
||||
legacyInput.AccountID = boundAccountIDFromGinContext(c)
|
||||
}
|
||||
deferredLegacy := deferAccountModerationIfNeeded(c, reqLog, legacy, legacyInput)
|
||||
if coordinator == nil {
|
||||
legacyDecision := runContentModeration(c, reqLog, legacy, apiKey, subject, protocol, model, body)
|
||||
if deferredLegacy {
|
||||
if cacheCompletion {
|
||||
c.Set(securityAuditCompletedContextKey, true)
|
||||
}
|
||||
return &securityaudit.Decision{Kind: securityaudit.DecisionAllow, HTTPStatus: http.StatusOK, AllowNextStage: true}
|
||||
}
|
||||
legacyDecision := runContentModerationWithInput(c.Request.Context(), reqLog, legacy, legacyInput)
|
||||
if legacyDecision == nil {
|
||||
return nil
|
||||
}
|
||||
@@ -94,7 +105,9 @@ func runSecurityAudit(c *gin.Context, reqLog *zap.Logger, coordinator *securitya
|
||||
}
|
||||
return &decision
|
||||
}
|
||||
request := buildSecurityAuditRequest(c, apiKey, subject, protocol, model, body, stage)
|
||||
request := buildSecurityAuditRequestFromLegacy(apiKey, legacyInput, body, stage)
|
||||
request.AccountID = legacyInput.AccountID
|
||||
request.SkipLegacy = deferredLegacy
|
||||
if isSecurityAuditWebSocketStage(request.Stage) {
|
||||
if turnNo, ok := securityAuditWSTurn(c); ok {
|
||||
bodyHash := sha256.Sum256(body)
|
||||
@@ -157,10 +170,9 @@ func securityAuditWSTurn(c *gin.Context) (int, bool) {
|
||||
return turnNo, ok
|
||||
}
|
||||
|
||||
func buildSecurityAuditRequest(c *gin.Context, apiKey *service.APIKey, subject middleware2.AuthSubject, protocol, model string, body []byte, stage string) securityaudit.Request {
|
||||
legacy := buildContentModerationInput(c, apiKey, subject, protocol, model, body)
|
||||
func buildSecurityAuditRequestFromLegacy(apiKey *service.APIKey, legacy service.ContentModerationCheckInput, body []byte, stage string) securityaudit.Request {
|
||||
request := securityaudit.Request{
|
||||
RequestID: legacy.RequestID, UserID: legacy.UserID, UserEmail: legacy.UserEmail,
|
||||
RequestID: legacy.RequestID, AccountID: legacy.AccountID, UserID: legacy.UserID, UserEmail: legacy.UserEmail,
|
||||
APIKeyID: legacy.APIKeyID, APIKeyName: legacy.APIKeyName, GroupID: cloneSecurityAuditGroupID(legacy.GroupID),
|
||||
GroupName: legacy.GroupName, Provider: legacy.Provider, Endpoint: legacy.Endpoint,
|
||||
Protocol: legacy.Protocol, Model: legacy.Model, Body: body, Stage: strings.TrimSpace(stage),
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
//go:build unit
|
||||
|
||||
package antigravity
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
type finishTestEvent struct {
|
||||
name string
|
||||
data map[string]any
|
||||
}
|
||||
|
||||
func runFinishTestStream(t *testing.T, chunks ...string) ([]finishTestEvent, *ClaudeUsage) {
|
||||
t.Helper()
|
||||
processor := NewStreamingProcessor("gemini-4-neon")
|
||||
var out strings.Builder
|
||||
for _, chunk := range chunks {
|
||||
out.Write(processor.ProcessLine("data: " + chunk))
|
||||
}
|
||||
final, usage := processor.Finish()
|
||||
out.Write(final)
|
||||
|
||||
var events []finishTestEvent
|
||||
var name string
|
||||
for _, line := range strings.Split(out.String(), "\n") {
|
||||
if v, ok := strings.CutPrefix(line, "event: "); ok {
|
||||
name = v
|
||||
continue
|
||||
}
|
||||
if v, ok := strings.CutPrefix(line, "data: "); ok {
|
||||
var data map[string]any
|
||||
require.NoError(t, json.Unmarshal([]byte(v), &data))
|
||||
events = append(events, finishTestEvent{name: name, data: data})
|
||||
}
|
||||
}
|
||||
return events, usage
|
||||
}
|
||||
|
||||
func finishTestStopReason(events []finishTestEvent) string {
|
||||
for _, event := range events {
|
||||
if event.name == "message_delta" {
|
||||
reason, _ := event.data["delta"].(map[string]any)["stop_reason"].(string)
|
||||
return reason
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func TestFinishReasonMapping(t *testing.T) {
|
||||
const usage = `"usageMetadata":{"promptTokenCount":12,"candidatesTokenCount":3}`
|
||||
text := func(reason string) string {
|
||||
return `{"candidates":[{"content":{"role":"model","parts":[{"text":"partial"}]},"finishReason":"` + reason + `"}],` + usage + `}`
|
||||
}
|
||||
call := func(reason string) string {
|
||||
return `{"candidates":[{"content":{"role":"model","parts":[{"functionCall":{"name":"Read","args":{}},"thoughtSignature":"SIG"}]},"finishReason":"` + reason + `"}],` + usage + `}`
|
||||
}
|
||||
empty := func(reason string) string {
|
||||
return `{"candidates":[{"content":{"role":"model","parts":[{"thoughtSignature":"SIG"}]},"finishReason":"` + reason + `"}],` + usage + `}`
|
||||
}
|
||||
thoughtOnly := func(reason string) string {
|
||||
return `{"candidates":[{"content":{"role":"model","parts":[{"text":"Plan the call.","thought":true}]},"finishReason":"` + reason + `"}],` + usage + `}`
|
||||
}
|
||||
const promptBlocked = `{"promptFeedback":{"blockReason":"PROHIBITED_CONTENT"},` + usage + `}`
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
chunk string
|
||||
wantStop string
|
||||
wantError bool
|
||||
}{
|
||||
{name: "STOP", chunk: text("STOP"), wantStop: "end_turn"},
|
||||
{name: "MAX_TOKENS", chunk: text("MAX_TOKENS"), wantStop: "max_tokens"},
|
||||
{name: "OTHER keeps end_turn", chunk: text("OTHER"), wantStop: "end_turn"},
|
||||
{name: "tool call with STOP", chunk: call("STOP"), wantStop: "tool_use"},
|
||||
{name: "SAFETY", chunk: text("SAFETY"), wantStop: "refusal"},
|
||||
{name: "PROHIBITED_CONTENT", chunk: text("PROHIBITED_CONTENT"), wantStop: "refusal"},
|
||||
{name: "SPII", chunk: text("SPII"), wantStop: "refusal"},
|
||||
{name: "BLOCKLIST", chunk: text("BLOCKLIST"), wantStop: "refusal"},
|
||||
{name: "IMAGE_SAFETY", chunk: text("IMAGE_SAFETY"), wantStop: "refusal"},
|
||||
{name: "RECITATION", chunk: text("RECITATION"), wantStop: "refusal"},
|
||||
{name: "SAFETY after a tool call", chunk: call("SAFETY"), wantStop: "refusal"},
|
||||
{name: "prompt blocked without candidates", chunk: promptBlocked, wantStop: "refusal"},
|
||||
{name: "UNEXPECTED_TOOL_CALL without content", chunk: empty("UNEXPECTED_TOOL_CALL"), wantError: true},
|
||||
{name: "TOO_MANY_TOOL_CALLS without content", chunk: empty("TOO_MANY_TOOL_CALLS"), wantError: true},
|
||||
{name: "MALFORMED_RESPONSE without content", chunk: empty("MALFORMED_RESPONSE"), wantError: true},
|
||||
{name: "MALFORMED_FUNCTION_CALL after thinking only", chunk: thoughtOnly("MALFORMED_FUNCTION_CALL"), wantError: true},
|
||||
{name: "UNEXPECTED_TOOL_CALL after thinking only", chunk: thoughtOnly("UNEXPECTED_TOOL_CALL"), wantError: true},
|
||||
{name: "UNEXPECTED_TOOL_CALL after text", chunk: text("UNEXPECTED_TOOL_CALL"), wantStop: "end_turn"},
|
||||
{name: "MALFORMED_FUNCTION_CALL after text", chunk: text("MALFORMED_FUNCTION_CALL"), wantStop: "end_turn"},
|
||||
{name: "TOO_MANY_TOOL_CALLS after a call", chunk: call("TOO_MANY_TOOL_CALLS"), wantStop: "tool_use"},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run("stream/"+tt.name, func(t *testing.T) {
|
||||
events, gotUsage := runFinishTestStream(t, tt.chunk)
|
||||
require.Equal(t, 12, gotUsage.InputTokens, "usage is still collected for billing")
|
||||
if tt.wantError {
|
||||
last := events[len(events)-1]
|
||||
require.Equal(t, "error", last.name)
|
||||
require.Equal(t, "api_error", last.data["error"].(map[string]any)["type"])
|
||||
require.Empty(t, finishTestStopReason(events))
|
||||
for _, event := range events {
|
||||
require.NotEqual(t, "message_stop", event.name)
|
||||
}
|
||||
return
|
||||
}
|
||||
require.Equal(t, tt.wantStop, finishTestStopReason(events))
|
||||
})
|
||||
|
||||
t.Run("non-stream/"+tt.name, func(t *testing.T) {
|
||||
body, _, err := TransformGeminiToClaude([]byte(tt.chunk), "gemini-4-neon")
|
||||
if tt.wantError {
|
||||
require.True(t, errors.Is(err, ErrInvalidOutputWithoutContent) || errors.Is(err, ErrMalformedFunctionCall), "got %v", err)
|
||||
require.Nil(t, body)
|
||||
return
|
||||
}
|
||||
require.NoError(t, err)
|
||||
var resp map[string]any
|
||||
require.NoError(t, json.Unmarshal(body, &resp))
|
||||
require.Equal(t, tt.wantStop, resp["stop_reason"])
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestFinishReasonMapping_MalformedFunctionCallWithoutContent(t *testing.T) {
|
||||
const chunk = `{"candidates":[{"content":{"role":"model","parts":[]},"finishReason":"MALFORMED_FUNCTION_CALL"}]}`
|
||||
events, _ := runFinishTestStream(t, chunk)
|
||||
require.Equal(t, "message_start", events[0].name)
|
||||
require.Equal(t, "error", events[len(events)-1].name)
|
||||
|
||||
_, _, err := TransformGeminiToClaude([]byte(chunk), "gemini-4-neon")
|
||||
require.ErrorIs(t, err, ErrMalformedFunctionCall)
|
||||
}
|
||||
|
||||
func TestFinishReasonMapping_NothingFollowsTheErrorEvent(t *testing.T) {
|
||||
events, usage := runFinishTestStream(t,
|
||||
`{"candidates":[{"content":{"role":"model","parts":[]},"finishReason":"MALFORMED_FUNCTION_CALL"}]}`,
|
||||
`{"candidates":[{"content":{"role":"model","parts":[{"text":"late"}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":40,"candidatesTokenCount":2}}`,
|
||||
)
|
||||
require.Equal(t, "error", events[len(events)-1].name)
|
||||
for _, event := range events {
|
||||
require.NotEqual(t, "content_block_start", event.name)
|
||||
require.NotEqual(t, "message_delta", event.name)
|
||||
}
|
||||
require.Equal(t, 40, usage.InputTokens)
|
||||
}
|
||||
@@ -147,10 +147,21 @@ type V1InternalResponse struct {
|
||||
|
||||
// GeminiResponse Gemini 响应
|
||||
type GeminiResponse struct {
|
||||
Candidates []GeminiCandidate `json:"candidates,omitempty"`
|
||||
UsageMetadata *GeminiUsageMetadata `json:"usageMetadata,omitempty"`
|
||||
ResponseID string `json:"responseId,omitempty"`
|
||||
ModelVersion string `json:"modelVersion,omitempty"`
|
||||
Candidates []GeminiCandidate `json:"candidates,omitempty"`
|
||||
PromptFeedback *GeminiPromptFeedback `json:"promptFeedback,omitempty"`
|
||||
UsageMetadata *GeminiUsageMetadata `json:"usageMetadata,omitempty"`
|
||||
ResponseID string `json:"responseId,omitempty"`
|
||||
ModelVersion string `json:"modelVersion,omitempty"`
|
||||
}
|
||||
|
||||
// GeminiPromptFeedback 是 prompt 被拦截时上游返回的原因,此时没有 candidates。
|
||||
type GeminiPromptFeedback struct {
|
||||
BlockReason string `json:"blockReason,omitempty"`
|
||||
}
|
||||
|
||||
// promptBlocked 判断 prompt 是否被拦截:没有 candidates 且带 blockReason。
|
||||
func (r *GeminiResponse) promptBlocked() bool {
|
||||
return len(r.Candidates) == 0 && r.PromptFeedback != nil && r.PromptFeedback.BlockReason != ""
|
||||
}
|
||||
|
||||
// GeminiCandidate Gemini 候选响应
|
||||
|
||||
@@ -421,9 +421,21 @@ func buildSystemInstruction(system json.RawMessage, modelName string, opts Trans
|
||||
}
|
||||
|
||||
// buildContents 构建 contents
|
||||
//
|
||||
// {role: "system"} messages before the first model turn are the conversation's
|
||||
// standing context and go to systemInstruction. Later ones are notices an agent
|
||||
// client adds as the conversation goes on (Claude Code adds one after each tool
|
||||
// result); they stay at their place as user text. systemInstruction precedes
|
||||
// the contents in the prompt, and Gemini's implicit cache only matches a prompt
|
||||
// prefix, so a notice appended there would change every request's prefix and
|
||||
// leave the whole conversation uncached.
|
||||
func buildContents(messages []ClaudeMessage, toolIDToName map[string]string, isThinkingEnabled, allowDummyThought, multimodalToolResults bool) ([]GeminiContent, []GeminiPart, bool, error) {
|
||||
var contents []GeminiContent
|
||||
var systemParts []GeminiPart
|
||||
// Notices that follow a model turn wait for the next user turn: a
|
||||
// functionCall must be followed directly by its functionResponse.
|
||||
var pendingNotices []GeminiPart
|
||||
seenModel := false
|
||||
strippedThinking := false
|
||||
|
||||
for i, msg := range messages {
|
||||
@@ -441,10 +453,31 @@ func buildContents(messages []ClaudeMessage, toolIDToName map[string]string, isT
|
||||
}
|
||||
|
||||
if role == "system" {
|
||||
systemParts = append(systemParts, parts...)
|
||||
parts = trimSystemTextParts(parts)
|
||||
if !seenModel {
|
||||
systemParts = append(systemParts, parts...)
|
||||
continue
|
||||
}
|
||||
notice := systemReminderParts(parts)
|
||||
if n := len(contents); n > 0 && contents[n-1].Role == "user" && len(pendingNotices) == 0 {
|
||||
contents[n-1].Parts = append(contents[n-1].Parts, notice...)
|
||||
} else {
|
||||
pendingNotices = append(pendingNotices, notice...)
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
if role == "model" {
|
||||
seenModel = true
|
||||
if len(pendingNotices) > 0 {
|
||||
contents = append(contents, GeminiContent{Role: "user", Parts: pendingNotices})
|
||||
pendingNotices = nil
|
||||
}
|
||||
} else if len(pendingNotices) > 0 {
|
||||
parts = append(parts, pendingNotices...)
|
||||
pendingNotices = nil
|
||||
}
|
||||
|
||||
// 只有 Gemini 模型支持 dummy thinking block workaround
|
||||
// 只对最后一条 assistant 消息添加(Pre-fill 场景)
|
||||
// 历史 assistant 消息不能添加没有 signature 的 dummy thinking block
|
||||
@@ -475,10 +508,48 @@ func buildContents(messages []ClaudeMessage, toolIDToName map[string]string, isT
|
||||
Parts: parts,
|
||||
})
|
||||
}
|
||||
if len(pendingNotices) > 0 {
|
||||
contents = append(contents, GeminiContent{Role: "user", Parts: pendingNotices})
|
||||
}
|
||||
|
||||
return contents, systemParts, strippedThinking, nil
|
||||
}
|
||||
|
||||
// trimSystemTextParts renders a system message's text the same way whether
|
||||
// the client sent it as a string (which buildParts trims) or as text blocks:
|
||||
// Claude Code sends its newest system message as blocks with cache_control and
|
||||
// the same message as a string once it is history.
|
||||
func trimSystemTextParts(parts []GeminiPart) []GeminiPart {
|
||||
out := parts[:0]
|
||||
for _, p := range parts {
|
||||
if isPlainTextPart(p) {
|
||||
p.Text = strings.TrimSpace(p.Text)
|
||||
if p.Text == "" {
|
||||
continue
|
||||
}
|
||||
}
|
||||
out = append(out, p)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// systemReminderParts marks a system notice placed in a user turn the way
|
||||
// agent clients mark harness text in user turns.
|
||||
func systemReminderParts(parts []GeminiPart) []GeminiPart {
|
||||
out := make([]GeminiPart, 0, len(parts))
|
||||
for _, p := range parts {
|
||||
if isPlainTextPart(p) {
|
||||
p.Text = "<system-reminder>\n" + p.Text + "\n</system-reminder>"
|
||||
}
|
||||
out = append(out, p)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func isPlainTextPart(p GeminiPart) bool {
|
||||
return !p.Thought && p.InlineData == nil && p.FunctionCall == nil && p.FunctionResponse == nil
|
||||
}
|
||||
|
||||
// DummyThoughtSignature 用于跳过 Gemini 3 thought_signature 验证
|
||||
// 参考: https://ai.google.dev/gemini-api/docs/thought-signatures
|
||||
// 导出供跨包使用(如 gemini_native_signature_cleaner 跨账号修复)
|
||||
|
||||
@@ -13,8 +13,68 @@ import (
|
||||
|
||||
var ErrMalformedFunctionCall = errors.New("upstream returned MALFORMED_FUNCTION_CALL")
|
||||
|
||||
// ErrInvalidOutputWithoutContent 表示上游以模型产出无效的结束原因结束,且没有 text 或 tool_use 内容,客户端应重试。
|
||||
var ErrInvalidOutputWithoutContent = errors.New("upstream finished with an invalid-output reason and no content")
|
||||
|
||||
// refusalFinishReasons 是内容被过滤的结束原因,对应 Claude 的 refusal。
|
||||
var refusalFinishReasons = map[string]bool{
|
||||
"SAFETY": true,
|
||||
"PROHIBITED_CONTENT": true,
|
||||
"SPII": true,
|
||||
"BLOCKLIST": true,
|
||||
"IMAGE_SAFETY": true,
|
||||
"RECITATION": true,
|
||||
}
|
||||
|
||||
// invalidOutputFinishReasons 是模型产出的调用或响应无效的结束原因。
|
||||
var invalidOutputFinishReasons = map[string]bool{
|
||||
"MALFORMED_FUNCTION_CALL": true,
|
||||
"UNEXPECTED_TOOL_CALL": true,
|
||||
"TOO_MANY_TOOL_CALLS": true,
|
||||
"MALFORMED_RESPONSE": true,
|
||||
}
|
||||
|
||||
// hasVisibleContent 判断响应里是否有 text 或 tool_use 块(思考块不算)。
|
||||
func hasVisibleContent(blocks []ClaudeContentItem) bool {
|
||||
for _, block := range blocks {
|
||||
if block.Type == "text" || block.Type == "tool_use" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// claudeStopReason 把 Gemini finishReason 映射为 Claude stop_reason。
|
||||
func claudeStopReason(finishReason string, usedTool bool) string {
|
||||
switch {
|
||||
case refusalFinishReasons[finishReason]:
|
||||
return "refusal"
|
||||
case usedTool:
|
||||
return "tool_use"
|
||||
case finishReason == "MAX_TOKENS":
|
||||
return "max_tokens"
|
||||
default:
|
||||
return "end_turn"
|
||||
}
|
||||
}
|
||||
|
||||
// ResponseTransformOptions 调整 Gemini→Claude 非流式转换的输出;零值不改变输出。
|
||||
type ResponseTransformOptions struct {
|
||||
// ThinkingSignaturePrefix 加在 thinking 块签名前;tool_use 的签名不加。
|
||||
ThinkingSignaturePrefix string
|
||||
// DropTextSignatures 丢弃 text part 上的签名,不再输出只为承载它的空 thinking 块。
|
||||
// Vertex 只强制校验 functionCall part 的签名,见
|
||||
// https://docs.cloud.google.com/vertex-ai/generative-ai/docs/thought-signatures
|
||||
DropTextSignatures bool
|
||||
}
|
||||
|
||||
// TransformGeminiToClaude 将 Gemini 响应转换为 Claude 格式(非流式)
|
||||
func TransformGeminiToClaude(geminiResp []byte, originalModel string) ([]byte, *ClaudeUsage, error) {
|
||||
return TransformGeminiToClaudeWithOptions(geminiResp, originalModel, ResponseTransformOptions{})
|
||||
}
|
||||
|
||||
// TransformGeminiToClaudeWithOptions 同 TransformGeminiToClaude,按 opts 调整输出。
|
||||
func TransformGeminiToClaudeWithOptions(geminiResp []byte, originalModel string, opts ResponseTransformOptions) ([]byte, *ClaudeUsage, error) {
|
||||
// 解包 v1internal 响应
|
||||
var v1Resp V1InternalResponse
|
||||
if err := json.Unmarshal(geminiResp, &v1Resp); err != nil {
|
||||
@@ -37,13 +97,25 @@ func TransformGeminiToClaude(geminiResp []byte, originalModel string) ([]byte, *
|
||||
v1Resp.ModelVersion = directResp.ModelVersion
|
||||
}
|
||||
|
||||
if len(v1Resp.Response.Candidates) > 0 && v1Resp.Response.Candidates[0].FinishReason == "MALFORMED_FUNCTION_CALL" {
|
||||
return nil, nil, ErrMalformedFunctionCall
|
||||
}
|
||||
|
||||
// 使用处理器转换
|
||||
processor := NewNonStreamingProcessor()
|
||||
processor.dropTextSignatures = opts.DropTextSignatures
|
||||
claudeResp := processor.Process(&v1Resp.Response, v1Resp.ResponseID, originalModel)
|
||||
if len(v1Resp.Response.Candidates) > 0 && !hasVisibleContent(claudeResp.Content) {
|
||||
switch finishReason := v1Resp.Response.Candidates[0].FinishReason; {
|
||||
case finishReason == "MALFORMED_FUNCTION_CALL":
|
||||
return nil, nil, ErrMalformedFunctionCall
|
||||
case invalidOutputFinishReasons[finishReason]:
|
||||
return nil, nil, fmt.Errorf("%w: %s", ErrInvalidOutputWithoutContent, finishReason)
|
||||
}
|
||||
}
|
||||
if opts.ThinkingSignaturePrefix != "" {
|
||||
for i := range claudeResp.Content {
|
||||
if block := &claudeResp.Content[i]; block.Type == "thinking" && block.Signature != "" {
|
||||
block.Signature = opts.ThinkingSignaturePrefix + block.Signature
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 序列化
|
||||
respBytes, err := json.Marshal(claudeResp)
|
||||
@@ -62,6 +134,8 @@ type NonStreamingProcessor struct {
|
||||
thinkingSignature string
|
||||
trailingSignature string
|
||||
hasToolCall bool
|
||||
// dropTextSignatures 见 ResponseTransformOptions.DropTextSignatures。
|
||||
dropTextSignatures bool
|
||||
}
|
||||
|
||||
// NewNonStreamingProcessor 创建非流式响应处理器
|
||||
@@ -134,11 +208,16 @@ func (p *NonStreamingProcessor) processPart(part *GeminiPart) {
|
||||
toolID = fmt.Sprintf("%s-%s", part.FunctionCall.Name, generateRandomID())
|
||||
}
|
||||
|
||||
// 无参调用也要带 input 字段:Anthropic 的 tool_use 块要求 input 是对象。
|
||||
input := part.FunctionCall.Args
|
||||
if input == nil {
|
||||
input = map[string]any{}
|
||||
}
|
||||
item := ClaudeContentItem{
|
||||
Type: "tool_use",
|
||||
ID: toolID,
|
||||
Name: part.FunctionCall.Name,
|
||||
Input: part.FunctionCall.Args,
|
||||
Input: input,
|
||||
}
|
||||
|
||||
if signature != "" {
|
||||
@@ -171,6 +250,9 @@ func (p *NonStreamingProcessor) processPart(part *GeminiPart) {
|
||||
p.thinkingSignature = signature
|
||||
}
|
||||
} else {
|
||||
if p.dropTextSignatures {
|
||||
signature = ""
|
||||
}
|
||||
// 普通 Text
|
||||
if part.Text == "" {
|
||||
// 空 text 带签名 - 暂存
|
||||
@@ -276,11 +358,9 @@ func (p *NonStreamingProcessor) buildResponse(geminiResp *GeminiResponse, respon
|
||||
}
|
||||
}
|
||||
|
||||
stopReason := "end_turn"
|
||||
if p.hasToolCall {
|
||||
stopReason = "tool_use"
|
||||
} else if finishReason == "MAX_TOKENS" {
|
||||
stopReason = "max_tokens"
|
||||
stopReason := claudeStopReason(finishReason, p.hasToolCall)
|
||||
if geminiResp.promptBlocked() {
|
||||
stopReason = "refusal"
|
||||
}
|
||||
|
||||
// 注意:Gemini 的 promptTokenCount 包含 cachedContentTokenCount,
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
//go:build unit
|
||||
|
||||
package antigravity
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestProcessorsKeepEmptyToolInputAndImageSignature(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
parts string
|
||||
wantSignatures []string
|
||||
wantNoArgsCall bool
|
||||
}{
|
||||
{
|
||||
name: "call without args keeps an empty input object",
|
||||
parts: `[{"functionCall":{"name":"TodoRead"},"thoughtSignature":"SIG_CALL"}]`,
|
||||
wantNoArgsCall: true,
|
||||
},
|
||||
{
|
||||
name: "signature on an image part stays out of the thinking blocks",
|
||||
parts: `[{"inlineData":{"mimeType":"image/png","data":"aGVsbG8="},"thoughtSignature":"SIG_IMAGE"}]`,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
chunk := `{"candidates":[{"content":{"role":"model","parts":` + tt.parts + `},"finishReason":"STOP"}]}`
|
||||
|
||||
t.Run("stream/"+tt.name, func(t *testing.T) {
|
||||
processor := NewStreamingProcessor("gemini-4-neon")
|
||||
out := string(processor.ProcessLine("data: " + chunk))
|
||||
final, _ := processor.Finish()
|
||||
out += string(final)
|
||||
|
||||
var got []string
|
||||
for _, line := range strings.Split(out, "\n") {
|
||||
data, ok := strings.CutPrefix(line, "data: ")
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
var event map[string]any
|
||||
require.NoError(t, json.Unmarshal([]byte(data), &event))
|
||||
if delta, _ := event["delta"].(map[string]any); delta["type"] == "signature_delta" {
|
||||
got = append(got, delta["signature"].(string))
|
||||
}
|
||||
}
|
||||
require.Equal(t, tt.wantSignatures, got)
|
||||
})
|
||||
|
||||
t.Run("non-stream/"+tt.name, func(t *testing.T) {
|
||||
body, _, err := TransformGeminiToClaude([]byte(chunk), "gemini-4-neon")
|
||||
require.NoError(t, err)
|
||||
var resp struct {
|
||||
Content []map[string]any `json:"content"`
|
||||
}
|
||||
require.NoError(t, json.Unmarshal(body, &resp))
|
||||
|
||||
var got []string
|
||||
for _, block := range resp.Content {
|
||||
if block["type"] == "thinking" {
|
||||
got = append(got, block["signature"].(string))
|
||||
}
|
||||
if block["type"] == "tool_use" && tt.wantNoArgsCall {
|
||||
require.Contains(t, block, "input")
|
||||
require.Equal(t, map[string]any{}, block["input"])
|
||||
}
|
||||
}
|
||||
require.Equal(t, tt.wantSignatures, got)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// 只带签名的 text part(空 text 或没有 text 字段)不产生内容块:回合以文本结束,与不设选项时一致。
|
||||
func TestSignatureOnlyTextPartAddsNoBlock(t *testing.T) {
|
||||
tails := map[string]string{
|
||||
"empty text part": `{"text":"","thoughtSignature":"SIG_TAIL"}`,
|
||||
"part without text": `{"thoughtSignature":"SIG_TAIL"}`,
|
||||
}
|
||||
options := map[string]ResponseTransformOptions{
|
||||
"zero options": {},
|
||||
"vertex options": {ThinkingSignaturePrefix: "vertex-thought-v1:", DropTextSignatures: true},
|
||||
}
|
||||
want := []testBlock{{Type: "text", Text: "Hello world"}}
|
||||
|
||||
for tailName, tail := range tails {
|
||||
for optionsName, opts := range options {
|
||||
t.Run("stream/"+optionsName+"/"+tailName, func(t *testing.T) {
|
||||
processor := NewStreamingProcessor("gemini-4-neon")
|
||||
processor.SetThinkingSignaturePrefix(opts.ThinkingSignaturePrefix)
|
||||
processor.SetDropTextSignatures(opts.DropTextSignatures)
|
||||
out := string(processor.ProcessLine(`data: {"candidates":[{"content":{"role":"model","parts":[{"text":"Hello world"}]}}]}`))
|
||||
out += string(processor.ProcessLine(`data: {"candidates":[{"content":{"role":"model","parts":[` + tail + `]},"finishReason":"STOP"}]}`))
|
||||
final, _ := processor.Finish()
|
||||
require.Equal(t, want, streamTestBlocks(t, out+string(final)))
|
||||
})
|
||||
|
||||
t.Run("non-stream/"+optionsName+"/"+tailName, func(t *testing.T) {
|
||||
body := `{"candidates":[{"content":{"role":"model","parts":[{"text":"Hello world"},` + tail + `]},"finishReason":"STOP"}]}`
|
||||
claudeResp, _, err := TransformGeminiToClaudeWithOptions([]byte(body), "gemini-4-neon", opts)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, want, nonStreamTestBlocks(t, claudeResp))
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -34,6 +34,10 @@ type StreamingProcessor struct {
|
||||
webSearchQueries []string
|
||||
groundingChunks []GeminiGroundingChunk
|
||||
usageMapHook UsageMapHook
|
||||
// thinkingSignaturePrefix 加在 thinking 块签名前;tool_use 的签名不加。
|
||||
thinkingSignaturePrefix string
|
||||
// dropTextSignatures 见 ResponseTransformOptions.DropTextSignatures。
|
||||
dropTextSignatures bool
|
||||
|
||||
// 累计 usage
|
||||
inputTokens int
|
||||
@@ -41,6 +45,12 @@ type StreamingProcessor struct {
|
||||
cacheReadTokens int
|
||||
imageOutputTokens int
|
||||
hasContent bool
|
||||
|
||||
promptBlocked bool
|
||||
// visibleContent 表示已开始过 text 或 tool_use 块(思考块不算)。
|
||||
visibleContent bool
|
||||
// streamFailed 表示已发出 error 事件,之后不再输出任何事件。
|
||||
streamFailed bool
|
||||
}
|
||||
|
||||
// NewStreamingProcessor 创建流式响应处理器
|
||||
@@ -51,6 +61,18 @@ func NewStreamingProcessor(originalModel string) *StreamingProcessor {
|
||||
}
|
||||
}
|
||||
|
||||
// SetThinkingSignaturePrefix sets a prefix for the signatures of thinking blocks.
|
||||
// tool_use signatures are not changed. An empty prefix keeps the output unchanged.
|
||||
func (p *StreamingProcessor) SetThinkingSignaturePrefix(prefix string) {
|
||||
p.thinkingSignaturePrefix = prefix
|
||||
}
|
||||
|
||||
// SetDropTextSignatures drops the signatures of text parts, so no empty thinking
|
||||
// block is emitted to carry them. Thinking and tool_use signatures are kept.
|
||||
func (p *StreamingProcessor) SetDropTextSignatures(drop bool) {
|
||||
p.dropTextSignatures = drop
|
||||
}
|
||||
|
||||
// SetUsageMapHook sets an optional hook that modifies usage maps before they are emitted.
|
||||
func (p *StreamingProcessor) SetUsageMapHook(fn UsageMapHook) {
|
||||
p.usageMapHook = fn
|
||||
@@ -128,6 +150,10 @@ func (p *StreamingProcessor) ProcessLine(line string) []byte {
|
||||
p.imageOutputTokens = geminiResp.UsageMetadata.ImageOutputTokens()
|
||||
}
|
||||
|
||||
if p.streamFailed {
|
||||
return result.Bytes()
|
||||
}
|
||||
|
||||
// 处理 parts
|
||||
if len(geminiResp.Candidates) > 0 && geminiResp.Candidates[0].Content != nil {
|
||||
for _, part := range geminiResp.Candidates[0].Content.Parts {
|
||||
@@ -154,6 +180,10 @@ func (p *StreamingProcessor) ProcessLine(line string) []byte {
|
||||
_, _ = result.Write(p.emitFinish(finishReason))
|
||||
}
|
||||
}
|
||||
if geminiResp.promptBlocked() {
|
||||
p.promptBlocked = true
|
||||
_, _ = result.Write(p.emitFinish(geminiResp.PromptFeedback.BlockReason))
|
||||
}
|
||||
|
||||
return result.Bytes()
|
||||
}
|
||||
@@ -264,6 +294,9 @@ func (p *StreamingProcessor) processPart(part *GeminiPart) []byte {
|
||||
if part.Thought {
|
||||
_, _ = result.Write(p.processThinking(part.Text, signature))
|
||||
} else {
|
||||
if p.dropTextSignatures {
|
||||
signature = ""
|
||||
}
|
||||
_, _ = result.Write(p.processText(part.Text, signature))
|
||||
}
|
||||
}
|
||||
@@ -430,6 +463,9 @@ func (p *StreamingProcessor) startBlock(blockType BlockType, contentBlock map[st
|
||||
|
||||
_, _ = result.Write(p.formatSSE("content_block_start", event))
|
||||
p.blockType = blockType
|
||||
if blockType == BlockTypeText || blockType == BlockTypeFunction {
|
||||
p.visibleContent = true
|
||||
}
|
||||
|
||||
return result.Bytes()
|
||||
}
|
||||
@@ -445,7 +481,7 @@ func (p *StreamingProcessor) endBlock() []byte {
|
||||
// Thinking 块结束时发送暂存的签名
|
||||
if p.blockType == BlockTypeThinking && p.pendingSignature != "" {
|
||||
_, _ = result.Write(p.emitDelta("signature_delta", map[string]any{
|
||||
"signature": p.pendingSignature,
|
||||
"signature": p.thinkingSignaturePrefix + p.pendingSignature,
|
||||
}))
|
||||
p.pendingSignature = ""
|
||||
}
|
||||
@@ -494,7 +530,7 @@ func (p *StreamingProcessor) emitEmptyThinkingWithSignature(signature string) []
|
||||
"thinking": "",
|
||||
}))
|
||||
_, _ = result.Write(p.emitDelta("signature_delta", map[string]any{
|
||||
"signature": signature,
|
||||
"signature": p.thinkingSignaturePrefix + signature,
|
||||
}))
|
||||
_, _ = result.Write(p.endBlock())
|
||||
|
||||
@@ -503,6 +539,23 @@ func (p *StreamingProcessor) emitEmptyThinkingWithSignature(signature string) []
|
||||
|
||||
// emitFinish 发送结束事件
|
||||
func (p *StreamingProcessor) emitFinish(finishReason string) []byte {
|
||||
if p.streamFailed {
|
||||
return nil
|
||||
}
|
||||
// 模型产出无效且没有输出 text 或 tool_use:发可重试的 error 事件,Claude 客户端会重发请求。
|
||||
// 思考块不算:开启思考时,无效调用之前几乎总有思考摘要。
|
||||
if invalidOutputFinishReasons[finishReason] && !p.visibleContent {
|
||||
p.streamFailed = true
|
||||
p.messageStopSent = true
|
||||
return p.formatSSE("error", map[string]any{
|
||||
"type": "error",
|
||||
"error": map[string]any{
|
||||
"type": "api_error",
|
||||
"message": "upstream finished with " + finishReason + " and no content",
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
var result bytes.Buffer
|
||||
|
||||
// 关闭最后一个块
|
||||
@@ -532,11 +585,9 @@ func (p *StreamingProcessor) emitFinish(finishReason string) []byte {
|
||||
}
|
||||
|
||||
// 确定 stop_reason
|
||||
stopReason := "end_turn"
|
||||
if p.usedTool {
|
||||
stopReason = "tool_use"
|
||||
} else if finishReason == "MAX_TOKENS" {
|
||||
stopReason = "max_tokens"
|
||||
stopReason := claudeStopReason(finishReason, p.usedTool)
|
||||
if p.promptBlocked {
|
||||
stopReason = "refusal"
|
||||
}
|
||||
|
||||
usage := ClaudeUsage{
|
||||
|
||||
@@ -0,0 +1,210 @@
|
||||
package antigravity
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"strings"
|
||||
"testing"
|
||||
"testing/quick"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// Messages shaped like Claude Code's: a {role: "system"} message with the
|
||||
// environment after the first user message, and another {role: "system"}
|
||||
// notice after every tool result. The newest system message carries
|
||||
// cache_control as a block list; once it is history the client sends it as a
|
||||
// plain string.
|
||||
const (
|
||||
ccAsk = `{"role":"user","content":[{"type":"text","text":"read f.txt"}]}`
|
||||
ccEnvLatest = `{"role":"system","content":[{"type":"text","text":"# Environment\nPrimary working directory: /repo","cache_control":{"type":"ephemeral"}}]}`
|
||||
ccEnv = `{"role":"system","content":"# Environment\nPrimary working directory: /repo"}`
|
||||
ccCall1 = `{"role":"assistant","content":[{"type":"tool_use","id":"toolu_1","name":"Read","input":{"file_path":"/repo/f.txt"}}]}`
|
||||
ccResult1 = `{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_1","content":"hello"}]}`
|
||||
ccCall2 = `{"role":"assistant","content":[{"type":"tool_use","id":"toolu_2","name":"Read","input":{"file_path":"/repo/g.txt"}}]}`
|
||||
ccResult2 = `{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_2","content":"world"}]}`
|
||||
ccNotice = `{"role":"system","content":"Plain output style is active."}`
|
||||
ccNoticeLast = `{"role":"system","content":[{"type":"text","text":"Plain output style is active.","cache_control":{"type":"ephemeral"}}]}`
|
||||
)
|
||||
|
||||
func transformClaudeCodeMessages(t *testing.T, msgs ...string) V1InternalRequest {
|
||||
t.Helper()
|
||||
var messages []ClaudeMessage
|
||||
require.NoError(t, json.Unmarshal([]byte("["+strings.Join(msgs, ",")+"]"), &messages))
|
||||
body, err := TransformClaudeToGeminiWithOptions(&ClaudeRequest{
|
||||
Model: "gemini-4-neon",
|
||||
System: json.RawMessage(`"You are Claude Code."`),
|
||||
Messages: messages,
|
||||
Tools: []ClaudeTool{{Name: "Read", Description: "Read a file", InputSchema: map[string]any{"type": "object"}}},
|
||||
}, "project-1", "gemini-4-neon-high", DefaultTransformOptions())
|
||||
require.NoError(t, err)
|
||||
var req V1InternalRequest
|
||||
require.NoError(t, json.Unmarshal(body, &req))
|
||||
return req
|
||||
}
|
||||
|
||||
func mustJSON(t *testing.T, v any) string {
|
||||
t.Helper()
|
||||
b, err := json.Marshal(v)
|
||||
require.NoError(t, err)
|
||||
return string(b)
|
||||
}
|
||||
|
||||
// Gemini's implicit cache matches the prompt from its first byte, and the
|
||||
// systemInstruction comes before the conversation. Each request of a tool loop
|
||||
// must therefore keep the previous request's systemInstruction, tools and
|
||||
// contents byte for byte and only add to the end.
|
||||
func TestClaudeCodeToolLoopKeepsThePromptPrefix(t *testing.T) {
|
||||
requests := []V1InternalRequest{
|
||||
transformClaudeCodeMessages(t, ccAsk, ccEnvLatest),
|
||||
transformClaudeCodeMessages(t, ccAsk, ccEnv, ccCall1, ccResult1, ccNoticeLast),
|
||||
transformClaudeCodeMessages(t, ccAsk, ccEnv, ccCall1, ccResult1, ccNotice, ccCall2, ccResult2, ccNoticeLast),
|
||||
}
|
||||
for n := 1; n < len(requests); n++ {
|
||||
before, now := requests[n-1].Request, requests[n].Request
|
||||
require.Equal(t, mustJSON(t, before.SystemInstruction), mustJSON(t, now.SystemInstruction), "request %d changed the systemInstruction", n+1)
|
||||
require.Equal(t, mustJSON(t, before.Tools), mustJSON(t, now.Tools), "request %d changed the tools", n+1)
|
||||
require.Greater(t, len(now.Contents), len(before.Contents))
|
||||
for i := range before.Contents {
|
||||
require.Equal(t, mustJSON(t, before.Contents[i]), mustJSON(t, now.Contents[i]), "request %d changed content %d of the request before", n+1, i)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The same holds for any conversation that grows the way Claude Code grows
|
||||
// it: tool calls, tool results with notices after some of them or between a
|
||||
// call and its result, finished replies and new questions.
|
||||
func TestGrowingConversationOnlyAddsToThePrompt(t *testing.T) {
|
||||
notices := []string{"Plain output style is active.", " The user hasn't heard from you in a while.\n", "Today's date is 2026-12-01."}
|
||||
// system renders a system message; the newest one comes as blocks with
|
||||
// cache_control, older ones as strings.
|
||||
system := func(text string, newest bool) string {
|
||||
if newest {
|
||||
return mustJSON(t, map[string]any{"role": "system", "content": []map[string]any{{"type": "text", "text": text, "cache_control": map[string]string{"type": "ephemeral"}}}})
|
||||
}
|
||||
return mustJSON(t, map[string]any{"role": "system", "content": text})
|
||||
}
|
||||
type message struct {
|
||||
json string
|
||||
notice string // the text of a system message, rendered by position
|
||||
}
|
||||
render := func(msgs []message) []string {
|
||||
out := make([]string, len(msgs))
|
||||
for i, m := range msgs {
|
||||
if m.notice != "" {
|
||||
out[i] = system(m.notice, i == len(msgs)-1)
|
||||
} else {
|
||||
out[i] = m.json
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
property := func(seed int64) bool {
|
||||
rng := rand.New(rand.NewSource(seed))
|
||||
msgs := []message{{json: ccAsk}, {notice: "# Environment\nPrimary working directory: /repo"}}
|
||||
var requests [][]string
|
||||
requests = append(requests, render(msgs))
|
||||
for step := 0; step < 2+rng.Intn(8); step++ {
|
||||
id := fmt.Sprintf("toolu_%d", step)
|
||||
if rng.Intn(4) == 0 {
|
||||
msgs = append(msgs,
|
||||
message{json: mustJSON(t, map[string]any{"role": "assistant", "content": fmt.Sprintf("answer %d", step)})},
|
||||
message{json: mustJSON(t, map[string]any{"role": "user", "content": fmt.Sprintf("question %d", step)})})
|
||||
} else {
|
||||
msgs = append(msgs, message{json: mustJSON(t, map[string]any{"role": "assistant", "content": []map[string]any{
|
||||
{"type": "tool_use", "id": id, "name": "Read", "input": map[string]string{"file_path": id}}}})})
|
||||
if rng.Intn(5) == 0 {
|
||||
msgs = append(msgs, message{notice: notices[rng.Intn(len(notices))]})
|
||||
}
|
||||
msgs = append(msgs, message{json: mustJSON(t, map[string]any{"role": "user", "content": []map[string]any{
|
||||
{"type": "tool_result", "tool_use_id": id, "content": fmt.Sprintf("result %d", step)}}})})
|
||||
}
|
||||
for n := rng.Intn(3); n > 0; n-- {
|
||||
msgs = append(msgs, message{notice: notices[rng.Intn(len(notices))]})
|
||||
}
|
||||
requests = append(requests, render(msgs))
|
||||
}
|
||||
var before V1InternalRequest
|
||||
for n, r := range requests {
|
||||
now := transformClaudeCodeMessages(t, r...)
|
||||
for i, c := range now.Request.Contents {
|
||||
if c.Role == "system" || (i > 0 && now.Request.Contents[i-1].Role == c.Role) {
|
||||
t.Logf("seed %d request %d: content %d has role %q after %q", seed, n, i, c.Role, now.Request.Contents[max(i-1, 0)].Role)
|
||||
return false
|
||||
}
|
||||
}
|
||||
if n > 0 {
|
||||
if mustJSON(t, before.Request.SystemInstruction) != mustJSON(t, now.Request.SystemInstruction) {
|
||||
t.Logf("seed %d request %d changed the systemInstruction", seed, n)
|
||||
return false
|
||||
}
|
||||
for i := range before.Request.Contents {
|
||||
if mustJSON(t, before.Request.Contents[i]) != mustJSON(t, now.Request.Contents[i]) {
|
||||
t.Logf("seed %d request %d changed content %d", seed, n, i)
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
before = now
|
||||
}
|
||||
return true
|
||||
}
|
||||
require.NoError(t, quick.Check(property, &quick.Config{MaxCount: 300}))
|
||||
}
|
||||
|
||||
func TestSystemMessagesBeforeTheFirstModelTurnStayInSystemInstruction(t *testing.T) {
|
||||
req := transformClaudeCodeMessages(t, ccAsk, ccEnvLatest, ccCall1, ccResult1, ccNoticeLast).Request
|
||||
|
||||
var system []string
|
||||
for _, p := range req.SystemInstruction.Parts {
|
||||
system = append(system, p.Text)
|
||||
}
|
||||
joined := strings.Join(system, "\n")
|
||||
require.Contains(t, joined, "# Environment")
|
||||
require.NotContains(t, joined, "Plain output style is active.")
|
||||
}
|
||||
|
||||
func TestSystemNoticeFollowsTheToolResultsOfItsUserTurn(t *testing.T) {
|
||||
req := transformClaudeCodeMessages(t, ccAsk, ccEnv, ccCall1, ccResult1, ccNotice, ccCall2, ccResult2, ccNoticeLast).Request
|
||||
|
||||
require.Len(t, req.Contents, 5)
|
||||
for i, c := range req.Contents {
|
||||
require.NotEqual(t, "system", c.Role)
|
||||
if i > 0 {
|
||||
require.NotEqual(t, req.Contents[i-1].Role, c.Role, "contents %d and %d share a role", i-1, i)
|
||||
}
|
||||
}
|
||||
for _, i := range []int{2, 4} {
|
||||
parts := req.Contents[i].Parts
|
||||
require.Equal(t, "user", req.Contents[i].Role)
|
||||
require.Len(t, parts, 2)
|
||||
require.NotNil(t, parts[0].FunctionResponse, "the tool result must come first")
|
||||
require.Equal(t, "<system-reminder>\nPlain output style is active.\n</system-reminder>", parts[1].Text)
|
||||
}
|
||||
}
|
||||
|
||||
// A notice between a model turn and the user turn holding its tool results
|
||||
// joins that user turn after the results: a functionCall must be followed
|
||||
// directly by its functionResponse.
|
||||
func TestSystemNoticeAfterAModelTurnWaitsForTheNextUserTurn(t *testing.T) {
|
||||
req := transformClaudeCodeMessages(t, ccAsk, ccEnv, ccCall1, ccNotice, ccResult1).Request
|
||||
|
||||
require.Len(t, req.Contents, 3)
|
||||
require.Equal(t, "model", req.Contents[1].Role)
|
||||
last := req.Contents[2]
|
||||
require.Equal(t, "user", last.Role)
|
||||
require.Len(t, last.Parts, 2)
|
||||
require.NotNil(t, last.Parts[0].FunctionResponse)
|
||||
require.Contains(t, last.Parts[1].Text, "Plain output style is active.")
|
||||
}
|
||||
|
||||
func TestSystemNoticeEndingTheRequestAfterAModelTurnBecomesAUserTurn(t *testing.T) {
|
||||
req := transformClaudeCodeMessages(t, ccAsk, ccEnv, `{"role":"assistant","content":"partial answer"}`, ccNotice).Request
|
||||
|
||||
require.Len(t, req.Contents, 3)
|
||||
require.Equal(t, "model", req.Contents[1].Role)
|
||||
require.Equal(t, "user", req.Contents[2].Role)
|
||||
require.Contains(t, req.Contents[2].Parts[0].Text, "Plain output style is active.")
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
//go:build unit
|
||||
|
||||
package antigravity
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// testBlock 是客户端看到的一个内容块:类型、文本(text 或 thinking)与签名。
|
||||
type testBlock struct {
|
||||
Type string
|
||||
Text string
|
||||
Signature string
|
||||
}
|
||||
|
||||
// streamTestBlocks 按 SSE 事件重建客户端的内容块。
|
||||
func streamTestBlocks(t *testing.T, sse string) []testBlock {
|
||||
t.Helper()
|
||||
var blocks []testBlock
|
||||
for _, line := range strings.Split(sse, "\n") {
|
||||
data, ok := strings.CutPrefix(line, "data: ")
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
var event struct {
|
||||
Type string `json:"type"`
|
||||
ContentBlock map[string]any `json:"content_block"`
|
||||
Delta map[string]any `json:"delta"`
|
||||
}
|
||||
require.NoError(t, json.Unmarshal([]byte(data), &event))
|
||||
switch event.Type {
|
||||
case "content_block_start":
|
||||
block := testBlock{Type: event.ContentBlock["type"].(string)}
|
||||
block.Signature, _ = event.ContentBlock["signature"].(string)
|
||||
blocks = append(blocks, block)
|
||||
case "content_block_delta":
|
||||
last := &blocks[len(blocks)-1]
|
||||
switch event.Delta["type"] {
|
||||
case "text_delta":
|
||||
last.Text += event.Delta["text"].(string)
|
||||
case "thinking_delta":
|
||||
last.Text += event.Delta["thinking"].(string)
|
||||
case "signature_delta":
|
||||
last.Signature = event.Delta["signature"].(string)
|
||||
}
|
||||
}
|
||||
}
|
||||
return blocks
|
||||
}
|
||||
|
||||
func nonStreamTestBlocks(t *testing.T, body []byte) []testBlock {
|
||||
t.Helper()
|
||||
var resp struct {
|
||||
Content []struct {
|
||||
Type string `json:"type"`
|
||||
Text string `json:"text"`
|
||||
Thinking string `json:"thinking"`
|
||||
Signature string `json:"signature"`
|
||||
} `json:"content"`
|
||||
}
|
||||
require.NoError(t, json.Unmarshal(body, &resp))
|
||||
blocks := make([]testBlock, 0, len(resp.Content))
|
||||
for _, item := range resp.Content {
|
||||
blocks = append(blocks, testBlock{Type: item.Type, Text: item.Text + item.Thinking, Signature: item.Signature})
|
||||
}
|
||||
return blocks
|
||||
}
|
||||
|
||||
func TestDropTextSignatures(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
parts string
|
||||
drop []testBlock
|
||||
keep []testBlock
|
||||
}{
|
||||
{
|
||||
name: "a signature on the final text part",
|
||||
parts: `{"text":"Answer.","thoughtSignature":"SIG_TEXT"}`,
|
||||
drop: []testBlock{{Type: "text", Text: "Answer."}},
|
||||
keep: []testBlock{{Type: "text", Text: "Answer."}, {Type: "thinking", Signature: "SIG_TEXT"}},
|
||||
},
|
||||
{
|
||||
name: "a signature in a trailing empty text part",
|
||||
parts: `{"text":"Answer."},{"text":"","thoughtSignature":"SIG_TAIL"}`,
|
||||
drop: []testBlock{{Type: "text", Text: "Answer."}},
|
||||
keep: []testBlock{{Type: "text", Text: "Answer."}},
|
||||
},
|
||||
{
|
||||
name: "a real thinking block keeps its signature",
|
||||
parts: `{"text":"plan","thought":true,"thoughtSignature":"SIG_THOUGHT"},{"text":"Answer.","thoughtSignature":"SIG_TEXT"}`,
|
||||
drop: []testBlock{{Type: "thinking", Text: "plan", Signature: "SIG_THOUGHT"}, {Type: "text", Text: "Answer."}},
|
||||
keep: []testBlock{{Type: "thinking", Text: "plan", Signature: "SIG_THOUGHT"}, {Type: "text", Text: "Answer."},
|
||||
{Type: "thinking", Signature: "SIG_TEXT"}},
|
||||
},
|
||||
{
|
||||
name: "a function call keeps tool_use.signature",
|
||||
parts: `{"text":"Reading.","thoughtSignature":"SIG_TEXT"},{"functionCall":{"name":"Read","args":{}},"thoughtSignature":"SIG_CALL"}`,
|
||||
drop: []testBlock{{Type: "text", Text: "Reading."}, {Type: "tool_use", Signature: "SIG_CALL"}},
|
||||
keep: []testBlock{{Type: "text", Text: "Reading."}, {Type: "thinking", Signature: "SIG_TEXT"},
|
||||
{Type: "tool_use", Signature: "SIG_CALL"}},
|
||||
},
|
||||
{
|
||||
name: "text split around a signed part stays in order",
|
||||
parts: `{"text":"One "},{"text":"two ","thoughtSignature":"SIG_TEXT"},{"text":"three."}`,
|
||||
drop: []testBlock{{Type: "text", Text: "One two three."}},
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
chunk := `{"candidates":[{"content":{"role":"model","parts":[` + tt.parts + `]},"finishReason":"STOP"}]}`
|
||||
for _, drop := range []bool{true, false} {
|
||||
want := tt.keep
|
||||
mode := "keep"
|
||||
if drop {
|
||||
want, mode = tt.drop, "drop"
|
||||
}
|
||||
if want == nil {
|
||||
continue
|
||||
}
|
||||
t.Run("stream/"+mode+"/"+tt.name, func(t *testing.T) {
|
||||
processor := NewStreamingProcessor("gemini-4-neon")
|
||||
processor.SetDropTextSignatures(drop)
|
||||
out := string(processor.ProcessLine("data: " + chunk))
|
||||
final, _ := processor.Finish()
|
||||
require.Equal(t, want, streamTestBlocks(t, out+string(final)))
|
||||
})
|
||||
t.Run("non-stream/"+mode+"/"+tt.name, func(t *testing.T) {
|
||||
body, _, err := TransformGeminiToClaudeWithOptions([]byte(chunk), "gemini-4-neon", ResponseTransformOptions{DropTextSignatures: drop})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, want, nonStreamTestBlocks(t, body))
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
//go:build unit
|
||||
|
||||
package antigravity
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestThinkingSignaturePrefixMarksOnlyThinkingBlocks(t *testing.T) {
|
||||
const chunk = `{"candidates":[{"content":{"role":"model","parts":[` +
|
||||
`{"text":"plan","thought":true,"thoughtSignature":"SIG_THOUGHT"},` +
|
||||
`{"functionCall":{"name":"Read","args":{}},"thoughtSignature":"SIG_CALL"},` +
|
||||
`{"text":"Done.","thoughtSignature":"SIG_TAIL"}]},"finishReason":"STOP"}]}`
|
||||
|
||||
for _, prefix := range []string{"", "p:"} {
|
||||
t.Run("stream/prefix="+prefix, func(t *testing.T) {
|
||||
processor := NewStreamingProcessor("gemini-4-neon")
|
||||
processor.SetThinkingSignaturePrefix(prefix)
|
||||
out := string(processor.ProcessLine("data: " + chunk))
|
||||
final, _ := processor.Finish()
|
||||
out += string(final)
|
||||
|
||||
var thinking, toolUse []string
|
||||
for _, line := range strings.Split(out, "\n") {
|
||||
data, ok := strings.CutPrefix(line, "data: ")
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
var event map[string]any
|
||||
require.NoError(t, json.Unmarshal([]byte(data), &event))
|
||||
if delta, _ := event["delta"].(map[string]any); delta["type"] == "signature_delta" {
|
||||
thinking = append(thinking, delta["signature"].(string))
|
||||
}
|
||||
if block, _ := event["content_block"].(map[string]any); block["type"] == "tool_use" {
|
||||
toolUse = append(toolUse, block["signature"].(string))
|
||||
}
|
||||
}
|
||||
require.Equal(t, []string{prefix + "SIG_THOUGHT", prefix + "SIG_TAIL"}, thinking)
|
||||
require.Equal(t, []string{"SIG_CALL"}, toolUse)
|
||||
})
|
||||
|
||||
t.Run("non-stream/prefix="+prefix, func(t *testing.T) {
|
||||
body, _, err := TransformGeminiToClaudeWithOptions([]byte(chunk), "gemini-4-neon", ResponseTransformOptions{ThinkingSignaturePrefix: prefix})
|
||||
require.NoError(t, err)
|
||||
var resp struct {
|
||||
Content []map[string]any `json:"content"`
|
||||
}
|
||||
require.NoError(t, json.Unmarshal(body, &resp))
|
||||
var thinking, toolUse []string
|
||||
for _, block := range resp.Content {
|
||||
switch block["type"] {
|
||||
case "thinking":
|
||||
thinking = append(thinking, block["signature"].(string))
|
||||
case "tool_use":
|
||||
toolUse = append(toolUse, block["signature"].(string))
|
||||
}
|
||||
}
|
||||
require.Equal(t, []string{prefix + "SIG_THOUGHT", prefix + "SIG_TAIL"}, thinking)
|
||||
require.Equal(t, []string{"SIG_CALL"}, toolUse)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package apicompat
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestAnthropicRequest_TopLevelCacheControlJSON(t *testing.T) {
|
||||
t.Run("omitted when nil", func(t *testing.T) {
|
||||
req := AnthropicRequest{
|
||||
Model: "claude-opus-5-5",
|
||||
MaxTokens: 1024,
|
||||
Messages: []AnthropicMessage{{Role: "user", Content: json.RawMessage(`"hi"`)}},
|
||||
}
|
||||
raw, err := json.Marshal(req)
|
||||
require.NoError(t, err)
|
||||
require.NotContains(t, string(raw), `"cache_control"`)
|
||||
})
|
||||
|
||||
t.Run("round-trips top-level cache_control", func(t *testing.T) {
|
||||
req := AnthropicRequest{
|
||||
Model: "claude-opus-5-5",
|
||||
MaxTokens: 1024,
|
||||
Messages: []AnthropicMessage{{Role: "user", Content: json.RawMessage(`"hi"`)}},
|
||||
CacheControl: &AnthropicCacheControl{Type: "ephemeral", TTL: "1h"},
|
||||
}
|
||||
raw, err := json.Marshal(req)
|
||||
require.NoError(t, err)
|
||||
require.Contains(t, string(raw), `"cache_control":{"type":"ephemeral","ttl":"1h"}`)
|
||||
|
||||
var decoded AnthropicRequest
|
||||
require.NoError(t, json.Unmarshal(raw, &decoded))
|
||||
require.NotNil(t, decoded.CacheControl)
|
||||
require.Equal(t, "ephemeral", decoded.CacheControl.Type)
|
||||
require.Equal(t, "1h", decoded.CacheControl.TTL)
|
||||
})
|
||||
}
|
||||
@@ -147,10 +147,30 @@ func ResponsesToAnthropicRequest(req *ResponsesRequest) (*AnthropicRequest, erro
|
||||
}
|
||||
}
|
||||
}
|
||||
ensureMaxTokensAboveThinkingBudget(out)
|
||||
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// thinkingBudgetMaxTokensPadding is the room left above budget_tokens when
|
||||
// max_tokens has to be raised; same value as antigravity.MaxTokensBudgetPadding.
|
||||
const thinkingBudgetMaxTokensPadding = 1000
|
||||
|
||||
// ensureMaxTokensAboveThinkingBudget keeps an enabled thinking budget valid.
|
||||
// Anthropic requires max_tokens > thinking.budget_tokens, but the effort-derived
|
||||
// budget (high 10240, max 32768) is larger than the 8192 default used when the
|
||||
// Responses request carries no max_output_tokens, and Codex never sends one,
|
||||
// so every effort above medium was rejected with a 400. Raise max_tokens the
|
||||
// same way the Antigravity transformer does (ensureMaxTokensGreaterThanBudget).
|
||||
func ensureMaxTokensAboveThinkingBudget(out *AnthropicRequest) {
|
||||
if out == nil || out.Thinking == nil || out.Thinking.Type != "enabled" {
|
||||
return
|
||||
}
|
||||
if budget := out.Thinking.BudgetTokens; budget > 0 && out.MaxTokens <= budget {
|
||||
out.MaxTokens = budget + thinkingBudgetMaxTokensPadding
|
||||
}
|
||||
}
|
||||
|
||||
// defaultThinkingBudget returns a sensible thinking budget based on effort level.
|
||||
func defaultThinkingBudget(effort string) int {
|
||||
switch effort {
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
package apicompat
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// #6569: Anthropic rejects thinking.budget_tokens >= max_tokens. The matrix
|
||||
// mirrors the reported probes on claude-opus-4-6, where every effort above
|
||||
// medium returned 400 without max_output_tokens (Codex never sends it).
|
||||
func TestResponsesToAnthropicRequestKeepsMaxTokensAboveThinkingBudget(t *testing.T) {
|
||||
intPtr := func(v int) *int { return &v }
|
||||
tests := []struct {
|
||||
name string
|
||||
effort string
|
||||
maxOutput *int
|
||||
wantBudget int
|
||||
wantMaxTokens int
|
||||
}{
|
||||
{name: "medium default fits", effort: "medium", wantBudget: 4096, wantMaxTokens: 8192},
|
||||
{name: "high default is raised", effort: "high", wantBudget: 10240, wantMaxTokens: 11240},
|
||||
{name: "high 8192 is raised", effort: "high", maxOutput: intPtr(8192), wantBudget: 10240, wantMaxTokens: 11240},
|
||||
{name: "high 10000 is raised", effort: "high", maxOutput: intPtr(10000), wantBudget: 10240, wantMaxTokens: 11240},
|
||||
{name: "high equal to budget is raised", effort: "high", maxOutput: intPtr(10240), wantBudget: 10240, wantMaxTokens: 11240},
|
||||
{name: "high 12000 already fits", effort: "high", maxOutput: intPtr(12000), wantBudget: 10240, wantMaxTokens: 12000},
|
||||
{name: "xhigh default is raised", effort: "xhigh", wantBudget: 32768, wantMaxTokens: 33768},
|
||||
{name: "xhigh 32000 is raised", effort: "xhigh", maxOutput: intPtr(32000), wantBudget: 32768, wantMaxTokens: 33768},
|
||||
{name: "xhigh 64000 already fits", effort: "xhigh", maxOutput: intPtr(64000), wantBudget: 32768, wantMaxTokens: 64000},
|
||||
{name: "max default is raised", effort: "max", wantBudget: 32768, wantMaxTokens: 33768},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
out, err := ResponsesToAnthropicRequest(&ResponsesRequest{
|
||||
Model: "claude-opus-4-6",
|
||||
Input: json.RawMessage(`"hi"`),
|
||||
MaxOutputTokens: tt.maxOutput,
|
||||
Reasoning: &ResponsesReasoning{Effort: tt.effort},
|
||||
})
|
||||
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, out.Thinking)
|
||||
require.Equal(t, "enabled", out.Thinking.Type)
|
||||
require.Equal(t, tt.wantBudget, out.Thinking.BudgetTokens)
|
||||
require.Equal(t, tt.wantMaxTokens, out.MaxTokens)
|
||||
require.Greater(t, out.MaxTokens, out.Thinking.BudgetTokens)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestResponsesToAnthropicRequestLeavesMaxTokensWithoutEnabledThinking(t *testing.T) {
|
||||
low, err := ResponsesToAnthropicRequest(&ResponsesRequest{
|
||||
Model: "claude-opus-4-6", Input: json.RawMessage(`"hi"`), Reasoning: &ResponsesReasoning{Effort: "low"},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Nil(t, low.Thinking)
|
||||
require.Equal(t, 8192, low.MaxTokens)
|
||||
|
||||
noReasoning, err := ResponsesToAnthropicRequest(&ResponsesRequest{Model: "claude-opus-4-6", Input: json.RawMessage(`"hi"`)})
|
||||
require.NoError(t, err)
|
||||
require.Nil(t, noReasoning.Thinking)
|
||||
require.Equal(t, 8192, noReasoning.MaxTokens)
|
||||
}
|
||||
|
||||
func TestEnsureMaxTokensAboveThinkingBudgetIgnoresNonEnabledThinking(t *testing.T) {
|
||||
adaptive := &AnthropicRequest{MaxTokens: 8192, Thinking: &AnthropicThinking{Type: "adaptive", BudgetTokens: 10240}}
|
||||
ensureMaxTokensAboveThinkingBudget(adaptive)
|
||||
require.Equal(t, 8192, adaptive.MaxTokens)
|
||||
|
||||
ensureMaxTokensAboveThinkingBudget(nil)
|
||||
noThinking := &AnthropicRequest{MaxTokens: 100}
|
||||
ensureMaxTokensAboveThinkingBudget(noThinking)
|
||||
require.Equal(t, 100, noThinking.MaxTokens)
|
||||
}
|
||||
@@ -33,6 +33,7 @@ type AnthropicRequest struct {
|
||||
// user_id,进而导致请求被归类为第三方 app。
|
||||
Metadata json.RawMessage `json:"metadata,omitempty"`
|
||||
OutputConfig *AnthropicOutputConfig `json:"output_config,omitempty"`
|
||||
CacheControl *AnthropicCacheControl `json:"cache_control,omitempty"`
|
||||
}
|
||||
|
||||
// AnthropicOutputConfig controls output generation parameters.
|
||||
|
||||
@@ -25,9 +25,16 @@ type Question struct {
|
||||
}
|
||||
|
||||
type Request struct {
|
||||
Model string `json:"model"`
|
||||
State string `json:"state"`
|
||||
Questions map[string]Question `json:"questions"`
|
||||
Model string `json:"model"`
|
||||
State string `json:"state"`
|
||||
Questions map[string]Question `json:"questions"`
|
||||
QuestionsJSON json.RawMessage `json:"-"`
|
||||
}
|
||||
|
||||
type rawQuestionsRequest struct {
|
||||
Model string `json:"model"`
|
||||
State string `json:"state"`
|
||||
Questions json.RawMessage `json:"questions"`
|
||||
}
|
||||
|
||||
type Result struct {
|
||||
@@ -130,7 +137,19 @@ func systemOneTokenCount(raw json.RawMessage) int {
|
||||
|
||||
// Evaluate performs one attempt. The caller owns timeouts, retries and key rotation.
|
||||
func Evaluate(ctx context.Context, client *http.Client, baseURL, key string, input Request) (*Result, int, error) {
|
||||
body, err := json.Marshal(input)
|
||||
var (
|
||||
body []byte
|
||||
err error
|
||||
)
|
||||
if len(input.QuestionsJSON) > 0 {
|
||||
body, err = json.Marshal(rawQuestionsRequest{
|
||||
Model: input.Model,
|
||||
State: input.State,
|
||||
Questions: input.QuestionsJSON,
|
||||
})
|
||||
} else {
|
||||
body, err = json.Marshal(input)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, 0, errors.New("typesafe invalid request")
|
||||
}
|
||||
@@ -147,9 +166,15 @@ func Evaluate(ctx context.Context, client *http.Client, baseURL, key string, inp
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
_, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 4096))
|
||||
// Do not log provider error bodies: they may echo user input or credentials.
|
||||
return nil, resp.StatusCode, fmt.Errorf("typesafe API status %d", resp.StatusCode)
|
||||
}
|
||||
const maxEvalRespBytes = 1 << 20
|
||||
respBytes, err := io.ReadAll(io.LimitReader(resp.Body, maxEvalRespBytes+1))
|
||||
if err != nil || len(respBytes) > maxEvalRespBytes {
|
||||
return nil, resp.StatusCode, errors.New("typesafe invalid response")
|
||||
}
|
||||
var out struct {
|
||||
Model string `json:"model"`
|
||||
Usage Usage `json:"usage"`
|
||||
@@ -158,7 +183,7 @@ func Evaluate(ctx context.Context, client *http.Client, baseURL, key string, inp
|
||||
Noul *float64 `json:"noul"`
|
||||
} `json:"answers"`
|
||||
}
|
||||
if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&out); err != nil || strings.TrimSpace(out.Model) == "" {
|
||||
if err := json.Unmarshal(respBytes, &out); err != nil || strings.TrimSpace(out.Model) == "" {
|
||||
return nil, resp.StatusCode, errors.New("typesafe invalid response")
|
||||
}
|
||||
result := &Result{Model: out.Model, Usage: out.Usage, Scores: make(map[string]float64, len(input.Questions))}
|
||||
|
||||
@@ -350,21 +350,27 @@ func (m *Manager) rollbackQuota(ctx context.Context, cfg ProviderConfig) {
|
||||
// --- Search execution ---
|
||||
|
||||
// TestSearch executes a search using the first available provider without reserving quota.
|
||||
// Intended for admin test functionality only.
|
||||
// Intended for admin test functionality only, so a failure keeps each provider's error:
|
||||
// the admin needs to see why the test failed (bad key, quota, network), not a generic message.
|
||||
func (m *Manager) TestSearch(ctx context.Context, req SearchRequest) (*SearchResponse, string, error) {
|
||||
if strings.TrimSpace(req.Query) == "" {
|
||||
return nil, "", fmt.Errorf("websearch: empty search query")
|
||||
}
|
||||
var failures []error
|
||||
for _, cfg := range m.configs {
|
||||
if !m.isProviderAvailable(cfg) {
|
||||
continue
|
||||
}
|
||||
resp, err := m.executeSearch(ctx, cfg, req)
|
||||
if err != nil {
|
||||
failures = append(failures, err)
|
||||
continue
|
||||
}
|
||||
return resp, cfg.Type, nil
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return nil, "", fmt.Errorf("websearch: all providers failed: %w", errors.Join(failures...))
|
||||
}
|
||||
return nil, "", fmt.Errorf("websearch: no available provider")
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
package websearch
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// hostStatusClient answers every request with the status and body configured for its host.
|
||||
func hostStatusClient(byHost map[string]struct {
|
||||
status int
|
||||
body string
|
||||
}) *http.Client {
|
||||
return &http.Client{Transport: exaRoundTripFunc(func(r *http.Request) (*http.Response, error) {
|
||||
reply := byHost[r.URL.Host]
|
||||
return &http.Response{
|
||||
StatusCode: reply.status,
|
||||
Body: io.NopCloser(strings.NewReader(reply.body)),
|
||||
Header: make(http.Header),
|
||||
}, nil
|
||||
})}
|
||||
}
|
||||
|
||||
func TestManager_TestSearch_ReportsEveryProviderFailure(t *testing.T) {
|
||||
m := NewManager([]ProviderConfig{
|
||||
{Type: ProviderTypeTavily, APIKey: "tvly-bad"},
|
||||
{Type: ProviderTypeExa, APIKey: "exa-bad"},
|
||||
}, nil)
|
||||
m.clientCache[""] = hostStatusClient(map[string]struct {
|
||||
status int
|
||||
body string
|
||||
}{
|
||||
"api.tavily.com": {http.StatusUnauthorized, `{"detail":{"error":"Unauthorized: missing or invalid API key."}}`},
|
||||
"api.exa.ai": {http.StatusPaymentRequired, `{"error":"credits exhausted"}`},
|
||||
})
|
||||
|
||||
_, _, err := m.TestSearch(context.Background(), SearchRequest{Query: "golang"})
|
||||
|
||||
require.Error(t, err)
|
||||
msg := err.Error()
|
||||
require.Contains(t, msg, "all providers failed")
|
||||
require.Contains(t, msg, "tavily: status 401")
|
||||
require.Contains(t, msg, "invalid API key")
|
||||
require.Contains(t, msg, "exa: status 402")
|
||||
require.Contains(t, msg, "credits exhausted")
|
||||
}
|
||||
|
||||
func TestManager_TestSearch_FallsThroughToWorkingProvider(t *testing.T) {
|
||||
m := NewManager([]ProviderConfig{
|
||||
{Type: ProviderTypeTavily, APIKey: "tvly-bad"},
|
||||
{Type: ProviderTypeExa, APIKey: "exa-good"},
|
||||
}, nil)
|
||||
m.clientCache[""] = hostStatusClient(map[string]struct {
|
||||
status int
|
||||
body string
|
||||
}{
|
||||
"api.tavily.com": {http.StatusUnauthorized, `{"detail":{"error":"Unauthorized"}}`},
|
||||
"api.exa.ai": {http.StatusOK, `{"results":[{"url":"https://go.dev","title":"Go","highlights":["Go"]}]}`},
|
||||
})
|
||||
|
||||
resp, provider, err := m.TestSearch(context.Background(), SearchRequest{Query: "golang"})
|
||||
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, ProviderTypeExa, provider)
|
||||
require.Len(t, resp.Results, 1)
|
||||
}
|
||||
|
||||
func TestManager_TestSearch_NoUsableProviderKeepsMessage(t *testing.T) {
|
||||
m := NewManager([]ProviderConfig{{Type: ProviderTypeTavily, APIKey: ""}}, nil)
|
||||
|
||||
_, _, err := m.TestSearch(context.Background(), SearchRequest{Query: "golang"})
|
||||
|
||||
require.EqualError(t, err, "websearch: no available provider")
|
||||
}
|
||||
@@ -39,7 +39,6 @@ func (t *TavilyProvider) Search(ctx context.Context, req SearchRequest) (*Search
|
||||
}
|
||||
|
||||
payload := tavilyRequest{
|
||||
APIKey: t.apiKey,
|
||||
Query: req.Query,
|
||||
MaxResults: maxResults,
|
||||
SearchDepth: tavilySearchDepthBasic,
|
||||
@@ -55,6 +54,8 @@ func (t *TavilyProvider) Search(ctx context.Context, req SearchRequest) (*Search
|
||||
return nil, fmt.Errorf("tavily: build request: %w", err)
|
||||
}
|
||||
httpReq.Header.Set("Content-Type", "application/json")
|
||||
// Tavily authenticates with a Bearer token; the documented request body has no api_key field.
|
||||
httpReq.Header.Set("Authorization", "Bearer "+t.apiKey)
|
||||
|
||||
resp, err := t.httpClient.Do(httpReq)
|
||||
if err != nil {
|
||||
@@ -89,7 +90,6 @@ func (t *TavilyProvider) Search(ctx context.Context, req SearchRequest) (*Search
|
||||
}
|
||||
|
||||
type tavilyRequest struct {
|
||||
APIKey string `json:"api_key"`
|
||||
Query string `json:"query"`
|
||||
MaxResults int `json:"max_results"`
|
||||
SearchDepth string `json:"search_depth"`
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
package websearch
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
@@ -12,23 +14,40 @@ func TestTavilyProvider_Name(t *testing.T) {
|
||||
require.Equal(t, "tavily", p.Name())
|
||||
}
|
||||
|
||||
func TestTavilyProvider_Search_RequestConstruction(t *testing.T) {
|
||||
// Verify tavilyRequest struct fields map correctly
|
||||
req := tavilyRequest{
|
||||
APIKey: "test-key",
|
||||
Query: "golang",
|
||||
MaxResults: 3,
|
||||
SearchDepth: tavilySearchDepthBasic,
|
||||
}
|
||||
data, err := json.Marshal(req)
|
||||
require.NoError(t, err)
|
||||
func TestTavilyProvider_Search_SendsBearerAuth(t *testing.T) {
|
||||
var seen http.Request
|
||||
var seenBody []byte
|
||||
resp := `{"results":[{"url":"https://go.dev","title":"Go","content":"Go programming language","score":0.95}]}`
|
||||
p := NewTavilyProvider("tvly-test-key", exaTestClient(http.StatusOK, resp, &seen, &seenBody))
|
||||
|
||||
var parsed map[string]any
|
||||
require.NoError(t, json.Unmarshal(data, &parsed))
|
||||
require.Equal(t, "test-key", parsed["api_key"])
|
||||
require.Equal(t, "golang", parsed["query"])
|
||||
require.Equal(t, float64(3), parsed["max_results"])
|
||||
require.Equal(t, "basic", parsed["search_depth"])
|
||||
out, err := p.Search(context.Background(), SearchRequest{Query: "golang", MaxResults: 3})
|
||||
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, http.MethodPost, seen.Method)
|
||||
require.Equal(t, tavilySearchEndpoint, seen.URL.String())
|
||||
require.Equal(t, "Bearer tvly-test-key", seen.Header.Get("Authorization"))
|
||||
require.Equal(t, "application/json", seen.Header.Get("Content-Type"))
|
||||
var body map[string]any
|
||||
require.NoError(t, json.Unmarshal(seenBody, &body))
|
||||
require.Equal(t, map[string]any{
|
||||
"query": "golang",
|
||||
"max_results": float64(3),
|
||||
"search_depth": "basic",
|
||||
}, body, "the API key must travel in the Authorization header, not the request body")
|
||||
|
||||
require.Equal(t, []SearchResult{
|
||||
{URL: "https://go.dev", Title: "Go", Snippet: "Go programming language"},
|
||||
}, out.Results)
|
||||
}
|
||||
|
||||
func TestTavilyProvider_Search_ReportsUpstreamStatus(t *testing.T) {
|
||||
var seen http.Request
|
||||
var seenBody []byte
|
||||
p := NewTavilyProvider("bad-key", exaTestClient(http.StatusUnauthorized, `{"detail":{"error":"Unauthorized"}}`, &seen, &seenBody))
|
||||
|
||||
_, err := p.Search(context.Background(), SearchRequest{Query: "golang"})
|
||||
|
||||
require.ErrorContains(t, err, "tavily: status 401")
|
||||
}
|
||||
|
||||
func TestTavilyProvider_Search_ResponseParsing(t *testing.T) {
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/lib/pq"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultModerationAccountSearchLimit = 20
|
||||
maxModerationAccountSearchLimit = 50
|
||||
maxModerationAccountSearchRunes = 100
|
||||
)
|
||||
|
||||
func escapeModerationLikePattern(raw string) string {
|
||||
replacer := strings.NewReplacer(`\`, `\\`, `%`, `\%`, `_`, `\_`)
|
||||
return replacer.Replace(raw)
|
||||
}
|
||||
|
||||
// truncateModerationAccountSearch 清洗非法 UTF-8 并按字符截断,避免 PG 拒绝截断出的半个多字节字符。
|
||||
func truncateModerationAccountSearch(raw string) string {
|
||||
search := strings.TrimSpace(strings.ToValidUTF8(raw, ""))
|
||||
if utf8.RuneCountInString(search) > maxModerationAccountSearchRunes {
|
||||
search = strings.TrimSpace(string([]rune(search)[:maxModerationAccountSearchRunes]))
|
||||
}
|
||||
return search
|
||||
}
|
||||
|
||||
func (r *contentModerationRepository) SearchModerationAccounts(
|
||||
ctx context.Context,
|
||||
filter service.ContentModerationAccountSearchFilter,
|
||||
) ([]service.ContentModerationExcludedAccount, error) {
|
||||
if r == nil || r.db == nil {
|
||||
return []service.ContentModerationExcludedAccount{}, nil
|
||||
}
|
||||
if !filter.AllGroups && len(filter.GroupIDs) == 0 {
|
||||
return []service.ContentModerationExcludedAccount{}, nil
|
||||
}
|
||||
|
||||
limit := filter.Limit
|
||||
if limit <= 0 {
|
||||
limit = defaultModerationAccountSearchLimit
|
||||
}
|
||||
if limit > maxModerationAccountSearchLimit {
|
||||
limit = maxModerationAccountSearchLimit
|
||||
}
|
||||
|
||||
var (
|
||||
conditions = []string{"a.deleted_at IS NULL"}
|
||||
args = make([]any, 0, 4)
|
||||
exactID int64
|
||||
hasExactID bool
|
||||
)
|
||||
|
||||
if !filter.AllGroups {
|
||||
args = append(args, pq.Array(filter.GroupIDs))
|
||||
conditions = append(conditions, fmt.Sprintf(
|
||||
"EXISTS (SELECT 1 FROM account_groups ag WHERE ag.account_id = a.id AND ag.group_id = ANY($%d))",
|
||||
len(args),
|
||||
))
|
||||
}
|
||||
|
||||
search := truncateModerationAccountSearch(filter.Search)
|
||||
if search != "" {
|
||||
idCandidate := strings.TrimSpace(strings.TrimPrefix(search, "#"))
|
||||
if parsedID, err := strconv.ParseInt(idCandidate, 10, 64); err == nil && parsedID > 0 {
|
||||
exactID = parsedID
|
||||
hasExactID = true
|
||||
}
|
||||
|
||||
likeArg := "%" + escapeModerationLikePattern(search) + "%"
|
||||
args = append(args, likeArg)
|
||||
likeIdx := len(args)
|
||||
|
||||
if hasExactID {
|
||||
args = append(args, exactID)
|
||||
idIdx := len(args)
|
||||
conditions = append(conditions, fmt.Sprintf("(a.id = $%d OR a.name ILIKE $%d ESCAPE '\\')", idIdx, likeIdx))
|
||||
} else {
|
||||
conditions = append(conditions, fmt.Sprintf("a.name ILIKE $%d ESCAPE '\\'", likeIdx))
|
||||
}
|
||||
}
|
||||
|
||||
orderClause := "a.name ASC, a.id ASC"
|
||||
if hasExactID {
|
||||
args = append(args, exactID)
|
||||
orderClause = fmt.Sprintf("CASE WHEN a.id = $%d THEN 0 ELSE 1 END ASC, a.name ASC, a.id ASC", len(args))
|
||||
}
|
||||
|
||||
args = append(args, limit)
|
||||
limitIdx := len(args)
|
||||
|
||||
query := fmt.Sprintf(`
|
||||
SELECT a.id, a.name, a.platform, a.type
|
||||
FROM accounts a
|
||||
WHERE %s
|
||||
ORDER BY %s
|
||||
LIMIT $%d`,
|
||||
strings.Join(conditions, " AND "),
|
||||
orderClause,
|
||||
limitIdx,
|
||||
)
|
||||
|
||||
rows, err := r.db.QueryContext(ctx, query, args...)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("search moderation accounts: %w", err)
|
||||
}
|
||||
defer func() { _ = rows.Close() }()
|
||||
|
||||
items := make([]service.ContentModerationExcludedAccount, 0, limit)
|
||||
for rows.Next() {
|
||||
var item service.ContentModerationExcludedAccount
|
||||
if err := rows.Scan(&item.ID, &item.Name, &item.Platform, &item.Type); err != nil {
|
||||
return nil, fmt.Errorf("scan moderation account: %w", err)
|
||||
}
|
||||
items = append(items, item)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, fmt.Errorf("iterate moderation accounts: %w", err)
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
func (r *contentModerationRepository) ListModerationAccountsByIDs(
|
||||
ctx context.Context,
|
||||
ids []int64,
|
||||
) ([]service.ContentModerationExcludedAccount, error) {
|
||||
if r == nil || r.db == nil || len(ids) == 0 {
|
||||
return []service.ContentModerationExcludedAccount{}, nil
|
||||
}
|
||||
|
||||
rows, err := r.db.QueryContext(ctx, `
|
||||
SELECT a.id, a.name, a.platform, a.type
|
||||
FROM accounts a
|
||||
WHERE a.deleted_at IS NULL AND a.id = ANY($1)`,
|
||||
pq.Array(ids),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list moderation accounts by ids: %w", err)
|
||||
}
|
||||
defer func() { _ = rows.Close() }()
|
||||
|
||||
byID := make(map[int64]service.ContentModerationExcludedAccount, len(ids))
|
||||
for rows.Next() {
|
||||
var item service.ContentModerationExcludedAccount
|
||||
if err := rows.Scan(&item.ID, &item.Name, &item.Platform, &item.Type); err != nil {
|
||||
return nil, fmt.Errorf("scan moderation account by id: %w", err)
|
||||
}
|
||||
byID[item.ID] = item
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, fmt.Errorf("iterate moderation accounts by id: %w", err)
|
||||
}
|
||||
|
||||
out := make([]service.ContentModerationExcludedAccount, 0, len(ids))
|
||||
for _, id := range ids {
|
||||
if item, ok := byID[id]; ok {
|
||||
out = append(out, item)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
//go:build unit
|
||||
|
||||
package repository
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestTruncateModerationAccountSearch_KeepsValidUTF8(t *testing.T) {
|
||||
// 99 个 ASCII + 多字节汉字:按字节截到 100 会切出半个字符,PG 报 invalid byte sequence。
|
||||
raw := strings.Repeat("a", 99) + "账户名称"
|
||||
got := truncateModerationAccountSearch(raw)
|
||||
require.True(t, utf8.ValidString(got))
|
||||
require.Equal(t, strings.Repeat("a", 99)+"账", got)
|
||||
|
||||
require.Equal(t, "ab", truncateModerationAccountSearch(" a\xffb "))
|
||||
require.Equal(t, "账户", truncateModerationAccountSearch("账户"))
|
||||
}
|
||||
@@ -289,16 +289,7 @@ func (r *proxyRepository) List(ctx context.Context, params pagination.Pagination
|
||||
|
||||
// ListWithFilters lists proxies with optional filtering by protocol, status, and search query
|
||||
func (r *proxyRepository) ListWithFilters(ctx context.Context, params pagination.PaginationParams, protocol, status, search string) ([]service.Proxy, *pagination.PaginationResult, error) {
|
||||
q := r.client.Proxy.Query()
|
||||
if protocol != "" {
|
||||
q = q.Where(proxy.ProtocolEQ(protocol))
|
||||
}
|
||||
if status != "" {
|
||||
q = q.Where(proxy.StatusEQ(status))
|
||||
}
|
||||
if search != "" {
|
||||
q = q.Where(proxy.NameContainsFold(search))
|
||||
}
|
||||
q := r.filteredProxyQuery(protocol, status, search)
|
||||
|
||||
total, err := q.Count(ctx)
|
||||
if err != nil {
|
||||
@@ -327,16 +318,7 @@ func (r *proxyRepository) ListWithFilters(ctx context.Context, params pagination
|
||||
|
||||
// ListWithFiltersAndAccountCount lists proxies with filters and includes account count per proxy
|
||||
func (r *proxyRepository) ListWithFiltersAndAccountCount(ctx context.Context, params pagination.PaginationParams, protocol, status, search string) ([]service.ProxyWithAccountCount, *pagination.PaginationResult, error) {
|
||||
q := r.client.Proxy.Query()
|
||||
if protocol != "" {
|
||||
q = q.Where(proxy.ProtocolEQ(protocol))
|
||||
}
|
||||
if status != "" {
|
||||
q = q.Where(proxy.StatusEQ(status))
|
||||
}
|
||||
if search != "" {
|
||||
q = q.Where(proxy.NameContainsFold(search))
|
||||
}
|
||||
q := r.filteredProxyQuery(protocol, status, search)
|
||||
|
||||
total, err := q.Count(ctx)
|
||||
if err != nil {
|
||||
@@ -362,6 +344,23 @@ func (r *proxyRepository) ListWithFiltersAndAccountCount(ctx context.Context, pa
|
||||
return r.buildProxyWithAccountCountResult(ctx, proxies, params, int64(total))
|
||||
}
|
||||
|
||||
func (r *proxyRepository) filteredProxyQuery(protocol, status, search string) *dbent.ProxyQuery {
|
||||
q := r.client.Proxy.Query()
|
||||
if protocol != "" {
|
||||
q = q.Where(proxy.ProtocolEQ(protocol))
|
||||
}
|
||||
if status != "" {
|
||||
q = q.Where(proxy.StatusEQ(status))
|
||||
}
|
||||
if search = strings.TrimSpace(search); search != "" {
|
||||
q = q.Where(proxy.Or(
|
||||
proxy.NameContainsFold(search),
|
||||
proxy.HostContainsFold(search),
|
||||
))
|
||||
}
|
||||
return q
|
||||
}
|
||||
|
||||
func (r *proxyRepository) listWithAccountCountSort(ctx context.Context, q *dbent.ProxyQuery, params pagination.PaginationParams, total int) ([]service.ProxyWithAccountCount, *pagination.PaginationResult, error) {
|
||||
proxies, err := q.
|
||||
Order(dbent.Desc(proxy.FieldID)).
|
||||
|
||||
@@ -125,13 +125,33 @@ func (s *ProxyRepoSuite) TestListWithFilters_Status() {
|
||||
}
|
||||
|
||||
func (s *ProxyRepoSuite) TestListWithFilters_Search() {
|
||||
s.mustCreateProxy(&service.Proxy{Name: "production-proxy", Protocol: "http", Host: "127.0.0.1", Port: 8080, Status: service.StatusActive})
|
||||
s.mustCreateProxy(&service.Proxy{Name: "dev-proxy", Protocol: "http", Host: "127.0.0.1", Port: 8081, Status: service.StatusActive})
|
||||
s.mustCreateProxy(&service.Proxy{Name: "production-proxy", Protocol: "http", Host: "10.20.30.40", Port: 8080, Status: service.StatusActive})
|
||||
s.mustCreateProxy(&service.Proxy{Name: "dev-proxy", Protocol: "http", Host: "Proxy.Example.COM", Port: 8081, Status: service.StatusActive})
|
||||
|
||||
proxies, _, err := s.repo.ListWithFilters(s.ctx, pagination.PaginationParams{Page: 1, PageSize: 10}, "", "", "prod")
|
||||
s.Require().NoError(err)
|
||||
s.Require().Len(proxies, 1)
|
||||
s.Require().Contains(proxies[0].Name, "production")
|
||||
|
||||
proxiesByIP, _, err := s.repo.ListWithFilters(s.ctx, pagination.PaginationParams{Page: 1, PageSize: 10}, "", "", "20.30")
|
||||
s.Require().NoError(err)
|
||||
s.Require().Len(proxiesByIP, 1)
|
||||
s.Require().Equal("production-proxy", proxiesByIP[0].Name)
|
||||
|
||||
proxiesByHostFold, _, err := s.repo.ListWithFilters(s.ctx, pagination.PaginationParams{Page: 1, PageSize: 10}, "", "", "example.com")
|
||||
s.Require().NoError(err)
|
||||
s.Require().Len(proxiesByHostFold, 1)
|
||||
s.Require().Equal("dev-proxy", proxiesByHostFold[0].Name)
|
||||
|
||||
withCounts, _, err := s.repo.ListWithFiltersAndAccountCount(s.ctx, pagination.PaginationParams{Page: 1, PageSize: 10}, "", "", "10.20.30.40")
|
||||
s.Require().NoError(err)
|
||||
s.Require().Len(withCounts, 1)
|
||||
s.Require().Equal("production-proxy", withCounts[0].Name)
|
||||
|
||||
withCountsByName, _, err := s.repo.ListWithFiltersAndAccountCount(s.ctx, pagination.PaginationParams{Page: 1, PageSize: 10}, "", "", "DEV")
|
||||
s.Require().NoError(err)
|
||||
s.Require().Len(withCountsByName, 1)
|
||||
s.Require().Equal("dev-proxy", withCountsByName[0].Name)
|
||||
}
|
||||
|
||||
// --- ListActive ---
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"entgo.io/ent/dialect"
|
||||
entsql "entgo.io/ent/dialect/sql"
|
||||
"github.com/DATA-DOG/go-sqlmock"
|
||||
dbent "github.com/Wei-Shaw/sub2api/ent"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/pagination"
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func proxyColumns() []string {
|
||||
return []string{
|
||||
"id", "created_at", "updated_at", "deleted_at", "name", "protocol", "host", "port",
|
||||
"username", "password", "status", "expires_at", "fallback_mode", "backup_proxy_id", "expiry_warn_days",
|
||||
}
|
||||
}
|
||||
|
||||
func newSearchQueryMatcher() sqlmock.QueryMatcher {
|
||||
return sqlmock.QueryMatcherFunc(func(expected, actual string) error {
|
||||
switch expected {
|
||||
case "count", "select":
|
||||
if !strings.Contains(actual, `"proxies"."name" ILIKE`) ||
|
||||
!strings.Contains(actual, `"proxies"."host" ILIKE`) ||
|
||||
!strings.Contains(actual, " OR ") {
|
||||
return fmt.Errorf("expected case-insensitive OR search across name and host, got: %s", actual)
|
||||
}
|
||||
case "account_counts":
|
||||
if !strings.Contains(actual, "FROM accounts") {
|
||||
return fmt.Errorf("expected account counts query, got: %s", actual)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func TestProxyRepoSearchByNameOrHostSQL(t *testing.T) {
|
||||
t.Run("ListWithFilters matches name or host case-insensitively", func(t *testing.T) {
|
||||
db, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(newSearchQueryMatcher()))
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { _ = db.Close() })
|
||||
|
||||
client := dbent.NewClient(dbent.Driver(entsql.OpenDB(dialect.Postgres, db)))
|
||||
t.Cleanup(func() { _ = client.Close() })
|
||||
|
||||
now := time.Now()
|
||||
mock.ExpectQuery("count").
|
||||
WithArgs("%192.168.1%", "%192.168.1%").
|
||||
WillReturnRows(sqlmock.NewRows([]string{"count"}).AddRow(1))
|
||||
mock.ExpectQuery("select").
|
||||
WithArgs("%192.168.1%", "%192.168.1%").
|
||||
WillReturnRows(sqlmock.NewRows(proxyColumns()).AddRow(
|
||||
int64(42), now, now, nil, "tokyo-node", "socks5", "192.168.1.50", 1080,
|
||||
nil, nil, service.StatusActive, nil, service.FallbackModeNone, nil, 7,
|
||||
))
|
||||
|
||||
repo := newProxyRepositoryWithSQL(client, db)
|
||||
items, page, err := repo.ListWithFilters(
|
||||
context.Background(),
|
||||
pagination.PaginationParams{Page: 1, PageSize: 20},
|
||||
"",
|
||||
"",
|
||||
" 192.168.1 ",
|
||||
)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, int64(1), page.Total)
|
||||
require.Len(t, items, 1)
|
||||
require.Equal(t, "192.168.1.50", items[0].Host)
|
||||
require.NoError(t, mock.ExpectationsWereMet())
|
||||
})
|
||||
|
||||
t.Run("ListWithFiltersAndAccountCount matches name or host case-insensitively", func(t *testing.T) {
|
||||
db, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(newSearchQueryMatcher()))
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { _ = db.Close() })
|
||||
|
||||
client := dbent.NewClient(dbent.Driver(entsql.OpenDB(dialect.Postgres, db)))
|
||||
t.Cleanup(func() { _ = client.Close() })
|
||||
|
||||
now := time.Now()
|
||||
mock.ExpectQuery("count").
|
||||
WithArgs("%proxy.example%", "%proxy.example%").
|
||||
WillReturnRows(sqlmock.NewRows([]string{"count"}).AddRow(1))
|
||||
mock.ExpectQuery("select").
|
||||
WithArgs("%proxy.example%", "%proxy.example%").
|
||||
WillReturnRows(sqlmock.NewRows(proxyColumns()).AddRow(
|
||||
int64(7), now, now, nil, "us-west", "http", "Proxy.Example.net", 8080,
|
||||
nil, nil, service.StatusActive, nil, service.FallbackModeNone, nil, 7,
|
||||
))
|
||||
mock.ExpectQuery("account_counts").
|
||||
WillReturnRows(sqlmock.NewRows([]string{"proxy_id", "count"}).AddRow(int64(7), int64(3)))
|
||||
|
||||
repo := newProxyRepositoryWithSQL(client, db)
|
||||
items, page, err := repo.ListWithFiltersAndAccountCount(
|
||||
context.Background(),
|
||||
pagination.PaginationParams{Page: 1, PageSize: 20},
|
||||
"",
|
||||
"",
|
||||
"Proxy.Example",
|
||||
)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, int64(1), page.Total)
|
||||
require.Len(t, items, 1)
|
||||
require.Equal(t, "Proxy.Example.net", items[0].Host)
|
||||
require.Equal(t, int64(3), items[0].AccountCount)
|
||||
require.NoError(t, mock.ExpectationsWereMet())
|
||||
})
|
||||
}
|
||||
@@ -16,6 +16,7 @@ import (
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/xai"
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/redis/go-redis/v9"
|
||||
"github.com/tidwall/gjson"
|
||||
@@ -1196,11 +1197,39 @@ func decodeCachedAccountPayload(payload string) (*service.Account, error) {
|
||||
return &account, nil
|
||||
}
|
||||
|
||||
// schedulerAccountCacheWrite 是一个已编码、待写入的账号载荷。
|
||||
type schedulerAccountCacheWrite struct {
|
||||
keyID string
|
||||
platform string
|
||||
fullPayload []byte
|
||||
metaPayload []byte
|
||||
}
|
||||
|
||||
// schedulerCachedAccountPayload 是写前从 Redis 读回的旧载荷;present 为 false 表示键不存在。
|
||||
type schedulerCachedAccountPayload struct {
|
||||
full string
|
||||
fullPresent bool
|
||||
meta string
|
||||
metaPresent bool
|
||||
}
|
||||
|
||||
// schedulerAccountCacheChange 描述一个账号相对 Redis 中旧载荷的变化。
|
||||
// platformChanged 仅在读到旧精简记录且平台不一致时为 true,用于保留旧平台 bucket 的失效语义。
|
||||
type schedulerAccountCacheChange struct {
|
||||
fullChanged bool
|
||||
metaChanged bool
|
||||
platformChanged bool
|
||||
}
|
||||
|
||||
// writeAccountIDs 分块写入整账号与精简记录,返回成功编码并写入的有序账号 ID。
|
||||
// 每块在追加下一个账号前才执行,最后一块总是非空;所涉平台的修订号追加在最后一块末尾,
|
||||
// 与最后一批精简记录同一次往返发出,且排在全部精简记录写入之后。
|
||||
// 精简记录用 SET ... GET 写入并取回旧值:旧值的平台与新平台不同时,旧平台 bucket 中可能仍缓存着该账号,
|
||||
// 全部写入完成后另行写入全局修订号。该检测尽力而为(客户端在 pipeline 内部重试时取回的可能已是本次写入的值),
|
||||
// 写入前按块读回旧载荷(完整记录与精简记录同批 MGET),只写入发生变化的账号:
|
||||
// 调度刷新反复写入相同内容时不再产生整键 SET,避免 AOF/复制放大。
|
||||
// 未变化的账号仍返回其 ID,调用方需要的成员列表不因此改变。
|
||||
// 所涉平台的修订号追加在最后一个有写入的块末尾,与最后一批精简记录同一次往返发出,
|
||||
// 且排在全部精简记录写入之后;全部未变化时不写修订号,读侧进程内缓存继续复用。
|
||||
// 读取失败时降级为原全量写(fail-open),此时用 SET ... GET 取回旧值:
|
||||
// 旧值的平台与新平台不同时,旧平台 bucket 中可能仍缓存着该账号,全部写入完成后另行写入全局修订号。
|
||||
// 该检测尽力而为(客户端在 pipeline 内部重试时取回的可能已是本次写入的值),
|
||||
// 漏检由进程内快照缓存的直接复用时长与宽限期兜底。
|
||||
// 任一块执行出错时,此前已执行的块与出错的块都可能已有精简记录生效,返回时启动后台写入全局修订号。
|
||||
func (c *schedulerCache) writeAccountIDs(ctx context.Context, accounts []service.Account) ([]int64, error) {
|
||||
@@ -1208,46 +1237,13 @@ func (c *schedulerCache) writeAccountIDs(ctx context.Context, accounts []service
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
type metaWrite struct {
|
||||
platform string
|
||||
previous *redis.StatusCmd
|
||||
}
|
||||
pipe := c.rdb.Pipeline()
|
||||
accountIDs := make([]int64, 0, len(accounts))
|
||||
platforms := make([]string, 0, 1)
|
||||
writes := make([]metaWrite, 0, min(len(accounts), c.writeChunkSize))
|
||||
pending := 0
|
||||
execFailed := false
|
||||
platformChanged := false
|
||||
defer func() {
|
||||
if execFailed {
|
||||
c.scheduleGlobalAccountMetaRevision(ctx)
|
||||
}
|
||||
}()
|
||||
exec := func() error {
|
||||
cmds, err := pipe.Exec(ctx)
|
||||
if err != nil && !errors.Is(err, redis.Nil) {
|
||||
execFailed = true
|
||||
return err
|
||||
}
|
||||
// SET ... GET 在键原本不存在时返回 redis.Nil,不算失败;其余命令的错误逐条检查。
|
||||
for _, cmd := range cmds {
|
||||
if cmdErr := cmd.Err(); cmdErr != nil && !errors.Is(cmdErr, redis.Nil) {
|
||||
execFailed = true
|
||||
return cmdErr
|
||||
}
|
||||
}
|
||||
for _, write := range writes {
|
||||
if schedulerMetaPlatformChanged(write.previous, write.platform) {
|
||||
platformChanged = true
|
||||
}
|
||||
}
|
||||
writes = writes[:0]
|
||||
pipe = c.rdb.Pipeline()
|
||||
pending = 0
|
||||
return nil
|
||||
chunkSize := c.writeChunkSize
|
||||
if chunkSize <= 0 {
|
||||
chunkSize = defaultSchedulerSnapshotWriteChunkSize
|
||||
}
|
||||
|
||||
writes := make([]schedulerAccountCacheWrite, 0, len(accounts))
|
||||
accountIDs := make([]int64, 0, len(accounts))
|
||||
for _, account := range accounts {
|
||||
fullPayload, metaPayload, err := marshalSchedulerCacheAccount(account)
|
||||
if err != nil {
|
||||
@@ -1257,35 +1253,94 @@ func (c *schedulerCache) writeAccountIDs(ctx context.Context, accounts []service
|
||||
)
|
||||
continue
|
||||
}
|
||||
if pending >= c.writeChunkSize {
|
||||
if err := exec(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
id := strconv.FormatInt(account.ID, 10)
|
||||
pipe.Set(ctx, schedulerAccountKey(id), fullPayload, 0)
|
||||
writes = append(writes, metaWrite{
|
||||
platform: account.Platform,
|
||||
previous: pipe.SetArgs(ctx, schedulerAccountMetaKey(id), metaPayload, redis.SetArgs{Get: true}),
|
||||
writes = append(writes, schedulerAccountCacheWrite{
|
||||
keyID: strconv.FormatInt(account.ID, 10),
|
||||
platform: account.Platform,
|
||||
fullPayload: fullPayload,
|
||||
metaPayload: metaPayload,
|
||||
})
|
||||
// Keep the hot LastUsedAt side key untouched: a lagging snapshot rebuild
|
||||
// must not overwrite a newer scheduler update.
|
||||
accountIDs = append(accountIDs, account.ID)
|
||||
if !slices.Contains(platforms, account.Platform) {
|
||||
platforms = append(platforms, account.Platform)
|
||||
}
|
||||
pending++
|
||||
}
|
||||
|
||||
if pending == 0 {
|
||||
if len(writes) == 0 {
|
||||
return accountIDs, nil
|
||||
}
|
||||
for _, platform := range platforms {
|
||||
pipe.Set(ctx, schedulerAccountMetaRevisionKeyForPlatform(platform), newSchedulerAccountMetaRevision(), 0)
|
||||
|
||||
changes, unconditional, lastWriteChunk := c.planSchedulerAccountWrites(ctx, writes, chunkSize)
|
||||
if lastWriteChunk < 0 {
|
||||
return accountIDs, nil
|
||||
}
|
||||
if err := exec(); err != nil {
|
||||
return nil, err
|
||||
|
||||
type metaWrite struct {
|
||||
platform string
|
||||
previous *redis.StatusCmd
|
||||
}
|
||||
execFailed := false
|
||||
platformChanged := false
|
||||
defer func() {
|
||||
if execFailed {
|
||||
c.scheduleGlobalAccountMetaRevision(ctx)
|
||||
}
|
||||
}()
|
||||
platforms := make([]string, 0, 2)
|
||||
for chunkIndex, start := 0, 0; start < len(writes); chunkIndex, start = chunkIndex+1, start+chunkSize {
|
||||
end := min(start+chunkSize, len(writes))
|
||||
chunk := writes[start:end]
|
||||
pipe := c.rdb.Pipeline()
|
||||
metaWrites := make([]metaWrite, 0, len(chunk))
|
||||
queued := 0
|
||||
for offset := range chunk {
|
||||
change := changes[start+offset]
|
||||
if !change.fullChanged && !change.metaChanged {
|
||||
continue
|
||||
}
|
||||
write := chunk[offset]
|
||||
if change.fullChanged {
|
||||
pipe.Set(ctx, schedulerAccountKey(write.keyID), write.fullPayload, 0)
|
||||
queued++
|
||||
}
|
||||
if change.metaChanged {
|
||||
if unconditional {
|
||||
metaWrites = append(metaWrites, metaWrite{
|
||||
platform: write.platform,
|
||||
previous: pipe.SetArgs(ctx, schedulerAccountMetaKey(write.keyID), write.metaPayload, redis.SetArgs{Get: true}),
|
||||
})
|
||||
} else {
|
||||
pipe.Set(ctx, schedulerAccountMetaKey(write.keyID), write.metaPayload, 0)
|
||||
platformChanged = platformChanged || change.platformChanged
|
||||
}
|
||||
queued++
|
||||
}
|
||||
if !slices.Contains(platforms, write.platform) {
|
||||
platforms = append(platforms, write.platform)
|
||||
}
|
||||
}
|
||||
if queued == 0 {
|
||||
continue
|
||||
}
|
||||
if chunkIndex == lastWriteChunk {
|
||||
for _, platform := range platforms {
|
||||
pipe.Set(ctx, schedulerAccountMetaRevisionKeyForPlatform(platform), newSchedulerAccountMetaRevision(), 0)
|
||||
}
|
||||
}
|
||||
cmds, err := pipe.Exec(ctx)
|
||||
if err != nil && !errors.Is(err, redis.Nil) {
|
||||
execFailed = true
|
||||
return nil, err
|
||||
}
|
||||
// SET ... GET 在键原本不存在时返回 redis.Nil,不算失败;其余命令的错误逐条检查。
|
||||
for _, cmd := range cmds {
|
||||
if cmdErr := cmd.Err(); cmdErr != nil && !errors.Is(cmdErr, redis.Nil) {
|
||||
execFailed = true
|
||||
return nil, cmdErr
|
||||
}
|
||||
}
|
||||
for _, write := range metaWrites {
|
||||
if schedulerMetaPlatformChanged(write.previous, write.platform) {
|
||||
platformChanged = true
|
||||
}
|
||||
}
|
||||
}
|
||||
if platformChanged {
|
||||
c.advanceGlobalAccountMetaRevision(ctx)
|
||||
@@ -1293,6 +1348,84 @@ func (c *schedulerCache) writeAccountIDs(ctx context.Context, accounts []service
|
||||
return accountIDs, nil
|
||||
}
|
||||
|
||||
// planSchedulerAccountWrites 按块读回旧载荷并标记需要写入的账号,返回最后一个有写入的块序号。
|
||||
// 读取失败时把剩余块标记为全量写(unconditional),由调用方沿用原写入与平台变化检测路径。
|
||||
func (c *schedulerCache) planSchedulerAccountWrites(ctx context.Context, writes []schedulerAccountCacheWrite, chunkSize int) ([]schedulerAccountCacheChange, bool, int) {
|
||||
changes := make([]schedulerAccountCacheChange, len(writes))
|
||||
unconditional := false
|
||||
lastWriteChunk := -1
|
||||
for chunkIndex, start := 0, 0; start < len(writes); chunkIndex, start = chunkIndex+1, start+chunkSize {
|
||||
end := min(start+chunkSize, len(writes))
|
||||
chunk := writes[start:end]
|
||||
var previous []schedulerCachedAccountPayload
|
||||
if !unconditional {
|
||||
cached, err := c.readSchedulerAccountPayloads(ctx, chunk)
|
||||
if err != nil {
|
||||
// 读失败时不能跳过任何账号,否则缓存可能停留在旧值;降级为原全量写。
|
||||
slog.Warn("scheduler cache falls back to unconditional account writes", "error", err)
|
||||
unconditional = true
|
||||
} else {
|
||||
previous = cached
|
||||
}
|
||||
}
|
||||
chunkChanged := false
|
||||
for offset := range chunk {
|
||||
change := schedulerAccountCacheChange{fullChanged: true, metaChanged: true}
|
||||
if !unconditional {
|
||||
cached := previous[offset]
|
||||
change.fullChanged = !cached.fullPresent || cached.full != string(chunk[offset].fullPayload)
|
||||
change.metaChanged = !cached.metaPresent || cached.meta != string(chunk[offset].metaPayload)
|
||||
if change.metaChanged && cached.metaPresent {
|
||||
change.platformChanged = schedulerMetaPlatformChangedValue(cached.meta, chunk[offset].platform)
|
||||
}
|
||||
}
|
||||
changes[start+offset] = change
|
||||
if change.fullChanged || change.metaChanged {
|
||||
chunkChanged = true
|
||||
}
|
||||
}
|
||||
if chunkChanged {
|
||||
lastWriteChunk = chunkIndex
|
||||
}
|
||||
}
|
||||
return changes, unconditional, lastWriteChunk
|
||||
}
|
||||
|
||||
// readSchedulerAccountPayloads 读回一批账号的完整与精简记录旧值,键顺序与 writes 一致。
|
||||
func (c *schedulerCache) readSchedulerAccountPayloads(ctx context.Context, writes []schedulerAccountCacheWrite) ([]schedulerCachedAccountPayload, error) {
|
||||
keys := make([]string, 0, len(writes)*2)
|
||||
for _, write := range writes {
|
||||
keys = append(keys, schedulerAccountKey(write.keyID), schedulerAccountMetaKey(write.keyID))
|
||||
}
|
||||
values, err := c.mgetChunked(ctx, keys)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(values) != len(keys) {
|
||||
return nil, fmt.Errorf("scheduler cache read %d cached payloads for %d keys", len(values), len(keys))
|
||||
}
|
||||
cached := make([]schedulerCachedAccountPayload, len(writes))
|
||||
for index := range writes {
|
||||
if raw := values[index*2]; raw != nil {
|
||||
payload, err := schedulerCachePayload(raw)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cached[index].full = payload
|
||||
cached[index].fullPresent = true
|
||||
}
|
||||
if raw := values[index*2+1]; raw != nil {
|
||||
payload, err := schedulerCachePayload(raw)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cached[index].meta = payload
|
||||
cached[index].metaPresent = true
|
||||
}
|
||||
}
|
||||
return cached, nil
|
||||
}
|
||||
|
||||
// schedulerMetaPlatformChanged 判断 SET ... GET 取回的旧精简记录是否属于另一个平台;
|
||||
// 旧值不是合法 JSON 或缺少字符串类型的顶层 Platform 时按已变化处理。
|
||||
func schedulerMetaPlatformChanged(previous *redis.StatusCmd, platform string) bool {
|
||||
@@ -1300,6 +1433,11 @@ func schedulerMetaPlatformChanged(previous *redis.StatusCmd, platform string) bo
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return schedulerMetaPlatformChangedValue(raw, platform)
|
||||
}
|
||||
|
||||
// schedulerMetaPlatformChangedValue 是 schedulerMetaPlatformChanged 的载荷版本,供写前读取的旧精简记录复用。
|
||||
func schedulerMetaPlatformChangedValue(raw string, platform string) bool {
|
||||
if !gjson.Valid(raw) {
|
||||
return true
|
||||
}
|
||||
@@ -1393,7 +1531,7 @@ func (c *schedulerCache) mgetChunked(ctx context.Context, keys []string) ([]any,
|
||||
}
|
||||
|
||||
func buildSchedulerMetadataAccount(account service.Account) service.Account {
|
||||
return service.Account{
|
||||
metadata := service.Account{
|
||||
ID: account.ID,
|
||||
Name: account.Name,
|
||||
Platform: account.Platform,
|
||||
@@ -1422,6 +1560,21 @@ func buildSchedulerMetadataAccount(account service.Account) service.Account {
|
||||
Credentials: filterSchedulerCredentials(account.Credentials),
|
||||
Extra: filterSchedulerExtra(account.Extra),
|
||||
}
|
||||
// Media admission runs on this projection before full-account hydration.
|
||||
// Preserve the live JWT tier precedence without copying tokens to metadata.
|
||||
if account.IsGrokOAuth() {
|
||||
tier := xai.SubscriptionTierFromJWT(account.GetCredential("access_token"))
|
||||
if tier == "" {
|
||||
tier = account.GetCredential("subscription_tier")
|
||||
}
|
||||
if tier != "" {
|
||||
if metadata.Credentials == nil {
|
||||
metadata.Credentials = make(map[string]any)
|
||||
}
|
||||
metadata.Credentials["subscription_tier"] = tier
|
||||
}
|
||||
}
|
||||
return metadata
|
||||
}
|
||||
|
||||
func filterSchedulerAccountGroups(accountGroups []service.AccountGroup) []service.AccountGroup {
|
||||
|
||||
@@ -577,9 +577,13 @@ func TestSchedulerCacheSnapshotMemoWriteAccountIDsAdvancesRevision(t *testing.T)
|
||||
require.Len(t, first, schedulerAccountMetaRevisionBytes*2)
|
||||
require.Len(t, memoRevision(t, cache, geminiRevisionKey), schedulerAccountMetaRevisionBytes*2)
|
||||
|
||||
recorder.reset()
|
||||
_, err = cache.writeAccountIDs(ctx, accounts[:1])
|
||||
require.NoError(t, err)
|
||||
require.NotEqual(t, first, memoRevision(t, cache, memoAnthropicRevisionKey))
|
||||
require.Equal(t, []string{"mget " + schedulerAccountKey("131")}, recorder.recorded(),
|
||||
"an unchanged payload is only read back")
|
||||
require.Equal(t, first, memoRevision(t, cache, memoAnthropicRevisionKey),
|
||||
"an unchanged payload must not rewrite the account or advance its revision")
|
||||
})
|
||||
|
||||
t.Run("account count is a multiple of the chunk size", func(t *testing.T) {
|
||||
@@ -601,7 +605,8 @@ func TestSchedulerCacheSnapshotMemoWriteAccountIDsAdvancesRevision(t *testing.T)
|
||||
"set " + schedulerAccountMetaKey("144"),
|
||||
"set " + memoAnthropicRevisionKey,
|
||||
}, batches[1])
|
||||
require.Len(t, recorder.recorded(), 9, "every command travels inside the two pipelines")
|
||||
require.Len(t, recorder.recorded(), 11, "one payload read per chunk plus every write inside the two pipelines")
|
||||
require.Equal(t, 2, recorder.countPrefix("mget "), "each chunk reads its old payloads once")
|
||||
})
|
||||
|
||||
t.Run("failure in a later chunk advances the global revision", func(t *testing.T) {
|
||||
@@ -1200,12 +1205,14 @@ func TestSchedulerCacheSnapshotMemoNilBeforeRealPipelineError(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
cache, mr, _ := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize)
|
||||
mr.HSet(schedulerAccountMetaKey("262"), "field", "value")
|
||||
// 让写前读取失败,覆盖降级后的 SET ... GET 错误处理路径。
|
||||
cache.rdb.AddHook(&schedulerCacheMGetFailHook{})
|
||||
|
||||
_, err := cache.writeAccountIDs(ctx, []service.Account{
|
||||
memoTestAccount(261, "fresh"),
|
||||
memoTestAccount(262, "wrong-type"),
|
||||
})
|
||||
require.Error(t, err, "a WRONGTYPE reply after a nil SET ... GET reply must fail the write")
|
||||
require.Error(t, err, "a WRONGTYPE reply on the fallback SET ... GET path must fail the write")
|
||||
require.Eventually(t, func() bool {
|
||||
return memoRevisionValue(cache, schedulerAccountMetaRevisionKey) != ""
|
||||
}, 2*time.Second, 5*time.Millisecond, "the global revision is advanced in the background")
|
||||
|
||||
@@ -4,6 +4,7 @@ package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
@@ -372,6 +373,59 @@ func TestBuildSchedulerMetadataAccount_KeepsGrokMediaEligibility(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
func TestBuildSchedulerMetadataAccount_ProjectsGrokSubscriptionTier(t *testing.T) {
|
||||
jwt := func(tier int) string {
|
||||
return "e30." + base64.RawURLEncoding.EncodeToString([]byte(fmt.Sprintf(`{"tier":%d}`, tier))) + ".signature"
|
||||
}
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
platform string
|
||||
token string
|
||||
saved string
|
||||
wantTier string
|
||||
wantEligible bool
|
||||
}{
|
||||
{"paid_live_jwt", service.PlatformGrok, jwt(7), "free", "supergrok_plus", true},
|
||||
{"paid_saved_tier", service.PlatformGrok, "", "supergrok_plus", "supergrok_plus", true},
|
||||
{"live_free_downgrade", service.PlatformGrok, jwt(0), "supergrok_plus", "free", false},
|
||||
{"live_basic_downgrade", service.PlatformGrok, jwt(2), "supergrok_plus", "x_basic", false},
|
||||
{"unclassified_billing", service.PlatformGrok, "", "", "", false},
|
||||
{"malformed_token_fallback", service.PlatformGrok, "invalid", "supergrok_plus", "supergrok_plus", true},
|
||||
{"other_platform_unchanged", service.PlatformOpenAI, jwt(7), "supergrok_plus", "", false},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
account := service.Account{
|
||||
Platform: tc.platform,
|
||||
Type: service.AccountTypeOAuth,
|
||||
Credentials: map[string]any{
|
||||
"access_token": tc.token,
|
||||
"refresh_token": "never-copy",
|
||||
"subscription_tier": tc.saved,
|
||||
},
|
||||
Extra: map[string]any{
|
||||
"grok_billing_snapshot": map[string]any{
|
||||
"status_code": 200,
|
||||
"monthly_limit_cents": 0,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
meta := buildSchedulerMetadataAccount(account)
|
||||
|
||||
require.Equal(t, tc.wantTier, meta.GetCredential("subscription_tier"))
|
||||
require.NotContains(t, meta.Credentials, "access_token")
|
||||
require.NotContains(t, meta.Credentials, "refresh_token")
|
||||
|
||||
eligible, _ := meta.GrokMediaGenerationEligibility()
|
||||
require.Equal(t, tc.wantEligible, eligible)
|
||||
require.Equal(t, tc.saved, account.GetCredential("subscription_tier"), "projection must not mutate original credentials")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildSchedulerMetadataAccount_KeepsSlimGroupMembership(t *testing.T) {
|
||||
account := service.Account{
|
||||
ID: 42,
|
||||
|
||||
@@ -0,0 +1,210 @@
|
||||
//go:build unit
|
||||
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/redis/go-redis/v9"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
var errSchedulerCacheInjectedMGet = errors.New("injected scheduler cache mget failure")
|
||||
|
||||
// schedulerCacheMGetFailHook 让写前读取失败,用于覆盖 MGET 失败后的降级写入路径。
|
||||
type schedulerCacheMGetFailHook struct {
|
||||
mu sync.Mutex
|
||||
failures int
|
||||
}
|
||||
|
||||
func (h *schedulerCacheMGetFailHook) DialHook(next redis.DialHook) redis.DialHook { return next }
|
||||
|
||||
func (h *schedulerCacheMGetFailHook) ProcessHook(next redis.ProcessHook) redis.ProcessHook {
|
||||
return func(ctx context.Context, cmd redis.Cmder) error {
|
||||
if strings.EqualFold(cmd.Name(), "mget") {
|
||||
h.recordFailure()
|
||||
return errSchedulerCacheInjectedMGet
|
||||
}
|
||||
return next(ctx, cmd)
|
||||
}
|
||||
}
|
||||
|
||||
func (h *schedulerCacheMGetFailHook) ProcessPipelineHook(next redis.ProcessPipelineHook) redis.ProcessPipelineHook {
|
||||
return func(ctx context.Context, cmds []redis.Cmder) error {
|
||||
for _, cmd := range cmds {
|
||||
if strings.EqualFold(cmd.Name(), "mget") {
|
||||
h.recordFailure()
|
||||
return errSchedulerCacheInjectedMGet
|
||||
}
|
||||
}
|
||||
return next(ctx, cmds)
|
||||
}
|
||||
}
|
||||
|
||||
func (h *schedulerCacheMGetFailHook) recordFailure() {
|
||||
h.mu.Lock()
|
||||
h.failures++
|
||||
h.mu.Unlock()
|
||||
}
|
||||
|
||||
func (h *schedulerCacheMGetFailHook) failureCount() int {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
return h.failures
|
||||
}
|
||||
|
||||
func TestSchedulerCacheWriteAccountIDsSkipsUnchangedPayloads(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
cache, _, recorder := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize)
|
||||
accounts := []service.Account{
|
||||
memoTestAccount(901, "steady"),
|
||||
memoTestAccountOn(service.PlatformGemini, 902, "steady-gemini"),
|
||||
}
|
||||
|
||||
ids, err := cache.writeAccountIDs(ctx, accounts)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []int64{901, 902}, ids)
|
||||
firstAnthropic := memoRevision(t, cache, memoAnthropicRevisionKey)
|
||||
firstGemini := memoRevision(t, cache, schedulerAccountMetaRevisionKeyForPlatform(service.PlatformGemini))
|
||||
require.NotEmpty(t, firstAnthropic)
|
||||
|
||||
recorder.reset()
|
||||
ids, err = cache.writeAccountIDs(ctx, accounts)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []int64{901, 902}, ids, "unchanged accounts are still reported to the caller")
|
||||
// 记录器只保留命令名与首个参数:一次 MGET 覆盖整块旧载荷。
|
||||
require.Equal(t, []string{"mget " + schedulerAccountKey("901")}, recorder.recorded(),
|
||||
"unchanged payloads must not be rewritten")
|
||||
require.Equal(t, firstAnthropic, memoRevision(t, cache, memoAnthropicRevisionKey),
|
||||
"a stable payload must not advance its platform revision")
|
||||
require.Equal(t, firstGemini, memoRevision(t, cache, schedulerAccountMetaRevisionKeyForPlatform(service.PlatformGemini)))
|
||||
require.Empty(t, memoRevision(t, cache, schedulerAccountMetaRevisionKey), "a stable payload must not advance the global revision")
|
||||
}
|
||||
|
||||
func TestSchedulerCacheWriteAccountIDsRewritesChangedPayloads(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
cache, _, recorder := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize)
|
||||
accounts := []service.Account{
|
||||
memoTestAccount(911, "steady"),
|
||||
memoTestAccount(912, "before"),
|
||||
}
|
||||
_, err := cache.writeAccountIDs(ctx, accounts)
|
||||
require.NoError(t, err)
|
||||
before := memoRevision(t, cache, memoAnthropicRevisionKey)
|
||||
|
||||
changed := []service.Account{accounts[0], accounts[1]}
|
||||
changed[1].Name = "after"
|
||||
changed[1].Status = service.StatusDisabled
|
||||
changed[1].GroupIDs = []int64{77}
|
||||
recorder.reset()
|
||||
ids, err := cache.writeAccountIDs(ctx, changed)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []int64{911, 912}, ids)
|
||||
require.Equal(t, []string{
|
||||
"mget " + schedulerAccountKey("911"),
|
||||
"set " + schedulerAccountKey("912"),
|
||||
"set " + schedulerAccountMetaKey("912"),
|
||||
"set " + memoAnthropicRevisionKey,
|
||||
}, recorder.recorded(), "only the changed account is rewritten; the revision shares the write batch")
|
||||
require.NotEqual(t, before, memoRevision(t, cache, memoAnthropicRevisionKey))
|
||||
|
||||
cached, err := cache.GetAccount(ctx, 912)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, cached)
|
||||
require.Equal(t, "after", cached.Name)
|
||||
require.Equal(t, service.StatusDisabled, cached.Status)
|
||||
require.Equal(t, []int64{77}, cached.GroupIDs)
|
||||
|
||||
unchanged, err := cache.GetAccount(ctx, 911)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, unchanged)
|
||||
require.Equal(t, "steady", unchanged.Name)
|
||||
}
|
||||
|
||||
func TestSchedulerCacheWriteAccountIDsSkipsUnchangedChunks(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
cache, _, recorder := newSchedulerCacheMemoUnit(t, 1)
|
||||
accounts := []service.Account{
|
||||
memoTestAccount(921, "a"),
|
||||
memoTestAccount(922, "b"),
|
||||
}
|
||||
_, err := cache.writeAccountIDs(ctx, accounts)
|
||||
require.NoError(t, err)
|
||||
|
||||
changed := []service.Account{accounts[0], accounts[1]}
|
||||
changed[1].Name = "b2"
|
||||
recorder.reset()
|
||||
_, err = cache.writeAccountIDs(ctx, changed)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []string{
|
||||
"mget " + schedulerAccountKey("921"),
|
||||
"mget " + schedulerAccountKey("922"),
|
||||
"set " + schedulerAccountKey("922"),
|
||||
"set " + schedulerAccountMetaKey("922"),
|
||||
"set " + memoAnthropicRevisionKey,
|
||||
}, recorder.recorded(), "unchanged chunks are read but not rewritten")
|
||||
}
|
||||
|
||||
func TestSchedulerCacheWriteAccountIDsPlatformChangeAdvancesGlobalRevision(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
cache, _, _ := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize)
|
||||
moved := memoTestAccountOn(service.PlatformGemini, 931, "moved")
|
||||
_, err := cache.writeAccountIDs(ctx, []service.Account{moved})
|
||||
require.NoError(t, err)
|
||||
require.NotEmpty(t, memoRevision(t, cache, schedulerAccountMetaRevisionKeyForPlatform(service.PlatformGemini)))
|
||||
require.Empty(t, memoRevision(t, cache, schedulerAccountMetaRevisionKey))
|
||||
|
||||
moved.Platform = service.PlatformAnthropic
|
||||
moved.Name = "moved-again"
|
||||
_, err = cache.writeAccountIDs(ctx, []service.Account{moved})
|
||||
require.NoError(t, err)
|
||||
require.NotEmpty(t, memoRevision(t, cache, schedulerAccountMetaRevisionKey),
|
||||
"a platform change must still advance the global revision")
|
||||
|
||||
cached, err := cache.GetAccount(ctx, 931)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, cached)
|
||||
require.Equal(t, service.PlatformAnthropic, cached.Platform)
|
||||
require.Equal(t, "moved-again", cached.Name)
|
||||
}
|
||||
|
||||
func TestSchedulerCacheWriteAccountIDsFallsBackWhenPayloadReadFails(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
cache, _, recorder := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize)
|
||||
account := memoTestAccount(941, "initial")
|
||||
_, err := cache.writeAccountIDs(ctx, []service.Account{account})
|
||||
require.NoError(t, err)
|
||||
|
||||
hook := &schedulerCacheMGetFailHook{}
|
||||
cache.rdb.AddHook(hook)
|
||||
|
||||
recorder.reset()
|
||||
_, err = cache.writeAccountIDs(ctx, []service.Account{account})
|
||||
require.NoError(t, err, "a payload read failure must not fail the write")
|
||||
require.Positive(t, hook.failureCount())
|
||||
require.Equal(t, []string{
|
||||
"mget " + schedulerAccountKey("941"),
|
||||
"set " + schedulerAccountKey("941"),
|
||||
"set " + schedulerAccountMetaKey("941"),
|
||||
"set " + memoAnthropicRevisionKey,
|
||||
}, recorder.recorded(), "the fallback reads first, then rewrites the account unconditionally")
|
||||
|
||||
account.Platform = service.PlatformGemini
|
||||
account.Name = "moved"
|
||||
recorder.reset()
|
||||
_, err = cache.writeAccountIDs(ctx, []service.Account{account})
|
||||
require.NoError(t, err)
|
||||
require.NotEmpty(t, memoRevision(t, cache, schedulerAccountMetaRevisionKey),
|
||||
"the fallback SET ... GET path still detects platform changes")
|
||||
|
||||
cachedPayload, err := cache.rdb.Get(ctx, schedulerAccountKey("941")).Result()
|
||||
require.NoError(t, err)
|
||||
cached, err := decodeCachedAccount(cachedPayload)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, service.PlatformGemini, cached.Platform)
|
||||
}
|
||||
@@ -61,23 +61,26 @@ func TestSchedulerSnapshotConfiguredMembership(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
for _, scope := range []string{"simple", "group", "ungrouped"} {
|
||||
for _, scope := range []struct {
|
||||
name, mode string
|
||||
isolate bool
|
||||
keyGroup *int64
|
||||
bucket int64
|
||||
members []int64
|
||||
}{
|
||||
{"simple", config.RunModeSimple, false, &group.ID, 0, []int64{0, group.ID, other.ID}},
|
||||
{"group", config.RunModeStandard, false, &group.ID, group.ID, []int64{group.ID}},
|
||||
{"ungrouped", config.RunModeStandard, false, nil, 0, []int64{0}},
|
||||
{"isolated_group", config.RunModeSimple, true, &group.ID, group.ID, []int64{group.ID}},
|
||||
{"isolated_ungrouped", config.RunModeSimple, true, nil, 0, []int64{0}},
|
||||
} {
|
||||
for _, forced := range []bool{false, true} {
|
||||
t.Run(fmt.Sprintf("%s/forced=%t", scope, forced), func(t *testing.T) {
|
||||
cfg := &config.Config{RunMode: config.RunModeStandard}
|
||||
t.Run(fmt.Sprintf("%s/forced=%t", scope.name, forced), func(t *testing.T) {
|
||||
cfg := &config.Config{RunMode: scope.mode, SimpleMode: config.SimpleModeConfig{GroupIsolation: scope.isolate}}
|
||||
cfg.Gateway.Scheduling.DbFallbackEnabled = true
|
||||
var groupID *int64
|
||||
groups := []int64{0}
|
||||
if scope == "group" {
|
||||
groupID, groups = &group.ID, []int64{group.ID}
|
||||
}
|
||||
if scope == "simple" {
|
||||
cfg.RunMode = config.RunModeSimple
|
||||
groupID, groups = &group.ID, []int64{0, group.ID, other.ID}
|
||||
}
|
||||
mixed := platform != service.PlatformOpenAI && !forced
|
||||
var wantReady, wantMembers []int64
|
||||
for _, gid := range groups {
|
||||
for _, gid := range scope.members {
|
||||
wantReady = append(wantReady, ids[gid]["ready"])
|
||||
wantMembers = append(wantMembers, ids[gid]["ready"], ids[gid]["cooling"], ids[gid]["expired"])
|
||||
if mixed {
|
||||
@@ -95,15 +98,12 @@ func TestSchedulerSnapshotConfiguredMembership(t *testing.T) {
|
||||
return out
|
||||
}
|
||||
for range 2 {
|
||||
accounts, useMixed, err := svc.ListSchedulableAccounts(ctx, groupID, platform, forced)
|
||||
accounts, useMixed, err := svc.ListSchedulableAccounts(ctx, scope.keyGroup, platform, forced)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, mixed, useMixed)
|
||||
require.ElementsMatch(t, wantReady, accountIDs(accounts), "both DB fallback and cache hit enforce current eligibility")
|
||||
}
|
||||
bucket := service.SchedulerBucket{Platform: platform, Mode: service.SchedulerModeSingle}
|
||||
if scope == "group" {
|
||||
bucket.GroupID = group.ID
|
||||
}
|
||||
bucket := service.SchedulerBucket{GroupID: scope.bucket, Platform: platform, Mode: service.SchedulerModeSingle}
|
||||
if forced {
|
||||
bucket.Mode = service.SchedulerModeForced
|
||||
} else if mixed {
|
||||
|
||||
@@ -21,6 +21,7 @@ import (
|
||||
"github.com/Wei-Shaw/sub2api/ent/userallowedgroup"
|
||||
"github.com/Wei-Shaw/sub2api/ent/usersubscription"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/pagination"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/timezone"
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/lib/pq"
|
||||
|
||||
@@ -665,6 +666,9 @@ func userListOrder(params pagination.PaginationParams) []func(*entsql.Selector)
|
||||
if sortBy == "last_used_at" {
|
||||
return userLastUsedAtOrder(sortOrder)
|
||||
}
|
||||
if platform, metric, ok := parseUserUsageSort(sortBy); ok {
|
||||
return userUsageOrder(platform, metric, sortOrder, time.Now())
|
||||
}
|
||||
|
||||
var field string
|
||||
defaultField := true
|
||||
@@ -723,6 +727,61 @@ func userListOrder(params pagination.PaginationParams) []func(*entsql.Selector)
|
||||
return []func(*entsql.Selector){dbent.Desc(field), dbent.Desc(dbuser.FieldID)}
|
||||
}
|
||||
|
||||
// Only known usage columns may select an aggregate; arbitrary sort keys retain
|
||||
// the existing ID fallback. "total" matches the displayed rolling 30-day cost.
|
||||
func parseUserUsageSort(key string) (platform, metric string, ok bool) {
|
||||
for _, period := range []string{"today", "total"} {
|
||||
column, found := strings.CutSuffix(key, "_"+period)
|
||||
if !found {
|
||||
continue
|
||||
}
|
||||
switch column {
|
||||
case "usage":
|
||||
return "", period, true
|
||||
case "usage_anthropic", "usage_openai", "usage_gemini", "usage_antigravity":
|
||||
return strings.TrimPrefix(column, "usage_"), period, true
|
||||
}
|
||||
}
|
||||
return "", "", false
|
||||
}
|
||||
|
||||
func userUsageOrder(platform, metric, sortOrder string, now time.Time) []func(*entsql.Selector) {
|
||||
return []func(*entsql.Selector){func(s *entsql.Selector) {
|
||||
ul := entsql.Table("usage_logs").As("ul")
|
||||
usage := entsql.Select(ul.C("user_id")).
|
||||
AppendSelectExpr(entsql.Expr("SUM(ul.actual_cost) AS cost")).
|
||||
From(ul).
|
||||
Where(entsql.ExprP(usageLogSuccessFilterUL)).
|
||||
GroupBy(ul.C("user_id"))
|
||||
// Keep the same time boundaries and platform attribution as
|
||||
// GetBatchUserUsageStats, which supplies the values shown in the table.
|
||||
if metric == "today" {
|
||||
usage.Where(entsql.GTE(ul.C("created_at"), timezone.Today()))
|
||||
} else {
|
||||
usage.Where(entsql.GTE(ul.C("created_at"), now.AddDate(0, 0, -30))).
|
||||
Where(entsql.LT(ul.C("created_at"), now))
|
||||
}
|
||||
if platform != "" {
|
||||
g, a := entsql.Table("groups").As("g"), entsql.Table("accounts").As("a")
|
||||
usage.LeftJoin(g).On(g.C("id"), ul.C("group_id")).
|
||||
LeftJoin(a).On(a.C("id"), ul.C("account_id")).
|
||||
Where(entsql.P(func(b *entsql.Builder) {
|
||||
b.WriteString(usageLogEffectivePlatformExpr + " = ").Arg(platform)
|
||||
}))
|
||||
}
|
||||
usage.As("user_usage_sort")
|
||||
s.LeftJoin(usage).On(s.C(dbuser.FieldID), usage.C("user_id"))
|
||||
direction := "DESC"
|
||||
if sortOrder == pagination.SortOrderAsc {
|
||||
direction = "ASC"
|
||||
}
|
||||
// Aggregate before LIMIT/OFFSET, retaining zero-usage users and using
|
||||
// a unique tie-breaker so equal costs cannot shuffle across pages.
|
||||
s.OrderExpr(entsql.Expr("COALESCE(" + usage.C("cost") + ", 0) " + direction))
|
||||
s.OrderExpr(entsql.Expr(s.C(dbuser.FieldID) + " " + direction))
|
||||
}}
|
||||
}
|
||||
|
||||
func (r *userRepository) GetLatestUsedAtByUserIDs(ctx context.Context, userIDs []int64) (map[int64]*time.Time, error) {
|
||||
result := make(map[int64]*time.Time, len(userIDs))
|
||||
if len(userIDs) == 0 {
|
||||
@@ -732,11 +791,23 @@ func (r *userRepository) GetLatestUsedAtByUserIDs(ctx context.Context, userIDs [
|
||||
return nil, fmt.Errorf("sql executor is not configured")
|
||||
}
|
||||
|
||||
// Resolve each user's latest usage timestamp with an index-backed LATERAL
|
||||
// probe instead of aggregating every historical usage_logs row. With the
|
||||
// idx_usage_logs_user_created(user_id, created_at) index, the inner
|
||||
// ORDER BY created_at DESC LIMIT 1 is a single backward index scan per user,
|
||||
// so the cost is O(page size * log n) rather than O(history size).
|
||||
// The inner join keeps the previous semantics: users without usage rows are
|
||||
// absent from the result map.
|
||||
const query = `
|
||||
SELECT user_id, MAX(created_at) AS last_used_at
|
||||
FROM usage_logs
|
||||
WHERE user_id = ANY($1)
|
||||
GROUP BY user_id
|
||||
SELECT u.user_id, latest.created_at
|
||||
FROM unnest($1::bigint[]) AS u(user_id)
|
||||
CROSS JOIN LATERAL (
|
||||
SELECT created_at
|
||||
FROM usage_logs
|
||||
WHERE user_id = u.user_id
|
||||
ORDER BY created_at DESC
|
||||
LIMIT 1
|
||||
) AS latest
|
||||
`
|
||||
|
||||
rows, err := r.sql.QueryContext(ctx, query, pq.Array(userIDs))
|
||||
|
||||
Loaded 100 of 354 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user