mirror of
https://github.com/Wei-Shaw/sub2api.git
synced 2026-12-04 23:51:08 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ac1b8f1271 | ||
|
|
8286268047 | ||
|
|
c5b811284a | ||
|
|
c591412c42 | ||
|
|
dba770d56a | ||
|
|
21cc926933 | ||
|
|
59100d324e | ||
|
|
7da09cab4e | ||
|
|
aa48a8bbd8 | ||
|
|
888c605733 | ||
|
|
5e45fa482b | ||
|
|
624874b313 | ||
|
|
67dca9687e | ||
|
|
a34f373973 | ||
|
|
b3e66f79a8 | ||
|
|
b6c366380b | ||
|
|
b751230512 | ||
|
|
98f83b7263 | ||
|
|
4c7e9b5b6b | ||
|
|
9a1680042a | ||
|
|
d744c22016 | ||
|
|
4942b2afc7 | ||
|
|
4c940c3cb7 | ||
|
|
cacc80b862 | ||
|
|
e0fa4b94f9 | ||
|
|
53002f677c | ||
|
|
d5dbb5c36b | ||
|
|
38b72d734e | ||
|
|
89654873ff | ||
|
|
4355236e00 | ||
|
|
47cb84b8b0 | ||
|
|
d6120b5d8e | ||
|
|
8f2cbb53d9 | ||
|
|
0fa02816af | ||
|
|
afbef7c8cc | ||
|
|
378984d87f | ||
|
|
ab71e12ec4 | ||
|
|
94c7d6b025 | ||
|
|
c7bfcd93aa | ||
|
|
9c41b32695 | ||
|
|
1cdecf4a88 | ||
|
|
2b1f129385 | ||
|
|
b0a02a3304 | ||
|
|
060d016041 | ||
|
|
b14f316ca2 | ||
|
|
43157c478e | ||
|
|
7fcaa32db4 | ||
|
|
71e6b6a971 | ||
|
|
f2e5b55f3e | ||
|
|
bdfe215cbb | ||
|
|
e068c3d02f | ||
|
|
455d317d6a | ||
|
|
a431e53f9e | ||
|
|
b8cfb78840 | ||
|
|
1b92038eaf | ||
|
|
52b3ca9609 | ||
|
|
86f8443045 | ||
|
|
f37b69b779 | ||
|
|
83337a0c65 | ||
|
|
44e35fbf84 | ||
|
|
f996b0bfaa | ||
|
|
7c6f70680d | ||
|
|
1b2243a4f5 | ||
|
|
26aab6dc07 | ||
|
|
c2cca510f2 | ||
|
|
698d142468 | ||
|
|
ddef05527e | ||
|
|
58b5e858c8 | ||
|
|
64211de8de | ||
|
|
857a76d4a0 | ||
|
|
9d3cc4507f | ||
|
|
8afd2abd97 | ||
|
|
dcde68aa58 | ||
|
|
abdc82725f | ||
|
|
3b83e045ed | ||
|
|
fdc7f1fa01 | ||
|
|
3856a02856 | ||
|
|
d19265ddb2 | ||
|
|
1774b79dcb | ||
|
|
92c9433d40 | ||
|
|
feab6d80dc | ||
|
|
2a8cb088af | ||
|
|
373d43533a | ||
|
|
16611a8ee0 | ||
|
|
7de15113c7 | ||
|
|
26e55cf332 | ||
|
|
867563ae76 | ||
|
|
c6c9935ae3 | ||
|
|
14cd587175 | ||
|
|
20c4bf5ae5 | ||
|
|
9c2cca9e62 | ||
|
|
89ad4c2caa | ||
|
|
4d9ac3e482 |
No files matched your search
@@ -35,7 +35,7 @@ jobs:
|
||||
cache-dependency-path: backend/go.sum
|
||||
- name: Verify Go version
|
||||
run: |
|
||||
go version | grep -q 'go1.27.2'
|
||||
go version | grep -q 'go1.27.3'
|
||||
- name: Unit tests
|
||||
working-directory: backend
|
||||
run: make test-unit
|
||||
@@ -75,7 +75,7 @@ jobs:
|
||||
cache-dependency-path: backend/go.sum
|
||||
- name: Verify Go version
|
||||
run: |
|
||||
go version | grep -q 'go1.27.2'
|
||||
go version | grep -q 'go1.27.3'
|
||||
- name: golangci-lint
|
||||
uses: golangci/golangci-lint-action@v9
|
||||
with:
|
||||
|
||||
@@ -137,7 +137,7 @@ jobs:
|
||||
check-latest: false
|
||||
cache: false
|
||||
- name: Verify Go version
|
||||
run: go version | grep -q 'go1.27.2'
|
||||
run: go version | grep -q 'go1.27.3'
|
||||
- name: Restore target-specific Go cache
|
||||
id: go-cache
|
||||
uses: actions/cache/restore@v6
|
||||
|
||||
@@ -23,7 +23,7 @@ jobs:
|
||||
cache-dependency-path: backend/go.sum
|
||||
- name: Verify Go version
|
||||
run: |
|
||||
go version | grep -q 'go1.27.2'
|
||||
go version | grep -q 'go1.27.3'
|
||||
- name: Run govulncheck
|
||||
working-directory: backend
|
||||
run: |
|
||||
|
||||
+1
-1
@@ -8,7 +8,7 @@
|
||||
# =============================================================================
|
||||
|
||||
ARG NODE_IMAGE=node:24-alpine
|
||||
ARG GOLANG_IMAGE=golang:1.27.2-alpine
|
||||
ARG GOLANG_IMAGE=golang:1.27.3-alpine
|
||||
ARG ALPINE_IMAGE=alpine:3.21
|
||||
ARG POSTGRES_IMAGE=postgres:18-alpine
|
||||
ARG GOPROXY=https://goproxy.cn,direct
|
||||
|
||||
@@ -54,8 +54,8 @@ Please read the following carefully before using this project:
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://aigocode.com/invite/SUB2API"><img src="assets/partners/logos/aigocode.png" alt="AIGoCode" width="150"></a></td>
|
||||
<td>Thanks to AIGoCode for sponsoring this project! AIGoCode is an all-in-one platform that integrates Claude Code, Codex, and the latest Gemini models, providing you with stable, efficient, and highly cost-effective AI coding services. The platform offers flexible subscription plans, zero risk of account suspension, direct access with no VPN required, and lightning-fast responses. AIGoCode has prepared a special benefit for sub2api users: if you register via <a href="https://aigocode.com/invite/SUB2API">this link</a>, you'll receive an extra 10% bonus credit on your first top-up!</td>
|
||||
<td width="180"><a href="https://api.aigocode.dev/invite/SUB2API"><img src="assets/partners/logos/aigocode.png" alt="AIGoCode" width="150"></a></td>
|
||||
<td>Thanks to AIGoCode for sponsoring this project! AIGoCode is an all-in-one platform that integrates Claude Code, Codex, and the latest Gemini models, providing you with stable, efficient, and highly cost-effective AI coding services. The platform offers flexible subscription plans, zero risk of account suspension, direct access with no VPN required, and lightning-fast responses. AIGoCode has prepared a special benefit for sub2api users: if you register via <a href="https://api.aigocode.dev/invite/SUB2API">this link</a>, you'll receive an extra 10% bonus credit on your first top-up!</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
@@ -63,11 +63,6 @@ Please read the following carefully before using this project:
|
||||
<td>Real GPT-5.6 series at 3% of OpenAI pricing — <a href="https://codex-everywhere.com">CodexEverywhere</a> is democratizing access to frontier models for developers worldwide. We believe in transparency and honesty, with model quality verified by active community oversight for months. USD and crypto friendly. Start with a free $20 trial at <a href="https://codex-everywhere.com">codex-everywhere.com</a>.</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://shop.bmoplus.com/?utm_source=github"><img src="assets/partners/logos/bmoplus.jpg" alt="bmoplus" width="150"></a></td>
|
||||
<td>Huge thanks to BmoPlus for sponsoring this project! BmoPlus is a highly reliable AI account provider built strictly for heavy AI users and developers. They offer rock-solid, ready-to-use accounts and official top-up services for ChatGPT Plus / ChatGPT Pro (Full Warranty) / Claude Pro / Super Grok / Gemini Pro. By registering and ordering through <a href="https://shop.bmoplus.com/?utm_source=github">BmoPlus - Premium AI Accounts & Top-ups</a>, users can unlock the mind-blowing rate of 10% of the official GPT subscription price (90% OFF)</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://bestproxy.com/?keyword=a2e8iuol"><img src="assets/partners/logos/bestproxy.png" alt="bestproxy" width="150"></a></td>
|
||||
<td>Thanks to Bestproxy for sponsoring this project! <a href="https://bestproxy.com/?keyword=a2e8iuol">Bestproxy</a> provides high-purity residential IPs with dedicated one-IP-per-account support. By combining real home networks with fingerprint isolation, it enables link environment isolation and reduces the probability of association-based risk control.</td>
|
||||
@@ -96,18 +91,6 @@ Please read the following carefully before using this project:
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://www.proxy4free.com/?keyword=4yjqecpc"><img src="assets/partners/logos/proxy4free.png" alt="proxy4free" width="150"></a></td>
|
||||
<td>Thanks to Proxy4Free for sponsoring this project! Proxy4Free is a data proxy service provider for developers and AI applications, offering residential proxies, static residential proxies, ISP proxies, and datacenter proxies for scenarios such as Web Scraping, Browser Automation, and AI Agents. With global IP resources, stable connections, and flexible switching, it helps developers improve data collection success rates and reduce the risk of IP bans. Register via <a href="https://www.proxy4free.com/?keyword=4yjqecpc">this link</a> to get started and easily build more stable and efficient automation workflows.
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="http://aimzoon.com"><img src="assets/partners/logos/aimzoon.jpg" alt="aimzoon" width="150"></a></td>
|
||||
<td>Thanks to Aimzoon for sponsoring this project! <a href="http://aimzoon.com">Aimzoon</a> provides stable, cost-effective AI API access services, enabling developers to quickly connect popular AI services to coding tools such as Codex, Claude Code, and Gemini CLI. No complex configuration — faster onboarding, more stable calls, and lower costs. Ongoing promotions including discounted Codex rates and special pricing, with free trial credits upon registration, bringing AI coding into your daily workflow. <a href="http://aimzoon.com">Click here</a> to register and try it out!
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://nagora.ai/"><img src="assets/partners/logos/nagora.png" alt="Nagora" width="150"></a></td>
|
||||
<td><a href="https://nagora.ai/">Nagora</a> is a multi-model AI API gateway built for developers and teams. With a single account and API key, you can access more than 26 leading text and image models through one unified interface. It is compatible with OpenAI, Anthropic, and Gemini protocols and integrates seamlessly with development tools such as Claude Code, Codex, and Gemini CLI. The platform provides intelligent routing, automatic failover, transparent pricing, and consolidated billing, along with budget management, rate limiting, and concurrency controls. This makes AI usage more reliable and manageable across individual development, team collaboration, and production environments. No changes to your existing application are required. Simply replace the Base URL and API key to complete the integration in as little as one minute.</td>
|
||||
@@ -143,11 +126,6 @@ Please read the following carefully before using this project:
|
||||
<td>Swiftproxy is a high-performance proxy solution built for developers, providing stable and reliable residential and static residential proxy services. With 90M+ clean residential IPs, global coverage, flexible rotation, and precise geo-targeting, it helps projects such as web scraping, AI automation, browser automation, SEO monitoring, and multi-account management overcome access restrictions and improve workflow efficiency. It supports HTTP(S) and SOCKS5 protocols, integrates with popular automation tools like Playwright, Selenium, and Puppeteer, with dynamic proxy traffic that never expires until used and free testing available — <a href="https://www.swiftproxy.net/?ref=sub2api">start your free test now</a>!</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://www.duckip.cn/?keyword=cu7oog6y"><img src="assets/partners/logos/duckip.png" alt="DuckIP" width="150"></a></td>
|
||||
<td><a href="https://www.duckip.cn/?keyword=cu7oog6y">DuckIP</a> - 90M+ global residential network resources across 195+ countries and regions, with rotation and sticky sessions for public data collection, RAG updates, model evaluation, and multi-region data workloads. 🟢Residential Proxy - 20% Off; 🟢Static Residential Proxy - Starting at ¥50.00/IP; 🟢Unlimited Residential Proxy - Starting at ¥19.8/Hour. ✅Get 500M Free Trial.</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://go.apimart.ai/gh-sub2api"><img src="assets/partners/logos/apimart.jpg" alt="APIMart" width="150"></a></td>
|
||||
<td>Thanks to APIMart for sponsoring this project! <a href="https://go.apimart.ai/gh-sub2api">APIMart</a> is a low-cost API platform for AI image and video generation — GPT-Image-2 from $0.006 per image, with 160+ images per dollar. One async API covers both image and video: submit a task, get an ID, and retrieve results via polling or callback. Batch tens of thousands of images without timeouts, and switch models without changing code. Pay as you go with no monthly fee — <a href="https://go.apimart.ai/gh-sub2api">sign up here</a> to get started.</td>
|
||||
@@ -168,6 +146,21 @@ Please read the following carefully before using this project:
|
||||
<td>ColaProxy provides high-quality residential proxies built for web scraping, automation, and multi-account management. Get a free trial with non-expiring traffic, pricing starting as low as $0.3/GB, unlimited concurrent connections, and intelligent IP rotation for a smoother, more stable proxy experience. Use discount code COLA10 to get 10% off and start scaling your projects with reliable residential proxies today. <a href="https://colaproxy.com/?utm_source=sub2api&utm_medium=sub2api&ref=sub2api">Get started with ColaProxy</a></td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://modelflare.dev/sign-up?utm_source=github&utm_campaign=sub2api"><img src="assets/partners/logos/modelflare.png" alt="Modelflare" width="150"></a></td>
|
||||
<td>Modelflare: Full strength, stable, nothing watered down. Global SOTA models at a lower cost. Operated by US-based Havenbyte LLC, Modelflare supports GPT, Claude, Gemini, Grok, and other leading models through common compatible protocols, plus 40+ image and video models. Cache compensation is a highlight: selected OpenAI groups (price-first, stable, and premium) guarantee daily cache hit rates of 65%, 75%, or 85%, and if eligible requests fall short, Modelflare refunds the difference, visible on the usage dashboard after settlement. Special offers: a single top-up of US$20 unlocks the GPT discount group at a 0.015x price multiplier, and a single top-up of US$50 unlocks the Claude discount group at a 0.03x multiplier. Register via <a href="https://modelflare.dev/sign-up?utm_source=github&utm_campaign=sub2api">this exclusive link</a> to get started.</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://x.com/chenju_ai"><img src="assets/partners/logos/chenju_ai.png" alt="Chenju" width="150"></a></td>
|
||||
<td>Thanks to <a href="https://x.com/chenju_ai">Chenju</a> for sponsoring this project! This is probably the only ad slot in this section that doesn't ask you to sign up for anything. Good open-source projects deserve to be paid for, so Chenju is chipping in a gift and raising a glass to the author. Find <a href="https://x.com/chenju_ai">Chenju</a> on X to chat about API relays, upstream providers, or just shoot the breeze.</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://t.me/AACC8888888"><img src="assets/partners/logos/ooko.ai.png" alt="ooko.ai" width="150"></a></td>
|
||||
<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>
|
||||
|
||||
</table>
|
||||
|
||||
## Overview
|
||||
|
||||
+17
-24
@@ -55,8 +55,8 @@
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://aigocode.com/invite/SUB2API"><img src="assets/partners/logos/aigocode.png" alt="AIGoCode" width="150"></a></td>
|
||||
<td>感谢 AIGoCode 赞助了本项目!AIGoCode 是一站式集成 Claude Code、Codex 以及最新 Gemini 模型的综合平台,为您提供稳定、高效、高性价比的 AI 编程服务。平台提供灵活的订阅方案,零封号风险,免 VPN 直连,响应极速。AIGoCode 为 sub2api 用户准备了专属福利:通过<a href="https://aigocode.com/invite/SUB2API">此链接</a>注册,首次充值可额外获得 10% 赠送额度!</td>
|
||||
<td width="180"><a href="https://api.aigocode.dev/invite/SUB2API"><img src="assets/partners/logos/aigocode.png" alt="AIGoCode" width="150"></a></td>
|
||||
<td>感谢 AIGoCode 赞助了本项目!AIGoCode 是一站式集成 Claude Code、Codex 以及最新 Gemini 模型的综合平台,为您提供稳定、高效、高性价比的 AI 编程服务。平台提供灵活的订阅方案,零封号风险,免 VPN 直连,响应极速。AIGoCode 为 sub2api 用户准备了专属福利:通过<a href="https://api.aigocode.dev/invite/SUB2API">此链接</a>注册,首次充值可额外获得 10% 赠送额度!</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
@@ -64,11 +64,6 @@
|
||||
<td>Real GPT-5.6 series at 3% of OpenAI pricing — <a href="https://codex-everywhere.com">CodexEverywhere</a> is democratizing access to frontier models for developers worldwide. We believe in transparency and honesty, with model quality verified by active community oversight for months. USD and crypto friendly. Start with a free $20 trial at <a href="https://codex-everywhere.com">codex-everywhere.com</a>.</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://shop.bmoplus.com/?utm_source=github"><img src="assets/partners/logos/bmoplus.jpg" alt="bmoplus" width="150"></a></td>
|
||||
<td>感谢 BmoPlus 赞助了本项目!BmoPlus 是一家专为AI订阅重度用户打造的可靠 AI 账号代充服务商,提供稳定的 ChatGPT Plus / ChatGPT Pro(全程质保) / Claude Pro / Super Grok / Gemini Pro 的官方代充&成品账号。 通过<a href="https://shop.bmoplus.com/?utm_source=github">BmoPlus AI成品号专卖/代充</a>注册下单的用户,可享GPT 官网订阅一折 的震撼价格!</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://bestproxy.com/?keyword=a2e8iuol"><img src="assets/partners/logos/bestproxy.png" alt="bestproxy" width="150"></a></td>
|
||||
<td>感谢 Bestproxy 赞助了本项目!<a href="https://bestproxy.com/?keyword=a2e8iuol">Bestproxy</a> 是一家提供高纯度住宅IP,支持一号一IP独享,结合真实家庭网络与指纹隔离,可实现链路环境隔离,降低关联风控概率。</td>
|
||||
@@ -99,18 +94,6 @@
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://www.proxy4free.com/?keyword=4yjqecpc"><img src="assets/partners/logos/proxy4free.png" alt="proxy4free" width="150"></a></td>
|
||||
<td>感谢 Proxy4Free 赞助本项目!Proxy4Free 是面向开发者和 AI 应用的数据代理服务商,提供住宅代理、静态住宅代理、ISP 代理及数据中心代理等多种代理解决方案,适用于 Web Scraping、Browser Automation、AI Agent 等场景。支持全球 IP 资源、稳定连接与灵活切换,帮助开发者提升数据采集成功率,降低 IP 封禁风险。通过<a href="https://www.proxy4free.com/?keyword=4yjqecpc">此链接注册</a>即可开始体验,轻松构建更稳定、高效的自动化工作流。
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="http://aimzoon.com"><img src="assets/partners/logos/aimzoon.jpg" alt="aimzoon" width="150"></a></td>
|
||||
<td>感谢 Aimzoon 对本项目的赞助! <a href="http://aimzoon.com">Aimzoon</a> 提供稳定、高性价比的 AI API 接入服务,支持开发者将常用 AI 服务快速接入 Codex、Claude Code、Gemini CLI 等编程工具。无需复杂配置,更快接入,更稳调用,更省成本。codex倍率优惠,特价倍率等促销不断,注册即送免费体验额度,让 AI 编程真正进入日常工作流。<a href="http://aimzoon.com">点击这里</a>注册体验!
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://nagora.ai/"><img src="assets/partners/logos/nagora.png" alt="Nagora" width="150"></a></td>
|
||||
<td><a href="https://nagora.ai/">Nagora</a> 是专为开发者和团队打造的多模型 AI API 网关。通过一个账户和一枚 API Key,即可统一调用 26+ 款主流文本与图像模型,兼容 OpenAI、Anthropic 与 Gemini 协议,并可无缝接入 Claude Code、Codex、Gemini CLI 等开发工具。平台提供智能路由、自动故障转移、透明计费与统一账单,同时支持预算、限速、并发控制,让个人开发、团队协作和生产环境中的 AI 调用更稳定、更可控。无需改造现有应用,只需替换 Base URL 与 API Key,最快 1 分钟即可完成接入。</td>
|
||||
@@ -146,11 +129,6 @@
|
||||
<td>Swiftproxy 是面向开发者的高性能代理解决方案,提供稳定可靠的住宅代理和静态住宅代理服务。拥有 9000 万+ 纯净住宅 IP,覆盖全球,支持灵活轮换和精准地理定位,帮助网页抓取、AI 自动化、浏览器自动化、SEO 监控和多账号管理等项目突破访问限制,提升工作流效率。支持 HTTP(S) 和 SOCKS5 协议,兼容 Playwright、Selenium、Puppeteer 等主流自动化工具,动态代理流量用完为止永不过期,支持免费测试 — <a href="https://www.swiftproxy.net/?ref=sub2api">立即开始免费测试</a>!</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://www.duckip.cn/?keyword=cu7oog6y"><img src="assets/partners/logos/duckip.png" alt="DuckIP" width="150"></a></td>
|
||||
<td><a href="https://www.duckip.cn/?keyword=cu7oog6y">DuckIP</a> - 9000 万+ 全球住宅网络资源,覆盖 195+ 国家和地区,支持轮换和粘性会话,适用于公共数据采集、RAG 更新、模型评估和多区域数据工作负载。🟢住宅代理 - 8 折优惠;🟢静态住宅代理 - ¥50.00/IP 起;🟢无限住宅代理 - ¥19.8/小时 起。✅免费领取 500M 试用流量。</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://go.apimart.ai/gh-sub2api"><img src="assets/partners/logos/apimart.jpg" alt="APIMart" width="150"></a></td>
|
||||
<td>感谢 APIMart 赞助了本项目!<a href="https://go.apimart.ai/gh-sub2api">APIMart</a> 是专注于 AI 图片/视频生成的低价 API 平台,GPT-Image-2 低至 $0.006/张,1 美元可生成 160+ 张图片。图片、视频一套异步 API 通吃:提交任务获取 ID,通过轮询或回调获取结果;批量生成上万张图片也不会超时,切换模型无需修改代码。按量付费、无月费,通过<a href="https://go.apimart.ai/gh-sub2api">此注册链接</a>注册即可开始使用。</td>
|
||||
@@ -171,6 +149,21 @@
|
||||
<td>ColaProxy 提供专为网页抓取、自动化和多账号管理打造的高质量住宅代理。免费试用,流量永不过期,价格低至 $0.3/GB,支持无限并发连接和智能 IP 轮换,带来更流畅、更稳定的代理体验。使用优惠码 COLA10 立享 9 折优惠,立即开始使用可靠的住宅代理扩展您的项目。<a href="https://colaproxy.com/?utm_source=sub2api&utm_medium=sub2api&ref=sub2api">立即开始使用 ColaProxy</a></td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://modelflare.dev/zh/sign-up?utm_source=github&utm_campaign=sub2api"><img src="assets/partners/logos/modelflare.png" alt="Modelflare" width="150"></a></td>
|
||||
<td>Modelflare:满血稳定不掺水,低成本享受全球 SOTA 模型。站点由美国 LLC 主体 Havenbyte LLC 运营,支持 GPT、Claude、Gemini、Grok 等主流模型和常用兼容协议,还支持 40 多种图片和视频模型。缓存补偿是一大亮点:部分 OpenAI 价格优先、稳定和高级分组提供每日 65%、75%、85% 的缓存命中率保障,符合条件的请求没达到目标的,平台补偿差额,结算后可在用量看板查看。特惠活动:单笔充值 US$20 即可解锁 0.015 倍价格倍率的 GPT 特惠分组,单笔充值 US$50 即可解锁 0.03 倍价格倍率的 Claude 特惠分组。通过<a href="https://modelflare.dev/zh/sign-up?utm_source=github&utm_campaign=sub2api">专属链接</a>注册即可参与</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://x.com/chenju_ai"><img src="assets/partners/logos/chenju_ai.png" alt="Chenju" width="150"></a></td>
|
||||
<td>感谢 <a href="https://x.com/chenju_ai">陈局</a> 赞助了本项目!这大概是本栏唯一一个不让你注册的广告位。好的开源项目值得被付费,陈局来随个份子,敬作者一杯。X 上找 <a href="https://x.com/chenju_ai">陈局</a>,聊中转、聊上游、吹吹水。</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://t.me/AACC8888888"><img src="assets/partners/logos/ooko.ai.png" alt="ooko.ai" width="150"></a></td>
|
||||
<td>🔑 高价收 AI 账号|Gemini · Claude · GPT|大小号通收,各种渠道都要|支持按量跑付|寻一手大厂资源,我上 KEY 。<br>微信:Liuyou-zawd|TG:<a href="https://t.me/AACC8888888">AACC8888888</a></td>
|
||||
</tr>
|
||||
|
||||
</table>
|
||||
|
||||
## 项目概述
|
||||
|
||||
+17
-24
@@ -54,8 +54,8 @@
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://aigocode.com/invite/SUB2API"><img src="assets/partners/logos/aigocode.png" alt="AIGoCode" width="150"></a></td>
|
||||
<td>AIGoCode のご支援に感謝します!AIGoCode は Claude Code、Codex、最新の Gemini モデルを統合したオールインワンプラットフォームで、安定的かつ効率的でコストパフォーマンスに優れた AI コーディングサービスを提供します。柔軟なサブスクリプションプラン、アカウント停止リスクゼロ、VPN 不要の直接アクセス、超高速レスポンスが特長です。AIGoCode は sub2api ユーザー向けに特別特典を用意しています:<a href="https://aigocode.com/invite/SUB2API">こちらのリンク</a>から登録すると、初回チャージ時に 10% のボーナスクレジットを追加プレゼント!</td>
|
||||
<td width="180"><a href="https://api.aigocode.dev/invite/SUB2API"><img src="assets/partners/logos/aigocode.png" alt="AIGoCode" width="150"></a></td>
|
||||
<td>AIGoCode のご支援に感謝します!AIGoCode は Claude Code、Codex、最新の Gemini モデルを統合したオールインワンプラットフォームで、安定的かつ効率的でコストパフォーマンスに優れた AI コーディングサービスを提供します。柔軟なサブスクリプションプラン、アカウント停止リスクゼロ、VPN 不要の直接アクセス、超高速レスポンスが特長です。AIGoCode は sub2api ユーザー向けに特別特典を用意しています:<a href="https://api.aigocode.dev/invite/SUB2API">こちらのリンク</a>から登録すると、初回チャージ時に 10% のボーナスクレジットを追加プレゼント!</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
@@ -63,11 +63,6 @@
|
||||
<td>OpenAI 公式価格のわずか 3% で本物の GPT-5.6 シリーズを提供 — <a href="https://codex-everywhere.com">CodexEverywhere</a> は世界中の開発者にフロンティアモデルへのアクセスを民主化しています。私たちは透明性と誠実さを信条とし、モデル品質は数か月にわたるアクティブなコミュニティの監視によって検証されています。USD および暗号通貨に対応。<a href="https://codex-everywhere.com">codex-everywhere.com</a> で $20 の無料トライアルから始めましょう。</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://shop.bmoplus.com/?utm_source=github"><img src="assets/partners/logos/bmoplus.jpg" alt="bmoplus" width="150"></a></td>
|
||||
<td>本プロジェクトにご支援いただいた BmoPlus に感謝いたします!BmoPlusは、AIサブスクリプションのヘビーユーザー向けに特化した信頼性の高いAIアカウントサービスプロバイダーであり、安定した ChatGPT Plus / ChatGPT Pro (完全保証) / Claude Pro / Super Grok / Gemini Pro の公式代行チャージおよび即納アカウントを提供しています。こちらの<a href="https://shop.bmoplus.com/?utm_source=github">BmoPlus AIアカウント専門店/代行チャージ</a>経由でご登録・ご注文いただいたユーザー様は、GPTを 公式サイト価格の約1割(90% OFF) という驚異的な価格でご利用いただけます!</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://bestproxy.com/?keyword=a2e8iuol"><img src="assets/partners/logos/bestproxy.png" alt="bestproxy" width="150"></a></td>
|
||||
<td>Bestproxy のご支援に感謝します!<a href="https://bestproxy.com/?keyword=a2e8iuol">Bestproxy</a> は高純度の住宅IPを提供し、1アカウント1IP専有をサポートしています。実際の家庭ネットワークとフィンガープリント分離を組み合わせることで、リンク環境の分離を実現し、関連付けによるリスク管理の確率を低減します。</td>
|
||||
@@ -98,18 +93,6 @@
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://www.proxy4free.com/?keyword=4yjqecpc"><img src="assets/partners/logos/proxy4free.png" alt="proxy4free" width="150"></a></td>
|
||||
<td>Proxy4Free のご支援に感謝します!Proxy4Free は開発者と AI アプリケーション向けのデータプロキシサービスプロバイダーで、住宅プロキシ、静的住宅プロキシ、ISP プロキシ、データセンタープロキシなど多様なプロキシソリューションを提供しており、Web Scraping、Browser Automation、AI Agent などのシナリオに適しています。グローバル IP リソース、安定した接続、柔軟な切り替えをサポートし、開発者のデータ収集成功率の向上と IP ブロックリスクの低減を支援します。<a href="https://www.proxy4free.com/?keyword=4yjqecpc">こちらのリンクから登録</a>して、より安定した効率的な自動化ワークフローを簡単に構築しましょう。
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="http://aimzoon.com"><img src="assets/partners/logos/aimzoon.jpg" alt="aimzoon" width="150"></a></td>
|
||||
<td>Aimzoon のご支援に感謝します!<a href="http://aimzoon.com">Aimzoon</a> は安定してコストパフォーマンスに優れた AI API 接続サービスを提供し、開発者が主要な AI サービスを Codex、Claude Code、Gemini CLI などのコーディングツールへ素早く接続できるようにします。複雑な設定は不要で、より速い接続、より安定した呼び出し、より低いコストを実現。Codex レート割引や特価レートなどのキャンペーンも随時開催中、登録するだけで無料お試しクレジットをプレゼント。AI コーディングを日常のワークフローへ。<a href="http://aimzoon.com">こちら</a>から登録してお試しください!
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://nagora.ai/"><img src="assets/partners/logos/nagora.png" alt="Nagora" width="150"></a></td>
|
||||
<td><a href="https://nagora.ai/">Nagora</a>は、開発者やチーム向けに設計されたマルチモデルAI APIゲートウェイです。1つのアカウントと1つのAPIキーだけで、26種類以上の主要なテキストモデルおよび画像モデルを一元的に利用できます。OpenAI、Anthropic、Geminiの各プロトコルに対応し、Claude Code、Codex、Gemini CLIなどの開発ツールにもシームレスに接続できます。 プラットフォームには、インテリジェントルーティング、自動フェイルオーバー、透明性の高い料金体系、請求の一元管理に加え、予算管理、レート制限、同時実行数の制御機能が備わっています。これにより、個人開発、チームでの共同作業、本番環境におけるAI APIの利用を、より安定的かつ柔軟に管理できます。 既存のアプリケーションを改修する必要はありません。Base URLとAPIキーを置き換えるだけで、最短1分で導入を完了できます。</td>
|
||||
@@ -145,11 +128,6 @@
|
||||
<td>Swiftproxy は開発者向けの高性能プロキシソリューションで、安定して信頼できるレジデンシャルおよび静的レジデンシャルプロキシサービスを提供します。9,000 万以上のクリーンな住宅 IP を保有し、グローバルカバレッジ、柔軟なローテーション、精密なジオターゲティングにより、Web スクレイピング、AI オートメーション、ブラウザ自動化、SEO モニタリング、マルチアカウント管理などのプロジェクトがアクセス制限を克服し、ワークフロー効率を向上させます。HTTP(S) および SOCKS5 プロトコルに対応し、Playwright、Selenium、Puppeteer などの主要な自動化ツールと統合可能。動的プロキシトラフィックは使い切るまで期限切れなし、無料テストも利用可能 — <a href="https://www.swiftproxy.net/?ref=sub2api">今すぐ無料テストを開始</a>!</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://www.duckip.cn/?keyword=cu7oog6y"><img src="assets/partners/logos/duckip.png" alt="DuckIP" width="150"></a></td>
|
||||
<td><a href="https://www.duckip.cn/?keyword=cu7oog6y">DuckIP</a> - 195 以上の国と地域にわたる 9,000 万以上のグローバルレジデンシャルネットワークリソース。ローテーションとスティッキーセッションに対応し、パブリックデータ収集、RAG 更新、モデル評価、マルチリージョンデータワークロードに最適。🟢レジデンシャルプロキシ - 20% オフ;🟢スタティックレジデンシャルプロキシ - ¥50.00/IP から;🟢無制限レジデンシャルプロキシ - ¥19.8/時間 から。✅500M 無料トライアルを取得。</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://go.apimart.ai/gh-sub2api"><img src="assets/partners/logos/apimart.jpg" alt="APIMart" width="150"></a></td>
|
||||
<td>APIMart のご支援に感謝します!<a href="https://go.apimart.ai/gh-sub2api">APIMart</a> は AI 画像・動画生成に特化した低価格 API プラットフォームです。GPT-Image-2 は 1 枚 $0.006 から、1 ドルで 160 枚以上の画像を生成できます。画像と動画の両方に対応する非同期 API を 1 つで利用でき、タスクを送信して ID を取得し、ポーリングまたはコールバックで結果を取得できます。数万枚規模のバッチ処理でもタイムアウトせず、モデルを変更してもコードの変更は不要です。月額料金なしの従量課金制で、<a href="https://go.apimart.ai/gh-sub2api">こちらの登録リンク</a>からすぐに利用を開始できます。</td>
|
||||
@@ -170,6 +148,21 @@
|
||||
<td>ColaProxy は、Web スクレイピング、自動化、マルチアカウント管理向けに構築された高品質な住宅プロキシを提供します。有効期限なしのトラフィックで無料トライアルが利用でき、料金は $0.3/GB から、無制限の同時接続とインテリジェントな IP ローテーションにより、よりスムーズで安定したプロキシ体験を実現します。割引コード COLA10 で 10% オフ、信頼性の高い住宅プロキシでプロジェクトを今すぐスケールしましょう。<a href="https://colaproxy.com/?utm_source=sub2api&utm_medium=sub2api&ref=sub2api">ColaProxy を始める</a></td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://modelflare.dev/ja/sign-up?utm_source=github&utm_campaign=sub2api"><img src="assets/partners/logos/modelflare.png" alt="Modelflare" width="150"></a></td>
|
||||
<td>Modelflare:フルスペック、安定、水増しなし。世界の SOTA モデルを、より低いコストで。米国拠点の Havenbyte LLC が運営する Modelflare は、一般的な互換プロトコルを通じて GPT、Claude、Gemini、Grok などの主要モデルに対応し、さらに 40 以上の画像・動画モデルも利用できます。注目はキャッシュ補償です。対象の OpenAI グループ(価格優先・安定・プレミアム)は、1 日のキャッシュヒット率をそれぞれ 65%、75%、85% で保証します。対象リクエストがこの水準に達しない場合、Modelflare が差額を返金し、精算後に利用状況ダッシュボードで確認できます。特別オファー:US$20 を 1 回チャージすると、価格倍率 0.015 倍の GPT 割引グループが解放されます。US$50 を 1 回チャージすると、価格倍率 0.03 倍の Claude 割引グループが解放されます。<a href="https://modelflare.dev/ja/sign-up?utm_source=github&utm_campaign=sub2api">こちらの専用リンク</a>から登録して始めましょう。</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://x.com/chenju_ai"><img src="assets/partners/logos/chenju_ai.png" alt="Chenju" width="150"></a></td>
|
||||
<td><a href="https://x.com/chenju_ai">陈局(Chenju)</a>様、本プロジェクトへのご支援ありがとうございます!これはおそらく、この欄で唯一「登録しなくていい」広告枠です。良いオープンソースには対価が払われるべき——というわけで、陈局がご祝儀を包んで作者に一杯おごります。X で <a href="https://x.com/chenju_ai">陈局</a> を見つけて、中継サービスや上流の話、雑談でもどうぞ。</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://t.me/AACC8888888"><img src="assets/partners/logos/ooko.ai.png" alt="ooko.ai" width="150"></a></td>
|
||||
<td>🔑 AI アカウント高価買取|Gemini · Claude · GPT|メイン・サブアカウントすべて買取、チャネル問わず歓迎|従量制での支払いに対応|大手の一次リソースを求めています、KEY は私が用意します。<br>WeChat:Liuyou-zawd|Telegram:<a href="https://t.me/AACC8888888">AACC8888888</a></td>
|
||||
</tr>
|
||||
|
||||
</table>
|
||||
|
||||
## 概要
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 25 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 113 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 5.4 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 9.3 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 7.4 KiB |
@@ -1 +1 @@
|
||||
0.2.15
|
||||
0.2.17
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
module github.com/Wei-Shaw/sub2api
|
||||
|
||||
go 1.27.2
|
||||
go 1.27.3
|
||||
|
||||
require (
|
||||
entgo.io/ent v0.14.5
|
||||
|
||||
@@ -979,6 +979,9 @@ const (
|
||||
|
||||
// GatewayConfig API网关相关配置
|
||||
type GatewayConfig struct {
|
||||
// MinOutputTokens is the minimum max_output_tokens used when
|
||||
// converting Chat Completions or Anthropic requests to Responses.
|
||||
MinOutputTokens int `mapstructure:"min_output_tokens"`
|
||||
// 等待上游响应头的超时时间(秒),0表示无超时
|
||||
// 注意:这不影响流式数据传输,只控制等待响应头的时间
|
||||
ResponseHeaderTimeout int `mapstructure:"response_header_timeout"`
|
||||
@@ -2035,6 +2038,7 @@ func configureConfigSource(setConfigFile, addConfigPath func(string)) {
|
||||
|
||||
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_key_rate_limit_enabled", false)
|
||||
|
||||
@@ -2707,6 +2711,9 @@ func setEnvReachableDefaults() {
|
||||
}
|
||||
|
||||
func (c *Config) Validate() error {
|
||||
if c.Gateway.MinOutputTokens < 16 {
|
||||
return fmt.Errorf("gateway.min_output_tokens must be at least 16")
|
||||
}
|
||||
forwardedClientIPHeaders, err := NormalizeForwardedClientIPHeaders(c.Security.ForwardedClientIPHeaders)
|
||||
if err != nil {
|
||||
return fmt.Errorf("security.forwarded_client_ip_headers: %w", err)
|
||||
|
||||
@@ -31,6 +31,29 @@ func TestLoadDefaultModelsListReadMaxBytes(t *testing.T) {
|
||||
require.Equal(t, DefaultModelsListReadMaxBytes, cfg.Gateway.ModelsListReadMaxBytes)
|
||||
}
|
||||
|
||||
func TestLoadDefaultMinOutputTokens(t *testing.T) {
|
||||
resetViperWithJWTSecret(t)
|
||||
cfg, err := Load()
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 128, cfg.Gateway.MinOutputTokens)
|
||||
}
|
||||
|
||||
func TestLoadMinOutputTokensFromEnv(t *testing.T) {
|
||||
resetViperWithJWTSecret(t)
|
||||
t.Setenv("GATEWAY_MIN_OUTPUT_TOKENS", "16")
|
||||
cfg, err := Load()
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 16, cfg.Gateway.MinOutputTokens)
|
||||
}
|
||||
|
||||
func TestValidateMinOutputTokensMinimum(t *testing.T) {
|
||||
resetViperWithJWTSecret(t)
|
||||
cfg, err := Load()
|
||||
require.NoError(t, err)
|
||||
cfg.Gateway.MinOutputTokens = 15
|
||||
require.EqualError(t, cfg.Validate(), "gateway.min_output_tokens must be at least 16")
|
||||
}
|
||||
|
||||
func TestLoadTimezonePrecedence(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
|
||||
@@ -113,6 +113,14 @@ var DefaultAntigravityModelMapping = map[string]string{
|
||||
// Claude 白名单
|
||||
"claude-fable-5-1": "claude-fable-5-1", // 官方模型
|
||||
"claude-fable-5": "claude-fable-5", // 官方模型
|
||||
"claude-opus-5-5": "claude-opus-5-5-high", // 简称映射
|
||||
"claude-opus-5-5-high": "claude-opus-5-5-high", // 官方模型
|
||||
"claude-opus-5-5-medium": "claude-opus-5-5-medium", // 官方模型
|
||||
"claude-opus-5-5-low": "claude-opus-5-5-low", // 官方模型
|
||||
"claude-sonnet-5-5": "claude-sonnet-5-5-high", // 简称映射
|
||||
"claude-sonnet-5-5-high": "claude-sonnet-5-5-high", // 官方模型
|
||||
"claude-sonnet-5-5-medium": "claude-sonnet-5-5-medium", // 官方模型
|
||||
"claude-sonnet-5-5-low": "claude-sonnet-5-5-low", // 官方模型
|
||||
"claude-opus-4-8": "claude-opus-4-8", // 官方模型
|
||||
"claude-opus-4-7": "claude-opus-4-7", // 官方模型
|
||||
"claude-opus-4-6-thinking": "claude-opus-4-6-thinking", // 官方模型
|
||||
@@ -170,6 +178,11 @@ var DefaultAntigravityModelMapping = map[string]string{
|
||||
"gemini-3.8-flash-low": "gemini-3.8-flash-low",
|
||||
"gemini-3.8-flash-medium": "gemini-3.8-flash-medium",
|
||||
"gemini-3.8-flash-tiered": "gemini-3.8-flash-tiered",
|
||||
// Gemini 4 Argon tiered models
|
||||
"gemini-4-argon": "gemini-4-argon-high",
|
||||
"gemini-4-argon-high": "gemini-4-argon-high",
|
||||
"gemini-4-argon-low": "gemini-4-argon-low",
|
||||
"gemini-4-argon-medium": "gemini-4-argon-medium",
|
||||
// Gemini 3 image 兼容映射(向 3.1 image 迁移)
|
||||
"gemini-3-pro-image": "gemini-3.1-flash-image",
|
||||
"gemini-3-pro-image-preview": "gemini-3.1-flash-image",
|
||||
|
||||
@@ -105,6 +105,28 @@ func TestDefaultAntigravityModelMapping_Gemini38FlashModels(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestDefaultAntigravityModelMapping_Gemini4ArgonAndClaude55Models(t *testing.T) {
|
||||
cases := map[string]string{
|
||||
"gemini-4-argon": "gemini-4-argon-high",
|
||||
"gemini-4-argon-high": "gemini-4-argon-high",
|
||||
"gemini-4-argon-low": "gemini-4-argon-low",
|
||||
"gemini-4-argon-medium": "gemini-4-argon-medium",
|
||||
"claude-opus-5-5": "claude-opus-5-5-high",
|
||||
"claude-opus-5-5-high": "claude-opus-5-5-high",
|
||||
"claude-opus-5-5-low": "claude-opus-5-5-low",
|
||||
"claude-opus-5-5-medium": "claude-opus-5-5-medium",
|
||||
"claude-sonnet-5-5": "claude-sonnet-5-5-high",
|
||||
"claude-sonnet-5-5-high": "claude-sonnet-5-5-high",
|
||||
"claude-sonnet-5-5-low": "claude-sonnet-5-5-low",
|
||||
"claude-sonnet-5-5-medium": "claude-sonnet-5-5-medium",
|
||||
}
|
||||
for from, want := range cases {
|
||||
if got := DefaultAntigravityModelMapping[from]; got != want {
|
||||
t.Fatalf("expected %s to map to %q, got %q", from, want, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDefaultBedrockModelMapping_ContainsNewClaudeModels(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
|
||||
@@ -908,14 +908,16 @@ func buildCodexAgentIdentityKeys(accountID string) []string {
|
||||
return []string{"account:" + accountID}
|
||||
}
|
||||
|
||||
// buildCodexStoredIdentityKeys 生成存量账号索引键,保留 user/account 维度,
|
||||
// 让 accessToken-only 账号后续升级为完整 OAuth 时仍能命中并更新原账号。
|
||||
// buildCodexStoredIdentityKeys 生成存量账号索引键,按 workspace/account
|
||||
// 和 user 组合隔离身份,避免同一用户在不同 workspace 的账号误合并。
|
||||
func buildCodexStoredIdentityKeys(accountID, userID, email, accessToken string) []string {
|
||||
keys := make([]string, 0, 3)
|
||||
accountID = strings.TrimSpace(accountID)
|
||||
userID = strings.TrimSpace(userID)
|
||||
accessToken = strings.TrimSpace(accessToken)
|
||||
if userID != "" {
|
||||
if accountID != "" && userID != "" {
|
||||
keys = append(keys, "account_user:"+codexCompositeIdentityKey(accountID, userID))
|
||||
} else if userID != "" {
|
||||
keys = append(keys, "user:"+userID)
|
||||
}
|
||||
if accountID == "" && userID == "" {
|
||||
@@ -932,6 +934,10 @@ func buildCodexStoredIdentityKeys(accountID, userID, email, accessToken string)
|
||||
return keys
|
||||
}
|
||||
|
||||
func codexCompositeIdentityKey(accountID, userID string) string {
|
||||
return fmt.Sprintf("%d:%s%d:%s", len(accountID), accountID, len(userID), userID)
|
||||
}
|
||||
|
||||
func buildCodexAccountIndex(accounts []service.Account) *codexAccountIndex {
|
||||
index := &codexAccountIndex{
|
||||
accountsByKey: map[string][]service.Account{},
|
||||
|
||||
@@ -303,8 +303,8 @@ func TestResolveCodexImportExpiryForNoRefreshTokenUsesEarlierRequestExpiry(t *te
|
||||
|
||||
func TestCodexIdentityKeysPreferStrongIdentifiers(t *testing.T) {
|
||||
keys := buildCodexImportIdentityKeys("acct-1", "user-1", "same@example.com", "token", "refresh")
|
||||
if len(keys) == 0 || keys[0] != "user:user-1" {
|
||||
t.Fatalf("user key should have highest priority when refresh token exists: %v", keys)
|
||||
if len(keys) == 0 || keys[0] != "account_user:6:acct-16:user-1" {
|
||||
t.Fatalf("workspace-scoped user key should have highest priority when refresh token exists: %v", keys)
|
||||
}
|
||||
if keys[len(keys)-1] != "account:acct-1" {
|
||||
t.Fatalf("shared account key should be the last fallback: %v", keys)
|
||||
@@ -465,12 +465,84 @@ func TestCodexAccountIndexKeepsAllCandidatesForSharedAccountKey(t *testing.T) {
|
||||
if got == nil || got.ID != member.ID {
|
||||
t.Fatalf("Find by user key = %v, want member account ID %d", got, member.ID)
|
||||
}
|
||||
if matchedKey != "user:user-2" {
|
||||
t.Fatalf("matched key = %q, want user:user-2", matchedKey)
|
||||
if matchedKey != "account_user:6:team-16:user-2" {
|
||||
t.Fatalf("matched key = %q, want account_user:6:team-16:user-2", matchedKey)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestImportCodexSessionsSameUserDifferentWorkspacesCreatesSeparateAccounts(t *testing.T) {
|
||||
svc := newCodexImportMemoryAdminService(nil)
|
||||
handler := NewAccountHandler(svc, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
|
||||
req := CodexSessionImportRequest{SkipDefaultGroupBind: boolPtr(true)}
|
||||
entries := []codexImportEntry{
|
||||
{Index: 1, Value: buildCodexRefreshImportValue(t, "workspace-1", "shared-user", "refresh-1")},
|
||||
{Index: 2, Value: buildCodexRefreshImportValue(t, "workspace-2", "shared-user", "refresh-2")},
|
||||
}
|
||||
|
||||
result, err := handler.importCodexSessions(context.Background(), req, entries)
|
||||
if err != nil {
|
||||
t.Fatalf("importCodexSessions error = %v", err)
|
||||
}
|
||||
if result.Created != 2 || result.Updated != 0 || result.Skipped != 0 || result.Failed != 0 {
|
||||
t.Fatalf("result = %+v, want two created accounts", result)
|
||||
}
|
||||
if len(svc.createdAccounts) != 2 {
|
||||
t.Fatalf("created accounts = %d, want 2", len(svc.createdAccounts))
|
||||
}
|
||||
if got := svc.createdAccounts[0].Credentials["chatgpt_account_id"]; got != "workspace-1" {
|
||||
t.Fatalf("first workspace = %v, want workspace-1", got)
|
||||
}
|
||||
if got := svc.createdAccounts[1].Credentials["chatgpt_account_id"]; got != "workspace-2" {
|
||||
t.Fatalf("second workspace = %v, want workspace-2", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCodexImportIdentityKeySeparatesDelimiterValues(t *testing.T) {
|
||||
left := buildCodexImportIdentityKeys("ab:c", "shared-user", "", "", "refresh")
|
||||
right := buildCodexImportIdentityKeys("ab", "c:shared-user", "", "", "refresh")
|
||||
if left[0] == right[0] {
|
||||
t.Fatalf("composite identity keys collided: %q", left[0])
|
||||
}
|
||||
}
|
||||
|
||||
func TestImportCodexSessionsSameWorkspaceAccountUpdatesAndDifferentUserIsolated(t *testing.T) {
|
||||
svc := newCodexImportMemoryAdminService(nil)
|
||||
handler := NewAccountHandler(svc, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
|
||||
req := CodexSessionImportRequest{SkipDefaultGroupBind: boolPtr(true)}
|
||||
initialEntries := []codexImportEntry{
|
||||
{Index: 1, Value: buildCodexRefreshImportValue(t, "workspace-1", "user-1", "refresh-1")},
|
||||
{Index: 2, Value: buildCodexRefreshImportValue(t, "workspace-1", "user-2", "refresh-2")},
|
||||
}
|
||||
|
||||
initialResult, err := handler.importCodexSessions(context.Background(), req, initialEntries)
|
||||
if err != nil {
|
||||
t.Fatalf("importCodexSessions error = %v", err)
|
||||
}
|
||||
if initialResult.Created != 2 || initialResult.Updated != 0 || initialResult.Skipped != 0 || initialResult.Failed != 0 {
|
||||
t.Fatalf("initial result = %+v, want two created accounts", initialResult)
|
||||
}
|
||||
|
||||
updateResult, err := handler.importCodexSessions(context.Background(), req, []codexImportEntry{
|
||||
{Index: 3, Value: buildCodexRefreshImportValue(t, "workspace-1", "user-1", "refresh-3")},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("importCodexSessions update error = %v", err)
|
||||
}
|
||||
if updateResult.Created != 0 || updateResult.Updated != 1 || updateResult.Skipped != 0 || updateResult.Failed != 0 {
|
||||
t.Fatalf("update result = %+v, want one updated account", updateResult)
|
||||
}
|
||||
if len(svc.createdAccounts) != 2 || len(svc.updatedAccounts) != 1 {
|
||||
t.Fatalf("created = %d, updated = %d, want 2 and 1", len(svc.createdAccounts), len(svc.updatedAccounts))
|
||||
}
|
||||
if svc.updatedAccounts[0].id != 100 {
|
||||
t.Fatalf("updated account ID = %d, want user-1 account ID 100", svc.updatedAccounts[0].id)
|
||||
}
|
||||
if got := svc.updatedAccounts[0].input.Credentials["chatgpt_user_id"]; got != "user-1" {
|
||||
t.Fatalf("updated user = %v, want user-1", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCodexAccountIndexUpsertReplacesSameAccount(t *testing.T) {
|
||||
legacy := service.Account{
|
||||
ID: 40,
|
||||
|
||||
@@ -3004,13 +3004,13 @@ func antigravityAccountTestModels(rawMapping any) []antigravity.ClaudeModel {
|
||||
switch mapping := rawMapping.(type) {
|
||||
case map[string]any:
|
||||
for id := range mapping {
|
||||
if strings.TrimSpace(id) != "" {
|
||||
if strings.TrimSpace(id) != "" && !strings.Contains(id, "*") {
|
||||
mappedIDs = append(mappedIDs, id)
|
||||
}
|
||||
}
|
||||
case map[string]string:
|
||||
for id := range mapping {
|
||||
if strings.TrimSpace(id) != "" {
|
||||
if strings.TrimSpace(id) != "" && !strings.Contains(id, "*") {
|
||||
mappedIDs = append(mappedIDs, id)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -345,11 +345,12 @@ func TestAccountHandlerGetAvailableModels_Antigravity(t *testing.T) {
|
||||
{name: "empty JSON mapping", credentials: map[string]any{"model_mapping": map[string]any{}}, want: defaults},
|
||||
{name: "empty string mapping", credentials: map[string]any{"model_mapping": map[string]string{}}, want: defaults},
|
||||
{name: "blank key", credentials: map[string]any{"model_mapping": map[string]any{" ": "upstream-model"}}, want: defaults},
|
||||
{name: "JSON mapping keys and metadata", credentials: map[string]any{"model_mapping": map[string]any{
|
||||
known.ID: known.ID, custom.ID: "upstream-model",
|
||||
{name: "wildcard only falls back to defaults", credentials: map[string]any{"model_mapping": map[string]any{"claude-*": "claude-sonnet-4-6", "gemini-3*": "gemini-3-flash"}}, want: defaults},
|
||||
{name: "JSON mapping keys and metadata skips wildcards", credentials: map[string]any{"model_mapping": map[string]any{
|
||||
known.ID: known.ID, custom.ID: "upstream-model", "claude-*": "claude-sonnet-4-6",
|
||||
}}, want: []antigravity.ClaudeModel{custom, known}},
|
||||
{name: "string mapping keys and metadata", credentials: map[string]any{"model_mapping": map[string]string{
|
||||
known.ID: known.ID, custom.ID: "upstream-model",
|
||||
{name: "string mapping keys and metadata skips wildcards", credentials: map[string]any{"model_mapping": map[string]string{
|
||||
known.ID: known.ID, custom.ID: "upstream-model", "gemini-*": "gemini-3-flash",
|
||||
}}, want: []antigravity.ClaudeModel{custom, known}},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
)
|
||||
|
||||
// service_account 与 apikey 同语义:设了总额度才输出 quota_limit / quota_used。
|
||||
func TestAccountFromServiceShallow_ServiceAccountQuota(t *testing.T) {
|
||||
t.Run("no limit omits quota fields", func(t *testing.T) {
|
||||
out := AccountFromServiceShallow(&service.Account{
|
||||
ID: 1,
|
||||
Platform: service.PlatformGemini,
|
||||
Type: service.AccountTypeServiceAccount,
|
||||
Extra: map[string]any{"quota_used": 12.5},
|
||||
})
|
||||
require.Nil(t, out.QuotaUsed)
|
||||
require.Nil(t, out.QuotaLimit)
|
||||
require.Nil(t, out.QuotaDailyLimit)
|
||||
require.Nil(t, out.QuotaWeeklyLimit)
|
||||
|
||||
payload, err := json.Marshal(out)
|
||||
require.NoError(t, err)
|
||||
var decoded map[string]any
|
||||
require.NoError(t, json.Unmarshal(payload, &decoded))
|
||||
require.NotContains(t, decoded, "quota_used")
|
||||
require.NotContains(t, decoded, "quota_limit")
|
||||
})
|
||||
|
||||
t.Run("with limits outputs limits and usage", func(t *testing.T) {
|
||||
out := AccountFromServiceShallow(&service.Account{
|
||||
ID: 3,
|
||||
Platform: service.PlatformGemini,
|
||||
Type: service.AccountTypeServiceAccount,
|
||||
Extra: map[string]any{
|
||||
"quota_used": 30.0,
|
||||
"quota_limit": 100.0,
|
||||
"quota_daily_limit": 10.0,
|
||||
},
|
||||
})
|
||||
require.NotNil(t, out.QuotaLimit)
|
||||
require.InDelta(t, 100.0, *out.QuotaLimit, 1e-9)
|
||||
require.NotNil(t, out.QuotaUsed)
|
||||
require.InDelta(t, 30.0, *out.QuotaUsed, 1e-9)
|
||||
require.NotNil(t, out.QuotaDailyLimit)
|
||||
require.NotNil(t, out.QuotaDailyUsed)
|
||||
})
|
||||
|
||||
t.Run("lite list item keeps quota fields", func(t *testing.T) {
|
||||
item := AccountListItemFromAccount(AccountFromServiceShallow(&service.Account{
|
||||
ID: 4,
|
||||
Platform: service.PlatformGemini,
|
||||
Type: service.AccountTypeServiceAccount,
|
||||
Extra: map[string]any{"quota_used": 7.25, "quota_limit": 290.0},
|
||||
}))
|
||||
payload, err := json.Marshal(item)
|
||||
require.NoError(t, err)
|
||||
var decoded map[string]any
|
||||
require.NoError(t, json.Unmarshal(payload, &decoded))
|
||||
require.InDelta(t, 7.25, decoded["quota_used"], 1e-9)
|
||||
require.InDelta(t, 290.0, decoded["quota_limit"], 1e-9)
|
||||
})
|
||||
}
|
||||
|
||||
// apikey 维持原语义:未设总额度时不输出 quota_used。
|
||||
func TestAccountFromServiceShallow_APIKeyWithoutLimitOmitsQuotaUsed(t *testing.T) {
|
||||
out := AccountFromServiceShallow(&service.Account{
|
||||
ID: 5,
|
||||
Type: service.AccountTypeAPIKey,
|
||||
Extra: map[string]any{"quota_used": 5.0},
|
||||
})
|
||||
require.Nil(t, out.QuotaUsed)
|
||||
require.Nil(t, out.QuotaLimit)
|
||||
}
|
||||
@@ -341,8 +341,8 @@ func AccountFromServiceShallow(a *service.Account) *Account {
|
||||
}
|
||||
}
|
||||
|
||||
// 提取账号配额限制(apikey / bedrock 类型有效)
|
||||
if a.IsAPIKeyOrBedrock() {
|
||||
// 提取账号配额限制(apikey / bedrock / service_account 类型有效)
|
||||
if a.SupportsAccountQuota() {
|
||||
if limit := a.GetQuotaLimit(); limit > 0 {
|
||||
out.QuotaLimit = &limit
|
||||
used := a.GetQuotaUsed()
|
||||
|
||||
@@ -0,0 +1,229 @@
|
||||
//go:build unit
|
||||
|
||||
package handler
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/tlsfingerprint"
|
||||
middleware "github.com/Wei-Shaw/sub2api/internal/server/middleware"
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
type compatStreamUsageUpstream struct {
|
||||
service.HTTPUpstream
|
||||
response *http.Response
|
||||
calls int
|
||||
}
|
||||
|
||||
func (u *compatStreamUsageUpstream) DoWithTLS(*http.Request, string, int64, int, *tlsfingerprint.Profile) (*http.Response, error) {
|
||||
u.calls++
|
||||
return u.response, nil
|
||||
}
|
||||
|
||||
type compatStreamUsageBillingRepo struct {
|
||||
service.UsageBillingRepository
|
||||
mu sync.Mutex
|
||||
commands []*service.UsageBillingCommand
|
||||
}
|
||||
|
||||
func (r *compatStreamUsageBillingRepo) Apply(ctx context.Context, cmd *service.UsageBillingCommand) (*service.UsageBillingApplyResult, error) {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
r.commands = append(r.commands, cmd)
|
||||
return &service.UsageBillingApplyResult{Applied: true}, nil
|
||||
}
|
||||
|
||||
const compatStreamUsagePartialStream = "event: message_start\n" +
|
||||
`data: {"type":"message_start","message":{"id":"msg_1","type":"message","role":"assistant","content":[],"model":"claude-sonnet-4.5","usage":{"input_tokens":12,"output_tokens":1}}}` + "\n\n" +
|
||||
"event: content_block_start\n" +
|
||||
`data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}` + "\n\n" +
|
||||
"event: content_block_delta\n" +
|
||||
`data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"partial"}}` + "\n\n"
|
||||
|
||||
const compatStreamUsageCompletion = "event: content_block_stop\n" +
|
||||
`data: {"type":"content_block_stop","index":0}` + "\n\n" +
|
||||
"event: message_delta\n" +
|
||||
`data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":7}}` + "\n\n" +
|
||||
"event: message_stop\n" +
|
||||
`data: {"type":"message_stop"}` + "\n\n"
|
||||
|
||||
type compatStreamUsageRun struct {
|
||||
rec *httptest.ResponseRecorder
|
||||
upstream *compatStreamUsageUpstream
|
||||
usageRepo *openAIWSUsageHandlerUsageLogRepoStub
|
||||
billingRepo *compatStreamUsageBillingRepo
|
||||
}
|
||||
|
||||
// runCompatStreamUsageHandler 经 GatewayHandler 转发一次流式请求;上游写完 upstreamStream 后,
|
||||
// closeUpstream 为 false 时保持连接不再发送数据。
|
||||
func runCompatStreamUsageHandler(t *testing.T, endpoint, upstreamStream string, closeUpstream bool) compatStreamUsageRun {
|
||||
t.Helper()
|
||||
cfg := &config.Config{Gateway: config.GatewayConfig{StreamDataIntervalTimeout: 1}}
|
||||
groupID := int64(9300)
|
||||
group := &service.Group{ID: groupID, Hydrated: true, Platform: service.PlatformAnthropic, Status: service.StatusActive, RateMultiplier: 1}
|
||||
account := &service.Account{
|
||||
ID: 9301, Platform: service.PlatformAnthropic, Type: service.AccountTypeAPIKey,
|
||||
Status: service.StatusActive, Schedulable: true, Concurrency: 1,
|
||||
Credentials: map[string]any{"api_key": "test-key"},
|
||||
AccountGroups: []service.AccountGroup{{AccountID: 9301, GroupID: groupID}},
|
||||
}
|
||||
snapshot := service.NewSchedulerSnapshotService(&fakeSchedulerCache{accounts: []*service.Account{account}}, nil, nil, nil, nil)
|
||||
run := compatStreamUsageRun{
|
||||
rec: httptest.NewRecorder(),
|
||||
usageRepo: &openAIWSUsageHandlerUsageLogRepoStub{created: make(chan *service.UsageLog, 2)},
|
||||
billingRepo: &compatStreamUsageBillingRepo{},
|
||||
}
|
||||
billingCache := service.NewBillingCacheService(newHandlerInflightCache(100), nil, nil, nil, nil, nil, cfg, nil)
|
||||
t.Cleanup(billingCache.Stop)
|
||||
|
||||
pr, pw := io.Pipe()
|
||||
t.Cleanup(func() { _ = pr.Close(); _ = pw.Close() })
|
||||
go func() {
|
||||
_, _ = io.WriteString(pw, upstreamStream)
|
||||
if closeUpstream {
|
||||
_ = pw.Close()
|
||||
}
|
||||
}()
|
||||
run.upstream = &compatStreamUsageUpstream{response: &http.Response{
|
||||
StatusCode: http.StatusOK, Body: pr,
|
||||
Header: http.Header{"X-Request-Id": []string{"compat-stream-usage"}},
|
||||
}}
|
||||
gw := service.NewGatewayService(
|
||||
nil, &fakeGroupRepo{group: group}, run.usageRepo, run.billingRepo, nil, nil, nil, nil, cfg,
|
||||
snapshot, nil, service.NewBillingService(cfg, nil), nil, nil, nil, run.upstream,
|
||||
&service.DeferredService{}, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil,
|
||||
)
|
||||
h := &GatewayHandler{
|
||||
gatewayService: gw, billingCacheService: billingCache, cfg: cfg, maxAccountSwitches: 1,
|
||||
concurrencyHelper: NewConcurrencyHelper(service.NewConcurrencyService(&fakeConcurrencyCache{}), SSEPingFormatClaude, 0),
|
||||
}
|
||||
|
||||
body := `{"model":"claude-sonnet-4.5","stream":true,"input":"hello"}`
|
||||
if endpoint == "chat/completions" {
|
||||
body = `{"model":"claude-sonnet-4.5","stream":true,"messages":[{"role":"user","content":"hello"}]}`
|
||||
}
|
||||
c, _ := gin.CreateTestContext(run.rec)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/v1/"+endpoint, bytes.NewBufferString(body))
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
apiKey := &service.APIKey{ID: 9302, UserID: 9303, GroupID: &groupID, Group: group, User: &service.User{ID: 9303, Balance: 100}}
|
||||
c.Set(string(middleware.ContextKeyAPIKey), apiKey)
|
||||
c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: 9303})
|
||||
|
||||
if endpoint == "chat/completions" {
|
||||
h.ChatCompletions(c)
|
||||
} else {
|
||||
h.Responses(c)
|
||||
}
|
||||
return run
|
||||
}
|
||||
|
||||
// compatStreamUsageMarkers 返回成功收尾与终止错误的标记。
|
||||
func compatStreamUsageMarkers(endpoint string) (success, failure string) {
|
||||
if endpoint == "responses" {
|
||||
return "event: response.completed", "event: response.failed"
|
||||
}
|
||||
return "[DONE]", `data: {"error":`
|
||||
}
|
||||
|
||||
func TestGatewayCompatibilityHandlers_StreamUsageRecordedOnceWithTerminalEvent(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
for _, endpoint := range []string{"chat/completions", "responses"} {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
completion string
|
||||
wantOutput int
|
||||
}{
|
||||
{name: "complete", completion: compatStreamUsageCompletion, wantOutput: 7},
|
||||
{name: "idle_before_message_stop", wantOutput: 1},
|
||||
} {
|
||||
t.Run(endpoint+"/"+tc.name, func(t *testing.T) {
|
||||
successMarker, failureMarker := compatStreamUsageMarkers(endpoint)
|
||||
wantMarker, denyMarker := successMarker, failureMarker
|
||||
if tc.completion == "" {
|
||||
wantMarker, denyMarker = failureMarker, successMarker
|
||||
}
|
||||
|
||||
run := runCompatStreamUsageHandler(t, endpoint, compatStreamUsagePartialStream+tc.completion, tc.completion != "")
|
||||
|
||||
require.Equal(t, 1, run.upstream.calls)
|
||||
out := run.rec.Body.String()
|
||||
require.Contains(t, out, "partial")
|
||||
require.Contains(t, out, wantMarker)
|
||||
require.NotContains(t, out, denyMarker)
|
||||
require.Equal(t, 1, strings.Count(out, wantMarker), "exactly one terminal event")
|
||||
require.NotContains(t, out, `data: {"type":"error"`, "the handler must not append a fallback frame")
|
||||
if tc.completion == "" {
|
||||
require.Contains(t, out, "stream_timeout")
|
||||
}
|
||||
|
||||
run.billingRepo.mu.Lock()
|
||||
defer run.billingRepo.mu.Unlock()
|
||||
require.Len(t, run.billingRepo.commands, 1, "usage must be settled exactly once")
|
||||
require.Equal(t, 12, run.billingRepo.commands[0].InputTokens)
|
||||
require.Equal(t, tc.wantOutput, run.billingRepo.commands[0].OutputTokens)
|
||||
require.Len(t, run.usageRepo.created, 1)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestGatewayCompatibilityHandlers_IdleBeforeAnyEventWritesStreamError(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
for _, endpoint := range []string{"chat/completions", "responses"} {
|
||||
t.Run(endpoint, func(t *testing.T) {
|
||||
successMarker, failureMarker := compatStreamUsageMarkers(endpoint)
|
||||
|
||||
run := runCompatStreamUsageHandler(t, endpoint, "", false)
|
||||
|
||||
require.Equal(t, 1, run.upstream.calls)
|
||||
require.Equal(t, http.StatusOK, run.rec.Code)
|
||||
require.Equal(t, "text/event-stream", run.rec.Header().Get("Content-Type"))
|
||||
out := run.rec.Body.String()
|
||||
require.Equal(t, 1, strings.Count(out, failureMarker), "exactly one terminal event")
|
||||
require.NotContains(t, out, `data: {"type":"error"`, "the handler must not append a fallback frame")
|
||||
require.Contains(t, out, "stream_timeout")
|
||||
require.NotContains(t, out, successMarker)
|
||||
|
||||
run.billingRepo.mu.Lock()
|
||||
defer run.billingRepo.mu.Unlock()
|
||||
require.Empty(t, run.billingRepo.commands, "no usage was observed")
|
||||
require.Empty(t, run.usageRepo.created)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGatewayCompatibilityHandlers_UpstreamErrorEventAfterOutputIsNotBilled(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
upstreamError := "event: error\n" + `data: {"type":"error","error":{"type":"overloaded_error","message":"Overloaded"}}` + "\n\n"
|
||||
for _, endpoint := range []string{"chat/completions", "responses"} {
|
||||
t.Run(endpoint, func(t *testing.T) {
|
||||
successMarker, failureMarker := compatStreamUsageMarkers(endpoint)
|
||||
|
||||
run := runCompatStreamUsageHandler(t, endpoint, compatStreamUsagePartialStream+upstreamError, true)
|
||||
|
||||
require.Equal(t, 1, run.upstream.calls)
|
||||
out := run.rec.Body.String()
|
||||
require.Contains(t, out, "partial")
|
||||
require.Equal(t, 1, strings.Count(out, failureMarker), "exactly one terminal event")
|
||||
require.NotContains(t, out, `data: {"type":"error"`, "the handler must not append a fallback frame")
|
||||
require.Contains(t, out, "Overloaded")
|
||||
require.NotContains(t, out, successMarker)
|
||||
|
||||
run.billingRepo.mu.Lock()
|
||||
defer run.billingRepo.mu.Unlock()
|
||||
require.Empty(t, run.billingRepo.commands, "an upstream error event is not billed while the client is online")
|
||||
require.Empty(t, run.usageRepo.created)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -228,6 +228,10 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
|
||||
if rejectSystemOneOnlyPlatform(c, apiKey, h.errorResponse) {
|
||||
return
|
||||
}
|
||||
if geminiImageGenerationRejected(c, apiKey, nil, reqModel, channelMapping.MappedModel) {
|
||||
h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", service.ImageGenerationPermissionMessage())
|
||||
return
|
||||
}
|
||||
|
||||
if decision := h.checkSecurityAudit(c, reqLog, apiKey, subject, service.ContentModerationProtocolAnthropicMessages, reqModel, body); decision != nil && !decision.AllowNextStage {
|
||||
h.anthropicSecurityAuditError(c, decision)
|
||||
@@ -339,12 +343,9 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
|
||||
if platform == service.PlatformGemini {
|
||||
fs := NewFailoverState(h.maxAccountSwitchesGemini, hasBoundSession)
|
||||
|
||||
// 单账号分组提前设置 SingleAccountRetry 标记,让 Service 层首次 503 就不设模型限流标记。
|
||||
// 避免单账号分组收到 503 (MODEL_CAPACITY_EXHAUSTED) 时设 29s 限流,导致后续请求连续快速失败。
|
||||
if h.gatewayService.IsSingleAntigravityAccountGroup(c.Request.Context(), apiKey.GroupID) {
|
||||
ctx := service.WithSingleAccountRetry(c.Request.Context(), true, h.metadataBridgeEnabled())
|
||||
c.Request = c.Request.WithContext(ctx)
|
||||
}
|
||||
// 单账号分组首次 503 就不设模型限流标记,避免设 29s 限流导致后续请求连续快速失败;
|
||||
// 是否单账号分组在 antigravity 账号遇到 503 或模型限流预检查时才判定。
|
||||
c.Request = c.Request.WithContext(h.gatewayService.WithSingleAntigravityAccountGroupProbe(c.Request.Context(), apiKey.GroupID))
|
||||
|
||||
for {
|
||||
selection, err := h.gatewayService.SelectAccountWithLoadAwareness(c.Request.Context(), apiKey.GroupID, sessionKey, reqModel, fs.FailedAccountIDs, "", int64(0)) // Gemini 不使用会话限制
|
||||
@@ -639,12 +640,9 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
|
||||
}
|
||||
fallbackUsed := false
|
||||
|
||||
// 单账号分组提前设置 SingleAccountRetry 标记,让 Service 层首次 503 就不设模型限流标记。
|
||||
// 避免单账号分组收到 503 (MODEL_CAPACITY_EXHAUSTED) 时设 29s 限流,导致后续请求连续快速失败。
|
||||
if h.gatewayService.IsSingleAntigravityAccountGroup(c.Request.Context(), currentAPIKey.GroupID) {
|
||||
ctx := service.WithSingleAccountRetry(c.Request.Context(), true, h.metadataBridgeEnabled())
|
||||
c.Request = c.Request.WithContext(ctx)
|
||||
}
|
||||
// 单账号分组首次 503 就不设模型限流标记,避免设 29s 限流导致后续请求连续快速失败;
|
||||
// 是否单账号分组在 antigravity 账号遇到 503 或模型限流预检查时才判定。
|
||||
c.Request = c.Request.WithContext(h.gatewayService.WithSingleAntigravityAccountGroupProbe(c.Request.Context(), currentAPIKey.GroupID))
|
||||
|
||||
// 会话槽失败释放:failover 链上每个选中的 Anthropic OAuth 账号都注册过同一会话
|
||||
// (checkAndRegisterSession)。若请求最终失败(转发失败/客户端中断/换号耗尽),
|
||||
@@ -1193,7 +1191,7 @@ func (h *GatewayHandler) Models(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
if len(availableModels) > 0 {
|
||||
if len(availableModels) > 0 || (platform == service.PlatformOpenAI && availableModels != nil) {
|
||||
writeModelsList(c, platform, availableModels)
|
||||
return
|
||||
}
|
||||
@@ -1308,7 +1306,7 @@ func (h *GatewayHandler) compositeAvailableModels(ctx context.Context, groupID *
|
||||
continue
|
||||
}
|
||||
platformModels := h.gatewayService.GetAvailableModels(ctx, groupID, platform)
|
||||
if len(platformModels) == 0 {
|
||||
if len(platformModels) == 0 && (platform != service.PlatformOpenAI || platformModels == nil) {
|
||||
// CN 供应商没有静态默认模型列表(defaultModelIDsForPlatform 的
|
||||
// default 分支是 Claude 列表),composite 下只暴露账号映射键。
|
||||
if _, ok := schedulablePlatforms[platform]; ok && !service.IsMultiProtocolAPIKeyProvider(platform) {
|
||||
@@ -1457,6 +1455,9 @@ func writeOpenAIModelsList(c *gin.Context, modelIDs []string) {
|
||||
// 与平台默认列表(fallbackModels)。账号映射为空时回落默认列表;Anthropic
|
||||
// 平台两者取并集,其余平台以账号映射键为准。
|
||||
func modelListingSource(platform string, availableModels, fallbackModels []string) []string {
|
||||
if platform == service.PlatformOpenAI && availableModels != nil {
|
||||
return availableModels
|
||||
}
|
||||
if len(availableModels) == 0 {
|
||||
return fallbackModels
|
||||
}
|
||||
|
||||
@@ -113,6 +113,10 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) {
|
||||
"This group is restricted to Claude Code clients (/v1/messages only)")
|
||||
return
|
||||
}
|
||||
if geminiImageGenerationRejected(c, apiKey, nil, reqModel, channelMapping.MappedModel) {
|
||||
h.chatCompletionsErrorResponse(c, http.StatusBadRequest, "invalid_request_error", service.ImageGenerationPermissionMessage())
|
||||
return
|
||||
}
|
||||
|
||||
if decision := h.checkSecurityAudit(c, reqLog, apiKey, subject, service.ContentModerationProtocolOpenAIChat, reqModel, body); decision != nil && !decision.AllowNextStage {
|
||||
h.openAISecurityAuditError(c, decision)
|
||||
@@ -317,6 +321,44 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) {
|
||||
accountReleaseFunc()
|
||||
}
|
||||
|
||||
// 提交 usage 记录。成功路径与"流中断但 Forward 已观测到 usage 的部分结果"
|
||||
// 错误路径共用;failover 错误恒定 result=nil,不会重复计费。
|
||||
submitForwardUsage := func(result *service.ForwardResult) {
|
||||
userAgent := c.GetHeader("User-Agent")
|
||||
clientIP := ip.GetClientIP(c)
|
||||
requestPayloadHash := service.HashUsageRequestPayload(body)
|
||||
inboundEndpoint := GetInboundEndpoint(c)
|
||||
upstreamEndpoint := GetUpstreamEndpoint(c, account.Platform)
|
||||
|
||||
quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey)
|
||||
sessionID := service.ExtractClientSessionID(c)
|
||||
stampForwardRequestedReasoningEffort(result, service.RequestedReasoningEffortFromContext(c.Request.Context()))
|
||||
h.submitUsageRecordTask(c.Request.Context(), func(ctx context.Context) {
|
||||
if err := h.gatewayService.RecordUsage(ctx, &service.RecordUsageInput{
|
||||
Result: result,
|
||||
QuotaPlatform: quotaPlatform,
|
||||
APIKey: apiKey,
|
||||
User: apiKey.User,
|
||||
Account: account,
|
||||
Subscription: subscription,
|
||||
PricingAt: pricingAt,
|
||||
InboundEndpoint: inboundEndpoint,
|
||||
UpstreamEndpoint: upstreamEndpoint,
|
||||
UserAgent: userAgent,
|
||||
IPAddress: clientIP,
|
||||
RequestPayloadHash: requestPayloadHash,
|
||||
APIKeyService: h.apiKeyService,
|
||||
SessionID: sessionID,
|
||||
ChannelUsageFields: clientRequestedUsageFields(c, channelMapping, reqModel, result.UpstreamModel),
|
||||
}); err != nil {
|
||||
reqLog.Error("gateway.cc.record_usage_failed",
|
||||
zap.Int64("account_id", account.ID),
|
||||
zap.Error(err),
|
||||
)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
var failoverErr *service.UpstreamFailoverError
|
||||
if errors.As(err, &failoverErr) {
|
||||
@@ -347,43 +389,14 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) {
|
||||
zap.Bool("upstream_error_response_already_written", upstreamErrorAlreadyCommunicated),
|
||||
zap.Error(err),
|
||||
)
|
||||
if result != nil {
|
||||
submitForwardUsage(result)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// 6. Record usage
|
||||
userAgent := c.GetHeader("User-Agent")
|
||||
clientIP := ip.GetClientIP(c)
|
||||
requestPayloadHash := service.HashUsageRequestPayload(body)
|
||||
inboundEndpoint := GetInboundEndpoint(c)
|
||||
upstreamEndpoint := GetUpstreamEndpoint(c, account.Platform)
|
||||
|
||||
quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey)
|
||||
sessionID := service.ExtractClientSessionID(c)
|
||||
stampForwardRequestedReasoningEffort(result, service.RequestedReasoningEffortFromContext(c.Request.Context()))
|
||||
h.submitUsageRecordTask(c.Request.Context(), func(ctx context.Context) {
|
||||
if err := h.gatewayService.RecordUsage(ctx, &service.RecordUsageInput{
|
||||
Result: result,
|
||||
QuotaPlatform: quotaPlatform,
|
||||
APIKey: apiKey,
|
||||
User: apiKey.User,
|
||||
Account: account,
|
||||
Subscription: subscription,
|
||||
PricingAt: pricingAt,
|
||||
InboundEndpoint: inboundEndpoint,
|
||||
UpstreamEndpoint: upstreamEndpoint,
|
||||
UserAgent: userAgent,
|
||||
IPAddress: clientIP,
|
||||
RequestPayloadHash: requestPayloadHash,
|
||||
APIKeyService: h.apiKeyService,
|
||||
SessionID: sessionID,
|
||||
ChannelUsageFields: clientRequestedUsageFields(c, channelMapping, reqModel, result.UpstreamModel),
|
||||
}); err != nil {
|
||||
reqLog.Error("gateway.cc.record_usage_failed",
|
||||
zap.Int64("account_id", account.ID),
|
||||
zap.Error(err),
|
||||
)
|
||||
}
|
||||
})
|
||||
submitForwardUsage(result)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
@@ -117,6 +117,10 @@ func (h *GatewayHandler) Responses(c *gin.Context) {
|
||||
"This group is restricted to Claude Code clients (/v1/messages only)")
|
||||
return
|
||||
}
|
||||
if geminiImageGenerationRejected(c, apiKey, nil, reqModel, channelMapping.MappedModel) {
|
||||
h.responsesErrorResponse(c, http.StatusBadRequest, "invalid_request_error", service.ImageGenerationPermissionMessage())
|
||||
return
|
||||
}
|
||||
|
||||
if decision := h.checkSecurityAudit(c, reqLog, apiKey, subject, service.ContentModerationProtocolOpenAIResponses, reqModel, body); decision != nil && !decision.AllowNextStage {
|
||||
h.responsesSecurityAuditError(c, decision)
|
||||
@@ -299,6 +303,44 @@ func (h *GatewayHandler) Responses(c *gin.Context) {
|
||||
accountReleaseFunc()
|
||||
}
|
||||
|
||||
// 提交 usage 记录。成功路径与"流中断但 Forward 已观测到 usage 的部分结果"
|
||||
// 错误路径共用;failover 错误恒定 result=nil,不会重复计费。
|
||||
submitForwardUsage := func(result *service.ForwardResult) {
|
||||
userAgent := c.GetHeader("User-Agent")
|
||||
clientIP := ip.GetClientIP(c)
|
||||
requestPayloadHash := service.HashUsageRequestPayload(body)
|
||||
inboundEndpoint := GetInboundEndpoint(c)
|
||||
upstreamEndpoint := GetUpstreamEndpoint(c, account.Platform)
|
||||
|
||||
quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey)
|
||||
sessionID := service.ExtractClientSessionID(c)
|
||||
stampForwardRequestedReasoningEffort(result, service.RequestedReasoningEffortFromContext(c.Request.Context()))
|
||||
h.submitUsageRecordTask(c.Request.Context(), func(ctx context.Context) {
|
||||
if err := h.gatewayService.RecordUsage(ctx, &service.RecordUsageInput{
|
||||
Result: result,
|
||||
QuotaPlatform: quotaPlatform,
|
||||
APIKey: apiKey,
|
||||
User: apiKey.User,
|
||||
Account: account,
|
||||
Subscription: subscription,
|
||||
PricingAt: pricingAt,
|
||||
InboundEndpoint: inboundEndpoint,
|
||||
UpstreamEndpoint: upstreamEndpoint,
|
||||
UserAgent: userAgent,
|
||||
IPAddress: clientIP,
|
||||
RequestPayloadHash: requestPayloadHash,
|
||||
APIKeyService: h.apiKeyService,
|
||||
SessionID: sessionID,
|
||||
ChannelUsageFields: clientRequestedUsageFields(c, channelMapping, reqModel, result.UpstreamModel),
|
||||
}); err != nil {
|
||||
reqLog.Error("gateway.responses.record_usage_failed",
|
||||
zap.Int64("account_id", account.ID),
|
||||
zap.Error(err),
|
||||
)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
var failoverErr *service.UpstreamFailoverError
|
||||
if errors.As(err, &failoverErr) {
|
||||
@@ -330,43 +372,14 @@ func (h *GatewayHandler) Responses(c *gin.Context) {
|
||||
zap.Bool("upstream_error_response_already_written", upstreamErrorAlreadyCommunicated),
|
||||
zap.Error(err),
|
||||
)
|
||||
if result != nil {
|
||||
submitForwardUsage(result)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// 6. Record usage
|
||||
userAgent := c.GetHeader("User-Agent")
|
||||
clientIP := ip.GetClientIP(c)
|
||||
requestPayloadHash := service.HashUsageRequestPayload(body)
|
||||
inboundEndpoint := GetInboundEndpoint(c)
|
||||
upstreamEndpoint := GetUpstreamEndpoint(c, account.Platform)
|
||||
|
||||
quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey)
|
||||
sessionID := service.ExtractClientSessionID(c)
|
||||
stampForwardRequestedReasoningEffort(result, service.RequestedReasoningEffortFromContext(c.Request.Context()))
|
||||
h.submitUsageRecordTask(c.Request.Context(), func(ctx context.Context) {
|
||||
if err := h.gatewayService.RecordUsage(ctx, &service.RecordUsageInput{
|
||||
Result: result,
|
||||
QuotaPlatform: quotaPlatform,
|
||||
APIKey: apiKey,
|
||||
User: apiKey.User,
|
||||
Account: account,
|
||||
Subscription: subscription,
|
||||
PricingAt: pricingAt,
|
||||
InboundEndpoint: inboundEndpoint,
|
||||
UpstreamEndpoint: upstreamEndpoint,
|
||||
UserAgent: userAgent,
|
||||
IPAddress: clientIP,
|
||||
RequestPayloadHash: requestPayloadHash,
|
||||
APIKeyService: h.apiKeyService,
|
||||
SessionID: sessionID,
|
||||
ChannelUsageFields: clientRequestedUsageFields(c, channelMapping, reqModel, result.UpstreamModel),
|
||||
}); err != nil {
|
||||
reqLog.Error("gateway.responses.record_usage_failed",
|
||||
zap.Int64("account_id", account.ID),
|
||||
zap.Error(err),
|
||||
)
|
||||
}
|
||||
})
|
||||
submitForwardUsage(result)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
@@ -158,8 +158,12 @@ func (f *fakeConcurrencyCache) CleanupStaleProcessSlots(context.Context, string)
|
||||
|
||||
func newTestGatewayHandler(t *testing.T, group *service.Group, accounts []*service.Account) (*GatewayHandler, func()) {
|
||||
t.Helper()
|
||||
return newTestGatewayHandlerWithSchedulerCache(t, group, &fakeSchedulerCache{accounts: accounts})
|
||||
}
|
||||
|
||||
func newTestGatewayHandlerWithSchedulerCache(t *testing.T, group *service.Group, schedulerCache service.SchedulerCache) (*GatewayHandler, func()) {
|
||||
t.Helper()
|
||||
|
||||
schedulerCache := &fakeSchedulerCache{accounts: accounts}
|
||||
schedulerSnapshot := service.NewSchedulerSnapshotService(schedulerCache, nil, nil, nil, nil)
|
||||
|
||||
gwSvc := service.NewGatewayService(
|
||||
|
||||
@@ -324,6 +324,12 @@ func TestGatewayModels_UnmappedOpenAIAccountsSupplementMappedModels(t *testing.T
|
||||
Credentials: map[string]any{"model_mapping": map[string]any{alias: "gpt-5.6-sol"}},
|
||||
},
|
||||
}
|
||||
subscriptionDefaults := make([]string, 0)
|
||||
for _, model := range openai.DefaultModelIDs() {
|
||||
if model != "gpt-5.5" {
|
||||
subscriptionDefaults = append(subscriptionDefaults, model)
|
||||
}
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
accounts []service.Account
|
||||
@@ -333,7 +339,7 @@ func TestGatewayModels_UnmappedOpenAIAccountsSupplementMappedModels(t *testing.T
|
||||
{
|
||||
name: "unmapped parent and Spark shadow retain defaults and aliases",
|
||||
accounts: accounts,
|
||||
want: append(openai.DefaultModelIDs(), alias),
|
||||
want: append(append([]string{}, subscriptionDefaults...), alias),
|
||||
},
|
||||
{
|
||||
name: "unmapped API key account also contributes defaults",
|
||||
@@ -343,7 +349,7 @@ func TestGatewayModels_UnmappedOpenAIAccountsSupplementMappedModels(t *testing.T
|
||||
{
|
||||
name: "unmapped accounts alone retain default response shape",
|
||||
accounts: accounts[:1],
|
||||
want: openai.DefaultModelIDs(),
|
||||
want: subscriptionDefaults,
|
||||
},
|
||||
{
|
||||
name: "custom list can select defaults and aliases",
|
||||
@@ -372,7 +378,7 @@ func TestGatewayModels_UnmappedOpenAIAccountsSupplementMappedModels(t *testing.T
|
||||
Credentials: map[string]any{"model_mapping": map[string]any{"stale-model": "stale-model"}},
|
||||
Extra: map[string]any{"openai_passthrough": true},
|
||||
}}, accounts[1:]...),
|
||||
want: append(openai.DefaultModelIDs(), alias),
|
||||
want: append(append([]string{}, subscriptionDefaults...), alias),
|
||||
},
|
||||
{
|
||||
name: "unmapped accounts from another platform do not add defaults",
|
||||
@@ -1408,6 +1414,60 @@ func modelIDsForTest(models []gatewayModelItemForTest) []string {
|
||||
return ids
|
||||
}
|
||||
|
||||
func TestGatewayModels_AntigravityExplicitMappingAppearsInBothCatalogs(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
const groupID int64 = 93
|
||||
mapping := map[string]any{
|
||||
"gemini-3.8-flash": "gemini-3.8-flash-high",
|
||||
"gemini-3.8-flash-high": "gemini-3.8-flash-high",
|
||||
"claude-opus-4-6-thinking": "claude-opus-4-6-thinking",
|
||||
"gemini-pro-agent": "gemini-pro-agent",
|
||||
}
|
||||
for _, platform := range []string{service.PlatformAntigravity, service.PlatformComposite, service.PlatformGemini} {
|
||||
t.Run(platform, func(t *testing.T) {
|
||||
h := newGatewayModelsHandlerForTest(&gatewayModelsAccountRepoStub{
|
||||
byGroup: map[int64][]service.Account{groupID: {{
|
||||
ID: 25, Platform: service.PlatformAntigravity,
|
||||
Extra: map[string]any{"mixed_scheduling": true},
|
||||
Credentials: map[string]any{"model_mapping": mapping},
|
||||
}}},
|
||||
})
|
||||
want := []string{"gemini-3.8-flash", "gemini-3.8-flash-high", "gemini-pro-agent", "claude-opus-4-6-thinking"}
|
||||
if platform == service.PlatformGemini {
|
||||
want = want[:3]
|
||||
}
|
||||
for _, codex := range []bool{false, true} {
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
c.Request = httptest.NewRequest(http.MethodGet, "/v1/models", nil)
|
||||
c.Set(string(middleware2.ContextKeyAPIKey), &service.APIKey{
|
||||
Group: &service.Group{ID: groupID, Platform: platform},
|
||||
})
|
||||
var ids []string
|
||||
if codex {
|
||||
h.CodexModels(c)
|
||||
var got codexModelsResponseForTest
|
||||
require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &got))
|
||||
for _, model := range got.Models {
|
||||
ids = append(ids, model.Slug)
|
||||
}
|
||||
} else {
|
||||
h.Models(c)
|
||||
var got gatewayModelsResponseForTest
|
||||
require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &got))
|
||||
ids = modelIDsForTest(got.Data)
|
||||
}
|
||||
require.Equal(t, http.StatusOK, rec.Code)
|
||||
// 显式条目必须同时出现在两种目录;默认透传补齐的条目不锁定。
|
||||
require.Subset(t, ids, want, "codex=%t", codex)
|
||||
if platform == service.PlatformGemini {
|
||||
require.NotContains(t, ids, "claude-opus-4-6-thinking", "codex=%t", codex)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// gemini 分组混合调度:组内 antigravity 账号的 gemini-* 映射也应出现在 /v1/models,
|
||||
// 与路由层(listSchedulableAccountsOnce 的 useMixedScheduling)同源;claude-* 不带入,
|
||||
// 非混合调度的异平台账号(anthropic)仍被过滤。
|
||||
|
||||
@@ -34,11 +34,12 @@ func (u *clientCancelUpstream) Do(req *http.Request, _ string, _ int64, _ int) (
|
||||
}
|
||||
|
||||
type geminiClientCancelFixture struct {
|
||||
handler *GatewayHandler
|
||||
group *service.Group
|
||||
apiKey *service.APIKey
|
||||
upstream *clientCancelUpstream
|
||||
ctx context.Context
|
||||
handler *GatewayHandler
|
||||
group *service.Group
|
||||
apiKey *service.APIKey
|
||||
upstream *clientCancelUpstream
|
||||
schedulerCache *bucketRecordingSchedulerCache
|
||||
ctx context.Context
|
||||
}
|
||||
|
||||
func newGeminiClientCancelFixture(t *testing.T) *geminiClientCancelFixture {
|
||||
@@ -57,7 +58,8 @@ func newGeminiClientCancelFixture(t *testing.T) *geminiClientCancelFixture {
|
||||
Priority: 1,
|
||||
AccountGroups: []service.AccountGroup{{AccountID: accountID, GroupID: groupID}},
|
||||
}
|
||||
h, cleanup := newTestGatewayHandler(t, group, []*service.Account{account})
|
||||
schedulerCache := &bucketRecordingSchedulerCache{fakeSchedulerCache: &fakeSchedulerCache{accounts: []*service.Account{account}}}
|
||||
h, cleanup := newTestGatewayHandlerWithSchedulerCache(t, group, schedulerCache)
|
||||
t.Cleanup(cleanup)
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
@@ -69,7 +71,7 @@ func newGeminiClientCancelFixture(t *testing.T) *geminiClientCancelFixture {
|
||||
ID: 9202, UserID: 9203, GroupID: &groupID, Group: group, Status: service.StatusActive,
|
||||
User: &service.User{ID: 9203, Concurrency: 10, Balance: 100},
|
||||
}
|
||||
return &geminiClientCancelFixture{handler: h, group: group, apiKey: apiKey, upstream: upstream, ctx: ctx}
|
||||
return &geminiClientCancelFixture{handler: h, group: group, apiKey: apiKey, upstream: upstream, schedulerCache: schedulerCache, ctx: ctx}
|
||||
}
|
||||
|
||||
// serve 经 ops 错误日志中间件执行请求,返回响应与 ops 队列中的条目数。
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// geminiImageGenerationRejected 在选号之前按客户端请求名、渠道映射名与请求体
|
||||
// 执行 Gemini 系分组的生图门禁。命中时把请求标记为本地功能门禁并返回 true,
|
||||
// 调用方按入口协议写出 400;账号级模型映射之后的判定由转发层负责。
|
||||
func geminiImageGenerationRejected(c *gin.Context, apiKey *service.APIKey, body []byte, models ...string) bool {
|
||||
if apiKey == nil || !service.GeminiImageGenerationDenied(apiKey.Group, body, models...) {
|
||||
return false
|
||||
}
|
||||
service.MarkOpsClientBusinessLimited(c, service.OpsClientBusinessLimitedReasonLocalFeatureGate)
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
//go:build unit
|
||||
|
||||
package handler
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey"
|
||||
middleware "github.com/Wei-Shaw/sub2api/internal/server/middleware"
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
type geminiImageGateEndpoint struct {
|
||||
name string
|
||||
path string
|
||||
body string
|
||||
params gin.Params
|
||||
forcePlatform string
|
||||
call func(*GatewayHandler, *gin.Context)
|
||||
}
|
||||
|
||||
func geminiImageGateEndpoints(model string) []geminiImageGateEndpoint {
|
||||
return []geminiImageGateEndpoint{
|
||||
{
|
||||
name: "messages", path: "/v1/messages",
|
||||
body: `{"model":"` + model + `","max_tokens":16,"messages":[{"role":"user","content":"draw a cat"}]}`,
|
||||
call: (*GatewayHandler).Messages,
|
||||
},
|
||||
{
|
||||
name: "chat completions", path: "/v1/chat/completions",
|
||||
body: `{"model":"` + model + `","messages":[{"role":"user","content":"draw a cat"}]}`,
|
||||
call: (*GatewayHandler).ChatCompletions,
|
||||
},
|
||||
{
|
||||
name: "responses", path: "/v1/responses",
|
||||
body: `{"model":"` + model + `","input":"draw a cat"}`,
|
||||
call: (*GatewayHandler).Responses,
|
||||
},
|
||||
{
|
||||
name: "gemini native", path: "/v1beta/models/" + model + ":generateContent",
|
||||
body: `{"contents":[{"role":"user","parts":[{"text":"draw a cat"}]}]}`,
|
||||
params: gin.Params{{Key: "modelAction", Value: "/" + model + ":generateContent"}},
|
||||
call: (*GatewayHandler).GeminiV1BetaModels,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func runGeminiImageGateEndpoint(t *testing.T, ep geminiImageGateEndpoint, group *service.Group, accountPlatform string) (*httptest.ResponseRecorder, *gin.Context, *groupScopedSchedulerCache) {
|
||||
t.Helper()
|
||||
const accountID = int64(9411)
|
||||
schedulerCache := &groupScopedSchedulerCache{fakeSchedulerCache: &fakeSchedulerCache{accounts: []*service.Account{{
|
||||
ID: accountID, Platform: accountPlatform, Type: service.AccountTypeAPIKey,
|
||||
Status: service.StatusActive, Schedulable: true, Concurrency: 1,
|
||||
AccountGroups: []service.AccountGroup{{AccountID: accountID, GroupID: group.ID}},
|
||||
}}}}
|
||||
gatewayService := service.NewGatewayService(
|
||||
nil, &groupMapRepo{fakeGroupRepo: &fakeGroupRepo{}, groups: map[int64]*service.Group{group.ID: group}},
|
||||
nil, nil, nil, nil, nil, nil, nil,
|
||||
service.NewSchedulerSnapshotService(schedulerCache, nil, nil, nil, nil),
|
||||
nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil,
|
||||
)
|
||||
cfg := &config.Config{RunMode: config.RunModeSimple}
|
||||
billingCacheService := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil)
|
||||
t.Cleanup(billingCacheService.Stop)
|
||||
h := &GatewayHandler{
|
||||
gatewayService: gatewayService,
|
||||
billingCacheService: billingCacheService,
|
||||
concurrencyHelper: NewConcurrencyHelper(service.NewConcurrencyService(&fakeConcurrencyCache{}), SSEPingFormatClaude, 0),
|
||||
maxAccountSwitches: 1,
|
||||
cfg: cfg,
|
||||
}
|
||||
|
||||
groupID := group.ID
|
||||
apiKey := &service.APIKey{
|
||||
ID: 9420, UserID: 9430, GroupID: &groupID, Group: group, Status: service.StatusActive,
|
||||
User: &service.User{ID: 9430, Concurrency: 10, Balance: 100},
|
||||
}
|
||||
recorder := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(recorder)
|
||||
ctx := context.WithValue(context.Background(), ctxkey.Group, group)
|
||||
req := httptest.NewRequest(http.MethodPost, ep.path, bytes.NewBufferString(ep.body)).WithContext(ctx)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
c.Request = req
|
||||
c.Params = ep.params
|
||||
if ep.forcePlatform != "" {
|
||||
c.Set(string(middleware.ContextKeyForcePlatform), ep.forcePlatform)
|
||||
}
|
||||
c.Set(string(middleware.ContextKeyAPIKey), apiKey)
|
||||
c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: apiKey.UserID, Concurrency: 10})
|
||||
|
||||
ep.call(h, c)
|
||||
return recorder, c, schedulerCache
|
||||
}
|
||||
|
||||
func TestGatewayHandlers_GeminiImageGenerationDisabledGroupRejectsBeforeSelection(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
for _, platform := range []string{service.PlatformGemini, service.PlatformAntigravity} {
|
||||
for _, ep := range geminiImageGateEndpoints("gemini-3-pro-image") {
|
||||
if platform == service.PlatformAntigravity && ep.params != nil {
|
||||
ep.path = "/antigravity" + ep.path
|
||||
ep.forcePlatform = service.PlatformAntigravity
|
||||
}
|
||||
t.Run(platform+"/"+ep.name, func(t *testing.T) {
|
||||
group := &service.Group{
|
||||
ID: 9400, Hydrated: true, Platform: platform, Status: service.StatusActive,
|
||||
AllowImageGeneration: false,
|
||||
}
|
||||
recorder, c, schedulerCache := runGeminiImageGateEndpoint(t, ep, group, platform)
|
||||
|
||||
require.Equal(t, http.StatusBadRequest, recorder.Code)
|
||||
require.Contains(t, recorder.Body.String(), service.ImageGenerationPermissionMessage())
|
||||
_, reachedSelection := c.Get(opsAccountIDKey)
|
||||
require.False(t, reachedSelection)
|
||||
require.Empty(t, schedulerCache.queriedGroupIDs())
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestGatewayHandlers_GeminiImageGenerationGateSkipsGroupsWithoutTheSwitch(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
// Anthropic 分组在后台不展示生图开关,混合调度 Antigravity 账号时不受门禁约束。
|
||||
for _, ep := range geminiImageGateEndpoints("gemini-3-pro-image")[:3] {
|
||||
t.Run(ep.name, func(t *testing.T) {
|
||||
group := &service.Group{
|
||||
ID: 9401, Hydrated: true, Platform: service.PlatformAnthropic, Status: service.StatusActive,
|
||||
AllowImageGeneration: false,
|
||||
}
|
||||
recorder, _, schedulerCache := runGeminiImageGateEndpoint(t, ep, group, service.PlatformAnthropic)
|
||||
|
||||
require.NotContains(t, recorder.Body.String(), service.ImageGenerationPermissionMessage())
|
||||
require.NotEmpty(t, schedulerCache.queriedGroupIDs())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGatewayHandlers_GeminiImageGenerationGateAllowsTextModelsAndEnabledGroups(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
cases := []struct {
|
||||
name string
|
||||
model string
|
||||
allow bool
|
||||
}{
|
||||
{name: "text model in disabled group", model: "gemini-3.7-flash", allow: false},
|
||||
{name: "image model in enabled group", model: "gemini-3-pro-image", allow: true},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
for _, ep := range geminiImageGateEndpoints(tc.model)[:3] {
|
||||
t.Run(tc.name+"/"+ep.name, func(t *testing.T) {
|
||||
group := &service.Group{
|
||||
ID: 9402, Hydrated: true, Platform: service.PlatformGemini, Status: service.StatusActive,
|
||||
AllowImageGeneration: tc.allow,
|
||||
}
|
||||
recorder, _, schedulerCache := runGeminiImageGateEndpoint(t, ep, group, service.PlatformGemini)
|
||||
|
||||
require.NotContains(t, recorder.Body.String(), service.ImageGenerationPermissionMessage())
|
||||
require.NotEmpty(t, schedulerCache.queriedGroupIDs())
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -39,9 +39,11 @@ func (h *GatewayHandler) GeminiV1BetaListModels(c *gin.Context) {
|
||||
googleError(c, http.StatusUnauthorized, "Invalid API key")
|
||||
return
|
||||
}
|
||||
// 检查平台:优先使用强制平台(/antigravity 路由),否则要求 gemini 分组
|
||||
// 检查平台:优先使用强制平台(/antigravity 路由),否则要求 gemini 分组(composite 分组允许路由到 antigravity)
|
||||
forcePlatform, hasForcePlatform := middleware.GetForcePlatformFromContext(c)
|
||||
if !hasForcePlatform && effectiveAPIKeyPlatform(c, apiKey) != service.PlatformGemini {
|
||||
effectivePlatform := effectiveAPIKeyPlatform(c, apiKey)
|
||||
if !hasForcePlatform && effectivePlatform != service.PlatformGemini &&
|
||||
!servesCompositeAntigravityGemini(apiKey, effectivePlatform) {
|
||||
googleError(c, http.StatusBadRequest, "API key group platform is not gemini")
|
||||
return
|
||||
}
|
||||
@@ -223,9 +225,11 @@ func (h *GatewayHandler) GeminiV1BetaGetModel(c *gin.Context) {
|
||||
googleError(c, http.StatusUnauthorized, "Invalid API key")
|
||||
return
|
||||
}
|
||||
// 检查平台:优先使用强制平台(/antigravity 路由),否则要求 gemini 分组
|
||||
// 检查平台:优先使用强制平台(/antigravity 路由),否则要求 gemini 分组(composite 分组允许路由到 antigravity)
|
||||
forcePlatform, hasForcePlatform := middleware.GetForcePlatformFromContext(c)
|
||||
if !hasForcePlatform && effectiveAPIKeyPlatform(c, apiKey) != service.PlatformGemini {
|
||||
effectivePlatform := effectiveAPIKeyPlatform(c, apiKey)
|
||||
if !hasForcePlatform && effectivePlatform != service.PlatformGemini &&
|
||||
!servesCompositeAntigravityGemini(apiKey, effectivePlatform) {
|
||||
googleError(c, http.StatusBadRequest, "API key group platform is not gemini")
|
||||
return
|
||||
}
|
||||
@@ -244,9 +248,13 @@ func (h *GatewayHandler) GeminiV1BetaGetModel(c *gin.Context) {
|
||||
if resolvedModel, ok := service.ResolvedUpstreamModelFromContext(c.Request.Context()); ok && strings.TrimSpace(resolvedModel) != "" {
|
||||
modelName = strings.TrimSpace(resolvedModel)
|
||||
}
|
||||
if !hasForcePlatform && servesCompositeAntigravityGemini(apiKey, effectivePlatform) && !isAntigravityGeminiModel(modelName) {
|
||||
googleError(c, http.StatusBadRequest, "API key group platform is not gemini")
|
||||
return
|
||||
}
|
||||
|
||||
// 强制 antigravity 模式:返回 antigravity 模型信息
|
||||
if forcePlatform == service.PlatformAntigravity {
|
||||
// 强制 antigravity 模式或 composite 路由到 antigravity:返回 antigravity 模型信息
|
||||
if forcePlatform == service.PlatformAntigravity || effectivePlatform == service.PlatformAntigravity {
|
||||
c.JSON(http.StatusOK, antigravity.FallbackGeminiModel(modelName))
|
||||
return
|
||||
}
|
||||
@@ -299,9 +307,11 @@ func (h *GatewayHandler) GeminiV1BetaModels(c *gin.Context) {
|
||||
zap.Any("group_id", apiKey.GroupID),
|
||||
)
|
||||
|
||||
// 检查平台:优先使用强制平台(/antigravity 路由,中间件已设置 request.Context),否则要求 gemini 分组
|
||||
// 检查平台:优先使用强制平台(/antigravity 路由,中间件已设置 request.Context),否则要求 gemini 分组(composite 分组允许路由到 antigravity)
|
||||
effectivePlatform := effectiveAPIKeyPlatform(c, apiKey)
|
||||
if !middleware.HasForcePlatform(c) {
|
||||
if effectiveAPIKeyPlatform(c, apiKey) != service.PlatformGemini {
|
||||
if effectivePlatform != service.PlatformGemini &&
|
||||
!servesCompositeAntigravityGemini(apiKey, effectivePlatform) {
|
||||
googleError(c, http.StatusBadRequest, "API key group platform is not gemini")
|
||||
return
|
||||
}
|
||||
@@ -318,9 +328,14 @@ func (h *GatewayHandler) GeminiV1BetaModels(c *gin.Context) {
|
||||
googleError(c, http.StatusBadRequest, "Invalid model in URL")
|
||||
return
|
||||
}
|
||||
urlModel := modelName
|
||||
if resolvedModel, ok := service.ResolvedUpstreamModelFromContext(c.Request.Context()); ok && strings.TrimSpace(resolvedModel) != "" {
|
||||
modelName = strings.TrimSpace(resolvedModel)
|
||||
}
|
||||
if !middleware.HasForcePlatform(c) && servesCompositeAntigravityGemini(apiKey, effectivePlatform) && !isAntigravityGeminiModel(modelName) {
|
||||
googleError(c, http.StatusBadRequest, "API key group platform is not gemini")
|
||||
return
|
||||
}
|
||||
|
||||
stream := action == "streamGenerateContent"
|
||||
reqLog = reqLog.With(zap.String("model", modelName), zap.String("action", action), zap.Bool("stream", stream))
|
||||
@@ -344,14 +359,19 @@ func (h *GatewayHandler) GeminiV1BetaModels(c *gin.Context) {
|
||||
pricingCtx, pricingAt := service.WithGatewayTokenRequestPricing(c.Request.Context())
|
||||
c.Request = c.Request.WithContext(pricingCtx)
|
||||
|
||||
if decision := h.checkSecurityAudit(c, reqLog, apiKey, authSubject, service.ContentModerationProtocolGemini, modelName, body); decision != nil && !decision.AllowNextStage {
|
||||
// 解析渠道级模型映射
|
||||
channelMapping, _ := h.gatewayService.ResolveChannelMappingAndRestrict(c.Request.Context(), apiKey.GroupID, modelName)
|
||||
reqModel := modelName // 保存映射前的原始模型名
|
||||
if action != "countTokens" && geminiImageGenerationRejected(c, apiKey, body, urlModel, reqModel, channelMapping.MappedModel) {
|
||||
googleError(c, http.StatusBadRequest, service.ImageGenerationPermissionMessage())
|
||||
return
|
||||
}
|
||||
|
||||
if decision := h.checkSecurityAudit(c, reqLog, apiKey, authSubject, service.ContentModerationProtocolGemini, reqModel, body); decision != nil && !decision.AllowNextStage {
|
||||
googleSecurityAuditError(c, decision)
|
||||
return
|
||||
}
|
||||
|
||||
// 解析渠道级模型映射
|
||||
channelMapping, _ := h.gatewayService.ResolveChannelMappingAndRestrict(c.Request.Context(), apiKey.GroupID, modelName)
|
||||
reqModel := modelName // 保存映射前的原始模型名
|
||||
if channelMapping.Mapped {
|
||||
modelName = channelMapping.MappedModel
|
||||
}
|
||||
@@ -532,12 +552,9 @@ func (h *GatewayHandler) GeminiV1BetaModels(c *gin.Context) {
|
||||
}
|
||||
fs := NewFailoverState(maxAccountSwitches, hasBoundSession)
|
||||
|
||||
// 单账号分组提前设置 SingleAccountRetry 标记,让 Service 层首次 503 就不设模型限流标记。
|
||||
// 避免单账号分组收到 503 (MODEL_CAPACITY_EXHAUSTED) 时设 29s 限流,导致后续请求连续快速失败。
|
||||
if h.gatewayService.IsSingleAntigravityAccountGroup(c.Request.Context(), apiKey.GroupID) {
|
||||
ctx := service.WithSingleAccountRetry(c.Request.Context(), true, h.metadataBridgeEnabled())
|
||||
c.Request = c.Request.WithContext(ctx)
|
||||
}
|
||||
// 单账号分组首次 503 就不设模型限流标记,避免设 29s 限流导致后续请求连续快速失败;
|
||||
// 是否单账号分组在 antigravity 账号遇到 503 或模型限流预检查时才判定。
|
||||
c.Request = c.Request.WithContext(h.gatewayService.WithSingleAntigravityAccountGroupProbe(c.Request.Context(), apiKey.GroupID))
|
||||
|
||||
for {
|
||||
excludedAccountIDs := fs.FailedAccountIDs
|
||||
@@ -567,7 +584,11 @@ func (h *GatewayHandler) GeminiV1BetaModels(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
if len(fs.FailedAccountIDs) == 0 {
|
||||
cls := classifyNoAccountErrorFromGin(c, h.gatewayService, apiKey, modelName, modelName, service.PlatformGemini)
|
||||
diagPlatform := service.PlatformGemini
|
||||
if p := effectiveAPIKeyPlatform(c, apiKey); p == service.PlatformAntigravity {
|
||||
diagPlatform = service.PlatformAntigravity
|
||||
}
|
||||
cls := classifyNoAccountErrorFromGin(c, h.gatewayService, apiKey, modelName, modelName, diagPlatform)
|
||||
if !cls.ModelNotFound {
|
||||
markOpsRoutingCapacityLimitedIfNoAvailable(c, err)
|
||||
}
|
||||
@@ -1053,3 +1074,16 @@ func derefGroupID(groupID *int64) int64 {
|
||||
}
|
||||
return *groupID
|
||||
}
|
||||
|
||||
func servesCompositeAntigravityGemini(apiKey *service.APIKey, effectivePlatform string) bool {
|
||||
return apiKey.Group != nil && apiKey.Group.Platform == service.PlatformComposite && effectivePlatform == service.PlatformAntigravity
|
||||
}
|
||||
|
||||
func isAntigravityGeminiModel(model string) bool {
|
||||
trimmed := strings.ToLower(strings.TrimSpace(strings.TrimPrefix(model, "models/")))
|
||||
if trimmed == "" || strings.HasPrefix(trimmed, "claude-") {
|
||||
return false
|
||||
}
|
||||
detected, ok := service.DetectModelPlatform(trimmed)
|
||||
return ok && detected == service.PlatformGemini
|
||||
}
|
||||
@@ -216,3 +216,75 @@ func TestShouldFallbackGeminiModel_DelegatesScopeFallback(t *testing.T) {
|
||||
}
|
||||
require.True(t, shouldFallbackGeminiModel("gemini-future-model", res))
|
||||
}
|
||||
|
||||
func TestGeminiV1BetaGetModel_CompositeAntigravityRoute(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
t.Run("composite route to antigravity gemini model succeeds", func(t *testing.T) {
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
req := httptest.NewRequest(http.MethodGet, "/v1beta/models/gemini-4-argon", nil)
|
||||
req = req.WithContext(service.WithCompositeRouteDecision(req.Context(), service.CompositeRouteDecision{
|
||||
Matched: true,
|
||||
TargetPlatform: service.PlatformAntigravity,
|
||||
UpstreamModel: "gemini-4-argon-high",
|
||||
}))
|
||||
c.Request = req
|
||||
c.Params = gin.Params{{Key: "model", Value: "gemini-4-argon"}}
|
||||
groupID := int64(4)
|
||||
c.Set(string(middleware.ContextKeyAPIKey), &service.APIKey{
|
||||
ID: 1,
|
||||
GroupID: &groupID,
|
||||
Group: &service.Group{ID: groupID, Platform: service.PlatformComposite},
|
||||
})
|
||||
|
||||
(&GatewayHandler{}).GeminiV1BetaGetModel(c)
|
||||
require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
|
||||
require.Contains(t, rec.Body.String(), "models/gemini-4-argon-high")
|
||||
})
|
||||
|
||||
t.Run("composite route to antigravity claude model is rejected on v1beta", func(t *testing.T) {
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
req := httptest.NewRequest(http.MethodGet, "/v1beta/models/claude-sonnet-5-5-high", nil)
|
||||
req = req.WithContext(service.WithCompositeRouteDecision(req.Context(), service.CompositeRouteDecision{
|
||||
Matched: true,
|
||||
TargetPlatform: service.PlatformAntigravity,
|
||||
UpstreamModel: "claude-sonnet-5-5-high",
|
||||
}))
|
||||
c.Request = req
|
||||
c.Params = gin.Params{{Key: "model", Value: "claude-sonnet-5-5-high"}}
|
||||
groupID := int64(4)
|
||||
c.Set(string(middleware.ContextKeyAPIKey), &service.APIKey{
|
||||
ID: 1,
|
||||
GroupID: &groupID,
|
||||
Group: &service.Group{ID: groupID, Platform: service.PlatformComposite},
|
||||
})
|
||||
|
||||
(&GatewayHandler{}).GeminiV1BetaGetModel(c)
|
||||
require.Equal(t, http.StatusBadRequest, rec.Code, rec.Body.String())
|
||||
})
|
||||
|
||||
t.Run("composite route to antigravity claude model is rejected on generateContent", func(t *testing.T) {
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
req := httptest.NewRequest(http.MethodPost, "/v1beta/models/claude-sonnet-5-5-high:generateContent", nil)
|
||||
req = req.WithContext(service.WithCompositeRouteDecision(req.Context(), service.CompositeRouteDecision{
|
||||
Matched: true,
|
||||
TargetPlatform: service.PlatformAntigravity,
|
||||
UpstreamModel: "claude-sonnet-5-5-high",
|
||||
}))
|
||||
c.Request = req
|
||||
c.Params = gin.Params{{Key: "modelAction", Value: "/claude-sonnet-5-5-high:generateContent"}}
|
||||
groupID := int64(4)
|
||||
c.Set(string(middleware.ContextKeyAPIKey), &service.APIKey{
|
||||
ID: 1,
|
||||
GroupID: &groupID,
|
||||
Group: &service.Group{ID: groupID, Platform: service.PlatformComposite},
|
||||
})
|
||||
c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: 1, Concurrency: 1})
|
||||
|
||||
(&GatewayHandler{}).GeminiV1BetaModels(c)
|
||||
require.Equal(t, http.StatusBadRequest, rec.Code, rec.Body.String())
|
||||
})
|
||||
}
|
||||
@@ -123,10 +123,14 @@ func classifyNoAccountError(
|
||||
|
||||
result := diag.DiagnoseModelAvailabilityForPlatform(ctx, apiKey.GroupID, routingModel, platform)
|
||||
if result.HasAccountsInPool && !result.HasModelSupport {
|
||||
message := fmt.Sprintf("Model %q is not supported by any configured account in this group", displayModel)
|
||||
if result.HasRetiredSubscriptionModel {
|
||||
message = fmt.Sprintf("Model %q targets GPT-5.5, which retired from Codex with ChatGPT sign-in on October 14, 2026. Select an available replacement such as GPT-6.1 Sol or GPT-6 Luna, or configure an API-key upstream that supports GPT-5.5.", displayModel)
|
||||
}
|
||||
return noAccountErrorClassification{
|
||||
Status: http.StatusNotFound,
|
||||
ErrType: "model_not_found",
|
||||
Message: fmt.Sprintf("Model %q is not supported by any configured account in this group", displayModel),
|
||||
Message: message,
|
||||
ModelNotFound: true,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -303,3 +303,22 @@ func TestClassifySelectionFailureError_StillUpgradesNonModelNotFoundFallback(t *
|
||||
require.Equal(t, "rate_limit_error", got.ErrType)
|
||||
require.False(t, got.ModelNotFound)
|
||||
}
|
||||
|
||||
func TestClassifyNoAccountError_GPT55Retirement(t *testing.T) {
|
||||
groupID := int64(1)
|
||||
apiKey := &service.APIKey{GroupID: &groupID}
|
||||
fd := &fakeDiagnoser{resp: service.ModelAvailabilityDiagnosis{HasAccountsInPool: true, HasRetiredSubscriptionModel: true}}
|
||||
cls := classifyNoAccountError(context.Background(), fd, apiKey, "gpt-5.5", "legacy", service.PlatformOpenAI)
|
||||
require.Equal(t, http.StatusNotFound, cls.Status)
|
||||
require.Equal(t, "model_not_found", cls.ErrType)
|
||||
require.Contains(t, cls.Message, "retired")
|
||||
require.Contains(t, cls.Message, "API-key")
|
||||
fd.resp.HasModelSupport = true
|
||||
cls = classifyNoAccountError(context.Background(), fd, apiKey, "gpt-5.5", "legacy", service.PlatformOpenAI)
|
||||
require.Equal(t, http.StatusServiceUnavailable, cls.Status, "a temporarily unavailable API pool is not a retirement error")
|
||||
}
|
||||
|
||||
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"}))
|
||||
}
|
||||
@@ -2540,6 +2540,11 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) {
|
||||
closeOpenAIClientWS(wsConn, coderws.StatusInternalError, "Failed to resolve composite model route")
|
||||
return
|
||||
}
|
||||
if decision.OAuthAmbiguous() {
|
||||
service.MarkOpsClientBusinessLimited(c, service.OpsClientBusinessLimitedReasonLocalModelConfiguration)
|
||||
closeOpenAIClientWS(wsConn, coderws.StatusPolicyViolation, decision.AmbiguousMessage())
|
||||
return
|
||||
}
|
||||
if decision.Matched {
|
||||
c.Request = c.Request.WithContext(service.WithCompositeRouteDecision(c.Request.Context(), decision))
|
||||
wsRouteModel = decision.UpstreamModel
|
||||
|
||||
@@ -103,7 +103,7 @@ func (h *PaymentWebhookHandler) handleNotify(c *gin.Context, providerKey string)
|
||||
headers[strings.ToLower(k)] = c.GetHeader(k)
|
||||
}
|
||||
|
||||
resolvedProviderKey, notification, err := verifyNotificationWithProviders(c.Request.Context(), providers, rawBody, headers)
|
||||
verifiedProvider, notification, err := verifyNotificationWithProviders(c.Request.Context(), providers, rawBody, headers)
|
||||
if err != nil {
|
||||
truncatedBody := rawBody
|
||||
if len(truncatedBody) > webhookLogTruncateLen {
|
||||
@@ -115,12 +115,20 @@ func (h *PaymentWebhookHandler) handleNotify(c *gin.Context, providerKey string)
|
||||
return
|
||||
}
|
||||
|
||||
resolvedProviderKey := verifiedProvider.ProviderKey()
|
||||
|
||||
// nil notification means irrelevant event (e.g. Stripe non-payment event); return success.
|
||||
if notification == nil {
|
||||
writeSuccessResponse(c, resolvedProviderKey)
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.paymentService.ConfirmNotificationUpstream(c.Request.Context(), verifiedProvider, notification); err != nil {
|
||||
slog.Error("[Payment Webhook] upstream confirmation failed", "provider", resolvedProviderKey, "outTradeNo", notification.OrderID, "tradeNo", notification.TradeNo, "error", err)
|
||||
c.String(http.StatusBadGateway, "confirm failed")
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.paymentService.HandlePaymentNotification(c.Request.Context(), notification, resolvedProviderKey); err != nil {
|
||||
// Unknown order: ack with 2xx so the provider stops retrying. This
|
||||
// guards against foreign environments whose webhook endpoints are
|
||||
@@ -170,7 +178,10 @@ func extractOutTradeNo(rawBody, providerKey string) string {
|
||||
return ""
|
||||
}
|
||||
|
||||
func verifyNotificationWithProviders(ctx context.Context, providers []payment.Provider, rawBody string, headers map[string]string) (string, *payment.PaymentNotification, error) {
|
||||
// verifyNotificationWithProviders returns the provider instance that verified
|
||||
// the notification so later steps (upstream confirmation) use the same
|
||||
// merchant configuration.
|
||||
func verifyNotificationWithProviders(ctx context.Context, providers []payment.Provider, rawBody string, headers map[string]string) (payment.Provider, *payment.PaymentNotification, error) {
|
||||
var lastErr error
|
||||
for _, provider := range providers {
|
||||
if provider == nil {
|
||||
@@ -181,12 +192,12 @@ func verifyNotificationWithProviders(ctx context.Context, providers []payment.Pr
|
||||
lastErr = err
|
||||
continue
|
||||
}
|
||||
return provider.ProviderKey(), notification, nil
|
||||
return provider, notification, nil
|
||||
}
|
||||
if lastErr != nil {
|
||||
return "", nil, lastErr
|
||||
return nil, nil, lastErr
|
||||
}
|
||||
return "", nil, fmt.Errorf("no webhook provider could verify notification")
|
||||
return nil, nil, fmt.Errorf("no webhook provider could verify notification")
|
||||
}
|
||||
|
||||
// wxpaySuccessResponse is the JSON response expected by WeChat Pay webhook.
|
||||
|
||||
@@ -204,9 +204,9 @@ func TestVerifyNotificationWithProvidersReturnsMatchedProvider(t *testing.T) {
|
||||
},
|
||||
}
|
||||
|
||||
providerKey, notification, err := verifyNotificationWithProviders(context.Background(), providers, "{}", map[string]string{"wechatpay-signature": "sig"})
|
||||
provider, notification, err := verifyNotificationWithProviders(context.Background(), providers, "{}", map[string]string{"wechatpay-signature": "sig"})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, payment.TypeWxpay, providerKey)
|
||||
require.Equal(t, payment.TypeWxpay, provider.ProviderKey())
|
||||
require.NotNil(t, notification)
|
||||
require.Equal(t, "sub2_42", notification.OrderID)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
//go:build unit
|
||||
|
||||
package handler
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"net/http/httptest"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey"
|
||||
middleware "github.com/Wei-Shaw/sub2api/internal/server/middleware"
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// bucketRecordingSchedulerCache 记录读取过的快照桶平台。
|
||||
type bucketRecordingSchedulerCache struct {
|
||||
*fakeSchedulerCache
|
||||
mu sync.Mutex
|
||||
platforms []string
|
||||
}
|
||||
|
||||
func (c *bucketRecordingSchedulerCache) GetSnapshot(ctx context.Context, bucket service.SchedulerBucket) ([]*service.Account, bool, error) {
|
||||
c.mu.Lock()
|
||||
c.platforms = append(c.platforms, bucket.Platform)
|
||||
c.mu.Unlock()
|
||||
return c.fakeSchedulerCache.GetSnapshot(ctx, bucket)
|
||||
}
|
||||
|
||||
func (c *bucketRecordingSchedulerCache) readPlatforms() []string {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
return append([]string(nil), c.platforms...)
|
||||
}
|
||||
|
||||
// 非 antigravity 账号的请求不读取单 antigravity 账号分组判定,选号之外不查询 antigravity 快照桶。
|
||||
func TestGeminiGroupRequestsDoNotReadAntigravityBucket(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
tests := []struct {
|
||||
name string
|
||||
route string
|
||||
path string
|
||||
body string
|
||||
call func(h *GatewayHandler) func(*gin.Context)
|
||||
}{
|
||||
{
|
||||
name: "gemini native",
|
||||
route: "/v1beta/models/*modelAction",
|
||||
path: "/v1beta/models/gemini-2.5-flash:generateContent",
|
||||
body: `{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}`,
|
||||
call: func(h *GatewayHandler) func(*gin.Context) { return h.GeminiV1BetaModels },
|
||||
},
|
||||
{
|
||||
name: "messages on gemini group",
|
||||
route: "/v1/messages",
|
||||
path: "/v1/messages",
|
||||
body: `{"model":"gemini-2.5-flash","max_tokens":16,"messages":[{"role":"user","content":"hi"}]}`,
|
||||
call: func(h *GatewayHandler) func(*gin.Context) { return h.Messages },
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
f := newGeminiClientCancelFixture(t)
|
||||
|
||||
f.serve(t, tt.route, tt.path, tt.body, tt.call(f.handler))
|
||||
|
||||
require.Equal(t, int32(1), f.upstream.calls.Load(), "请求应完成选号并到达上游")
|
||||
platforms := f.schedulerCache.readPlatforms()
|
||||
require.NotEmpty(t, platforms)
|
||||
require.NotContains(t, platforms, service.PlatformAntigravity)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessagesAnthropicGroupDoesNotReadAntigravityBucket(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
groupID := int64(9400)
|
||||
accountID := int64(9401)
|
||||
group := &service.Group{ID: groupID, Hydrated: true, Platform: service.PlatformAnthropic, Status: service.StatusActive}
|
||||
account := &service.Account{
|
||||
ID: accountID,
|
||||
Platform: service.PlatformAnthropic,
|
||||
Type: service.AccountTypeAPIKey,
|
||||
Credentials: map[string]any{"api_key": "test-key", "intercept_warmup_requests": true},
|
||||
Status: service.StatusActive,
|
||||
Schedulable: true,
|
||||
Concurrency: 1,
|
||||
Priority: 1,
|
||||
AccountGroups: []service.AccountGroup{{AccountID: accountID, GroupID: groupID}},
|
||||
}
|
||||
schedulerCache := &bucketRecordingSchedulerCache{fakeSchedulerCache: &fakeSchedulerCache{accounts: []*service.Account{account}}}
|
||||
h, cleanup := newTestGatewayHandlerWithSchedulerCache(t, group, schedulerCache)
|
||||
t.Cleanup(cleanup)
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
body := `{"model":"claude-sonnet-4-5","max_tokens":256,"messages":[{"role":"user","content":[{"type":"text","text":"Warmup"}]}]}`
|
||||
req := httptest.NewRequest("POST", "/v1/messages", bytes.NewBufferString(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
c.Request = req.WithContext(context.WithValue(req.Context(), ctxkey.Group, group))
|
||||
apiKey := &service.APIKey{
|
||||
ID: 9402, UserID: 9403, GroupID: &groupID, Group: group, Status: service.StatusActive,
|
||||
User: &service.User{ID: 9403, Concurrency: 10, Balance: 100},
|
||||
}
|
||||
c.Set(string(middleware.ContextKeyAPIKey), apiKey)
|
||||
c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: apiKey.UserID, Concurrency: 10})
|
||||
|
||||
h.Messages(c)
|
||||
|
||||
require.Equal(t, 200, rec.Code)
|
||||
selected, ok := c.Get(opsAccountIDKey)
|
||||
require.True(t, ok)
|
||||
require.Equal(t, accountID, selected)
|
||||
platforms := schedulerCache.readPlatforms()
|
||||
require.NotEmpty(t, platforms)
|
||||
require.NotContains(t, platforms, service.PlatformAntigravity)
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/payment"
|
||||
infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors"
|
||||
"github.com/smartwalle/alipay/v3"
|
||||
)
|
||||
|
||||
@@ -24,7 +25,10 @@ const (
|
||||
const (
|
||||
alipayFundChangeYes = "Y"
|
||||
alipayErrTradeNotExist = "ACQ.TRADE_NOT_EXIST"
|
||||
alipayRefundSuffix = "-refund"
|
||||
alipayRefundStatusSucc = "REFUND_SUCCESS"
|
||||
alipayRefundRequestSep = "-refund-"
|
||||
// 支付宝提示退款发起后过早查询可能查不到、之后又处理成功;超过该时长仍无记录才判定失败。
|
||||
alipayRefundQueryNotFoundGrace = 10 * time.Minute
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -37,6 +41,12 @@ var (
|
||||
alipayTradePagePay = func(client *alipay.Client, param alipay.TradePagePay) (*url.URL, error) {
|
||||
return client.TradePagePay(param)
|
||||
}
|
||||
alipayTradeRefund = func(ctx context.Context, client *alipay.Client, param alipay.TradeRefund) (*alipay.TradeRefundRsp, error) {
|
||||
return client.TradeRefund(ctx, param)
|
||||
}
|
||||
alipayTradeFastPayRefundQuery = func(ctx context.Context, client *alipay.Client, param alipay.TradeFastPayRefundQuery) (*alipay.TradeFastPayRefundQueryRsp, error) {
|
||||
return client.TradeFastPayRefundQuery(ctx, param)
|
||||
}
|
||||
)
|
||||
|
||||
// Alipay implements payment.Provider and payment.CancelableProvider using the smartwalle/alipay SDK.
|
||||
@@ -338,32 +348,76 @@ func (a *Alipay) Refund(ctx context.Context, req payment.RefundRequest) (*paymen
|
||||
return nil, err
|
||||
}
|
||||
|
||||
result, err := client.TradeRefund(ctx, alipay.TradeRefund{
|
||||
outRequestNo := fmt.Sprintf("%s%s%d", req.OrderID, alipayRefundRequestSep, time.Now().UnixNano())
|
||||
result, err := alipayTradeRefund(ctx, client, alipay.TradeRefund{
|
||||
OutTradeNo: req.OrderID,
|
||||
RefundAmount: req.Amount,
|
||||
RefundReason: req.Reason,
|
||||
OutRequestNo: fmt.Sprintf("%s-refund-%d", req.OrderID, time.Now().UnixNano()),
|
||||
OutRequestNo: outRequestNo,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("alipay TradeRefund: %w", err)
|
||||
}
|
||||
if result == nil {
|
||||
return nil, fmt.Errorf("alipay TradeRefund: empty response")
|
||||
}
|
||||
|
||||
refundStatus := payment.ProviderStatusPending
|
||||
if result.FundChange == alipayFundChangeYes {
|
||||
refundStatus = payment.ProviderStatusSuccess
|
||||
}
|
||||
|
||||
refundID := result.TradeNo
|
||||
if refundID == "" {
|
||||
refundID = req.OrderID + alipayRefundSuffix
|
||||
}
|
||||
|
||||
// fund_change != Y 时需凭退款请求号查询终态,因此 RefundID 记录 out_request_no。
|
||||
return &payment.RefundResponse{
|
||||
RefundID: refundID,
|
||||
RefundID: outRequestNo,
|
||||
Status: refundStatus,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// QueryRefund 通过 alipay.trade.fastpay.refund.query 查询退款终态。refund_status 为 REFUND_SUCCESS
|
||||
// 表示成功;退款发起超过宽限期仍查不到记录表示支付宝未受理或退款失败;其余情况视为仍在处理中。
|
||||
func (a *Alipay) QueryRefund(ctx context.Context, req payment.RefundQueryRequest) (*payment.RefundResponse, error) {
|
||||
orderID := strings.TrimSpace(req.OrderID)
|
||||
outRequestNo := strings.TrimSpace(req.RefundID)
|
||||
// 旧版本把支付宝交易号记为 RefundID,无法据此查询退款请求,只能人工核实。
|
||||
if orderID == "" || !strings.HasPrefix(outRequestNo, orderID+alipayRefundRequestSep) {
|
||||
return nil, infraerrors.BadRequest("REFUND_QUERY_UNSUPPORTED", "this refund was issued without a queryable refund request number; please verify manually")
|
||||
}
|
||||
client, err := a.getClient()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result, err := alipayTradeFastPayRefundQuery(ctx, client, alipay.TradeFastPayRefundQuery{
|
||||
OutTradeNo: orderID,
|
||||
OutRequestNo: outRequestNo,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("alipay query refund: %w", err)
|
||||
}
|
||||
if result == nil {
|
||||
return nil, fmt.Errorf("alipay query refund: empty response")
|
||||
}
|
||||
// SDK 对带签名的业务失败响应(如 ACQ.SYSTEM_ERROR)不返回 error,字段为空;
|
||||
// 不检查错误码会被误判为"无退款记录"而失败收尾。
|
||||
if result.IsFailure() {
|
||||
return nil, fmt.Errorf("alipay query refund: %w", result.Error)
|
||||
}
|
||||
|
||||
status := payment.ProviderStatusPending
|
||||
switch {
|
||||
case strings.TrimSpace(result.RefundStatus) == alipayRefundStatusSucc:
|
||||
status = payment.ProviderStatusSuccess
|
||||
case strings.TrimSpace(result.OutRequestNo) == "" && strings.TrimSpace(result.RefundAmount) == "" &&
|
||||
alipayRefundAbsenceIsFinal(req.RequestedAt, time.Now()):
|
||||
status = payment.ProviderStatusFailed
|
||||
}
|
||||
return &payment.RefundResponse{RefundID: outRequestNo, Status: status}, nil
|
||||
}
|
||||
|
||||
func alipayRefundAbsenceIsFinal(requestedAt, now time.Time) bool {
|
||||
return !requestedAt.IsZero() && now.Sub(requestedAt) >= alipayRefundQueryNotFoundGrace
|
||||
}
|
||||
|
||||
// CancelPayment closes a pending trade on Alipay.
|
||||
func (a *Alipay) CancelPayment(ctx context.Context, tradeNo string) error {
|
||||
client, err := a.getClient()
|
||||
@@ -406,5 +460,6 @@ func parseAlipayAmount(values ...string) (float64, error) {
|
||||
var (
|
||||
_ payment.Provider = (*Alipay)(nil)
|
||||
_ payment.CancelableProvider = (*Alipay)(nil)
|
||||
_ payment.RefundQueryProvider = (*Alipay)(nil)
|
||||
_ payment.MerchantIdentityProvider = (*Alipay)(nil)
|
||||
)
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/payment"
|
||||
"github.com/smartwalle/alipay/v3"
|
||||
@@ -444,3 +445,129 @@ func TestParseAlipayAmount(t *testing.T) {
|
||||
t.Fatal("expected error when no valid amount field exists")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAlipayRefundRecordsOutRequestNoAsRefundID(t *testing.T) {
|
||||
origRefund := alipayTradeRefund
|
||||
t.Cleanup(func() { alipayTradeRefund = origRefund })
|
||||
|
||||
for _, tc := range []struct {
|
||||
fundChange string
|
||||
wantStatus string
|
||||
}{
|
||||
{fundChange: alipayFundChangeYes, wantStatus: payment.ProviderStatusSuccess},
|
||||
{fundChange: "N", wantStatus: payment.ProviderStatusPending},
|
||||
} {
|
||||
var gotOutRequestNo string
|
||||
alipayTradeRefund = func(_ context.Context, _ *alipay.Client, param alipay.TradeRefund) (*alipay.TradeRefundRsp, error) {
|
||||
if param.OutTradeNo != "sub2_7" || param.RefundAmount != "12.50" {
|
||||
t.Fatalf("unexpected refund param: %+v", param)
|
||||
}
|
||||
gotOutRequestNo = param.OutRequestNo
|
||||
return &alipay.TradeRefundRsp{TradeNo: "2026101522001", FundChange: tc.fundChange}, nil
|
||||
}
|
||||
|
||||
provider := &Alipay{client: &alipay.Client{}}
|
||||
resp, err := provider.Refund(context.Background(), payment.RefundRequest{OrderID: "sub2_7", Amount: "12.50", Reason: "r"})
|
||||
if err != nil {
|
||||
t.Fatalf("Refund() error = %v", err)
|
||||
}
|
||||
if resp.Status != tc.wantStatus {
|
||||
t.Fatalf("fund_change=%s status = %q, want %q", tc.fundChange, resp.Status, tc.wantStatus)
|
||||
}
|
||||
if !strings.HasPrefix(gotOutRequestNo, "sub2_7-refund-") || resp.RefundID != gotOutRequestNo {
|
||||
t.Fatalf("RefundID = %q, out_request_no = %q", resp.RefundID, gotOutRequestNo)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAlipayQueryRefundMapsStatus(t *testing.T) {
|
||||
origQuery := alipayTradeFastPayRefundQuery
|
||||
t.Cleanup(func() { alipayTradeFastPayRefundQuery = origQuery })
|
||||
|
||||
const outRequestNo = "sub2_7-refund-1760500000000000000"
|
||||
ok := alipay.Error{Code: alipay.CodeSuccess, Msg: "Success"}
|
||||
settled := time.Now().Add(-alipayRefundQueryNotFoundGrace - time.Minute)
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
rsp *alipay.TradeFastPayRefundQueryRsp
|
||||
requestedAt time.Time
|
||||
wantStatus string
|
||||
}{
|
||||
{name: "success", rsp: &alipay.TradeFastPayRefundQueryRsp{Error: ok, OutRequestNo: outRequestNo, RefundAmount: "12.50", RefundStatus: alipayRefundStatusSucc}, requestedAt: settled, wantStatus: payment.ProviderStatusSuccess},
|
||||
{name: "record without final status", rsp: &alipay.TradeFastPayRefundQueryRsp{Error: ok, OutRequestNo: outRequestNo, RefundAmount: "12.50"}, requestedAt: settled, wantStatus: payment.ProviderStatusPending},
|
||||
{name: "no refund record after grace", rsp: &alipay.TradeFastPayRefundQueryRsp{Error: ok}, requestedAt: settled, wantStatus: payment.ProviderStatusFailed},
|
||||
{name: "no refund record within grace", rsp: &alipay.TradeFastPayRefundQueryRsp{Error: ok}, requestedAt: time.Now().Add(-time.Minute), wantStatus: payment.ProviderStatusPending},
|
||||
{name: "no refund record with unknown request time", rsp: &alipay.TradeFastPayRefundQueryRsp{Error: ok}, wantStatus: payment.ProviderStatusPending},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
alipayTradeFastPayRefundQuery = func(_ context.Context, _ *alipay.Client, param alipay.TradeFastPayRefundQuery) (*alipay.TradeFastPayRefundQueryRsp, error) {
|
||||
if param.OutTradeNo != "sub2_7" || param.OutRequestNo != outRequestNo {
|
||||
t.Fatalf("unexpected query param: %+v", param)
|
||||
}
|
||||
return tc.rsp, nil
|
||||
}
|
||||
provider := &Alipay{client: &alipay.Client{}}
|
||||
resp, err := provider.QueryRefund(context.Background(), payment.RefundQueryRequest{OrderID: "sub2_7", RefundID: outRequestNo, RequestedAt: tc.requestedAt})
|
||||
if err != nil {
|
||||
t.Fatalf("QueryRefund() error = %v", err)
|
||||
}
|
||||
if resp.Status != tc.wantStatus || resp.RefundID != outRequestNo {
|
||||
t.Fatalf("QueryRefund() = %+v, want status %q", resp, tc.wantStatus)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// SDK 对带签名的业务失败响应返回 err == nil,错误码只在响应体里。
|
||||
func TestAlipayQueryRefundBusinessFailureKeepsRefundPending(t *testing.T) {
|
||||
origQuery := alipayTradeFastPayRefundQuery
|
||||
t.Cleanup(func() { alipayTradeFastPayRefundQuery = origQuery })
|
||||
|
||||
for _, rspErr := range []alipay.Error{
|
||||
{Code: "40004", Msg: "Business Failed", SubCode: "ACQ.SYSTEM_ERROR", SubMsg: "系统错误"},
|
||||
{Code: "20000", Msg: "Service Currently Unavailable", SubCode: "isp.unknow-error"},
|
||||
{},
|
||||
} {
|
||||
alipayTradeFastPayRefundQuery = func(context.Context, *alipay.Client, alipay.TradeFastPayRefundQuery) (*alipay.TradeFastPayRefundQueryRsp, error) {
|
||||
return &alipay.TradeFastPayRefundQueryRsp{Error: rspErr}, nil
|
||||
}
|
||||
provider := &Alipay{client: &alipay.Client{}}
|
||||
resp, err := provider.QueryRefund(context.Background(), payment.RefundQueryRequest{
|
||||
OrderID: "sub2_7",
|
||||
RefundID: "sub2_7-refund-1",
|
||||
RequestedAt: time.Now().Add(-24 * time.Hour),
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatalf("code %q: QueryRefund() = %+v, want error", rspErr.Code, resp)
|
||||
}
|
||||
if rspErr.SubCode != "" && !strings.Contains(err.Error(), string(rspErr.Code)) {
|
||||
t.Fatalf("code %q: error %q should carry the gateway code", rspErr.Code, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAlipayQueryRefundErrorsKeepRefundPending(t *testing.T) {
|
||||
origQuery := alipayTradeFastPayRefundQuery
|
||||
t.Cleanup(func() { alipayTradeFastPayRefundQuery = origQuery })
|
||||
|
||||
calls := 0
|
||||
alipayTradeFastPayRefundQuery = func(context.Context, *alipay.Client, alipay.TradeFastPayRefundQuery) (*alipay.TradeFastPayRefundQueryRsp, error) {
|
||||
calls++
|
||||
return nil, errors.New("ACQ.SYSTEM_ERROR")
|
||||
}
|
||||
provider := &Alipay{client: &alipay.Client{}}
|
||||
|
||||
// 旧版本记录的是支付宝交易号,无法查询退款请求,需人工核实,且不能调用网关。
|
||||
for _, legacyID := range []string{"", "2026101522001", "sub2_7-refund", "sub2_70-refund-1"} {
|
||||
if _, err := provider.QueryRefund(context.Background(), payment.RefundQueryRequest{OrderID: "sub2_7", RefundID: legacyID}); err == nil || !strings.Contains(err.Error(), "verify manually") {
|
||||
t.Fatalf("legacy refund id %q: err = %v", legacyID, err)
|
||||
}
|
||||
}
|
||||
if calls != 0 {
|
||||
t.Fatalf("legacy refund ids must not reach the gateway, calls = %d", calls)
|
||||
}
|
||||
|
||||
if _, err := provider.QueryRefund(context.Background(), payment.RefundQueryRequest{OrderID: "sub2_7", RefundID: "sub2_7-refund-1"}); err == nil {
|
||||
t.Fatal("gateway error must be returned so the refund stays pending")
|
||||
}
|
||||
}
|
||||
@@ -7,8 +7,10 @@ import (
|
||||
"crypto/md5"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"sort"
|
||||
@@ -27,6 +29,7 @@ const (
|
||||
easypayHTTPTimeout = 10 * time.Second
|
||||
maxEasypayResponseSize = 1 << 20 // 1MB
|
||||
maxEasypayErrorSummary = 512
|
||||
easypayAmountTolerance = 0.005
|
||||
tradeStatusSuccess = "TRADE_SUCCESS"
|
||||
signTypeMD5 = "MD5"
|
||||
paymentModePopup = "popup"
|
||||
@@ -301,32 +304,86 @@ func (e *EasyPay) upstreamPaymentType(paymentType string) string {
|
||||
}
|
||||
|
||||
func (e *EasyPay) QueryOrder(ctx context.Context, tradeNo string) (*payment.QueryOrderResponse, error) {
|
||||
result, err := e.queryOrder(ctx, tradeNo)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
responseTradeNo := tradeNo
|
||||
if result.tradeNo != "" {
|
||||
responseTradeNo = result.tradeNo
|
||||
}
|
||||
amount, _ := strconv.ParseFloat(result.money, 64)
|
||||
return &payment.QueryOrderResponse{
|
||||
TradeNo: responseTradeNo,
|
||||
Status: result.status,
|
||||
Amount: amount,
|
||||
Metadata: e.MerchantIdentityMetadata(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// easyPayQueryResult is the normalized api.php?act=order answer. tradeNo is
|
||||
// the upstream trade number exactly as returned (empty when absent).
|
||||
type easyPayQueryResult struct {
|
||||
status string
|
||||
money string
|
||||
tradeNo string
|
||||
}
|
||||
|
||||
func (e *EasyPay) queryOrder(ctx context.Context, outTradeNo string) (*easyPayQueryResult, error) {
|
||||
params := map[string]string{
|
||||
"act": "order", "pid": e.config["pid"],
|
||||
"key": e.config["pkey"], "out_trade_no": tradeNo,
|
||||
"key": e.config["pkey"], "out_trade_no": outTradeNo,
|
||||
}
|
||||
body, err := e.post(ctx, e.apiBase()+"/api.php", params)
|
||||
// 彩虹易支付 and ZPay read act=order parameters from $_GET only (a
|
||||
// body-only request is answered with "No Act!"), while other forks read
|
||||
// the form body; send them in both places.
|
||||
query := url.Values{}
|
||||
for k, v := range params {
|
||||
query.Set(k, v)
|
||||
}
|
||||
body, err := e.post(ctx, e.apiBase()+"/api.php?"+query.Encode(), params)
|
||||
if err != nil {
|
||||
// The request URL carries the merchant key; never let it reach logs
|
||||
// or audit records through *url.Error.
|
||||
var urlErr *url.Error
|
||||
if errors.As(err, &urlErr) {
|
||||
err = urlErr.Err
|
||||
}
|
||||
return nil, fmt.Errorf("easypay query: %w", err)
|
||||
}
|
||||
// Scalars are decoded leniently: PHP deployments commonly serialize
|
||||
// integer columns as strings ("status":"1").
|
||||
type easyPayQueryData struct {
|
||||
TradeStatus *string `json:"trade_status"`
|
||||
Status *int `json:"status"`
|
||||
Money *string `json:"money"`
|
||||
TradeNo *string `json:"trade_no"`
|
||||
TradeStatus *string `json:"trade_status"`
|
||||
Status json.RawMessage `json:"status"`
|
||||
Money json.RawMessage `json:"money"`
|
||||
TradeNo json.RawMessage `json:"trade_no"`
|
||||
OutTradeNo json.RawMessage `json:"out_trade_no"`
|
||||
}
|
||||
var resp struct {
|
||||
Code int `json:"code"`
|
||||
Msg string `json:"msg"`
|
||||
TradeStatus *string `json:"trade_status"`
|
||||
Status *int `json:"status"`
|
||||
Money *string `json:"money"`
|
||||
TradeNo *string `json:"trade_no"`
|
||||
Data easyPayQueryData `json:"data"`
|
||||
easyPayQueryData
|
||||
Code any `json:"code"`
|
||||
Msg string `json:"msg"`
|
||||
Data easyPayQueryData `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &resp); err != nil {
|
||||
return nil, fmt.Errorf("easypay parse query: %w", err)
|
||||
}
|
||||
// An explicit failure code wins over any paid-looking status field that
|
||||
// may accompany it.
|
||||
if resp.Code != nil && !easyPayResponseCodeIsSuccess(resp.Code) {
|
||||
msg := strings.TrimSpace(resp.Msg)
|
||||
if msg == "" {
|
||||
msg = summarizeEasyPayResponse(body)
|
||||
}
|
||||
return nil, fmt.Errorf("easypay query failed: %s", msg)
|
||||
}
|
||||
// When the upstream echoes the order identity it must be this order; some
|
||||
// implementations silently ignore unknown lookup parameters.
|
||||
if echoed := easyPayJSONScalar(pickEasyPayJSON(resp.OutTradeNo, resp.Data.OutTradeNo)); echoed != "" && echoed != strings.TrimSpace(outTradeNo) {
|
||||
return nil, fmt.Errorf("easypay query out_trade_no mismatch: expected %s, got %s", strings.TrimSpace(outTradeNo), echoed)
|
||||
}
|
||||
|
||||
status := payment.ProviderStatusPending
|
||||
if resp.TradeStatus != nil {
|
||||
if *resp.TradeStatus == tradeStatusSuccess {
|
||||
@@ -336,38 +393,74 @@ func (e *EasyPay) QueryOrder(ctx context.Context, tradeNo string) (*payment.Quer
|
||||
if *resp.Data.TradeStatus == tradeStatusSuccess {
|
||||
status = payment.ProviderStatusPaid
|
||||
}
|
||||
} else if resp.Status != nil {
|
||||
if *resp.Status == easypayStatusPaid {
|
||||
} else if raw := pickEasyPayJSON(resp.Status, resp.Data.Status); raw != nil {
|
||||
if easyPayJSONScalar(raw) == strconv.Itoa(easypayStatusPaid) {
|
||||
status = payment.ProviderStatusPaid
|
||||
}
|
||||
} else if resp.Data.Status != nil && *resp.Data.Status == easypayStatusPaid {
|
||||
status = payment.ProviderStatusPaid
|
||||
}
|
||||
|
||||
money := ""
|
||||
if resp.Money != nil {
|
||||
money = *resp.Money
|
||||
} else if resp.Data.Money != nil {
|
||||
money = *resp.Data.Money
|
||||
}
|
||||
responseTradeNo := tradeNo
|
||||
if resp.TradeNo != nil {
|
||||
if *resp.TradeNo != "" {
|
||||
responseTradeNo = *resp.TradeNo
|
||||
}
|
||||
} else if resp.Data.TradeNo != nil && *resp.Data.TradeNo != "" {
|
||||
responseTradeNo = *resp.Data.TradeNo
|
||||
}
|
||||
|
||||
amount, _ := strconv.ParseFloat(money, 64)
|
||||
return &payment.QueryOrderResponse{
|
||||
TradeNo: responseTradeNo,
|
||||
Status: status,
|
||||
Amount: amount,
|
||||
Metadata: e.MerchantIdentityMetadata(),
|
||||
return &easyPayQueryResult{
|
||||
status: status,
|
||||
money: easyPayJSONScalar(pickEasyPayJSON(resp.Money, resp.Data.Money)),
|
||||
tradeNo: easyPayJSONScalar(pickEasyPayJSON(resp.TradeNo, resp.Data.TradeNo)),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// ConfirmNotification checks a verified success notification against the
|
||||
// upstream order before it is fulfilled, so crediting follows the gateway's
|
||||
// own order state (paid, amount, trade_no). The query is sent to this
|
||||
// instance's own apiBase with its own credentials.
|
||||
func (e *EasyPay) ConfirmNotification(ctx context.Context, n *payment.PaymentNotification) error {
|
||||
if n == nil || n.Status != payment.NotificationStatusSuccess {
|
||||
return nil
|
||||
}
|
||||
result, err := e.queryOrder(ctx, n.OrderID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("easypay confirm: %w", err)
|
||||
}
|
||||
if result.status != payment.ProviderStatusPaid {
|
||||
return fmt.Errorf("easypay confirm: upstream reports order %s as not paid", n.OrderID)
|
||||
}
|
||||
queriedAmount, err := strconv.ParseFloat(result.money, 64)
|
||||
if err != nil || math.Abs(queriedAmount-n.Amount) > easypayAmountTolerance {
|
||||
return fmt.Errorf("easypay confirm: amount mismatch: notified %v, upstream %q", n.Amount, result.money)
|
||||
}
|
||||
if result.tradeNo != "" {
|
||||
if n.TradeNo != "" && n.TradeNo != result.tradeNo {
|
||||
return fmt.Errorf("easypay confirm: trade_no mismatch: notified %s, upstream %s", n.TradeNo, result.tradeNo)
|
||||
}
|
||||
n.TradeNo = result.tradeNo
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func easyPayJSONScalar(raw json.RawMessage) string {
|
||||
if len(raw) == 0 {
|
||||
return ""
|
||||
}
|
||||
var str string
|
||||
if err := json.Unmarshal(raw, &str); err == nil {
|
||||
return strings.TrimSpace(str)
|
||||
}
|
||||
var num json.Number
|
||||
if err := json.Unmarshal(raw, &num); err == nil {
|
||||
return num.String()
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// pickEasyPayJSON returns the top-level field when present, otherwise the
|
||||
// nested data field. JSON null counts as absent.
|
||||
func pickEasyPayJSON(top, nested json.RawMessage) json.RawMessage {
|
||||
if len(top) > 0 && string(top) != "null" {
|
||||
return top
|
||||
}
|
||||
if len(nested) > 0 && string(nested) != "null" {
|
||||
return nested
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (e *EasyPay) VerifyNotification(_ context.Context, rawBody string, _ map[string]string) (*payment.PaymentNotification, error) {
|
||||
values, err := url.ParseQuery(rawBody)
|
||||
if err != nil {
|
||||
@@ -379,7 +472,14 @@ func (e *EasyPay) VerifyNotification(_ context.Context, rawBody string, _ map[st
|
||||
if !easyPayNotifyAllowedParams[k] {
|
||||
return nil, fmt.Errorf("unexpected notify param: %s", k)
|
||||
}
|
||||
params[k] = values.Get(k)
|
||||
v := values.Get(k)
|
||||
// Notify values are plain tokens; only the merchant-defined product
|
||||
// name is free text. Delimiter characters elsewhere are rejected so
|
||||
// each value maps to exactly one field of the signed string.
|
||||
if k != "name" && strings.ContainsAny(v, "&=") {
|
||||
return nil, fmt.Errorf("invalid notify param value: %s", k)
|
||||
}
|
||||
params[k] = v
|
||||
}
|
||||
sign := params["sign"]
|
||||
if sign == "" {
|
||||
@@ -388,22 +488,20 @@ func (e *EasyPay) VerifyNotification(_ context.Context, rawBody string, _ map[st
|
||||
if !easyPayVerifySign(params, e.config["pkey"], sign) {
|
||||
return nil, fmt.Errorf("invalid signature")
|
||||
}
|
||||
// Bind the notification to this instance's merchant directly instead of
|
||||
// relying on the order snapshot, which legacy orders do not carry.
|
||||
if expected, actual := strings.TrimSpace(e.config["pid"]), strings.TrimSpace(params["pid"]); actual != expected {
|
||||
return nil, fmt.Errorf("easypay pid mismatch: expected %s, got %s", expected, actual)
|
||||
}
|
||||
status := payment.ProviderStatusFailed
|
||||
if params["trade_status"] == tradeStatusSuccess {
|
||||
status = payment.ProviderStatusSuccess
|
||||
}
|
||||
amount, _ := strconv.ParseFloat(params["money"], 64)
|
||||
|
||||
metadata := e.MerchantIdentityMetadata()
|
||||
if pid := strings.TrimSpace(params["pid"]); pid != "" {
|
||||
if metadata == nil {
|
||||
metadata = map[string]string{}
|
||||
}
|
||||
metadata["pid"] = pid
|
||||
}
|
||||
return &payment.PaymentNotification{
|
||||
TradeNo: params["trade_no"], OrderID: params["out_trade_no"],
|
||||
Amount: amount, Status: status, RawData: rawBody, Metadata: metadata,
|
||||
Amount: amount, Status: status, RawData: rawBody, Metadata: e.MerchantIdentityMetadata(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,253 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/payment"
|
||||
)
|
||||
|
||||
func newConfirmTestEasyPay(t *testing.T, body string, status int) (*EasyPay, *atomic.Int32) {
|
||||
t.Helper()
|
||||
var calls atomic.Int32
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
calls.Add(1)
|
||||
if err := r.ParseForm(); err != nil {
|
||||
t.Errorf("ParseForm: %v", err)
|
||||
}
|
||||
q := r.URL.Query()
|
||||
if r.URL.Path != "/api.php" || q.Get("act") != "order" || q.Get("pid") != "1001" || q.Get("key") != "pkey-1" || q.Get("out_trade_no") != "sub2_ORDER1" {
|
||||
t.Errorf("unexpected query request: path=%s query=%v", r.URL.Path, q)
|
||||
}
|
||||
w.WriteHeader(status)
|
||||
_, _ = w.Write([]byte(body))
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
provider, err := NewEasyPay("test-instance", map[string]string{
|
||||
"pid": "1001",
|
||||
"pkey": "pkey-1",
|
||||
"apiBase": server.URL,
|
||||
"notifyUrl": "https://example.com/notify",
|
||||
"returnUrl": "https://example.com/return",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("NewEasyPay: %v", err)
|
||||
}
|
||||
return provider, &calls
|
||||
}
|
||||
|
||||
func confirmTestNotification() *payment.PaymentNotification {
|
||||
return &payment.PaymentNotification{
|
||||
TradeNo: "2026101600001",
|
||||
OrderID: "sub2_ORDER1",
|
||||
Amount: 10,
|
||||
Status: payment.NotificationStatusSuccess,
|
||||
}
|
||||
}
|
||||
|
||||
func TestEasyPayConfirmNotification(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
body string
|
||||
status int
|
||||
notifyTrade string
|
||||
wantErr string
|
||||
wantTradeNo string
|
||||
}{
|
||||
{
|
||||
name: "paid with matching amount and trade_no",
|
||||
body: `{"code":1,"pid":1001,"out_trade_no":"sub2_ORDER1","trade_no":"2026101600001","money":"10.00","status":1}`,
|
||||
notifyTrade: "2026101600001",
|
||||
wantTradeNo: "2026101600001",
|
||||
},
|
||||
{
|
||||
name: "missing notify trade_no is filled from upstream",
|
||||
body: `{"code":1,"trade_no":"2026101600001","money":"10.00","trade_status":"TRADE_SUCCESS"}`,
|
||||
wantTradeNo: "2026101600001",
|
||||
},
|
||||
{
|
||||
name: "upstream not paid",
|
||||
body: `{"code":1,"trade_no":"2026101600001","money":"10.00","status":0}`,
|
||||
notifyTrade: "2026101600001",
|
||||
wantErr: "not paid",
|
||||
},
|
||||
{
|
||||
name: "upstream failure code with paid status",
|
||||
body: `{"code":-1,"msg":"订单号不存在","status":1,"money":"10.00"}`,
|
||||
notifyTrade: "2026101600001",
|
||||
wantErr: "订单号不存在",
|
||||
},
|
||||
{
|
||||
name: "amount mismatch",
|
||||
body: `{"code":1,"trade_no":"2026101600001","money":"0.01","status":1}`,
|
||||
notifyTrade: "2026101600001",
|
||||
wantErr: "amount mismatch",
|
||||
},
|
||||
{
|
||||
name: "missing upstream amount",
|
||||
body: `{"code":1,"trade_no":"2026101600001","status":1}`,
|
||||
notifyTrade: "2026101600001",
|
||||
wantErr: "amount mismatch",
|
||||
},
|
||||
{
|
||||
name: "trade_no conflict",
|
||||
body: `{"code":1,"trade_no":"2026101699999","money":"10.00","status":1}`,
|
||||
notifyTrade: "2026101600001",
|
||||
wantErr: "trade_no mismatch",
|
||||
},
|
||||
{
|
||||
name: "string status from PHP deployment",
|
||||
body: `{"code":"1","pid":"1001","out_trade_no":"sub2_ORDER1","trade_no":"2026101600001","money":"10.00","status":"1"}`,
|
||||
notifyTrade: "2026101600001",
|
||||
wantTradeNo: "2026101600001",
|
||||
},
|
||||
{
|
||||
name: "foreign order echo",
|
||||
body: `{"code":1,"out_trade_no":"sub2_OTHER","trade_no":"2026101600001","money":"10.00","status":1}`,
|
||||
notifyTrade: "2026101600001",
|
||||
wantErr: "out_trade_no mismatch",
|
||||
},
|
||||
{
|
||||
name: "upstream HTTP error body",
|
||||
body: `<html>502 Bad Gateway</html>`,
|
||||
status: http.StatusBadGateway,
|
||||
notifyTrade: "2026101600001",
|
||||
wantErr: "parse query",
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
tt := tt
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
status := tt.status
|
||||
if status == 0 {
|
||||
status = http.StatusOK
|
||||
}
|
||||
provider, calls := newConfirmTestEasyPay(t, tt.body, status)
|
||||
n := confirmTestNotification()
|
||||
n.TradeNo = tt.notifyTrade
|
||||
err := provider.ConfirmNotification(context.Background(), n)
|
||||
if calls.Load() != 1 {
|
||||
t.Fatalf("upstream query calls = %d, want 1", calls.Load())
|
||||
}
|
||||
if tt.wantErr != "" {
|
||||
if err == nil || !strings.Contains(err.Error(), tt.wantErr) {
|
||||
t.Fatalf("ConfirmNotification error = %v, want containing %q", err, tt.wantErr)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("ConfirmNotification returned error: %v", err)
|
||||
}
|
||||
if n.TradeNo != tt.wantTradeNo {
|
||||
t.Fatalf("trade_no = %q, want %q", n.TradeNo, tt.wantTradeNo)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestEasyPayConfirmNotificationSkipsNonSuccess(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
provider, calls := newConfirmTestEasyPay(t, `{}`, http.StatusOK)
|
||||
n := confirmTestNotification()
|
||||
n.Status = payment.ProviderStatusFailed
|
||||
if err := provider.ConfirmNotification(context.Background(), n); err != nil {
|
||||
t.Fatalf("ConfirmNotification returned error: %v", err)
|
||||
}
|
||||
if calls.Load() != 0 {
|
||||
t.Fatalf("upstream query calls = %d, want 0", calls.Load())
|
||||
}
|
||||
}
|
||||
|
||||
func TestEasyPayConfirmNotificationQueryTransportError(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
server := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))
|
||||
apiBase := server.URL
|
||||
server.Close()
|
||||
provider := newTestEasyPay(t, apiBase)
|
||||
err := provider.ConfirmNotification(context.Background(), confirmTestNotification())
|
||||
if err == nil {
|
||||
t.Fatal("ConfirmNotification must fail when the upstream is unreachable")
|
||||
}
|
||||
// The query URL carries the merchant key; errors are logged and stored in
|
||||
// the payment audit trail, so they must not echo the URL.
|
||||
if strings.Contains(err.Error(), "pkey-1") || strings.Contains(err.Error(), "key=") {
|
||||
t.Fatalf("error contains the merchant key: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEasyPayNotifyRejectsForeignPid(t *testing.T) {
|
||||
t.Parallel()
|
||||
e := easyPayPoCProvider()
|
||||
|
||||
for _, pid := range []string{"2000", ""} {
|
||||
params := map[string]string{
|
||||
"trade_no": "T1",
|
||||
"out_trade_no": "ORDER123",
|
||||
"type": "alipay",
|
||||
"name": "balance recharge",
|
||||
"money": "650.00",
|
||||
"trade_status": tradeStatusSuccess,
|
||||
}
|
||||
if pid != "" {
|
||||
params["pid"] = pid
|
||||
}
|
||||
params["sign"] = easyPaySign(params, e.config["pkey"])
|
||||
q := url.Values{}
|
||||
for k, v := range params {
|
||||
q.Set(k, v)
|
||||
}
|
||||
if _, err := e.VerifyNotification(context.Background(), q.Encode(), nil); err == nil {
|
||||
t.Fatalf("callback with pid %q must be rejected", pid)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestEasyPayNotifyAllowsFreeTextNameOnly(t *testing.T) {
|
||||
t.Parallel()
|
||||
e := easyPayPoCProvider()
|
||||
|
||||
base := map[string]string{
|
||||
"pid": "1000",
|
||||
"trade_no": "T1",
|
||||
"out_trade_no": "ORDER123",
|
||||
"type": "alipay",
|
||||
"name": "Plan A&B = Pro",
|
||||
"money": "650.00",
|
||||
"trade_status": tradeStatusSuccess,
|
||||
}
|
||||
encode := func(params map[string]string) string {
|
||||
signed := map[string]string{}
|
||||
for k, v := range params {
|
||||
signed[k] = v
|
||||
}
|
||||
signed["sign"] = easyPaySign(params, e.config["pkey"])
|
||||
q := url.Values{}
|
||||
for k, v := range signed {
|
||||
q.Set(k, v)
|
||||
}
|
||||
return q.Encode()
|
||||
}
|
||||
if _, err := e.VerifyNotification(context.Background(), encode(base), nil); err != nil {
|
||||
t.Fatalf("free-text name must be accepted: %v", err)
|
||||
}
|
||||
for _, field := range []string{"trade_no", "out_trade_no", "type", "money", "param"} {
|
||||
params := map[string]string{}
|
||||
for k, v := range base {
|
||||
params[k] = v
|
||||
}
|
||||
params[field] = "v&k=x"
|
||||
if _, err := e.VerifyNotification(context.Background(), encode(params), nil); err == nil {
|
||||
t.Fatalf("value with &/= in %s must be rejected", field)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -20,6 +20,7 @@ func TestEasyPayQueryOrderStatusMapping(t *testing.T) {
|
||||
wantStatus string
|
||||
wantTradeNo string
|
||||
wantAmount float64
|
||||
wantErr bool
|
||||
}{
|
||||
{
|
||||
name: "top level trade success is paid",
|
||||
@@ -64,10 +65,64 @@ func TestEasyPayQueryOrderStatusMapping(t *testing.T) {
|
||||
wantAmount: 3.21,
|
||||
},
|
||||
{
|
||||
name: "query failure with missing status is pending",
|
||||
body: `{"code":0,"msg":"订单不存在"}`,
|
||||
name: "query failure code is an error",
|
||||
body: `{"code":0,"msg":"订单不存在"}`,
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "explicit failure code wins over paid status fields",
|
||||
body: `{"code":-1,"msg":"签名错误","status":1,"trade_status":"TRADE_SUCCESS","money":"12.34"}`,
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "string failure code is an error",
|
||||
body: `{"code":"-1","msg":"error","status":1}`,
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "foreign order echo is rejected",
|
||||
body: `{"code":1,"pid":"pid-1","out_trade_no":"order-999","trade_status":"TRADE_SUCCESS","money":"12.34"}`,
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "foreign order echo in nested data is rejected",
|
||||
body: `{"code":1,"data":{"out_trade_no":"order-999","trade_status":"TRADE_SUCCESS","money":"12.34"}}`,
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "string numeric status from PHP deployments is paid",
|
||||
body: `{"code":"1","msg":"查询订单号成功!","trade_no":"2026101600001","out_trade_no":"order-123","pid":"1001","money":"12.34","status":"1"}`,
|
||||
wantStatus: payment.ProviderStatusPaid,
|
||||
wantTradeNo: "2026101600001",
|
||||
wantAmount: 12.34,
|
||||
},
|
||||
{
|
||||
name: "string numeric unpaid status is pending",
|
||||
body: `{"code":1,"trade_no":"2026101600001","money":"12.34","status":"0"}`,
|
||||
wantStatus: payment.ProviderStatusPending,
|
||||
wantTradeNo: orderID,
|
||||
wantTradeNo: "2026101600001",
|
||||
wantAmount: 12.34,
|
||||
},
|
||||
{
|
||||
name: "documented caihong response with integer pid and status is paid",
|
||||
body: `{"code":1,"msg":"查询订单号成功!","trade_no":"2016080622555342651","out_trade_no":"order-123","api_trade_no":"4200001","type":"alipay","pid":1001,"addtime":"2016-08-06 22:55:52","endtime":"2016-08-06 22:55:52","name":"VIP会员","money":"1.00","status":1,"param":"","buyer":""}`,
|
||||
wantStatus: payment.ProviderStatusPaid,
|
||||
wantTradeNo: "2016080622555342651",
|
||||
wantAmount: 1,
|
||||
},
|
||||
{
|
||||
name: "null top-level fields fall back to nested data",
|
||||
body: `{"code":1,"status":null,"money":null,"trade_no":null,"data":{"status":1,"money":"5.00","trade_no":"data-789"}}`,
|
||||
wantStatus: payment.ProviderStatusPaid,
|
||||
wantTradeNo: "data-789",
|
||||
wantAmount: 5,
|
||||
},
|
||||
{
|
||||
name: "matching identity echo with numeric fields is paid",
|
||||
body: `{"code":"1","pid":"pid-1","out_trade_no":"order-123","trade_status":"TRADE_SUCCESS","money":12.34,"trade_no":2026101600001}`,
|
||||
wantStatus: payment.ProviderStatusPaid,
|
||||
wantTradeNo: "2026101600001",
|
||||
wantAmount: 12.34,
|
||||
},
|
||||
{
|
||||
name: "missing fields are pending",
|
||||
@@ -93,9 +148,16 @@ func TestEasyPayQueryOrderStatusMapping(t *testing.T) {
|
||||
if err := r.ParseForm(); err != nil {
|
||||
t.Errorf("ParseForm: %v", err)
|
||||
}
|
||||
gotForm = make(url.Values, len(r.PostForm))
|
||||
// Parameters must be in the URL query (彩虹易支付 reads $_GET)
|
||||
// and mirrored in the body for forks that read $_POST.
|
||||
gotForm = r.URL.Query()
|
||||
for key, values := range r.PostForm {
|
||||
gotForm[key] = append([]string(nil), values...)
|
||||
if got := gotForm.Get(key); got != values[0] {
|
||||
t.Errorf("body[%s] = %q, query has %q", key, values[0], got)
|
||||
}
|
||||
}
|
||||
if len(r.PostForm) != len(gotForm) {
|
||||
t.Errorf("body params %v do not mirror query params %v", r.PostForm, gotForm)
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(tt.body))
|
||||
@@ -104,6 +166,12 @@ func TestEasyPayQueryOrderStatusMapping(t *testing.T) {
|
||||
|
||||
provider := newTestEasyPay(t, server.URL)
|
||||
resp, err := provider.QueryOrder(context.Background(), orderID)
|
||||
if tt.wantErr {
|
||||
if err == nil {
|
||||
t.Fatalf("QueryOrder succeeded, want error (response=%+v)", resp)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("QueryOrder returned error: %v", err)
|
||||
}
|
||||
|
||||
@@ -2,7 +2,10 @@
|
||||
// registry, load balancing, and shared utilities for the payment subsystem.
|
||||
package payment
|
||||
|
||||
import "context"
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
)
|
||||
|
||||
// PaymentType represents a supported payment method.
|
||||
type PaymentType = string
|
||||
@@ -192,6 +195,8 @@ type RefundQueryRequest struct {
|
||||
OrderID string
|
||||
RefundID string
|
||||
Amount string
|
||||
// RequestedAt 为退款进入 pending 的时间;零值表示未知。
|
||||
RequestedAt time.Time
|
||||
}
|
||||
|
||||
// RefundResponse is returned after a refund request.
|
||||
@@ -234,6 +239,16 @@ type RefundQueryProvider interface {
|
||||
QueryRefund(ctx context.Context, req RefundQueryRequest) (*RefundResponse, error)
|
||||
}
|
||||
|
||||
// NotificationConfirmer extends Provider for gateways whose verified
|
||||
// notifications are not sufficient proof of payment on their own. The webhook
|
||||
// path calls ConfirmNotification on the instance that verified the
|
||||
// notification before fulfillment; implementations query the upstream order
|
||||
// and may fill in missing notification fields (e.g. TradeNo) from it.
|
||||
type NotificationConfirmer interface {
|
||||
Provider
|
||||
ConfirmNotification(ctx context.Context, n *PaymentNotification) error
|
||||
}
|
||||
|
||||
// CancelableProvider extends Provider with the ability to cancel pending payments.
|
||||
type CancelableProvider interface {
|
||||
Provider
|
||||
|
||||
@@ -169,6 +169,12 @@ type modelDef struct {
|
||||
var claudeModels = []modelDef{
|
||||
{ID: "claude-fable-5-1", DisplayName: "Claude Fable 5.1", CreatedAt: "2026-09-01T00:00:00Z"},
|
||||
{ID: "claude-fable-5", DisplayName: "Claude Fable 5", CreatedAt: "2026-06-09T00:00:00Z"},
|
||||
{ID: "claude-opus-5-5-high", DisplayName: "Claude Opus 5.5 (High)", CreatedAt: "2026-09-22T00:00:00Z"},
|
||||
{ID: "claude-opus-5-5-medium", DisplayName: "Claude Opus 5.5 (Medium)", CreatedAt: "2026-09-22T00:00:00Z"},
|
||||
{ID: "claude-opus-5-5-low", DisplayName: "Claude Opus 5.5 (Low)", CreatedAt: "2026-09-22T00:00:00Z"},
|
||||
{ID: "claude-sonnet-5-5-high", DisplayName: "Claude Sonnet 5.5 (High)", CreatedAt: "2026-09-28T00:00:00Z"},
|
||||
{ID: "claude-sonnet-5-5-medium", DisplayName: "Claude Sonnet 5.5 (Medium)", CreatedAt: "2026-09-28T00:00:00Z"},
|
||||
{ID: "claude-sonnet-5-5-low", DisplayName: "Claude Sonnet 5.5 (Low)", CreatedAt: "2026-09-28T00:00:00Z"},
|
||||
{ID: "claude-opus-4-5-thinking", DisplayName: "Claude Opus 4.5 Thinking", CreatedAt: "2025-11-01T00:00:00Z"},
|
||||
{ID: "claude-sonnet-4-5", DisplayName: "Claude Sonnet 4.5", CreatedAt: "2025-09-29T00:00:00Z"},
|
||||
{ID: "claude-sonnet-4-5-thinking", DisplayName: "Claude Sonnet 4.5 Thinking", CreatedAt: "2025-09-29T00:00:00Z"},
|
||||
@@ -208,6 +214,9 @@ var geminiModels = []modelDef{
|
||||
{ID: "gemini-3.8-flash-low", DisplayName: "Gemini 3.8 Flash Low", CreatedAt: "2026-09-02T00:00:00Z", IsReasoning: true},
|
||||
{ID: "gemini-3.8-flash-medium", DisplayName: "Gemini 3.8 Flash Medium", CreatedAt: "2026-09-02T00:00:00Z", IsReasoning: true},
|
||||
{ID: "gemini-3.8-flash-tiered", DisplayName: "Gemini 3.8 Flash", CreatedAt: "2026-09-02T00:00:00Z", IsReasoning: true},
|
||||
{ID: "gemini-4-argon-high", DisplayName: "Gemini 4 Argon (High)", CreatedAt: "2026-10-13T00:00:00Z", IsReasoning: true},
|
||||
{ID: "gemini-4-argon-low", DisplayName: "Gemini 4 Argon (Low)", CreatedAt: "2026-10-13T00:00:00Z", IsReasoning: true},
|
||||
{ID: "gemini-4-argon-medium", DisplayName: "Gemini 4 Argon (Medium)", CreatedAt: "2026-10-13T00:00:00Z", IsReasoning: true},
|
||||
{ID: "gemini-3-pro-preview", DisplayName: "Gemini 3 Pro Preview", CreatedAt: "2025-06-01T00:00:00Z", IsReasoning: true},
|
||||
{ID: "gemini-3-pro-image", DisplayName: "Gemini 3 Pro Image", CreatedAt: "2025-06-01T00:00:00Z"},
|
||||
}
|
||||
@@ -277,6 +286,9 @@ func FallbackGeminiModel(model string) GeminiModel {
|
||||
// IsGeminiReasoningModel 判断是否为不支持参数和强制 ToolConfig 的 Gemini 推理模型
|
||||
func IsGeminiReasoningModel(modelID string) bool {
|
||||
lowerID := strings.ToLower(modelID)
|
||||
if strings.Contains(lowerID, "gemini-pro-agent") || strings.Contains(lowerID, "gemini-4-argon") {
|
||||
return true
|
||||
}
|
||||
for _, m := range geminiModels {
|
||||
if strings.Contains(lowerID, m.ID) && m.IsReasoning {
|
||||
return true
|
||||
|
||||
@@ -39,6 +39,15 @@ func TestDefaultModels_ContainsNewAndLegacyImageModels(t *testing.T) {
|
||||
"gemini-3.8-flash-low",
|
||||
"gemini-3.8-flash-medium",
|
||||
"gemini-3.8-flash-tiered",
|
||||
"gemini-4-argon-high",
|
||||
"gemini-4-argon-low",
|
||||
"gemini-4-argon-medium",
|
||||
"claude-opus-5-5-high",
|
||||
"claude-opus-5-5-low",
|
||||
"claude-opus-5-5-medium",
|
||||
"claude-sonnet-5-5-high",
|
||||
"claude-sonnet-5-5-low",
|
||||
"claude-sonnet-5-5-medium",
|
||||
}
|
||||
|
||||
for _, id := range requiredIDs {
|
||||
@@ -67,3 +76,23 @@ func TestClaudeContentItem_ThinkingAlwaysHasSignature(t *testing.T) {
|
||||
t.Fatalf("text block = %s, want %s", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsGeminiReasoningModel_IncludesProAgent(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
if !IsGeminiReasoningModel("gemini-pro-agent") {
|
||||
t.Fatal("expected gemini-pro-agent to be recognized as a Gemini reasoning model")
|
||||
}
|
||||
if !IsGeminiReasoningModel("gemini-3.8-flash-high") {
|
||||
t.Fatal("expected gemini-3.8-flash-high to be recognized as a Gemini reasoning model")
|
||||
}
|
||||
if !IsGeminiReasoningModel("gemini-4-argon") {
|
||||
t.Fatal("expected gemini-4-argon to be recognized as a Gemini reasoning model")
|
||||
}
|
||||
if !IsGeminiReasoningModel("gemini-4-argon-high") {
|
||||
t.Fatal("expected gemini-4-argon-high to be recognized as a Gemini reasoning model")
|
||||
}
|
||||
if IsGeminiReasoningModel("gemini-2.5-flash") {
|
||||
t.Fatal("did not expect gemini-2.5-flash to be recognized as a Gemini reasoning model")
|
||||
}
|
||||
}
|
||||
@@ -239,10 +239,39 @@ func TierIDToPlanType(tierID string) string {
|
||||
if tierID == "" {
|
||||
return "Free"
|
||||
}
|
||||
// Google 新增的细分档位(如 g1-ultra-lite-tier、g1-pro-plus-tier)仍归入 Ultra / Pro。
|
||||
if plan := paidPlanFromTierID(tierID); plan != "" {
|
||||
return plan
|
||||
}
|
||||
return tierID
|
||||
}
|
||||
}
|
||||
|
||||
// paidPlanFromTierID 识别 g1-ultra-*-tier / g1-pro-*-tier 形式的付费档位 ID,未知时返回空串。
|
||||
func paidPlanFromTierID(tierID string) string {
|
||||
id := strings.ToLower(strings.TrimSpace(tierID))
|
||||
if !strings.HasSuffix(id, "-tier") {
|
||||
return ""
|
||||
}
|
||||
switch {
|
||||
case strings.HasPrefix(id, "g1-ultra-"):
|
||||
return "Ultra"
|
||||
case strings.HasPrefix(id, "g1-pro-"):
|
||||
return "Pro"
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
// IsPaidPlanType 判断账号记录的 plan_type 是否为付费套餐,兼容旧记录里直接保存的档位 ID。
|
||||
func IsPaidPlanType(planType string) bool {
|
||||
switch strings.ToLower(strings.TrimSpace(planType)) {
|
||||
case "pro", "ultra":
|
||||
return true
|
||||
}
|
||||
return paidPlanFromTierID(planType) != ""
|
||||
}
|
||||
|
||||
// Client Antigravity API 客户端
|
||||
type Client struct {
|
||||
httpClient *http.Client
|
||||
@@ -653,8 +682,22 @@ type FetchAvailableModelsResponse struct {
|
||||
}
|
||||
|
||||
// FetchAvailableModels 获取可用模型和配额信息,返回解析后的结构体和原始 JSON
|
||||
// 支持 URL fallback:sandbox → daily → prod
|
||||
// 保留旧调用的 URL fallback:prod → daily。
|
||||
func (c *Client) FetchAvailableModels(ctx context.Context, accessToken, projectID string, bodyLimit int64) (*FetchAvailableModelsResponse, map[string]any, error) {
|
||||
return c.fetchAvailableModels(ctx, BaseURLs, accessToken, projectID, bodyLimit, false)
|
||||
}
|
||||
|
||||
// FetchAvailableModelsFromURL 获取指定端点的模型目录,不回退到其他端点。
|
||||
// 模型发现应使用与生成请求相同的端点,避免返回该端点无法访问的模型。
|
||||
func (c *Client) FetchAvailableModelsFromURL(ctx context.Context, baseURL, accessToken, projectID string, bodyLimit int64) (*FetchAvailableModelsResponse, map[string]any, error) {
|
||||
baseURL = strings.TrimRight(strings.TrimSpace(baseURL), "/")
|
||||
if baseURL == "" {
|
||||
return nil, nil, errors.New("fetchAvailableModels base URL is required")
|
||||
}
|
||||
return c.fetchAvailableModels(ctx, []string{baseURL}, accessToken, projectID, bodyLimit, true)
|
||||
}
|
||||
|
||||
func (c *Client) fetchAvailableModels(ctx context.Context, availableURLs []string, accessToken, projectID string, bodyLimit int64, fixedEndpoint bool) (*FetchAvailableModelsResponse, map[string]any, error) {
|
||||
if c == nil || c.httpClient == nil {
|
||||
return nil, nil, errors.New("antigravity client is not configured")
|
||||
}
|
||||
@@ -668,10 +711,10 @@ func (c *Client) FetchAvailableModels(ctx context.Context, accessToken, projectI
|
||||
return nil, nil, fmt.Errorf("序列化请求失败: %w", err)
|
||||
}
|
||||
|
||||
// 固定顺序:prod -> daily
|
||||
availableURLs := BaseURLs
|
||||
|
||||
fetchClient := c.fetchAvailableModelsHTTPClient()
|
||||
if fixedEndpoint {
|
||||
fetchClient.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
|
||||
}
|
||||
var lastErr error
|
||||
for urlIdx, baseURL := range availableURLs {
|
||||
apiURL := baseURL + "/v1internal:fetchAvailableModels"
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
@@ -260,6 +261,8 @@ func TestTierIDToPlanType(t *testing.T) {
|
||||
{"free-tier", "Free"},
|
||||
{"g1-pro-tier", "Pro"},
|
||||
{"g1-ultra-tier", "Ultra"},
|
||||
{"g1-ultra-lite-tier", "Ultra"},
|
||||
{"G1-Pro-Plus-Tier", "Pro"},
|
||||
{"FREE-TIER", "Free"},
|
||||
{"", "Free"},
|
||||
{"unknown-tier", "unknown-tier"},
|
||||
@@ -1468,6 +1471,113 @@ func TestClient_LoadCodeAssist_ContextCanceled_RealCall(t *testing.T) {
|
||||
// Client.FetchAvailableModels - 真正调用方法的测试
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func TestClient_FetchAvailableModelsFromURL_UsesSelectedEndpoint(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/v1internal:fetchAvailableModels" || r.Method != http.MethodPost {
|
||||
t.Errorf("unexpected model list request: %s %s", r.Method, r.URL.Path)
|
||||
}
|
||||
if r.Header.Get("Authorization") != "Bearer selected-token" {
|
||||
t.Errorf("unexpected authorization header")
|
||||
}
|
||||
var body FetchAvailableModelsRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil || body.Project != "selected-project" {
|
||||
t.Errorf("unexpected project request: %+v, %v", body, err)
|
||||
}
|
||||
_, _ = w.Write([]byte(`{"models":{"gemini-3.8-flash-high":{"displayName":"Gemini 3.8 Flash High","supportsImages":true,"supportsThinking":true,"thinkingBudget":24576,"maxTokens":1048576,"maxOutputTokens":65536}}}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
client := mustNewClient(t, "")
|
||||
response, raw, err := client.FetchAvailableModelsFromURL(context.Background(), server.URL, "selected-token", "selected-project", defaultFetchAvailableModelsBodyLimit)
|
||||
if err != nil {
|
||||
t.Fatalf("selected endpoint should return its catalog: %v", err)
|
||||
}
|
||||
model, ok := response.Models["gemini-3.8-flash-high"]
|
||||
if !ok || model.SupportsThinking == nil || !*model.SupportsThinking || model.MaxTokens == nil || *model.MaxTokens != 1048576 {
|
||||
t.Fatalf("selected endpoint metadata must remain available: %+v", model)
|
||||
}
|
||||
if raw["models"] == nil {
|
||||
t.Fatal("selected endpoint raw catalog must remain available")
|
||||
}
|
||||
}
|
||||
|
||||
func TestClient_FetchAvailableModelsFromURL_DoesNotFollowAnotherEndpoint(t *testing.T) {
|
||||
otherEndpointCalls := 0
|
||||
other := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
otherEndpointCalls++
|
||||
_, _ = w.Write([]byte(`{"models":{"other-endpoint-model":{}}}`))
|
||||
}))
|
||||
defer other.Close()
|
||||
selected := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
http.Redirect(w, r, other.URL+"/v1internal:fetchAvailableModels", http.StatusTemporaryRedirect)
|
||||
}))
|
||||
defer selected.Close()
|
||||
withMockBaseURLs(t, []string{selected.URL, other.URL})
|
||||
|
||||
response, _, err := mustNewClient(t, "").FetchAvailableModelsFromURL(context.Background(), selected.URL, "token", "project", defaultFetchAvailableModelsBodyLimit)
|
||||
if err == nil || response != nil {
|
||||
t.Fatalf("selected endpoint redirect must not produce another endpoint's catalog: %v, %v", response, err)
|
||||
}
|
||||
if otherEndpointCalls != 0 {
|
||||
t.Fatalf("model discovery must stay on selected endpoint; other endpoint received %d requests", otherEndpointCalls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClient_FetchAvailableModelsFromURL_DoesNotFallbackOnFailure(t *testing.T) {
|
||||
for _, status := range []int{http.StatusNotFound, http.StatusTooManyRequests, http.StatusInternalServerError, http.StatusForbidden} {
|
||||
t.Run(fmt.Sprint(status), func(t *testing.T) {
|
||||
otherEndpointCalls := 0
|
||||
other := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
otherEndpointCalls++
|
||||
_, _ = w.Write([]byte(`{"models":{"other-endpoint-model":{}}}`))
|
||||
}))
|
||||
defer other.Close()
|
||||
selected := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(status)
|
||||
_, _ = w.Write([]byte(`{"error":"selected endpoint unavailable"}`))
|
||||
}))
|
||||
defer selected.Close()
|
||||
withMockBaseURLs(t, []string{selected.URL, other.URL})
|
||||
|
||||
response, raw, err := mustNewClient(t, "").FetchAvailableModelsFromURL(context.Background(), selected.URL, "token", "project", defaultFetchAvailableModelsBodyLimit)
|
||||
if err == nil || response != nil || raw != nil {
|
||||
t.Fatalf("selected endpoint HTTP %d must fail without another catalog: %v, %v", status, response, err)
|
||||
}
|
||||
if otherEndpointCalls != 0 {
|
||||
t.Fatalf("another endpoint must not receive fallback requests: %d", otherEndpointCalls)
|
||||
}
|
||||
if status == http.StatusForbidden {
|
||||
if _, ok := err.(*ForbiddenError); !ok {
|
||||
t.Fatalf("403 must preserve typed forbidden error: %T", err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestClient_FetchAvailableModelsFromURL_ValidatesResponseAndLimit(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
body string
|
||||
limit int64
|
||||
}{
|
||||
{name: "invalid JSON", body: `not JSON`, limit: defaultFetchAvailableModelsBodyLimit},
|
||||
{name: "oversized response", body: `{"models":{"model":{}}}`, limit: 8},
|
||||
{name: "nonpositive limit", body: `{"models":{"model":{}}}`, limit: 0},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
_, _ = io.WriteString(w, tc.body)
|
||||
}))
|
||||
defer server.Close()
|
||||
_, _, err := mustNewClient(t, "").FetchAvailableModelsFromURL(context.Background(), server.URL, "token", "project", tc.limit)
|
||||
if err == nil {
|
||||
t.Fatal("invalid model catalog response or limit must fail")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestClient_FetchAvailableModels_Success_RealCall(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
@@ -1787,6 +1897,51 @@ func TestClient_FetchAvailableModels_404Fallback_RealCall(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestClient_HubUserAgentAndIDEVersionUseContextOverride(t *testing.T) {
|
||||
withTestUserAgentVersionResolver(t)
|
||||
ctx := context.WithValue(context.Background(), userAgentVersionTestContextKey{}, "3.4.5")
|
||||
const expectedUserAgent = "antigravity/hub/3.4.5 windows/amd64"
|
||||
for _, action := range []string{"generateContent", "streamGenerateContent"} {
|
||||
req, err := NewAPIRequestWithURL(ctx, "https://upstream.example", action, "test-token", []byte(`{}`))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := req.Header.Get("User-Agent"); got != expectedUserAgent {
|
||||
t.Fatalf("generation request must use the context Hub user agent: %q", got)
|
||||
}
|
||||
}
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if got := r.Header.Get("User-Agent"); got != expectedUserAgent {
|
||||
t.Errorf("client API must use the context Hub user agent: %q", got)
|
||||
}
|
||||
switch r.URL.Path {
|
||||
case "/v1internal:loadCodeAssist":
|
||||
var body LoadCodeAssistRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
if body.Metadata.IDEVersion != "3.4.5" {
|
||||
t.Errorf("ideVersion must match the user agent version: %q", body.Metadata.IDEVersion)
|
||||
}
|
||||
_, _ = io.WriteString(w, `{"cloudaicompanionProject":"test-project"}`)
|
||||
case "/v1internal:fetchAvailableModels":
|
||||
_, _ = io.WriteString(w, `{"models":{"gemini-4-argon-high":{}}}`)
|
||||
default:
|
||||
t.Errorf("unexpected client endpoint: %s", r.URL.Path)
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
}
|
||||
}))
|
||||
defer server.Close()
|
||||
withMockBaseURLs(t, []string{server.URL})
|
||||
client := mustNewClient(t, "")
|
||||
if _, _, err := client.LoadCodeAssist(ctx, "test-token"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, _, err := client.FetchAvailableModelsFromURL(ctx, server.URL, "test-token", "test-project", defaultFetchAvailableModelsBodyLimit); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractProjectIDFromOnboardResponse(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
|
||||
@@ -34,7 +34,7 @@ const (
|
||||
AntigravityUserAgentVersionEnv = "ANTIGRAVITY_USER_AGENT_VERSION"
|
||||
|
||||
// DefaultUserAgentVersion 是未通过环境变量或后台设置覆盖时使用的默认版本号。
|
||||
DefaultUserAgentVersion = "2.9.1"
|
||||
DefaultUserAgentVersion = "2.23.0"
|
||||
|
||||
// 固定的 redirect_uri(用户需手动复制 code)
|
||||
RedirectURI = "http://localhost:8085/callback"
|
||||
@@ -123,9 +123,9 @@ func GetUserAgentVersionForContext(ctx context.Context) string {
|
||||
// BuildUserAgent 使用指定版本号构造 User-Agent;版本为空或非法时回退默认值。
|
||||
func BuildUserAgent(version string) string {
|
||||
if normalized := NormalizeUserAgentVersion(version); normalized != "" {
|
||||
return fmt.Sprintf("antigravity/%s windows/amd64", normalized)
|
||||
return fmt.Sprintf("antigravity/hub/%s windows/amd64", normalized)
|
||||
}
|
||||
return fmt.Sprintf("antigravity/%s windows/amd64", defaultUserAgentVersion)
|
||||
return fmt.Sprintf("antigravity/hub/%s windows/amd64", defaultUserAgentVersion)
|
||||
}
|
||||
|
||||
// GetUserAgentForContext 返回当前请求应使用的 User-Agent。
|
||||
|
||||
@@ -3,16 +3,119 @@
|
||||
package antigravity
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"net/url"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestBuildUserAgentUsesHubClientFamily(t *testing.T) {
|
||||
if got := BuildUserAgent(" 2.23.0 "); got != "antigravity/hub/2.23.0 windows/amd64" {
|
||||
t.Fatalf("Hub client family must be sent with the configured version: %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildUserAgentValidatesCustomVersion(t *testing.T) {
|
||||
previous := defaultUserAgentVersion
|
||||
defaultUserAgentVersion = "2.23.0"
|
||||
t.Cleanup(func() { defaultUserAgentVersion = previous })
|
||||
for _, tc := range []struct {
|
||||
version string
|
||||
want string
|
||||
}{
|
||||
{version: " 3.4.5 ", want: "antigravity/hub/3.4.5 windows/amd64"},
|
||||
{version: "", want: "antigravity/hub/2.23.0 windows/amd64"},
|
||||
{version: "hub/3.4.5", want: "antigravity/hub/2.23.0 windows/amd64"},
|
||||
{version: "3.4", want: "antigravity/hub/2.23.0 windows/amd64"},
|
||||
{version: "3.4.5\r\nInjected: header", want: "antigravity/hub/2.23.0 windows/amd64"},
|
||||
} {
|
||||
t.Run(tc.version, func(t *testing.T) {
|
||||
if got := BuildUserAgent(tc.version); got != tc.want {
|
||||
t.Fatalf("custom version must be validated before building Hub user agent: got %q, want %q", got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
type userAgentVersionTestContextKey struct{}
|
||||
|
||||
func withTestUserAgentVersionResolver(t *testing.T) {
|
||||
t.Helper()
|
||||
userAgentVersionMu.RLock()
|
||||
previous := userAgentVersionResolver
|
||||
userAgentVersionMu.RUnlock()
|
||||
SetUserAgentVersionResolver(func(ctx context.Context) string {
|
||||
version, _ := ctx.Value(userAgentVersionTestContextKey{}).(string)
|
||||
return version
|
||||
})
|
||||
t.Cleanup(func() { SetUserAgentVersionResolver(previous) })
|
||||
}
|
||||
|
||||
func TestGetUserAgentForContextPreservesVersionOverride(t *testing.T) {
|
||||
withTestUserAgentVersionResolver(t)
|
||||
previous := defaultUserAgentVersion
|
||||
defaultUserAgentVersion = "2.23.0"
|
||||
t.Cleanup(func() { defaultUserAgentVersion = previous })
|
||||
for _, tc := range []struct {
|
||||
version string
|
||||
want string
|
||||
}{
|
||||
{version: " 3.4.5 ", want: "antigravity/hub/3.4.5 windows/amd64"},
|
||||
{version: "invalid", want: "antigravity/hub/2.23.0 windows/amd64"},
|
||||
} {
|
||||
ctx := context.WithValue(context.Background(), userAgentVersionTestContextKey{}, tc.version)
|
||||
if got := GetUserAgentForContext(ctx); got != tc.want {
|
||||
t.Fatalf("context version override must use Hub family: got %q, want %q", got, tc.want)
|
||||
}
|
||||
}
|
||||
if got := GetUserAgentForContext(nil); got != "antigravity/hub/2.23.0 windows/amd64" {
|
||||
t.Fatalf("nil context must keep the default Hub user agent: %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetUserAgentEnvironmentOverride(t *testing.T) {
|
||||
const expectedVersionEnv = "SUB2API_TEST_EXPECTED_ANTIGRAVITY_VERSION"
|
||||
if expected := os.Getenv(expectedVersionEnv); expected != "" {
|
||||
if got := GetDefaultUserAgentVersion(); got != expected {
|
||||
t.Fatalf("environment version must be loaded during initialization: got %q, want %q", got, expected)
|
||||
}
|
||||
if got := GetUserAgent(); got != "antigravity/hub/"+expected+" windows/amd64" {
|
||||
t.Fatalf("environment override must keep Hub family: %q", got)
|
||||
}
|
||||
return
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
version string
|
||||
want string
|
||||
}{
|
||||
{version: " 3.4.5 ", want: "3.4.5"},
|
||||
{version: "invalid", want: "2.23.0"},
|
||||
} {
|
||||
t.Run(tc.version, func(t *testing.T) {
|
||||
binary, err := os.Executable()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
command := exec.Command(binary, "-test.run=^TestGetUserAgentEnvironmentOverride$")
|
||||
for _, variable := range os.Environ() {
|
||||
if !strings.HasPrefix(variable, AntigravityUserAgentVersionEnv+"=") && !strings.HasPrefix(variable, expectedVersionEnv+"=") {
|
||||
command.Env = append(command.Env, variable)
|
||||
}
|
||||
}
|
||||
command.Env = append(command.Env, AntigravityUserAgentVersionEnv+"="+tc.version, expectedVersionEnv+"="+tc.want)
|
||||
if output, err := command.CombinedOutput(); err != nil {
|
||||
t.Fatalf("environment override failed: %v\n%s", err, output)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// getClientSecret
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -693,7 +796,10 @@ func TestConstants_值正确(t *testing.T) {
|
||||
if RedirectURI != "http://localhost:8085/callback" {
|
||||
t.Errorf("RedirectURI 不匹配: got %s", RedirectURI)
|
||||
}
|
||||
if GetUserAgent() != "antigravity/2.9.1 windows/amd64" {
|
||||
if DefaultUserAgentVersion != "2.23.0" {
|
||||
t.Errorf("default Hub version must match the verified upstream release: got %s", DefaultUserAgentVersion)
|
||||
}
|
||||
if GetUserAgent() != "antigravity/hub/2.23.0 windows/amd64" {
|
||||
t.Errorf("UserAgent 不匹配: got %s", GetUserAgent())
|
||||
}
|
||||
if SessionTTL != 30*time.Minute {
|
||||
|
||||
@@ -588,6 +588,7 @@ func buildParts(content json.RawMessage, toolIDToName map[string]string, allowDu
|
||||
ID: block.ToolUseID,
|
||||
},
|
||||
})
|
||||
parts = append(parts, extractToolResultInlineParts(block.Content)...)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -638,6 +639,31 @@ func parseToolResultContent(content json.RawMessage, isError bool) string {
|
||||
return string(content)
|
||||
}
|
||||
|
||||
func extractToolResultInlineParts(content json.RawMessage) []GeminiPart {
|
||||
if len(content) == 0 {
|
||||
return nil
|
||||
}
|
||||
var innerBlocks []ContentBlock
|
||||
if err := json.Unmarshal(content, &innerBlocks); err != nil {
|
||||
return nil
|
||||
}
|
||||
var inlineParts []GeminiPart
|
||||
for _, item := range innerBlocks {
|
||||
if (item.Type == "image" || item.Type == "document") &&
|
||||
item.Source != nil &&
|
||||
item.Source.Type == "base64" &&
|
||||
strings.TrimSpace(item.Source.Data) != "" {
|
||||
inlineParts = append(inlineParts, GeminiPart{
|
||||
InlineData: &GeminiInlineData{
|
||||
MimeType: item.Source.MediaType,
|
||||
Data: item.Source.Data,
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
return inlineParts
|
||||
}
|
||||
|
||||
// buildGenerationConfig 构建 generationConfig
|
||||
const (
|
||||
defaultMaxOutputTokens = 64000
|
||||
|
||||
@@ -694,3 +694,64 @@ func TestToolConfigAlwaysPresent(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestTransformClaudeToGemini_ToolResultImagesReachUpstream(t *testing.T) {
|
||||
claudeReq := &ClaudeRequest{
|
||||
Model: "claude-sonnet-4-5",
|
||||
Messages: []ClaudeMessage{
|
||||
{
|
||||
Role: "assistant",
|
||||
Content: json.RawMessage(`[
|
||||
{"type":"tool_use","id":"toolu_img_1","name":"read_image","input":{"path":"colors.png"}}
|
||||
]`),
|
||||
},
|
||||
{
|
||||
Role: "user",
|
||||
Content: json.RawMessage(`[
|
||||
{
|
||||
"type":"tool_result",
|
||||
"tool_use_id":"toolu_img_1",
|
||||
"content":[
|
||||
{"type":"text","text":"loaded colors.png"},
|
||||
{"type":"image","source":{"type":"base64","media_type":"image/png","data":"aGVsbG8="}}
|
||||
]
|
||||
},
|
||||
{
|
||||
"type":"tool_result",
|
||||
"tool_use_id":"toolu_img_1",
|
||||
"content":[
|
||||
{"type":"image","source":{"type":"base64","media_type":"image/jpeg","data":"d29ybGQ="}}
|
||||
]
|
||||
}
|
||||
]`),
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
body, err := TransformClaudeToGeminiWithOptions(claudeReq, "project-1", "claude-sonnet-4-5", DefaultTransformOptions())
|
||||
require.NoError(t, err)
|
||||
|
||||
var req V1InternalRequest
|
||||
require.NoError(t, json.Unmarshal(body, &req))
|
||||
require.Len(t, req.Request.Contents, 2)
|
||||
|
||||
userParts := req.Request.Contents[1].Parts
|
||||
require.Len(t, userParts, 4)
|
||||
|
||||
require.NotNil(t, userParts[0].FunctionResponse)
|
||||
require.Equal(t, "read_image", userParts[0].FunctionResponse.Name)
|
||||
require.Equal(t, "toolu_img_1", userParts[0].FunctionResponse.ID)
|
||||
require.Equal(t, "loaded colors.png", userParts[0].FunctionResponse.Response["result"])
|
||||
|
||||
require.NotNil(t, userParts[1].InlineData)
|
||||
require.Equal(t, "image/png", userParts[1].InlineData.MimeType)
|
||||
require.Equal(t, "aGVsbG8=", userParts[1].InlineData.Data)
|
||||
|
||||
require.NotNil(t, userParts[2].FunctionResponse)
|
||||
require.Equal(t, "read_image", userParts[2].FunctionResponse.Name)
|
||||
require.Equal(t, "Command executed successfully.", userParts[2].FunctionResponse.Response["result"])
|
||||
|
||||
require.NotNil(t, userParts[3].InlineData)
|
||||
require.Equal(t, "image/jpeg", userParts[3].InlineData.MimeType)
|
||||
require.Equal(t, "d29ybGQ=", userParts[3].InlineData.Data)
|
||||
}
|
||||
@@ -277,11 +277,12 @@ func (p *NonStreamingProcessor) buildResponse(geminiResp *GeminiResponse, respon
|
||||
}
|
||||
|
||||
// 注意:Gemini 的 promptTokenCount 包含 cachedContentTokenCount,
|
||||
// 但 Claude 的 input_tokens 不包含 cache_read_input_tokens,需要减去
|
||||
// 但 Claude 的 input_tokens 不包含 cache_read_input_tokens,需要减去。
|
||||
// prompt 被拦截时上游可能只报 cachedContentTokenCount,差值下限为 0。
|
||||
usage := ClaudeUsage{}
|
||||
if geminiResp.UsageMetadata != nil {
|
||||
cached := geminiResp.UsageMetadata.CachedContentTokenCount
|
||||
usage.InputTokens = geminiResp.UsageMetadata.PromptTokenCount - cached
|
||||
usage.InputTokens = max(geminiResp.UsageMetadata.PromptTokenCount-cached, 0)
|
||||
usage.OutputTokens = geminiResp.UsageMetadata.CandidatesTokenCount + geminiResp.UsageMetadata.ThoughtsTokenCount
|
||||
usage.CacheReadInputTokens = cached
|
||||
usage.ImageOutputTokens = geminiResp.UsageMetadata.ImageOutputTokens()
|
||||
|
||||
@@ -109,10 +109,11 @@ func (p *StreamingProcessor) ProcessLine(line string) []byte {
|
||||
|
||||
// 更新 usage
|
||||
// 注意:Gemini 的 promptTokenCount 包含 cachedContentTokenCount,
|
||||
// 但 Claude 的 input_tokens 不包含 cache_read_input_tokens,需要减去
|
||||
// 但 Claude 的 input_tokens 不包含 cache_read_input_tokens,需要减去。
|
||||
// prompt 被拦截时上游可能只报 cachedContentTokenCount,差值下限为 0。
|
||||
if geminiResp.UsageMetadata != nil {
|
||||
cached := geminiResp.UsageMetadata.CachedContentTokenCount
|
||||
p.inputTokens = geminiResp.UsageMetadata.PromptTokenCount - cached
|
||||
p.inputTokens = max(geminiResp.UsageMetadata.PromptTokenCount-cached, 0)
|
||||
p.outputTokens = geminiResp.UsageMetadata.CandidatesTokenCount + geminiResp.UsageMetadata.ThoughtsTokenCount
|
||||
p.cacheReadTokens = cached
|
||||
p.imageOutputTokens = geminiResp.UsageMetadata.ImageOutputTokens()
|
||||
@@ -190,7 +191,7 @@ func (p *StreamingProcessor) emitMessageStart(v1Resp *V1InternalResponse) []byte
|
||||
usage := ClaudeUsage{}
|
||||
if v1Resp.Response.UsageMetadata != nil {
|
||||
cached := v1Resp.Response.UsageMetadata.CachedContentTokenCount
|
||||
usage.InputTokens = v1Resp.Response.UsageMetadata.PromptTokenCount - cached
|
||||
usage.InputTokens = max(v1Resp.Response.UsageMetadata.PromptTokenCount-cached, 0)
|
||||
usage.OutputTokens = v1Resp.Response.UsageMetadata.CandidatesTokenCount + v1Resp.Response.UsageMetadata.ThoughtsTokenCount
|
||||
usage.CacheReadInputTokens = cached
|
||||
usage.ImageOutputTokens = v1Resp.Response.UsageMetadata.ImageOutputTokens()
|
||||
|
||||
@@ -38,3 +38,29 @@ func TestGeminiUsageMapping_NoCacheCreationTokens(t *testing.T) {
|
||||
require.Zero(t, usage.CacheCreationInputTokens)
|
||||
})
|
||||
}
|
||||
|
||||
// usageMetadata 缺 promptTokenCount、只有 cachedContentTokenCount 时,input_tokens 下限为 0,
|
||||
// 缓存命中仍计入 cache_read_input_tokens。
|
||||
func TestGeminiUsageMapping_MissingPromptTokenCountKeepsInputNonNegative(t *testing.T) {
|
||||
const geminiBody = `{"candidates":[{"content":{"parts":[{"text":"hi"}],"role":"model"},"finishReason":"STOP"}],` +
|
||||
`"usageMetadata":{"cachedContentTokenCount":30}}`
|
||||
|
||||
t.Run("non-stream", func(t *testing.T) {
|
||||
_, usage, err := TransformGeminiToClaude([]byte(geminiBody), "gemini-3.1-pro-preview")
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, usage)
|
||||
require.Zero(t, usage.InputTokens)
|
||||
require.Equal(t, 30, usage.CacheReadInputTokens)
|
||||
})
|
||||
|
||||
t.Run("stream", func(t *testing.T) {
|
||||
p := NewStreamingProcessor("gemini-3.1-pro-preview")
|
||||
out := p.ProcessLine(`data: {"response":` + geminiBody + `}`)
|
||||
require.True(t, strings.Contains(string(out), `"message_start"`))
|
||||
require.NotContains(t, string(out), `"input_tokens":-`, "message_start 的 input_tokens 不应为负")
|
||||
_, usage := p.Finish()
|
||||
require.NotNil(t, usage)
|
||||
require.Zero(t, usage.InputTokens)
|
||||
require.Equal(t, 30, usage.CacheReadInputTokens)
|
||||
})
|
||||
}
|
||||
@@ -13,6 +13,12 @@ import (
|
||||
// Chat Completions intermediary round-trip (e.g. thinking, cache_control,
|
||||
// structured system prompts).
|
||||
func AnthropicToResponses(req *AnthropicRequest) (*ResponsesRequest, error) {
|
||||
return AnthropicToResponsesWithMinOutputTokens(req, DefaultMinMaxOutputTokens)
|
||||
}
|
||||
|
||||
// AnthropicToResponsesWithMinOutputTokens converts an Anthropic request using
|
||||
// the supplied max_output_tokens floor.
|
||||
func AnthropicToResponsesWithMinOutputTokens(req *AnthropicRequest, minOutputTokens int) (*ResponsesRequest, error) {
|
||||
if err := openai.ValidateGPT61SolReasoningEffort(req.Model, anthropicReasoningEffort(req)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -50,8 +56,8 @@ func AnthropicToResponses(req *AnthropicRequest) (*ResponsesRequest, error) {
|
||||
|
||||
if req.MaxTokens > 0 {
|
||||
v := req.MaxTokens
|
||||
if v < minMaxOutputTokens {
|
||||
v = minMaxOutputTokens
|
||||
if v < minOutputTokens {
|
||||
v = minOutputTokens
|
||||
}
|
||||
out.MaxOutputTokens = &v
|
||||
}
|
||||
|
||||
@@ -40,6 +40,12 @@ import (
|
||||
// ResponsesToChatCompletionsRequest but avoids materializing the intermediate
|
||||
// ResponsesRequest and the extra marshal/unmarshal cycle.
|
||||
func AnthropicToChatCompletionsRequest(req *AnthropicRequest) (*ChatCompletionsRequest, error) {
|
||||
return AnthropicToChatCompletionsRequestWithMinOutputTokens(req, DefaultMinMaxOutputTokens)
|
||||
}
|
||||
|
||||
// AnthropicToChatCompletionsRequestWithMinOutputTokens converts an Anthropic
|
||||
// Messages request using the supplied max_completion_tokens floor.
|
||||
func AnthropicToChatCompletionsRequestWithMinOutputTokens(req *AnthropicRequest, minOutputTokens int) (*ChatCompletionsRequest, error) {
|
||||
if req == nil {
|
||||
return nil, fmt.Errorf("anthropic request is nil")
|
||||
}
|
||||
@@ -63,8 +69,8 @@ func AnthropicToChatCompletionsRequest(req *AnthropicRequest) (*ChatCompletionsR
|
||||
|
||||
if req.MaxTokens > 0 {
|
||||
v := req.MaxTokens
|
||||
if v < minMaxOutputTokens {
|
||||
v = minMaxOutputTokens
|
||||
if v < minOutputTokens {
|
||||
v = minOutputTokens
|
||||
}
|
||||
out.MaxCompletionTokens = &v
|
||||
}
|
||||
|
||||
@@ -267,6 +267,43 @@ func TestAnthropicToChatCompletionsRequest_MaxTokensFloor(t *testing.T) {
|
||||
require.Equal(t, minMaxOutputTokens, *out.MaxCompletionTokens)
|
||||
}
|
||||
|
||||
func TestAnthropicToChatCompletionsRequestWithMinOutputTokens_ConfiguredFloor(t *testing.T) {
|
||||
req := &AnthropicRequest{
|
||||
Model: "claude-sonnet-4-20250514",
|
||||
MaxTokens: 16,
|
||||
Messages: []AnthropicMessage{{Role: "user", Content: json.RawMessage(`"hi"`)}},
|
||||
}
|
||||
|
||||
out, err := AnthropicToChatCompletionsRequestWithMinOutputTokens(req, 64)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, out.MaxCompletionTokens)
|
||||
require.Equal(t, 64, *out.MaxCompletionTokens)
|
||||
}
|
||||
|
||||
func TestAnthropicToResponses_ConfiguredMaxTokensFloor(t *testing.T) {
|
||||
for _, input := range []int{16, 64, 127} {
|
||||
req := &AnthropicRequest{
|
||||
Model: "claude-sonnet-4-20250514",
|
||||
MaxTokens: input,
|
||||
Messages: []AnthropicMessage{{Role: "user", Content: json.RawMessage(`"hi"`)}},
|
||||
}
|
||||
out, err := AnthropicToResponsesWithMinOutputTokens(req, 16)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, out.MaxOutputTokens)
|
||||
require.Equal(t, input, *out.MaxOutputTokens)
|
||||
}
|
||||
|
||||
req := &AnthropicRequest{
|
||||
Model: "claude-sonnet-4-20250514",
|
||||
MaxTokens: 1,
|
||||
Messages: []AnthropicMessage{{Role: "user", Content: json.RawMessage(`"hi"`)}},
|
||||
}
|
||||
out, err := AnthropicToResponsesWithMinOutputTokens(req, 16)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, out.MaxOutputTokens)
|
||||
require.Equal(t, 16, *out.MaxOutputTokens)
|
||||
}
|
||||
|
||||
func TestAnthropicToChatCompletionsRequest_ReasoningEffortMapping(t *testing.T) {
|
||||
req := &AnthropicRequest{
|
||||
Model: "gpt-5.4",
|
||||
|
||||
@@ -2,6 +2,7 @@ package apicompat
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
@@ -290,6 +291,46 @@ func mustMarshalJSON(t *testing.T, value any) []byte {
|
||||
}
|
||||
|
||||
func TestChatCompletionsToResponses_MaxTokens(t *testing.T) {
|
||||
t.Run("default floor", func(t *testing.T) {
|
||||
maxTokens := 1
|
||||
req := &ChatCompletionsRequest{
|
||||
Model: "gpt-4o",
|
||||
MaxTokens: &maxTokens,
|
||||
Messages: []ChatMessage{{Role: "user", Content: json.RawMessage(`"Hi"`)}},
|
||||
}
|
||||
resp, err := ChatCompletionsToResponses(req)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, resp.MaxOutputTokens)
|
||||
assert.Equal(t, DefaultMinMaxOutputTokens, *resp.MaxOutputTokens)
|
||||
})
|
||||
|
||||
t.Run("configured floor", func(t *testing.T) {
|
||||
for _, input := range []int{16, 64, 127, 128} {
|
||||
input := input
|
||||
t.Run(fmt.Sprintf("input_%d", input), func(t *testing.T) {
|
||||
req := &ChatCompletionsRequest{
|
||||
Model: "gpt-4o",
|
||||
MaxTokens: &input,
|
||||
Messages: []ChatMessage{{Role: "user", Content: json.RawMessage(`"Hi"`)}},
|
||||
}
|
||||
resp, err := ChatCompletionsToResponsesWithMinOutputTokens(req, 16)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, resp.MaxOutputTokens)
|
||||
assert.Equal(t, input, *resp.MaxOutputTokens)
|
||||
})
|
||||
}
|
||||
input := 1
|
||||
req := &ChatCompletionsRequest{
|
||||
Model: "gpt-4o",
|
||||
MaxTokens: &input,
|
||||
Messages: []ChatMessage{{Role: "user", Content: json.RawMessage(`"Hi"`)}},
|
||||
}
|
||||
resp, err := ChatCompletionsToResponsesWithMinOutputTokens(req, 16)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, resp.MaxOutputTokens)
|
||||
assert.Equal(t, 16, *resp.MaxOutputTokens)
|
||||
})
|
||||
|
||||
t.Run("max_tokens", func(t *testing.T) {
|
||||
maxTokens := 100
|
||||
req := &ChatCompletionsRequest{
|
||||
@@ -318,6 +359,21 @@ func TestChatCompletionsToResponses_MaxTokens(t *testing.T) {
|
||||
require.NotNil(t, resp.MaxOutputTokens)
|
||||
assert.Equal(t, 500, *resp.MaxOutputTokens)
|
||||
})
|
||||
|
||||
t.Run("max_completion_tokens_preferred before configured floor", func(t *testing.T) {
|
||||
maxTokens := 500
|
||||
maxCompletion := 1
|
||||
req := &ChatCompletionsRequest{
|
||||
Model: "gpt-4o",
|
||||
MaxTokens: &maxTokens,
|
||||
MaxCompletionTokens: &maxCompletion,
|
||||
Messages: []ChatMessage{{Role: "user", Content: json.RawMessage(`"Hi"`)}},
|
||||
}
|
||||
resp, err := ChatCompletionsToResponsesWithMinOutputTokens(req, 16)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, resp.MaxOutputTokens)
|
||||
assert.Equal(t, 16, *resp.MaxOutputTokens)
|
||||
})
|
||||
}
|
||||
|
||||
func TestChatCompletionsToResponses_ReasoningEffort(t *testing.T) {
|
||||
|
||||
@@ -18,6 +18,12 @@ type chatMessageContent struct {
|
||||
// true. store is always false and reasoning.encrypted_content is always
|
||||
// included so that the response translator has full context.
|
||||
func ChatCompletionsToResponses(req *ChatCompletionsRequest) (*ResponsesRequest, error) {
|
||||
return ChatCompletionsToResponsesWithMinOutputTokens(req, DefaultMinMaxOutputTokens)
|
||||
}
|
||||
|
||||
// ChatCompletionsToResponsesWithMinOutputTokens converts a Chat Completions
|
||||
// request using the supplied max_output_tokens floor.
|
||||
func ChatCompletionsToResponsesWithMinOutputTokens(req *ChatCompletionsRequest, minOutputTokens int) (*ResponsesRequest, error) {
|
||||
if err := openai.ValidateGPT61SolReasoningEffort(req.Model, req.ReasoningEffort); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -62,8 +68,8 @@ func ChatCompletionsToResponses(req *ChatCompletionsRequest) (*ResponsesRequest,
|
||||
}
|
||||
if maxTokens > 0 {
|
||||
v := maxTokens
|
||||
if v < minMaxOutputTokens {
|
||||
v = minMaxOutputTokens
|
||||
if v < minOutputTokens {
|
||||
v = minOutputTokens
|
||||
}
|
||||
out.MaxOutputTokens = &v
|
||||
}
|
||||
|
||||
@@ -860,6 +860,9 @@ func (d ChatDelta) reasoningText() *string {
|
||||
// Shared constants
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// minMaxOutputTokens is the floor for max_output_tokens in a Responses request.
|
||||
// Very small values may cause upstream API errors, so we enforce a minimum.
|
||||
const minMaxOutputTokens = 128
|
||||
// DefaultMinMaxOutputTokens is the default floor for max_output_tokens in a
|
||||
// Responses request. Very small values may cause upstream API errors, so we
|
||||
// enforce a minimum.
|
||||
const DefaultMinMaxOutputTokens = 128
|
||||
|
||||
const minMaxOutputTokens = DefaultMinMaxOutputTokens
|
||||
@@ -28,6 +28,7 @@ func DefaultModels() []Model {
|
||||
{Name: "models/gemini-3.1-pro-preview", SupportedGenerationMethods: methods},
|
||||
{Name: "models/gemini-3.1-pro-preview-customtools", SupportedGenerationMethods: methods},
|
||||
{Name: "models/gemini-3.1-flash-image", SupportedGenerationMethods: methods},
|
||||
{Name: "models/gemini-4-argon", SupportedGenerationMethods: methods},
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -20,6 +20,7 @@ var DefaultModels = []Model{
|
||||
{ID: "gemini-3-pro-preview", Type: "model", DisplayName: "Gemini 3 Pro Preview", CreatedAt: ""},
|
||||
{ID: "gemini-3.1-pro-preview", Type: "model", DisplayName: "Gemini 3.1 Pro Preview", CreatedAt: ""},
|
||||
{ID: "gemini-3.1-flash-image", Type: "model", DisplayName: "Gemini 3.1 Flash Image", CreatedAt: ""},
|
||||
{ID: "gemini-4-argon", Type: "model", DisplayName: "Gemini 4 Argon", CreatedAt: ""},
|
||||
}
|
||||
|
||||
// GoogleOneModels is the conservative model set exposed for legacy Google One
|
||||
|
||||
@@ -49,7 +49,7 @@ const codexOfficialClientFamilyPrefix = "codex "
|
||||
// 或在 bump context/codex 时同步补入本集合。
|
||||
var codexOfficialClientOriginators = map[string]bool{
|
||||
"codex_cli_rs": true, // CLI 默认 DEFAULT_ORIGINATOR
|
||||
"codex-tui": true, // 交互式 TUI(连字符,真实流量占比最高)
|
||||
CodexTUIOriginator: true, // 交互式 TUI(连字符,真实流量占比最高)
|
||||
"codex_vscode": true, // VSCode/Cursor 扩展
|
||||
"codex_vscode_copilot": true, // 扩展 GitHub Copilot 集成模式
|
||||
"codex_app": true, // 历史保留
|
||||
@@ -259,11 +259,43 @@ func canonicalizeCodexOriginator(name string) string {
|
||||
return name
|
||||
}
|
||||
|
||||
// CodexCLIOriginator 是 codex-rs 客户端的历史默认 originator,保留用于兼容识别。
|
||||
// CodexCLIOriginator 是 codex-rs 客户端的默认 originator。
|
||||
const CodexCLIOriginator = "codex_cli_rs"
|
||||
|
||||
// CodexDefaultOriginator 是网关默认使用的 Codex TUI originator。
|
||||
const CodexDefaultOriginator = "codex-tui"
|
||||
// CodexTUIOriginator 是交互式 Codex TUI 使用的 originator。
|
||||
const CodexTUIOriginator = "codex-tui"
|
||||
|
||||
// CodexDefaultOriginator 是网关默认发送的 Codex originator。
|
||||
// 历史 TUI 身份曾触发上游的身份风控分层,因此默认使用 CLI 身份;TUI 仍保留在官方身份集合中,
|
||||
// 供入站识别和兼容归一化。
|
||||
const CodexDefaultOriginator = CodexCLIOriginator
|
||||
|
||||
// NormalizeCodexClientIdentityToCLI 将已配对的 TUI 身份归一为 CLI 身份。
|
||||
// sub2api 历史默认 UA 使用 codex-tui;上游仓库的 #5198 记录了该身份会收到
|
||||
// server_is_overloaded,而相同请求改用 codex_cli_rs 可以成功。归一化必须同时改写
|
||||
// originator 和 User-Agent 首段,避免触发 #3901 的身份配对校验。
|
||||
//
|
||||
// 版本、操作系统、架构和终端指纹保持不变;尾部 `(name; version)` 客户端标识组
|
||||
// 属于 TUI 身份时移除,因为真实 CLI UA 不携带该组。
|
||||
func NormalizeCodexClientIdentityToCLI(originator, userAgent string) (string, string, bool) {
|
||||
if !strings.EqualFold(strings.TrimSpace(originator), CodexTUIOriginator) {
|
||||
return originator, userAgent, false
|
||||
}
|
||||
|
||||
ua := strings.TrimSpace(userAgent)
|
||||
slash := strings.IndexByte(ua, '/')
|
||||
if slash <= 0 {
|
||||
return CodexCLIOriginator, ua, true
|
||||
}
|
||||
|
||||
rest := ua[slash:]
|
||||
if trailer := codexUATrailerName(ua); trailer != "" && IsCodexOfficialClientOriginator(trailer) {
|
||||
if open := strings.LastIndex(rest, "("); open > 0 {
|
||||
rest = strings.TrimRight(rest[:open], " ")
|
||||
}
|
||||
}
|
||||
return CodexCLIOriginator, CodexCLIOriginator + rest, true
|
||||
}
|
||||
|
||||
// CodexUserAgentVersion 提取 Codex UA 的完整版本段,即 `{client}/{version} (...` 中的 version。
|
||||
// 与 ParseCodexEngineVersion 的区别:后者只取三段数字用于引擎版本比较(会丢掉 -alpha.4
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
package openai
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestNormalizeCodexClientIdentityToCLI(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
originator string
|
||||
userAgent string
|
||||
wantOriginator string
|
||||
wantUserAgent string
|
||||
wantChanged bool
|
||||
}{
|
||||
{
|
||||
name: "TUI 完整身份",
|
||||
originator: CodexTUIOriginator,
|
||||
userAgent: "codex-tui/0.163.0 (Windows 11; x86_64) WindowsTerminal (codex-tui; 0.163.0)",
|
||||
wantOriginator: CodexCLIOriginator,
|
||||
wantUserAgent: "codex_cli_rs/0.163.0 (Windows 11; x86_64) WindowsTerminal",
|
||||
wantChanged: true,
|
||||
},
|
||||
{
|
||||
name: "TUI 只有系统指纹",
|
||||
originator: CodexTUIOriginator,
|
||||
userAgent: "codex-tui/0.163.0 (Windows 11; x86_64) WindowsTerminal",
|
||||
wantOriginator: CodexCLIOriginator,
|
||||
wantUserAgent: "codex_cli_rs/0.163.0 (Windows 11; x86_64) WindowsTerminal",
|
||||
wantChanged: true,
|
||||
},
|
||||
{
|
||||
name: "CLI 身份保持不变",
|
||||
originator: CodexCLIOriginator,
|
||||
userAgent: "codex_cli_rs/0.163.0 (Windows 11; x86_64) WindowsTerminal",
|
||||
wantOriginator: CodexCLIOriginator,
|
||||
wantUserAgent: "codex_cli_rs/0.163.0 (Windows 11; x86_64) WindowsTerminal",
|
||||
wantChanged: false,
|
||||
},
|
||||
{
|
||||
name: "其他官方客户端保持不变",
|
||||
originator: "codex_vscode",
|
||||
userAgent: "codex_vscode/0.163.0 (Windows 11; x86_64) vscode (codex_vscode; 0.163.0)",
|
||||
wantOriginator: "codex_vscode",
|
||||
wantUserAgent: "codex_vscode/0.163.0 (Windows 11; x86_64) vscode (codex_vscode; 0.163.0)",
|
||||
wantChanged: false,
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
originator, userAgent, changed := NormalizeCodexClientIdentityToCLI(test.originator, test.userAgent)
|
||||
require.Equal(t, test.wantOriginator, originator)
|
||||
require.Equal(t, test.wantUserAgent, userAgent)
|
||||
require.Equal(t, test.wantChanged, changed)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeCodexClientIdentityToCLIIsPairedAndIdempotent(t *testing.T) {
|
||||
originator, userAgent, changed := NormalizeCodexClientIdentityToCLI(
|
||||
CodexTUIOriginator,
|
||||
"codex-tui/0.163.0 (Windows 11; x86_64) WindowsTerminal (codex-tui; 0.163.0)",
|
||||
)
|
||||
require.True(t, changed)
|
||||
|
||||
pairedOriginator, pairedUserAgent, ok := PairCodexClientIdentity(userAgent)
|
||||
require.True(t, ok)
|
||||
require.Equal(t, originator, pairedOriginator)
|
||||
require.Equal(t, userAgent, pairedUserAgent)
|
||||
|
||||
againOriginator, againUserAgent, changedAgain := NormalizeCodexClientIdentityToCLI(originator, userAgent)
|
||||
require.False(t, changedAgain)
|
||||
require.Equal(t, originator, againOriginator)
|
||||
require.Equal(t, userAgent, againUserAgent)
|
||||
}
|
||||
@@ -5,13 +5,18 @@ import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"slices"
|
||||
"strconv"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/redis/go-redis/v9"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -27,6 +32,12 @@ const (
|
||||
schedulerRetiredPrefix = "sched:retired:"
|
||||
schedulerSnapshotPrefix = "sched:"
|
||||
schedulerLockPrefix = "sched:lock:"
|
||||
// 账号精简记录(sched:meta:<id>)的修订号:全局修订号与按平台划分的修订号(前缀后接平台名)。
|
||||
// 改写精简记录后写入所涉平台的修订号;删除记录、改写平台为空或平台发生变化的记录、写入出错时写入全局修订号。
|
||||
// 取值都是新的随机串,读侧只比较是否相等,键丢失后重建也不会与旧取值相同;
|
||||
// Redis 回滚恢复出缓存记录过的旧取值时,由最长复用时长兜底。
|
||||
schedulerAccountMetaRevisionKey = "sched:meta:rev"
|
||||
schedulerAccountMetaPlatformRevisionPrefix = "sched:meta:rev:"
|
||||
|
||||
defaultSchedulerSnapshotMGetChunkSize = 128
|
||||
defaultSchedulerSnapshotWriteChunkSize = 256
|
||||
@@ -35,6 +46,16 @@ const (
|
||||
// snapshotGraceTTLSeconds 旧快照过期的宽限期(秒)。
|
||||
// 替代立即 DEL,让正在读取旧版本的 reader 有足够时间完成 ZRANGE。
|
||||
snapshotGraceTTLSeconds = 60
|
||||
|
||||
// schedulerSnapshotCacheMaxAge 是进程内快照缓存条目的最长复用时长,
|
||||
// 限定了未推进修订号的精简记录改写在本进程的最长可见延迟,与 outbox_lag_rebuild_seconds 默认 10 秒的陈旧容忍度相同。
|
||||
schedulerSnapshotCacheMaxAge = 10 * time.Second
|
||||
// schedulerSnapshotCacheEvictAge:写入条目时,加载时间早于该时长的其它条目一并清除,
|
||||
// 已退休分组的条目不会长期驻留。
|
||||
schedulerSnapshotCacheEvictAge = 10 * schedulerSnapshotCacheMaxAge
|
||||
|
||||
schedulerAccountMetaRevisionBytes = 16
|
||||
schedulerAccountMetaRevisionWriteTimeout = 3 * time.Second
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -223,6 +244,28 @@ type schedulerCache struct {
|
||||
rdb *redis.Client
|
||||
mgetChunkSize int
|
||||
writeChunkSize int
|
||||
|
||||
// now 是进程内快照缓存判定条目年龄的时钟。
|
||||
now func() time.Time
|
||||
|
||||
snapshotMu sync.RWMutex
|
||||
snapshotEntries map[string]*schedulerSnapshotEntry
|
||||
|
||||
// globalRevisionPending 与 globalRevisionWriting 合并写入出错后的后台全局修订号写入,见 scheduleGlobalAccountMetaRevision。
|
||||
globalRevisionPending atomic.Bool
|
||||
globalRevisionWriting atomic.Bool
|
||||
}
|
||||
|
||||
// schedulerSnapshotEntry 是一个 bucket 的已解码快照。
|
||||
// revisions 依次是全局修订号与该 bucket 成员可能涉及的各平台修订号(见 schedulerSnapshotTagKeys)。
|
||||
// accounts 是按快照顺序排列的母本,发布后只读,指针不外泄;
|
||||
// 每次读取都按值复制出本次请求独占的副本再套用 last_used。
|
||||
type schedulerSnapshotEntry struct {
|
||||
active string
|
||||
revisions []string
|
||||
loadedAt time.Time
|
||||
accounts []*service.Account
|
||||
lastUsedKeys []string
|
||||
}
|
||||
|
||||
func NewSchedulerCache(rdb *redis.Client) service.SchedulerCache {
|
||||
@@ -237,42 +280,67 @@ func newSchedulerCacheWithChunkSizes(rdb *redis.Client, mgetChunkSize, writeChun
|
||||
writeChunkSize = defaultSchedulerSnapshotWriteChunkSize
|
||||
}
|
||||
return &schedulerCache{
|
||||
rdb: rdb,
|
||||
mgetChunkSize: mgetChunkSize,
|
||||
writeChunkSize: writeChunkSize,
|
||||
rdb: rdb,
|
||||
mgetChunkSize: mgetChunkSize,
|
||||
writeChunkSize: writeChunkSize,
|
||||
now: time.Now,
|
||||
snapshotEntries: make(map[string]*schedulerSnapshotEntry),
|
||||
}
|
||||
}
|
||||
|
||||
// GetSnapshot 读取 bucket 的激活快照。解码后的精简记录按 bucket 常驻进程内存,
|
||||
// 只有 ready、active 版本、全局修订号与该 bucket 所涉平台的修订号都与 Redis 一致且未超过最长复用时长时才复用;
|
||||
// 否则重新从 Redis 加载。last_used 每次都从 Redis 读取。
|
||||
// 返回的账号对象由本次调用独占,可以修改其顶层字段;map、切片底层数组与指针指向的值与其它调用共享,不得原地修改。
|
||||
func (c *schedulerCache) GetSnapshot(ctx context.Context, bucket service.SchedulerBucket) ([]*service.Account, bool, error) {
|
||||
readyKey := schedulerBucketKey(schedulerReadyPrefix, bucket)
|
||||
readyVal, err := c.rdb.Get(ctx, readyKey).Result()
|
||||
if err == redis.Nil {
|
||||
return nil, false, nil
|
||||
}
|
||||
bucketKey := bucket.String()
|
||||
tagKeys := schedulerSnapshotTagKeys(bucket)
|
||||
tags, err := c.rdb.MGet(ctx, tagKeys...).Result()
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
if readyVal != "1" {
|
||||
return nil, false, nil
|
||||
}
|
||||
|
||||
activeKey := schedulerBucketKey(schedulerActivePrefix, bucket)
|
||||
activeVal, err := c.rdb.Get(ctx, activeKey).Result()
|
||||
if err == redis.Nil {
|
||||
return nil, false, nil
|
||||
if len(tags) != len(tagKeys) {
|
||||
return nil, false, fmt.Errorf("unexpected scheduler snapshot tag count: got %d, want %d", len(tags), len(tagKeys))
|
||||
}
|
||||
readyVal, err := schedulerCacheOptionalString(tags[0])
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
activeVal, err := schedulerCacheOptionalString(tags[1])
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
// 修订号缺失(nil)按空字符串比较:它是一个独立取值,不会与任何写入过的随机修订号相等。
|
||||
revisions := make([]string, 0, len(tags)-2)
|
||||
for _, tag := range tags[2:] {
|
||||
revision, err := schedulerCacheOptionalString(tag)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
revisions = append(revisions, revision)
|
||||
}
|
||||
if readyVal != "1" || activeVal == "" {
|
||||
c.dropSnapshotEntry(bucketKey)
|
||||
return nil, false, nil
|
||||
}
|
||||
|
||||
snapshotKey := schedulerSnapshotKey(bucket, activeVal)
|
||||
ids, err := c.rdb.ZRange(ctx, snapshotKey, 0, -1).Result()
|
||||
now := c.now()
|
||||
if entry := c.lookupSnapshotEntry(bucketKey); entry != nil && entry.matches(activeVal, revisions, now) {
|
||||
accounts, err := c.snapshotAccountsFromEntry(ctx, entry)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
return accounts, true, nil
|
||||
}
|
||||
|
||||
ids, err := c.rdb.ZRange(ctx, schedulerSnapshotKey(bucket, activeVal), 0, -1).Result()
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
// 空快照视为缓存未命中,触发数据库回退查询
|
||||
// 这解决了新分组创建后立即绑定账号时的竞态条件问题
|
||||
c.dropSnapshotEntry(bucketKey)
|
||||
return nil, false, nil
|
||||
}
|
||||
|
||||
@@ -286,29 +354,143 @@ func (c *schedulerCache) GetSnapshot(ctx context.Context, bucket service.Schedul
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
lastUsedValues, err := c.mgetChunked(ctx, lastUsedKeys)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
|
||||
accounts := make([]*service.Account, 0, len(values))
|
||||
for i, val := range values {
|
||||
masters := make([]*service.Account, 0, len(values))
|
||||
for _, val := range values {
|
||||
if val == nil {
|
||||
c.dropSnapshotEntry(bucketKey)
|
||||
return nil, false, nil
|
||||
}
|
||||
account, err := decodeCachedAccount(val)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
if err := applySchedulerLastUsed(account, lastUsedValues[i]); err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
accounts = append(accounts, account)
|
||||
masters = append(masters, account)
|
||||
}
|
||||
// 母本发布进缓存前由本 goroutine 完成预处理,发布后只读。
|
||||
for _, master := range masters {
|
||||
master.PrepareSharedSnapshot()
|
||||
}
|
||||
|
||||
// 条目记录的是加载前读到的 (active, 修订号) 与当时的时钟:精简记录读取晚于这组取值,
|
||||
// 之后若再有改写,修订号或 active 必然不同,或在最长复用时长后过期。
|
||||
entry := &schedulerSnapshotEntry{
|
||||
active: activeVal,
|
||||
revisions: revisions,
|
||||
loadedAt: now,
|
||||
accounts: masters,
|
||||
lastUsedKeys: lastUsedKeys,
|
||||
}
|
||||
c.storeSnapshotEntry(bucketKey, entry)
|
||||
|
||||
accounts, err := c.snapshotAccountsFromEntry(ctx, entry)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
return accounts, true, nil
|
||||
}
|
||||
|
||||
func (e *schedulerSnapshotEntry) matches(active string, revisions []string, now time.Time) bool {
|
||||
if e.active != active || !slices.Equal(e.revisions, revisions) {
|
||||
return false
|
||||
}
|
||||
age := now.Sub(e.loadedAt)
|
||||
return age >= 0 && age < schedulerSnapshotCacheMaxAge
|
||||
}
|
||||
|
||||
// snapshotAccountsFromEntry 读取最新 last_used,并为本次调用一次性分配一组母本副本。
|
||||
func (c *schedulerCache) snapshotAccountsFromEntry(ctx context.Context, entry *schedulerSnapshotEntry) ([]*service.Account, error) {
|
||||
lastUsedValues, err := c.mgetChunked(ctx, entry.lastUsedKeys)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(lastUsedValues) != len(entry.accounts) {
|
||||
return nil, fmt.Errorf("unexpected scheduler last_used value count: got %d, want %d", len(lastUsedValues), len(entry.accounts))
|
||||
}
|
||||
slab := make([]service.Account, len(entry.accounts))
|
||||
accounts := make([]*service.Account, len(entry.accounts))
|
||||
for i, master := range entry.accounts {
|
||||
slab[i] = *master
|
||||
account := &slab[i]
|
||||
if err := applySchedulerLastUsed(account, lastUsedValues[i]); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
accounts[i] = account
|
||||
}
|
||||
return accounts, nil
|
||||
}
|
||||
|
||||
func (c *schedulerCache) lookupSnapshotEntry(bucketKey string) *schedulerSnapshotEntry {
|
||||
c.snapshotMu.RLock()
|
||||
defer c.snapshotMu.RUnlock()
|
||||
return c.snapshotEntries[bucketKey]
|
||||
}
|
||||
|
||||
// storeSnapshotEntry 写入条目,并清除加载时间早于 schedulerSnapshotCacheEvictAge 的其它条目。
|
||||
// 已有条目的加载时间晚于新条目时保留已有条目:它基于更晚读到的 (active, 修订号)。
|
||||
func (c *schedulerCache) storeSnapshotEntry(bucketKey string, entry *schedulerSnapshotEntry) {
|
||||
c.snapshotMu.Lock()
|
||||
defer c.snapshotMu.Unlock()
|
||||
if current := c.snapshotEntries[bucketKey]; current == nil || !current.loadedAt.After(entry.loadedAt) {
|
||||
c.snapshotEntries[bucketKey] = entry
|
||||
}
|
||||
for key, other := range c.snapshotEntries {
|
||||
if key != bucketKey && entry.loadedAt.Sub(other.loadedAt) > schedulerSnapshotCacheEvictAge {
|
||||
delete(c.snapshotEntries, key)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *schedulerCache) dropSnapshotEntry(bucketKey string) {
|
||||
c.snapshotMu.RLock()
|
||||
_, ok := c.snapshotEntries[bucketKey]
|
||||
c.snapshotMu.RUnlock()
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
c.snapshotMu.Lock()
|
||||
delete(c.snapshotEntries, bucketKey)
|
||||
c.snapshotMu.Unlock()
|
||||
}
|
||||
|
||||
// schedulerSnapshotTagKeys 返回 GetSnapshot 一次读取的键:ready、active、全局修订号、bucket 平台的修订号,
|
||||
// mixed 模式再加 antigravity 平台的修订号。按平台判定失效依赖 bucket 成员只取自 bucket 平台
|
||||
// (mixed 模式另含开启混合调度的 antigravity 账号);账号平台发生变化时,写入方另行写入全局修订号。
|
||||
func schedulerSnapshotTagKeys(bucket service.SchedulerBucket) []string {
|
||||
keys := make([]string, 0, 5)
|
||||
keys = append(keys,
|
||||
schedulerBucketKey(schedulerReadyPrefix, bucket),
|
||||
schedulerBucketKey(schedulerActivePrefix, bucket),
|
||||
schedulerAccountMetaRevisionKey,
|
||||
schedulerAccountMetaRevisionKeyForPlatform(bucket.Platform),
|
||||
)
|
||||
if bucket.Mode == service.SchedulerModeMixed && bucket.Platform != service.PlatformAntigravity {
|
||||
keys = append(keys, schedulerAccountMetaRevisionKeyForPlatform(service.PlatformAntigravity))
|
||||
}
|
||||
return keys
|
||||
}
|
||||
|
||||
// schedulerAccountMetaRevisionKeyForPlatform 返回平台修订号的键;平台为空时返回全局修订号的键。
|
||||
func schedulerAccountMetaRevisionKeyForPlatform(platform string) string {
|
||||
if platform == "" {
|
||||
return schedulerAccountMetaRevisionKey
|
||||
}
|
||||
return schedulerAccountMetaPlatformRevisionPrefix + platform
|
||||
}
|
||||
|
||||
func schedulerCacheOptionalString(value any) (string, error) {
|
||||
switch typed := value.(type) {
|
||||
case nil:
|
||||
return "", nil
|
||||
case string:
|
||||
return typed, nil
|
||||
case []byte:
|
||||
return string(typed), nil
|
||||
default:
|
||||
return "", fmt.Errorf("unexpected scheduler cache value type: %T", value)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *schedulerCache) CaptureBucketWriteToken(ctx context.Context, bucket service.SchedulerBucket) (service.SchedulerBucketWriteToken, error) {
|
||||
result, err := captureBucketWriteTokenScript.Run(ctx, c.rdb, []string{
|
||||
schedulerBucketKey(schedulerEpochPrefix, bucket),
|
||||
@@ -604,7 +786,13 @@ func (c *schedulerCache) DeleteAccount(ctx context.Context, accountID int64) err
|
||||
return nil
|
||||
}
|
||||
id := strconv.FormatInt(accountID, 10)
|
||||
return c.rdb.Del(ctx, schedulerAccountKey(id), schedulerAccountMetaKey(id), schedulerLastUsedKey(id)).Err()
|
||||
// 删除精简记录与推进全局修订号在同一个 MULTI 中原子执行:读到删除结果的读者也读到新修订号,
|
||||
// 进程内快照缓存不会给出已删除的账号。
|
||||
pipe := c.rdb.TxPipeline()
|
||||
pipe.Del(ctx, schedulerAccountKey(id), schedulerAccountMetaKey(id), schedulerLastUsedKey(id))
|
||||
pipe.Set(ctx, schedulerAccountMetaRevisionKey, newSchedulerAccountMetaRevision(), 0)
|
||||
_, err := pipe.Exec(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *schedulerCache) UpdateLastUsed(ctx context.Context, updates map[int64]time.Time) error {
|
||||
@@ -614,6 +802,7 @@ func (c *schedulerCache) UpdateLastUsed(ctx context.Context, updates map[int64]t
|
||||
|
||||
pipe := c.rdb.Pipeline()
|
||||
queued := 0
|
||||
metaDeleted := false
|
||||
keys := make([]string, 0, schedulerLastUsedUpdateChunkSize*2)
|
||||
args := make([]any, 0, schedulerLastUsedUpdateChunkSize)
|
||||
queueBatch := func() {
|
||||
@@ -638,6 +827,7 @@ func (c *schedulerCache) UpdateLastUsed(ctx context.Context, updates map[int64]t
|
||||
idText := strconv.FormatInt(id, 10)
|
||||
pipe.Del(ctx, schedulerAccountKey(idText), schedulerAccountMetaKey(idText), schedulerLastUsedKey(idText))
|
||||
queued++
|
||||
metaDeleted = true
|
||||
continue
|
||||
}
|
||||
idText := strconv.FormatInt(id, 10)
|
||||
@@ -651,6 +841,10 @@ func (c *schedulerCache) UpdateLastUsed(ctx context.Context, updates map[int64]t
|
||||
if queued == 0 {
|
||||
return nil
|
||||
}
|
||||
if metaDeleted {
|
||||
// 被删账号的平台未知,全局修订号排在同一 pipeline 的 DEL 之后。
|
||||
pipe.Set(ctx, schedulerAccountMetaRevisionKey, newSchedulerAccountMetaRevision(), 0)
|
||||
}
|
||||
_, err := pipe.Exec(ctx)
|
||||
return err
|
||||
}
|
||||
@@ -776,21 +970,53 @@ func decodeCachedAccount(val any) (*service.Account, error) {
|
||||
return &account, nil
|
||||
}
|
||||
|
||||
// writeAccountIDs 分块写入整账号与精简记录,返回成功编码并写入的有序账号 ID。
|
||||
// 每块在追加下一个账号前才执行,最后一块总是非空;所涉平台的修订号追加在最后一块末尾,
|
||||
// 与最后一批精简记录同一次往返发出,且排在全部精简记录写入之后。
|
||||
// 精简记录用 SET ... GET 写入并取回旧值:旧值的平台与新平台不同时,旧平台 bucket 中可能仍缓存着该账号,
|
||||
// 全部写入完成后另行写入全局修订号。该检测尽力而为(客户端在 pipeline 内部重试时取回的可能已是本次写入的值),
|
||||
// 漏检由进程内快照缓存的最长复用时长兜底。
|
||||
// 任一块执行出错时,此前已执行的块与出错的块都可能已有精简记录生效,返回时启动后台写入全局修订号。
|
||||
func (c *schedulerCache) writeAccountIDs(ctx context.Context, accounts []service.Account) ([]int64, error) {
|
||||
if len(accounts) == 0 {
|
||||
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
|
||||
flush := func() error {
|
||||
if pending == 0 {
|
||||
return nil
|
||||
execFailed := false
|
||||
platformChanged := false
|
||||
defer func() {
|
||||
if execFailed {
|
||||
c.scheduleGlobalAccountMetaRevision(ctx)
|
||||
}
|
||||
if _, err := pipe.Exec(ctx); err != nil {
|
||||
}()
|
||||
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
|
||||
@@ -805,27 +1031,93 @@ func (c *schedulerCache) writeAccountIDs(ctx context.Context, accounts []service
|
||||
)
|
||||
continue
|
||||
}
|
||||
|
||||
id := strconv.FormatInt(account.ID, 10)
|
||||
pipe.Set(ctx, schedulerAccountKey(id), fullPayload, 0)
|
||||
pipe.Set(ctx, schedulerAccountMetaKey(id), metaPayload, 0)
|
||||
// Keep the hot LastUsedAt side key untouched: a lagging snapshot rebuild
|
||||
// must not overwrite a newer scheduler update.
|
||||
accountIDs = append(accountIDs, account.ID)
|
||||
pending++
|
||||
if pending >= c.writeChunkSize {
|
||||
if err := flush(); err != nil {
|
||||
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}),
|
||||
})
|
||||
// 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 err := flush(); err != nil {
|
||||
if pending == 0 {
|
||||
return accountIDs, nil
|
||||
}
|
||||
for _, platform := range platforms {
|
||||
pipe.Set(ctx, schedulerAccountMetaRevisionKeyForPlatform(platform), newSchedulerAccountMetaRevision(), 0)
|
||||
}
|
||||
if err := exec(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if platformChanged {
|
||||
c.advanceGlobalAccountMetaRevision(ctx)
|
||||
}
|
||||
return accountIDs, nil
|
||||
}
|
||||
|
||||
// schedulerMetaPlatformChanged 判断 SET ... GET 取回的旧精简记录是否属于另一个平台;
|
||||
// 旧值不是合法 JSON 或缺少字符串类型的顶层 Platform 时按已变化处理。
|
||||
func schedulerMetaPlatformChanged(previous *redis.StatusCmd, platform string) bool {
|
||||
raw, err := previous.Result()
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
if !gjson.Valid(raw) {
|
||||
return true
|
||||
}
|
||||
old := gjson.Get(raw, "Platform")
|
||||
return old.Type != gjson.String || old.Str != platform
|
||||
}
|
||||
|
||||
// scheduleGlobalAccountMetaRevision 在后台写入全局修订号,不阻塞调用方。
|
||||
// 同一时刻至多一个后台写入:写入前先清除待写标记,写完后标记再次被置位就再写一轮,
|
||||
// 因此每次调用之后都至少还有一次完整的写入发生在它之后。
|
||||
func (c *schedulerCache) scheduleGlobalAccountMetaRevision(ctx context.Context) {
|
||||
c.globalRevisionPending.Store(true)
|
||||
if !c.globalRevisionWriting.CompareAndSwap(false, true) {
|
||||
return
|
||||
}
|
||||
go func() {
|
||||
for {
|
||||
c.globalRevisionPending.Store(false)
|
||||
c.advanceGlobalAccountMetaRevision(ctx)
|
||||
c.globalRevisionWriting.Store(false)
|
||||
if !c.globalRevisionPending.Load() || !c.globalRevisionWriting.CompareAndSwap(false, true) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// advanceGlobalAccountMetaRevision 单独写入新的全局修订号,使所有 bucket 的进程内快照失效。
|
||||
// 不受调用方取消影响;失败只记录日志,由进程内快照缓存的最长复用时长兜底。
|
||||
func (c *schedulerCache) advanceGlobalAccountMetaRevision(ctx context.Context) {
|
||||
writeCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), schedulerAccountMetaRevisionWriteTimeout)
|
||||
defer cancel()
|
||||
if err := c.rdb.Set(writeCtx, schedulerAccountMetaRevisionKey, newSchedulerAccountMetaRevision(), 0).Err(); err != nil {
|
||||
slog.Warn("scheduler cache failed to advance account metadata revision", "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
func newSchedulerAccountMetaRevision() string {
|
||||
raw := make([]byte, schedulerAccountMetaRevisionBytes)
|
||||
// crypto/rand.Read 读取失败时直接终止进程,不会返回错误。
|
||||
_, _ = rand.Read(raw)
|
||||
return hex.EncodeToString(raw)
|
||||
}
|
||||
|
||||
func marshalSchedulerCacheAccount(account service.Account) ([]byte, []byte, error) {
|
||||
fullPayload, err := json.Marshal(account)
|
||||
if err != nil {
|
||||
|
||||
@@ -0,0 +1,980 @@
|
||||
//go:build unit
|
||||
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/alicebob/miniredis/v2"
|
||||
"github.com/redis/go-redis/v9"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// schedulerCacheCommandRecorder 记录发往 Redis 的命令(名称 + 首个参数)与每次 pipeline 执行的命令批次,
|
||||
// 并可让第 N 次 pipeline 执行失败。新连接的握手命令不计入。
|
||||
type schedulerCacheCommandRecorder struct {
|
||||
mu sync.Mutex
|
||||
commands []string
|
||||
batches [][]string
|
||||
pipelines int
|
||||
failPipelineAt int
|
||||
}
|
||||
|
||||
func (r *schedulerCacheCommandRecorder) DialHook(next redis.DialHook) redis.DialHook { return next }
|
||||
|
||||
func (r *schedulerCacheCommandRecorder) ProcessHook(next redis.ProcessHook) redis.ProcessHook {
|
||||
return func(ctx context.Context, cmd redis.Cmder) error {
|
||||
if !isSchedulerCacheHandshakeCommand(cmd) {
|
||||
r.record(cmd)
|
||||
}
|
||||
return next(ctx, cmd)
|
||||
}
|
||||
}
|
||||
|
||||
func (r *schedulerCacheCommandRecorder) ProcessPipelineHook(next redis.ProcessPipelineHook) redis.ProcessPipelineHook {
|
||||
return func(ctx context.Context, cmds []redis.Cmder) error {
|
||||
handshake := len(cmds) > 0
|
||||
for _, cmd := range cmds {
|
||||
handshake = handshake && isSchedulerCacheHandshakeCommand(cmd)
|
||||
}
|
||||
if handshake {
|
||||
return next(ctx, cmds)
|
||||
}
|
||||
r.mu.Lock()
|
||||
r.pipelines++
|
||||
fail := r.failPipelineAt > 0 && r.pipelines == r.failPipelineAt
|
||||
r.mu.Unlock()
|
||||
batch := make([]string, 0, len(cmds))
|
||||
for _, cmd := range cmds {
|
||||
batch = append(batch, r.record(cmd))
|
||||
}
|
||||
r.mu.Lock()
|
||||
r.batches = append(r.batches, batch)
|
||||
r.mu.Unlock()
|
||||
if fail {
|
||||
err := errors.New("injected pipeline failure")
|
||||
for _, cmd := range cmds {
|
||||
cmd.SetErr(err)
|
||||
}
|
||||
return err
|
||||
}
|
||||
return next(ctx, cmds)
|
||||
}
|
||||
}
|
||||
|
||||
func isSchedulerCacheHandshakeCommand(cmd redis.Cmder) bool {
|
||||
switch strings.ToLower(cmd.Name()) {
|
||||
case "hello", "auth", "client", "select":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func (r *schedulerCacheCommandRecorder) record(cmd redis.Cmder) string {
|
||||
entry := strings.ToLower(cmd.Name())
|
||||
if args := cmd.Args(); len(args) > 1 {
|
||||
entry += " " + fmt.Sprint(args[1])
|
||||
}
|
||||
r.mu.Lock()
|
||||
r.commands = append(r.commands, entry)
|
||||
r.mu.Unlock()
|
||||
return entry
|
||||
}
|
||||
|
||||
func (r *schedulerCacheCommandRecorder) reset() {
|
||||
r.mu.Lock()
|
||||
r.commands = nil
|
||||
r.batches = nil
|
||||
r.pipelines = 0
|
||||
r.mu.Unlock()
|
||||
}
|
||||
|
||||
func (r *schedulerCacheCommandRecorder) pipelineBatches() [][]string {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
return append([][]string(nil), r.batches...)
|
||||
}
|
||||
|
||||
func (r *schedulerCacheCommandRecorder) setFailPipelineAt(n int) {
|
||||
r.mu.Lock()
|
||||
r.failPipelineAt = n
|
||||
r.mu.Unlock()
|
||||
}
|
||||
|
||||
func (r *schedulerCacheCommandRecorder) recorded() []string {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
return append([]string(nil), r.commands...)
|
||||
}
|
||||
|
||||
func (r *schedulerCacheCommandRecorder) countPrefix(prefix string) int {
|
||||
count := 0
|
||||
for _, command := range r.recorded() {
|
||||
if strings.HasPrefix(command, prefix) {
|
||||
count++
|
||||
}
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
func newSchedulerCacheMemoUnit(t *testing.T, writeChunkSize int) (*schedulerCache, *miniredis.Miniredis, *schedulerCacheCommandRecorder) {
|
||||
t.Helper()
|
||||
mr := miniredis.RunT(t)
|
||||
rdb := redis.NewClient(&redis.Options{Addr: mr.Addr()})
|
||||
t.Cleanup(func() { _ = rdb.Close() })
|
||||
recorder := &schedulerCacheCommandRecorder{}
|
||||
rdb.AddHook(recorder)
|
||||
cache, ok := newSchedulerCacheWithChunkSizes(rdb, defaultSchedulerSnapshotMGetChunkSize, writeChunkSize).(*schedulerCache)
|
||||
require.True(t, ok)
|
||||
return cache, mr, recorder
|
||||
}
|
||||
|
||||
func memoTestBucket(groupID int64) service.SchedulerBucket {
|
||||
return service.SchedulerBucket{GroupID: groupID, Platform: service.PlatformAnthropic, Mode: service.SchedulerModeSingle}
|
||||
}
|
||||
|
||||
func memoTestAccount(id int64, name string) service.Account {
|
||||
return memoTestAccountOn(service.PlatformAnthropic, id, name)
|
||||
}
|
||||
|
||||
func memoTestAccountOn(platform string, id int64, name string) service.Account {
|
||||
return service.Account{
|
||||
ID: id,
|
||||
Name: name,
|
||||
Platform: platform,
|
||||
Type: service.AccountTypeOAuth,
|
||||
Status: service.StatusActive,
|
||||
Schedulable: true,
|
||||
Concurrency: 2,
|
||||
Credentials: map[string]any{
|
||||
"model_mapping": map[string]any{"claude-sonnet": "sonnet-" + name},
|
||||
"access_token": "dropped-by-projection",
|
||||
},
|
||||
Extra: map[string]any{"session_window_utilization": 0.25},
|
||||
}
|
||||
}
|
||||
|
||||
func memoPublish(t *testing.T, cache *schedulerCache, bucket service.SchedulerBucket, accounts ...service.Account) {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
token, err := cache.CaptureBucketWriteToken(ctx, bucket)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, cache.SetSnapshot(ctx, bucket, token, accounts))
|
||||
}
|
||||
|
||||
func memoRead(t *testing.T, cache *schedulerCache, bucket service.SchedulerBucket) []*service.Account {
|
||||
t.Helper()
|
||||
accounts, hit, err := cache.GetSnapshot(context.Background(), bucket)
|
||||
require.NoError(t, err)
|
||||
require.True(t, hit)
|
||||
return accounts
|
||||
}
|
||||
|
||||
func memoRequireMiss(t *testing.T, cache *schedulerCache, bucket service.SchedulerBucket) {
|
||||
t.Helper()
|
||||
accounts, hit, err := cache.GetSnapshot(context.Background(), bucket)
|
||||
require.NoError(t, err)
|
||||
require.False(t, hit)
|
||||
require.Nil(t, accounts)
|
||||
}
|
||||
|
||||
func memoIDs(accounts []*service.Account) []int64 {
|
||||
ids := make([]int64, 0, len(accounts))
|
||||
for _, account := range accounts {
|
||||
ids = append(ids, account.ID)
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
func memoRevision(t *testing.T, cache *schedulerCache, key string) string {
|
||||
t.Helper()
|
||||
revision, err := cache.rdb.Get(context.Background(), key).Result()
|
||||
if errors.Is(err, redis.Nil) {
|
||||
return ""
|
||||
}
|
||||
require.NoError(t, err)
|
||||
return revision
|
||||
}
|
||||
|
||||
// memoRevisionValue 读取修订号,不做断言,供 require.Eventually 的条件函数使用。
|
||||
func memoRevisionValue(cache *schedulerCache, key string) string {
|
||||
revision, _ := cache.rdb.Get(context.Background(), key).Result()
|
||||
return revision
|
||||
}
|
||||
|
||||
var memoAnthropicRevisionKey = schedulerAccountMetaRevisionKeyForPlatform(service.PlatformAnthropic)
|
||||
|
||||
func memoEntryCount(cache *schedulerCache) int {
|
||||
cache.snapshotMu.RLock()
|
||||
defer cache.snapshotMu.RUnlock()
|
||||
return len(cache.snapshotEntries)
|
||||
}
|
||||
|
||||
func TestSchedulerCacheSnapshotMemoSecondReadOnlyFetchesTagsAndLastUsed(t *testing.T) {
|
||||
cache, _, recorder := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize)
|
||||
bucket := memoTestBucket(101)
|
||||
memoPublish(t, cache, bucket, memoTestAccount(1, "a"), memoTestAccount(2, "b"), memoTestAccount(3, "c"))
|
||||
|
||||
recorder.reset()
|
||||
first := memoRead(t, cache, bucket)
|
||||
require.Equal(t, 1, recorder.countPrefix("zrange "))
|
||||
require.Equal(t, 1, recorder.countPrefix("mget "+schedulerAccountMetaPrefix))
|
||||
|
||||
recorder.reset()
|
||||
second := memoRead(t, cache, bucket)
|
||||
require.Equal(t, []string{
|
||||
"mget " + schedulerBucketKey(schedulerReadyPrefix, bucket),
|
||||
"mget " + schedulerLastUsedKey("1"),
|
||||
}, recorder.recorded())
|
||||
|
||||
require.Equal(t, []int64{1, 2, 3}, memoIDs(second))
|
||||
require.Equal(t, first, second)
|
||||
for i := range first {
|
||||
require.NotSame(t, first[i], second[i])
|
||||
}
|
||||
require.Equal(t, "sonnet-b", second[1].GetMappedModel("claude-sonnet"))
|
||||
require.NotContains(t, second[1].Credentials, "access_token")
|
||||
}
|
||||
|
||||
func TestSchedulerCacheSnapshotMemoLastUsedIsFreshAndCopiesAreIndependent(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
cache, _, recorder := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize)
|
||||
bucket := memoTestBucket(102)
|
||||
embedded := time.Now().UTC().Truncate(time.Millisecond).Add(-time.Hour)
|
||||
account := memoTestAccount(11, "a")
|
||||
account.LastUsedAt = &embedded
|
||||
memoPublish(t, cache, bucket, account)
|
||||
|
||||
first := memoRead(t, cache, bucket)
|
||||
require.Equal(t, embedded, *first[0].LastUsedAt)
|
||||
|
||||
latest := embedded.Add(42 * time.Second)
|
||||
require.NoError(t, cache.UpdateLastUsed(ctx, map[int64]time.Time{account.ID: latest}))
|
||||
recorder.reset()
|
||||
second := memoRead(t, cache, bucket)
|
||||
require.Zero(t, recorder.countPrefix("zrange "), "last_used updates must not invalidate the decoded snapshot")
|
||||
require.Equal(t, latest, *second[0].LastUsedAt)
|
||||
require.Equal(t, embedded, *first[0].LastUsedAt, "an earlier result must not observe later reads")
|
||||
|
||||
// 修改返回对象的顶层字段只影响本次结果。
|
||||
second[0].Schedulable = false
|
||||
second[0].Name = "mutated"
|
||||
second[0].LastUsedAt = nil
|
||||
second[0].Credentials = map[string]any{"model_mapping": map[string]any{"claude-sonnet": "replaced"}}
|
||||
require.Equal(t, "replaced", second[0].GetMappedModel("claude-sonnet"))
|
||||
|
||||
// 删除 last_used 侧键(不改精简记录):若母本曾被套用 last_used,这里会读到 latest。
|
||||
require.NoError(t, cache.rdb.Del(ctx, schedulerLastUsedKey("11")).Err())
|
||||
recorder.reset()
|
||||
third := memoRead(t, cache, bucket)
|
||||
require.Zero(t, recorder.countPrefix("zrange "))
|
||||
require.Equal(t, embedded, *third[0].LastUsedAt)
|
||||
require.True(t, third[0].Schedulable)
|
||||
require.Equal(t, "a", third[0].Name)
|
||||
require.Equal(t, "sonnet-a", third[0].GetMappedModel("claude-sonnet"))
|
||||
}
|
||||
|
||||
func TestSchedulerCacheSnapshotMemoSetAccountIsVisibleImmediately(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
cache, _, _ := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize)
|
||||
bucket := memoTestBucket(103)
|
||||
account := memoTestAccount(21, "a")
|
||||
memoPublish(t, cache, bucket, account, memoTestAccount(22, "b"))
|
||||
require.True(t, memoRead(t, cache, bucket)[0].Schedulable)
|
||||
|
||||
globalBefore := memoRevision(t, cache, schedulerAccountMetaRevisionKey)
|
||||
platformBefore := memoRevision(t, cache, memoAnthropicRevisionKey)
|
||||
account.Schedulable = false
|
||||
account.Extra = map[string]any{"session_window_utilization": 0.9}
|
||||
require.NoError(t, cache.SetAccount(ctx, &account))
|
||||
require.NotEqual(t, platformBefore, memoRevision(t, cache, memoAnthropicRevisionKey))
|
||||
require.Equal(t, globalBefore, memoRevision(t, cache, schedulerAccountMetaRevisionKey))
|
||||
|
||||
got := memoRead(t, cache, bucket)
|
||||
require.Equal(t, []int64{21, 22}, memoIDs(got))
|
||||
require.False(t, got[0].Schedulable)
|
||||
require.Equal(t, 0.9, got[0].Extra["session_window_utilization"])
|
||||
require.True(t, got[1].Schedulable)
|
||||
}
|
||||
|
||||
func TestSchedulerCacheSnapshotMemoDeleteAccountMisses(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
cache, _, _ := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize)
|
||||
bucket := memoTestBucket(104)
|
||||
memoPublish(t, cache, bucket, memoTestAccount(31, "a"), memoTestAccount(32, "b"))
|
||||
memoRead(t, cache, bucket)
|
||||
|
||||
revisionBefore := memoRevision(t, cache, schedulerAccountMetaRevisionKey)
|
||||
require.NoError(t, cache.DeleteAccount(ctx, 32))
|
||||
require.NotEqual(t, revisionBefore, memoRevision(t, cache, schedulerAccountMetaRevisionKey))
|
||||
memoRequireMiss(t, cache, bucket)
|
||||
require.Zero(t, memoEntryCount(cache))
|
||||
}
|
||||
|
||||
func TestSchedulerCacheSnapshotMemoCrossBucketMetadataRewrite(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
cache, _, _ := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize)
|
||||
bucketA := memoTestBucket(105)
|
||||
bucketB := memoTestBucket(106)
|
||||
shared := memoTestAccount(41, "shared")
|
||||
memoPublish(t, cache, bucketA, shared)
|
||||
memoPublish(t, cache, bucketB, shared, memoTestAccount(42, "b-only"))
|
||||
require.Equal(t, "shared", memoRead(t, cache, bucketB)[0].Name)
|
||||
activeB := cache.rdb.Get(ctx, schedulerBucketKey(schedulerActivePrefix, bucketB)).Val()
|
||||
|
||||
shared.Name = "shared-renamed"
|
||||
shared.Priority = 9
|
||||
memoPublish(t, cache, bucketA, shared)
|
||||
|
||||
require.Equal(t, activeB, cache.rdb.Get(ctx, schedulerBucketKey(schedulerActivePrefix, bucketB)).Val())
|
||||
got := memoRead(t, cache, bucketB)
|
||||
require.Equal(t, []int64{41, 42}, memoIDs(got))
|
||||
require.Equal(t, "shared-renamed", got[0].Name)
|
||||
require.Equal(t, 9, got[0].Priority)
|
||||
}
|
||||
|
||||
func TestSchedulerCacheSnapshotMemoUnencodableLastUsedDeletionMisses(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
cache, _, _ := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize)
|
||||
bucket := memoTestBucket(107)
|
||||
memoPublish(t, cache, bucket, memoTestAccount(51, "a"), memoTestAccount(52, "b"))
|
||||
memoRead(t, cache, bucket)
|
||||
|
||||
revisionBefore := memoRevision(t, cache, schedulerAccountMetaRevisionKey)
|
||||
invalid := time.Date(10000, time.January, 1, 0, 0, 0, 0, time.UTC)
|
||||
require.NoError(t, cache.UpdateLastUsed(ctx, map[int64]time.Time{52: invalid}))
|
||||
require.NotEqual(t, revisionBefore, memoRevision(t, cache, schedulerAccountMetaRevisionKey))
|
||||
memoRequireMiss(t, cache, bucket)
|
||||
|
||||
// 正常的 last_used 写入不推进任何修订号。
|
||||
globalAfterDelete := memoRevision(t, cache, schedulerAccountMetaRevisionKey)
|
||||
platformAfterDelete := memoRevision(t, cache, memoAnthropicRevisionKey)
|
||||
require.NoError(t, cache.UpdateLastUsed(ctx, map[int64]time.Time{51: time.Now()}))
|
||||
require.Equal(t, globalAfterDelete, memoRevision(t, cache, schedulerAccountMetaRevisionKey))
|
||||
require.Equal(t, platformAfterDelete, memoRevision(t, cache, memoAnthropicRevisionKey))
|
||||
}
|
||||
|
||||
func TestSchedulerCacheSnapshotMemoMembershipChangeByAccountIDs(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
cache, _, _ := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize)
|
||||
bucket := memoTestBucket(108)
|
||||
token, err := cache.CaptureBucketWriteToken(ctx, bucket)
|
||||
require.NoError(t, err)
|
||||
ids, err := cache.SetSnapshotAndReturnAccountIDs(ctx, bucket, token, []service.Account{memoTestAccount(61, "a"), memoTestAccount(62, "b")})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []int64{61, 62}, ids)
|
||||
require.Equal(t, []int64{61, 62}, memoIDs(memoRead(t, cache, bucket)))
|
||||
|
||||
globalBefore := memoRevision(t, cache, schedulerAccountMetaRevisionKey)
|
||||
platformBefore := memoRevision(t, cache, memoAnthropicRevisionKey)
|
||||
activeBefore := cache.rdb.Get(ctx, schedulerBucketKey(schedulerActivePrefix, bucket)).Val()
|
||||
token, err = cache.CaptureBucketWriteToken(ctx, bucket)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, cache.SetSnapshotByAccountIDs(ctx, bucket, token, []int64{62}))
|
||||
|
||||
require.Equal(t, globalBefore, memoRevision(t, cache, schedulerAccountMetaRevisionKey), "membership-only publishing does not touch metadata")
|
||||
require.Equal(t, platformBefore, memoRevision(t, cache, memoAnthropicRevisionKey), "membership-only publishing does not touch metadata")
|
||||
require.NotEqual(t, activeBefore, cache.rdb.Get(ctx, schedulerBucketKey(schedulerActivePrefix, bucket)).Val())
|
||||
require.Equal(t, []int64{62}, memoIDs(memoRead(t, cache, bucket)))
|
||||
}
|
||||
|
||||
func TestSchedulerCacheSnapshotMemoRetireReopenAndRepublish(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
cache, _, _ := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize)
|
||||
bucket := memoTestBucket(109)
|
||||
memoPublish(t, cache, bucket, memoTestAccount(71, "before"))
|
||||
memoRead(t, cache, bucket)
|
||||
|
||||
require.NoError(t, cache.RetireBucket(ctx, bucket))
|
||||
memoRequireMiss(t, cache, bucket)
|
||||
require.Zero(t, memoEntryCount(cache))
|
||||
|
||||
token, err := cache.ReopenBucket(ctx, bucket)
|
||||
require.NoError(t, err)
|
||||
memoRequireMiss(t, cache, bucket)
|
||||
|
||||
require.NoError(t, cache.SetSnapshot(ctx, bucket, token, []service.Account{memoTestAccount(72, "after")}))
|
||||
got := memoRead(t, cache, bucket)
|
||||
require.Equal(t, []int64{72}, memoIDs(got))
|
||||
require.Equal(t, "after", got[0].Name)
|
||||
}
|
||||
|
||||
func TestSchedulerCacheSnapshotMemoEmptyAndNilMetadataAreNotCached(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
cache, _, _ := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize)
|
||||
|
||||
t.Run("empty zset", func(t *testing.T) {
|
||||
bucket := memoTestBucket(110)
|
||||
_, err := cache.writeAccountIDs(ctx, []service.Account{memoTestAccount(81, "a")})
|
||||
require.NoError(t, err)
|
||||
memoPublish(t, cache, bucket)
|
||||
memoRequireMiss(t, cache, bucket)
|
||||
|
||||
active := cache.rdb.Get(ctx, schedulerBucketKey(schedulerActivePrefix, bucket)).Val()
|
||||
require.NotEmpty(t, active)
|
||||
require.NoError(t, cache.rdb.ZAdd(ctx, schedulerSnapshotKey(bucket, active), redis.Z{Score: 0, Member: "81"}).Err())
|
||||
require.Equal(t, []int64{81}, memoIDs(memoRead(t, cache, bucket)))
|
||||
})
|
||||
|
||||
t.Run("nil metadata", func(t *testing.T) {
|
||||
bucket := memoTestBucket(111)
|
||||
memoPublish(t, cache, bucket, memoTestAccount(91, "a"), memoTestAccount(92, "b"))
|
||||
metaKey := schedulerAccountMetaKey("92")
|
||||
payload, err := cache.rdb.Get(ctx, metaKey).Bytes()
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, cache.rdb.Del(ctx, metaKey).Err())
|
||||
memoRequireMiss(t, cache, bucket)
|
||||
|
||||
require.NoError(t, cache.rdb.Set(ctx, metaKey, payload, 0).Err())
|
||||
require.Equal(t, []int64{91, 92}, memoIDs(memoRead(t, cache, bucket)))
|
||||
})
|
||||
}
|
||||
|
||||
func TestSchedulerCacheSnapshotMemoDecodeFailureIsNotCached(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
cache, _, _ := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize)
|
||||
bucket := memoTestBucket(112)
|
||||
memoPublish(t, cache, bucket, memoTestAccount(101, "a"))
|
||||
metaKey := schedulerAccountMetaKey("101")
|
||||
payload, err := cache.rdb.Get(ctx, metaKey).Bytes()
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, cache.rdb.Set(ctx, metaKey, "{not-json", 0).Err())
|
||||
|
||||
accounts, hit, err := cache.GetSnapshot(ctx, bucket)
|
||||
require.Error(t, err)
|
||||
require.False(t, hit)
|
||||
require.Nil(t, accounts)
|
||||
require.Zero(t, memoEntryCount(cache))
|
||||
|
||||
require.NoError(t, cache.rdb.Set(ctx, metaKey, payload, 0).Err())
|
||||
require.Equal(t, "a", memoRead(t, cache, bucket)[0].Name)
|
||||
}
|
||||
|
||||
func TestSchedulerCacheSnapshotMemoRedisErrorIsReturned(t *testing.T) {
|
||||
cache, mr, _ := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize)
|
||||
bucket := memoTestBucket(113)
|
||||
memoPublish(t, cache, bucket, memoTestAccount(111, "a"))
|
||||
memoRead(t, cache, bucket)
|
||||
|
||||
mr.SetError("injected failure")
|
||||
accounts, hit, err := cache.GetSnapshot(context.Background(), bucket)
|
||||
require.Error(t, err)
|
||||
require.False(t, hit)
|
||||
require.Nil(t, accounts)
|
||||
|
||||
mr.SetError("")
|
||||
require.Equal(t, []int64{111}, memoIDs(memoRead(t, cache, bucket)))
|
||||
}
|
||||
|
||||
func TestSchedulerCacheSnapshotMemoConcurrentReadersAndWriters(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
cache, _, _ := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize)
|
||||
bucket := memoTestBucket(114)
|
||||
accounts := []service.Account{memoTestAccount(121, "a"), memoTestAccount(122, "b"), memoTestAccount(123, "c")}
|
||||
memoPublish(t, cache, bucket, accounts...)
|
||||
|
||||
var wg sync.WaitGroup
|
||||
for reader := 0; reader < 8; reader++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for i := 0; i < 40; i++ {
|
||||
got, hit, err := cache.GetSnapshot(ctx, bucket)
|
||||
if err != nil || !hit {
|
||||
t.Errorf("GetSnapshot: hit=%v err=%v", hit, err)
|
||||
return
|
||||
}
|
||||
for _, account := range got {
|
||||
if account.GetModelMapping()["claude-sonnet"] == "" {
|
||||
t.Errorf("account %d lost its model mapping", account.ID)
|
||||
return
|
||||
}
|
||||
_ = account.IsSchedulableForModel("claude-sonnet")
|
||||
_ = account.GetHeaderOverrides()
|
||||
account.Schedulable = !account.Schedulable
|
||||
account.LastUsedAt = nil
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
for writer := 0; writer < 2; writer++ {
|
||||
wg.Add(1)
|
||||
go func(writer int) {
|
||||
defer wg.Done()
|
||||
for i := 0; i < 20; i++ {
|
||||
account := memoTestAccount(int64(121+writer), fmt.Sprintf("w%d-%d", writer, i))
|
||||
account.Extra = map[string]any{"session_window_utilization": float64(i) / 100}
|
||||
if err := cache.SetAccount(ctx, &account); err != nil {
|
||||
t.Errorf("SetAccount: %v", err)
|
||||
return
|
||||
}
|
||||
if err := cache.UpdateLastUsed(ctx, map[int64]time.Time{account.ID: time.Now()}); err != nil {
|
||||
t.Errorf("UpdateLastUsed: %v", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
}(writer)
|
||||
}
|
||||
wg.Wait()
|
||||
|
||||
got := memoRead(t, cache, bucket)
|
||||
require.Equal(t, "w0-19", got[0].Name)
|
||||
require.Equal(t, "w1-19", got[1].Name)
|
||||
require.Equal(t, "c", got[2].Name)
|
||||
}
|
||||
|
||||
func TestSchedulerCacheSnapshotMemoWriteAccountIDsAdvancesRevision(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
geminiRevisionKey := schedulerAccountMetaRevisionKeyForPlatform(service.PlatformGemini)
|
||||
|
||||
t.Run("revisions share the last chunk", func(t *testing.T) {
|
||||
cache, _, recorder := newSchedulerCacheMemoUnit(t, 2)
|
||||
accounts := []service.Account{
|
||||
memoTestAccount(131, "a"),
|
||||
memoTestAccountOn(service.PlatformGemini, 132, "b"),
|
||||
memoTestAccount(133, "c"),
|
||||
}
|
||||
recorder.reset()
|
||||
ids, err := cache.writeAccountIDs(ctx, accounts)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []int64{131, 132, 133}, ids)
|
||||
|
||||
batches := recorder.pipelineBatches()
|
||||
require.Len(t, batches, 2, "one execution per chunk")
|
||||
require.Equal(t, []string{
|
||||
"set " + schedulerAccountKey("133"),
|
||||
"set " + schedulerAccountMetaKey("133"),
|
||||
"set " + memoAnthropicRevisionKey,
|
||||
"set " + geminiRevisionKey,
|
||||
}, batches[1])
|
||||
require.NotContains(t, strings.Join(batches[0], "\n"), schedulerAccountMetaRevisionKey)
|
||||
require.Equal(t, 2, recorder.countPrefix("set "+schedulerAccountMetaRevisionKey), "no revision write outside the last chunk")
|
||||
require.Empty(t, memoRevision(t, cache, schedulerAccountMetaRevisionKey))
|
||||
first := memoRevision(t, cache, memoAnthropicRevisionKey)
|
||||
require.Len(t, first, schedulerAccountMetaRevisionBytes*2)
|
||||
require.Len(t, memoRevision(t, cache, geminiRevisionKey), schedulerAccountMetaRevisionBytes*2)
|
||||
|
||||
_, err = cache.writeAccountIDs(ctx, accounts[:1])
|
||||
require.NoError(t, err)
|
||||
require.NotEqual(t, first, memoRevision(t, cache, memoAnthropicRevisionKey))
|
||||
})
|
||||
|
||||
t.Run("account count is a multiple of the chunk size", func(t *testing.T) {
|
||||
cache, _, recorder := newSchedulerCacheMemoUnit(t, 2)
|
||||
accounts := []service.Account{
|
||||
memoTestAccount(141, "a"), memoTestAccount(142, "b"),
|
||||
memoTestAccount(143, "c"), memoTestAccount(144, "d"),
|
||||
}
|
||||
recorder.reset()
|
||||
_, err := cache.writeAccountIDs(ctx, accounts)
|
||||
require.NoError(t, err)
|
||||
|
||||
batches := recorder.pipelineBatches()
|
||||
require.Len(t, batches, 2, "no extra execution for the revision")
|
||||
require.Equal(t, []string{
|
||||
"set " + schedulerAccountKey("143"),
|
||||
"set " + schedulerAccountMetaKey("143"),
|
||||
"set " + schedulerAccountKey("144"),
|
||||
"set " + schedulerAccountMetaKey("144"),
|
||||
"set " + memoAnthropicRevisionKey,
|
||||
}, batches[1])
|
||||
require.Len(t, recorder.recorded(), 9, "every command travels inside the two pipelines")
|
||||
})
|
||||
|
||||
t.Run("failure in a later chunk advances the global revision", func(t *testing.T) {
|
||||
cache, _, recorder := newSchedulerCacheMemoUnit(t, 1)
|
||||
accounts := []service.Account{memoTestAccount(151, "a"), memoTestAccount(152, "b"), memoTestAccount(153, "c")}
|
||||
bucket := memoTestBucket(115)
|
||||
memoPublish(t, cache, bucket, accounts...)
|
||||
memoRead(t, cache, bucket)
|
||||
globalBefore := memoRevision(t, cache, schedulerAccountMetaRevisionKey)
|
||||
platformBefore := memoRevision(t, cache, memoAnthropicRevisionKey)
|
||||
|
||||
renamed := []service.Account{memoTestAccount(151, "a2"), memoTestAccount(152, "b2"), memoTestAccount(153, "c2")}
|
||||
recorder.reset()
|
||||
recorder.setFailPipelineAt(2)
|
||||
_, err := cache.writeAccountIDs(ctx, renamed)
|
||||
require.Error(t, err)
|
||||
recorder.setFailPipelineAt(0)
|
||||
require.Eventually(t, func() bool {
|
||||
return memoRevisionValue(cache, schedulerAccountMetaRevisionKey) != globalBefore
|
||||
}, 2*time.Second, 5*time.Millisecond, "the global revision is advanced in the background")
|
||||
require.Equal(t, platformBefore, memoRevision(t, cache, memoAnthropicRevisionKey))
|
||||
|
||||
recorder.reset()
|
||||
got := memoRead(t, cache, bucket)
|
||||
require.Equal(t, 1, recorder.countPrefix("zrange "), "the cached snapshot must be reloaded")
|
||||
require.Equal(t, []string{"a2", "b", "c"}, []string{got[0].Name, got[1].Name, got[2].Name})
|
||||
})
|
||||
|
||||
t.Run("failure in the last chunk advances the global revision", func(t *testing.T) {
|
||||
cache, _, recorder := newSchedulerCacheMemoUnit(t, 2)
|
||||
recorder.reset()
|
||||
recorder.setFailPipelineAt(1)
|
||||
_, err := cache.writeAccountIDs(ctx, []service.Account{memoTestAccount(161, "a")})
|
||||
require.Error(t, err)
|
||||
recorder.setFailPipelineAt(0)
|
||||
require.Eventually(t, func() bool {
|
||||
return memoRevisionValue(cache, schedulerAccountMetaRevisionKey) != ""
|
||||
}, 2*time.Second, 5*time.Millisecond, "the global revision is advanced in the background")
|
||||
require.Empty(t, memoRevision(t, cache, memoAnthropicRevisionKey))
|
||||
})
|
||||
|
||||
t.Run("nothing encodable", func(t *testing.T) {
|
||||
cache, _, recorder := newSchedulerCacheMemoUnit(t, 1)
|
||||
invalid := time.Date(10000, time.January, 1, 0, 0, 0, 0, time.UTC)
|
||||
recorder.reset()
|
||||
ids, err := cache.writeAccountIDs(ctx, []service.Account{{ID: 171, Platform: service.PlatformAnthropic, ExpiresAt: &invalid}})
|
||||
require.NoError(t, err)
|
||||
require.Empty(t, ids)
|
||||
require.Empty(t, recorder.recorded())
|
||||
require.Empty(t, memoRevision(t, cache, schedulerAccountMetaRevisionKey))
|
||||
require.Empty(t, memoRevision(t, cache, memoAnthropicRevisionKey))
|
||||
})
|
||||
|
||||
t.Run("empty platform uses the global revision", func(t *testing.T) {
|
||||
cache, _, _ := newSchedulerCacheMemoUnit(t, 2)
|
||||
_, err := cache.writeAccountIDs(ctx, []service.Account{{ID: 181, Name: "no-platform"}})
|
||||
require.NoError(t, err)
|
||||
require.NotEmpty(t, memoRevision(t, cache, schedulerAccountMetaRevisionKey))
|
||||
})
|
||||
}
|
||||
|
||||
// memoReadExpectHit 读取一次并报告是否重新加载(发出过 ZRANGE)。
|
||||
func memoReadExpectHit(t *testing.T, cache *schedulerCache, recorder *schedulerCacheCommandRecorder, bucket service.SchedulerBucket) ([]*service.Account, bool) {
|
||||
t.Helper()
|
||||
recorder.reset()
|
||||
accounts := memoRead(t, cache, bucket)
|
||||
return accounts, recorder.countPrefix("zrange ") > 0
|
||||
}
|
||||
|
||||
func TestSchedulerCacheSnapshotMemoPlatformRevisionScopesInvalidation(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
cache, _, recorder := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize)
|
||||
geminiSingle := service.SchedulerBucket{GroupID: 201, Platform: service.PlatformGemini, Mode: service.SchedulerModeSingle}
|
||||
gemini := memoTestAccountOn(service.PlatformGemini, 211, "gemini")
|
||||
memoPublish(t, cache, geminiSingle, gemini)
|
||||
_, reloaded := memoReadExpectHit(t, cache, recorder, geminiSingle)
|
||||
require.True(t, reloaded)
|
||||
|
||||
anthropic := memoTestAccount(212, "anthropic")
|
||||
require.NoError(t, cache.SetAccount(ctx, &anthropic))
|
||||
recorder.reset()
|
||||
memoRead(t, cache, geminiSingle)
|
||||
require.Equal(t, []string{
|
||||
"mget " + schedulerBucketKey(schedulerReadyPrefix, geminiSingle),
|
||||
"mget " + schedulerLastUsedKey("211"),
|
||||
}, recorder.recorded(), "an Anthropic account write must not invalidate a Gemini bucket")
|
||||
|
||||
gemini.Name = "gemini-renamed"
|
||||
require.NoError(t, cache.SetAccount(ctx, &gemini))
|
||||
got, reloaded := memoReadExpectHit(t, cache, recorder, geminiSingle)
|
||||
require.True(t, reloaded)
|
||||
require.Equal(t, "gemini-renamed", got[0].Name)
|
||||
}
|
||||
|
||||
func TestSchedulerCacheSnapshotMemoPlatformChangeInvalidatesOldPlatformBuckets(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
cache, _, recorder := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize)
|
||||
geminiSingle := service.SchedulerBucket{GroupID: 202, Platform: service.PlatformGemini, Mode: service.SchedulerModeSingle}
|
||||
moved := memoTestAccountOn(service.PlatformGemini, 221, "moved")
|
||||
memoPublish(t, cache, geminiSingle, moved)
|
||||
globalBefore := memoRevision(t, cache, schedulerAccountMetaRevisionKey)
|
||||
|
||||
moved.Name = "same-platform"
|
||||
require.NoError(t, cache.SetAccount(ctx, &moved))
|
||||
require.Equal(t, globalBefore, memoRevision(t, cache, schedulerAccountMetaRevisionKey), "a same-platform rewrite only advances its platform revision")
|
||||
memoRead(t, cache, geminiSingle)
|
||||
|
||||
moved.Platform = service.PlatformAnthropic
|
||||
moved.Name = "now-anthropic"
|
||||
require.NoError(t, cache.SetAccount(ctx, &moved))
|
||||
require.NotEqual(t, globalBefore, memoRevision(t, cache, schedulerAccountMetaRevisionKey), "a platform change advances the global revision")
|
||||
|
||||
got, reloaded := memoReadExpectHit(t, cache, recorder, geminiSingle)
|
||||
require.True(t, reloaded, "the old platform bucket must drop the cached account")
|
||||
require.Equal(t, service.PlatformAnthropic, got[0].Platform)
|
||||
require.Equal(t, "now-anthropic", got[0].Name)
|
||||
}
|
||||
|
||||
func TestSchedulerCacheSnapshotMemoNewAccountOnlyAdvancesPlatformRevision(t *testing.T) {
|
||||
cache, _, _ := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize)
|
||||
fresh := memoTestAccountOn(service.PlatformGemini, 231, "fresh")
|
||||
require.NoError(t, cache.SetAccount(context.Background(), &fresh))
|
||||
require.Empty(t, memoRevision(t, cache, schedulerAccountMetaRevisionKey))
|
||||
require.NotEmpty(t, memoRevision(t, cache, schedulerAccountMetaRevisionKeyForPlatform(service.PlatformGemini)))
|
||||
}
|
||||
|
||||
func TestSchedulerCacheSnapshotMemoAntigravityRevisionInvalidatesMixedBuckets(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
cache, _, recorder := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize)
|
||||
antigravity := memoTestAccountOn(service.PlatformAntigravity, 221, "ag")
|
||||
antigravity.Extra = map[string]any{"mixed_scheduling": true}
|
||||
gemini := memoTestAccountOn(service.PlatformGemini, 222, "gemini")
|
||||
anthropic := memoTestAccount(223, "anthropic")
|
||||
|
||||
geminiMixed := service.SchedulerBucket{GroupID: 202, Platform: service.PlatformGemini, Mode: service.SchedulerModeMixed}
|
||||
anthropicMixed := service.SchedulerBucket{GroupID: 202, Platform: service.PlatformAnthropic, Mode: service.SchedulerModeMixed}
|
||||
geminiSingle := service.SchedulerBucket{GroupID: 202, Platform: service.PlatformGemini, Mode: service.SchedulerModeSingle}
|
||||
geminiForced := service.SchedulerBucket{GroupID: 202, Platform: service.PlatformGemini, Mode: service.SchedulerModeForced}
|
||||
memoPublish(t, cache, geminiMixed, gemini, antigravity)
|
||||
memoPublish(t, cache, anthropicMixed, anthropic, antigravity)
|
||||
memoPublish(t, cache, geminiSingle, gemini)
|
||||
memoPublish(t, cache, geminiForced, gemini)
|
||||
for _, bucket := range []service.SchedulerBucket{geminiMixed, anthropicMixed, geminiSingle, geminiForced} {
|
||||
memoRead(t, cache, bucket)
|
||||
}
|
||||
|
||||
antigravity.Name = "ag-renamed"
|
||||
require.NoError(t, cache.SetAccount(ctx, &antigravity))
|
||||
|
||||
got, reloaded := memoReadExpectHit(t, cache, recorder, geminiMixed)
|
||||
require.True(t, reloaded)
|
||||
require.Equal(t, "ag-renamed", got[1].Name)
|
||||
got, reloaded = memoReadExpectHit(t, cache, recorder, anthropicMixed)
|
||||
require.True(t, reloaded)
|
||||
require.Equal(t, "ag-renamed", got[1].Name)
|
||||
_, reloaded = memoReadExpectHit(t, cache, recorder, geminiSingle)
|
||||
require.False(t, reloaded, "single buckets never contain Antigravity accounts")
|
||||
_, reloaded = memoReadExpectHit(t, cache, recorder, geminiForced)
|
||||
require.False(t, reloaded, "forced buckets never contain Antigravity accounts")
|
||||
}
|
||||
|
||||
func TestSchedulerCacheSnapshotMemoGlobalRevisionInvalidatesEveryPlatform(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
buckets := []service.SchedulerBucket{
|
||||
{GroupID: 203, Platform: service.PlatformGemini, Mode: service.SchedulerModeSingle},
|
||||
{GroupID: 203, Platform: service.PlatformAnthropic, Mode: service.SchedulerModeSingle},
|
||||
{GroupID: 203, Platform: service.PlatformOpenAI, Mode: service.SchedulerModeSingle},
|
||||
}
|
||||
setup := func(t *testing.T) (*schedulerCache, *schedulerCacheCommandRecorder) {
|
||||
cache, _, recorder := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize)
|
||||
for i, bucket := range buckets {
|
||||
memoPublish(t, cache, bucket, memoTestAccountOn(bucket.Platform, int64(231+i), bucket.Platform))
|
||||
memoRead(t, cache, bucket)
|
||||
}
|
||||
// 不属于任何上述 bucket 的账号。
|
||||
unrelated := memoTestAccountOn(service.PlatformGrok, 239, "grok")
|
||||
require.NoError(t, cache.SetAccount(ctx, &unrelated))
|
||||
for _, bucket := range buckets {
|
||||
_, reloaded := memoReadExpectHit(t, cache, recorder, bucket)
|
||||
require.False(t, reloaded)
|
||||
}
|
||||
return cache, recorder
|
||||
}
|
||||
|
||||
t.Run("DeleteAccount", func(t *testing.T) {
|
||||
cache, recorder := setup(t)
|
||||
require.NoError(t, cache.DeleteAccount(ctx, 239))
|
||||
for _, bucket := range buckets {
|
||||
_, reloaded := memoReadExpectHit(t, cache, recorder, bucket)
|
||||
require.True(t, reloaded, bucket.String())
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("UpdateLastUsed unencodable deletion", func(t *testing.T) {
|
||||
cache, recorder := setup(t)
|
||||
invalid := time.Date(10000, time.January, 1, 0, 0, 0, 0, time.UTC)
|
||||
require.NoError(t, cache.UpdateLastUsed(ctx, map[int64]time.Time{239: invalid}))
|
||||
for _, bucket := range buckets {
|
||||
_, reloaded := memoReadExpectHit(t, cache, recorder, bucket)
|
||||
require.True(t, reloaded, bucket.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestSchedulerCacheSnapshotMemoFlushAllAndRepublishSameVersion(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
cache, mr, _ := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize)
|
||||
bucket := memoTestBucket(116)
|
||||
memoPublish(t, cache, bucket, memoTestAccount(141, "before"))
|
||||
require.Equal(t, "before", memoRead(t, cache, bucket)[0].Name)
|
||||
activeBefore := cache.rdb.Get(ctx, schedulerBucketKey(schedulerActivePrefix, bucket)).Val()
|
||||
|
||||
mr.FlushAll()
|
||||
memoPublish(t, cache, bucket, memoTestAccount(141, "after"))
|
||||
require.Equal(t, activeBefore, cache.rdb.Get(ctx, schedulerBucketKey(schedulerActivePrefix, bucket)).Val())
|
||||
require.Equal(t, "after", memoRead(t, cache, bucket)[0].Name)
|
||||
}
|
||||
|
||||
type memoTestClock struct {
|
||||
mu sync.Mutex
|
||||
now time.Time
|
||||
}
|
||||
|
||||
func (c *memoTestClock) Now() time.Time {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
return c.now
|
||||
}
|
||||
|
||||
func (c *memoTestClock) Advance(d time.Duration) {
|
||||
c.mu.Lock()
|
||||
c.now = c.now.Add(d)
|
||||
c.mu.Unlock()
|
||||
}
|
||||
|
||||
func TestSchedulerCacheSnapshotMemoMaxAgeBoundsUnversionedWrites(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
cache, _, _ := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize)
|
||||
clock := &memoTestClock{now: time.Date(2026, 10, 20, 8, 0, 0, 0, time.UTC)}
|
||||
cache.now = clock.Now
|
||||
bucket := memoTestBucket(117)
|
||||
memoPublish(t, cache, bucket, memoTestAccount(151, "old"))
|
||||
require.Equal(t, "old", memoRead(t, cache, bucket)[0].Name)
|
||||
|
||||
// 模拟不推进修订号的旧实例:直接改写精简记录。
|
||||
_, metaPayload, err := marshalSchedulerCacheAccount(memoTestAccount(151, "new"))
|
||||
require.NoError(t, err)
|
||||
globalBefore := memoRevision(t, cache, schedulerAccountMetaRevisionKey)
|
||||
platformBefore := memoRevision(t, cache, memoAnthropicRevisionKey)
|
||||
require.NoError(t, cache.rdb.Set(ctx, schedulerAccountMetaKey("151"), metaPayload, 0).Err())
|
||||
require.Equal(t, globalBefore, memoRevision(t, cache, schedulerAccountMetaRevisionKey))
|
||||
require.Equal(t, platformBefore, memoRevision(t, cache, memoAnthropicRevisionKey))
|
||||
|
||||
clock.Advance(schedulerSnapshotCacheMaxAge - time.Millisecond)
|
||||
require.Equal(t, "old", memoRead(t, cache, bucket)[0].Name)
|
||||
|
||||
clock.Advance(time.Millisecond)
|
||||
require.Equal(t, "new", memoRead(t, cache, bucket)[0].Name)
|
||||
}
|
||||
|
||||
func TestSchedulerCacheSnapshotMemoEvictsLongIdleEntries(t *testing.T) {
|
||||
cache, _, _ := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize)
|
||||
clock := &memoTestClock{now: time.Date(2026, 10, 20, 8, 0, 0, 0, time.UTC)}
|
||||
cache.now = clock.Now
|
||||
idle := memoTestBucket(118)
|
||||
recent := memoTestBucket(119)
|
||||
active := memoTestBucket(120)
|
||||
memoPublish(t, cache, idle, memoTestAccount(161, "idle"))
|
||||
memoPublish(t, cache, recent, memoTestAccount(162, "recent"))
|
||||
memoPublish(t, cache, active, memoTestAccount(163, "active"))
|
||||
|
||||
memoRead(t, cache, idle)
|
||||
clock.Advance(schedulerSnapshotCacheEvictAge / 2)
|
||||
memoRead(t, cache, recent)
|
||||
clock.Advance(schedulerSnapshotCacheEvictAge/2 + time.Second)
|
||||
memoRead(t, cache, active)
|
||||
|
||||
cache.snapshotMu.RLock()
|
||||
defer cache.snapshotMu.RUnlock()
|
||||
require.NotContains(t, cache.snapshotEntries, idle.String())
|
||||
require.Contains(t, cache.snapshotEntries, recent.String())
|
||||
require.Contains(t, cache.snapshotEntries, active.String())
|
||||
}
|
||||
|
||||
func TestSchedulerCacheSnapshotMemoKeepsNewerEntryOnLateStore(t *testing.T) {
|
||||
cache, _, _ := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize)
|
||||
base := time.Date(2026, 10, 20, 8, 0, 0, 0, time.UTC)
|
||||
newer := &schedulerSnapshotEntry{active: "2", revisions: []string{"r2"}, loadedAt: base.Add(time.Second)}
|
||||
older := &schedulerSnapshotEntry{active: "1", revisions: []string{"r1"}, loadedAt: base}
|
||||
cache.storeSnapshotEntry("b", newer)
|
||||
cache.storeSnapshotEntry("b", older)
|
||||
require.Same(t, newer, cache.lookupSnapshotEntry("b"))
|
||||
}
|
||||
|
||||
// 母本在发布前预解析了模型映射:副本命中时不计算签名。此处故意原地改写共享的原始映射,
|
||||
// 只用来观察副本走的是免签名路径(生产代码不会原地修改该 map)。
|
||||
func TestSchedulerCacheSnapshotMemoPreparesSharedModelMapping(t *testing.T) {
|
||||
cache, _, _ := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize)
|
||||
bucket := memoTestBucket(121)
|
||||
memoPublish(t, cache, bucket, memoTestAccount(171, "a"))
|
||||
memoRead(t, cache, bucket)
|
||||
|
||||
hit := memoRead(t, cache, bucket)[0]
|
||||
require.Equal(t, "sonnet-a", hit.GetMappedModel("claude-sonnet"))
|
||||
|
||||
replaced := memoRead(t, cache, bucket)[0]
|
||||
replaced.Credentials = map[string]any{"model_mapping": map[string]any{"claude-sonnet": "sonnet-replaced"}}
|
||||
require.Equal(t, "sonnet-replaced", replaced.GetMappedModel("claude-sonnet"))
|
||||
|
||||
probe := memoRead(t, cache, bucket)[0]
|
||||
rawMapping, ok := probe.Credentials["model_mapping"].(map[string]any)
|
||||
require.True(t, ok)
|
||||
rawMapping["claude-sonnet"] = "sonnet-mutated-in-place"
|
||||
require.Equal(t, "sonnet-a", probe.GetMappedModel("claude-sonnet"))
|
||||
}
|
||||
|
||||
func TestSchedulerCacheSnapshotMemoRevisionValuesAreUnique(t *testing.T) {
|
||||
seen := make(map[string]struct{}, 64)
|
||||
for i := 0; i < 64; i++ {
|
||||
revision := newSchedulerAccountMetaRevision()
|
||||
require.Len(t, revision, schedulerAccountMetaRevisionBytes*2)
|
||||
_, err := strconv.ParseUint(revision[:8], 16, 32)
|
||||
require.NoError(t, err)
|
||||
_, dup := seen[revision]
|
||||
require.False(t, dup)
|
||||
seen[revision] = struct{}{}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSchedulerCacheSnapshotMemoPlatformChangeInEarlierChunk(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
cache, _, _ := newSchedulerCacheMemoUnit(t, 1)
|
||||
require.NoError(t, cache.SetAccount(ctx, ptrAccount(memoTestAccountOn(service.PlatformGemini, 241, "moved"))))
|
||||
require.NoError(t, cache.SetAccount(ctx, ptrAccount(memoTestAccount(242, "stays"))))
|
||||
globalBefore := memoRevision(t, cache, schedulerAccountMetaRevisionKey)
|
||||
|
||||
_, err := cache.writeAccountIDs(ctx, []service.Account{
|
||||
memoTestAccount(241, "moved"),
|
||||
memoTestAccount(242, "stays"),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.NotEqual(t, globalBefore, memoRevision(t, cache, schedulerAccountMetaRevisionKey))
|
||||
}
|
||||
|
||||
func TestSchedulerCacheSnapshotMemoUnparsableOldMetadataAdvancesGlobalRevision(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
cache, mr, _ := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize)
|
||||
require.NoError(t, mr.Set(schedulerAccountMetaKey("251"), "not-json"))
|
||||
|
||||
require.NoError(t, cache.SetAccount(ctx, ptrAccount(memoTestAccount(251, "replaced"))))
|
||||
require.NotEmpty(t, memoRevision(t, cache, schedulerAccountMetaRevisionKey))
|
||||
}
|
||||
|
||||
func TestSchedulerCacheSnapshotMemoNilBeforeRealPipelineError(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
cache, mr, _ := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize)
|
||||
mr.HSet(schedulerAccountMetaKey("262"), "field", "value")
|
||||
|
||||
_, 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.Eventually(t, func() bool {
|
||||
return memoRevisionValue(cache, schedulerAccountMetaRevisionKey) != ""
|
||||
}, 2*time.Second, 5*time.Millisecond, "the global revision is advanced in the background")
|
||||
}
|
||||
|
||||
func TestSchedulerCacheSnapshotMemoCoalescesBackgroundGlobalRevisionWrites(t *testing.T) {
|
||||
cache, _, recorder := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize)
|
||||
recorder.reset()
|
||||
for range 50 {
|
||||
cache.scheduleGlobalAccountMetaRevision(context.Background())
|
||||
}
|
||||
require.Eventually(t, func() bool {
|
||||
return !cache.globalRevisionWriting.Load() && memoRevisionValue(cache, schedulerAccountMetaRevisionKey) != ""
|
||||
}, 2*time.Second, 5*time.Millisecond)
|
||||
writes := 0
|
||||
for _, command := range recorder.recorded() {
|
||||
if command == "set "+schedulerAccountMetaRevisionKey {
|
||||
writes++
|
||||
}
|
||||
}
|
||||
require.GreaterOrEqual(t, writes, 1)
|
||||
require.LessOrEqual(t, writes, 3, "concurrent schedules collapse into at most a couple of background writes")
|
||||
}
|
||||
|
||||
func ptrAccount(account service.Account) *service.Account {
|
||||
return &account
|
||||
}
|
||||
@@ -77,7 +77,7 @@ func createGroupIfNotExists(ctx context.Context, client *dbent.Client, name, pla
|
||||
SetSubscriptionType(service.SubscriptionTypeStandard).
|
||||
SetRateMultiplier(1.0).
|
||||
SetIsExclusive(false).
|
||||
SetAllowImageGeneration(platform == service.PlatformGrok).
|
||||
SetAllowImageGeneration(service.DefaultAllowImageGenerationForPlatform(platform)).
|
||||
Save(ctx)
|
||||
if err != nil {
|
||||
if dbent.IsConstraintError(err) {
|
||||
|
||||
@@ -34,11 +34,18 @@ func TestEnsureSimpleModeDefaultGroups_CreatesMissingDefaults(t *testing.T) {
|
||||
assertGroupExists(service.PlatformAntigravity + "-default-1")
|
||||
assertGroupExists(service.PlatformAntigravity + "-default-2")
|
||||
|
||||
grokDefault, err := client.Group.Query().
|
||||
Where(group.NameEQ(service.PlatformGrok+"-default"), group.DeletedAtIsNil()).
|
||||
Only(seedCtx)
|
||||
require.NoError(t, err)
|
||||
require.True(t, grokDefault.AllowImageGeneration)
|
||||
for _, name := range []string{
|
||||
service.PlatformGrok + "-default",
|
||||
service.PlatformGemini + "-default",
|
||||
service.PlatformAntigravity + "-default-1",
|
||||
service.PlatformAntigravity + "-default-2",
|
||||
} {
|
||||
imageDefault, err := client.Group.Query().
|
||||
Where(group.NameEQ(name), group.DeletedAtIsNil()).
|
||||
Only(seedCtx)
|
||||
require.NoError(t, err)
|
||||
require.True(t, imageDefault.AllowImageGeneration, "expected group %s to allow image generation", name)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnsureSimpleModeDefaultGroups_BackfillsOnlyAutoCreatedGrokDefault(t *testing.T) {
|
||||
|
||||
@@ -202,9 +202,10 @@ func (r *usageBillingRepository) applyUsageBillingEffects(ctx context.Context, t
|
||||
}
|
||||
}
|
||||
|
||||
if cmd.AccountQuotaCost > 0 && (strings.EqualFold(cmd.AccountType, service.AccountTypeAPIKey) || strings.EqualFold(cmd.AccountType, service.AccountTypeBedrock)) {
|
||||
quotaState, err := incrementUsageBillingAccountQuota(ctx, tx, cmd.AccountID, cmd.AccountQuotaCost)
|
||||
if err != nil {
|
||||
// 账号已不存在时跳过其配额计数,其余结算项不受影响。
|
||||
if cmd.AccountQuotaCost > 0 && service.AccountTypeSupportsQuota(cmd.AccountType) {
|
||||
quotaState, err := incrementUsageBillingAccountQuota(ctx, tx, cmd.AccountID, cmd.AccountQuotaCost, cmd.AccountQuotaHasDailyLimit, cmd.AccountQuotaHasWeeklyLimit)
|
||||
if err != nil && !errors.Is(err, service.ErrAccountNotFound) {
|
||||
return err
|
||||
}
|
||||
result.QuotaState = quotaState
|
||||
@@ -465,83 +466,130 @@ func incrementUsageBillingAPIKeyRateLimit(ctx context.Context, tx *sql.Tx, apiKe
|
||||
return nil
|
||||
}
|
||||
|
||||
func incrementUsageBillingAccountQuota(ctx context.Context, tx *sql.Tx, accountID int64, amount float64) (*service.AccountQuotaState, error) {
|
||||
rows, err := tx.QueryContext(ctx,
|
||||
`UPDATE accounts SET extra = (
|
||||
COALESCE(extra, '{}'::jsonb)
|
||||
|| jsonb_build_object('quota_used', COALESCE((extra->>'quota_used')::numeric, 0) + $1)
|
||||
// accountQuotaTotalIncrementExpr 累加总额度已用量。
|
||||
const accountQuotaTotalIncrementExpr = `COALESCE(extra, '{}'::jsonb)
|
||||
|| jsonb_build_object('quota_used', COALESCE((extra->>'quota_used')::numeric, 0) + $1)`
|
||||
|
||||
// accountQuotaDailyIncrementExpr 在库中设置了日上限时累加日用量,周期过期时从本次金额重新计数。
|
||||
const accountQuotaDailyIncrementExpr = `
|
||||
|| CASE WHEN COALESCE((extra->>'quota_daily_limit')::numeric, 0) > 0 THEN
|
||||
jsonb_build_object(
|
||||
'quota_daily_used',
|
||||
CASE WHEN `+dailyExpiredExpr+`
|
||||
CASE WHEN ` + dailyExpiredExpr + `
|
||||
THEN $1
|
||||
ELSE COALESCE((extra->>'quota_daily_used')::numeric, 0) + $1 END,
|
||||
'quota_daily_start',
|
||||
CASE WHEN `+dailyExpiredExpr+`
|
||||
THEN `+nowUTC+`
|
||||
ELSE COALESCE(extra->>'quota_daily_start', `+nowUTC+`) END
|
||||
CASE WHEN ` + dailyExpiredExpr + `
|
||||
THEN ` + nowUTC + `
|
||||
ELSE COALESCE(extra->>'quota_daily_start', ` + nowUTC + `) END
|
||||
)
|
||||
|| CASE WHEN `+dailyExpiredExpr+` AND `+nextDailyResetAtExpr+` IS NOT NULL
|
||||
THEN jsonb_build_object('quota_daily_reset_at', `+nextDailyResetAtExpr+`)
|
||||
|| CASE WHEN ` + dailyExpiredExpr + ` AND ` + nextDailyResetAtExpr + ` IS NOT NULL
|
||||
THEN jsonb_build_object('quota_daily_reset_at', ` + nextDailyResetAtExpr + `)
|
||||
ELSE '{}'::jsonb END
|
||||
ELSE '{}'::jsonb END
|
||||
ELSE '{}'::jsonb END`
|
||||
|
||||
// accountQuotaWeeklyIncrementExpr 在库中设置了周上限时累加周用量,周期过期时从本次金额重新计数。
|
||||
const accountQuotaWeeklyIncrementExpr = `
|
||||
|| CASE WHEN COALESCE((extra->>'quota_weekly_limit')::numeric, 0) > 0 THEN
|
||||
jsonb_build_object(
|
||||
'quota_weekly_used',
|
||||
CASE WHEN `+weeklyExpiredExpr+`
|
||||
CASE WHEN ` + weeklyExpiredExpr + `
|
||||
THEN $1
|
||||
ELSE COALESCE((extra->>'quota_weekly_used')::numeric, 0) + $1 END,
|
||||
'quota_weekly_start',
|
||||
CASE WHEN `+weeklyExpiredExpr+`
|
||||
THEN `+nowUTC+`
|
||||
ELSE COALESCE(extra->>'quota_weekly_start', `+nowUTC+`) END
|
||||
CASE WHEN ` + weeklyExpiredExpr + `
|
||||
THEN ` + nowUTC + `
|
||||
ELSE COALESCE(extra->>'quota_weekly_start', ` + nowUTC + `) END
|
||||
)
|
||||
|| CASE WHEN `+weeklyExpiredExpr+` AND `+nextWeeklyResetAtExpr+` IS NOT NULL
|
||||
THEN jsonb_build_object('quota_weekly_reset_at', `+nextWeeklyResetAtExpr+`)
|
||||
|| CASE WHEN ` + weeklyExpiredExpr + ` AND ` + nextWeeklyResetAtExpr + ` IS NOT NULL
|
||||
THEN jsonb_build_object('quota_weekly_reset_at', ` + nextWeeklyResetAtExpr + `)
|
||||
ELSE '{}'::jsonb END
|
||||
ELSE '{}'::jsonb END
|
||||
), updated_at = NOW()
|
||||
WHERE id = $2 AND deleted_at IS NULL
|
||||
ELSE '{}'::jsonb END`
|
||||
|
||||
// accountQuotaExtraIsObjectCond 要求 extra 为 JSON 对象:省略某个维度的语句只在对象上与完整语句等价。
|
||||
//
|
||||
// accountQuotaDailyLimitUnsetCond / accountQuotaWeeklyLimitUnsetCond 在库中未设置日/周上限时为真:
|
||||
// 键不存在、值为 JSON null 或不大于 0 的数字。其他取值一律为假,交给包含该维度的语句处理。
|
||||
// 三个条件都只使用 ->、jsonb_typeof 与 jsonb 比较,对任何行求值都不会报错。
|
||||
const (
|
||||
accountQuotaExtraIsObjectCond = `jsonb_typeof(extra) = 'object'`
|
||||
accountQuotaDailyLimitUnsetCond = `(extra->'quota_daily_limit' IS NULL
|
||||
OR jsonb_typeof(extra->'quota_daily_limit') = 'null'
|
||||
OR (jsonb_typeof(extra->'quota_daily_limit') = 'number' AND extra->'quota_daily_limit' <= '0'::jsonb))`
|
||||
accountQuotaWeeklyLimitUnsetCond = `(extra->'quota_weekly_limit' IS NULL
|
||||
OR jsonb_typeof(extra->'quota_weekly_limit') = 'null'
|
||||
OR (jsonb_typeof(extra->'quota_weekly_limit') = 'number' AND extra->'quota_weekly_limit' <= '0'::jsonb))`
|
||||
)
|
||||
|
||||
const accountQuotaIncrementReturning = `
|
||||
RETURNING
|
||||
COALESCE((extra->>'quota_used')::numeric, 0),
|
||||
COALESCE((extra->>'quota_limit')::numeric, 0),
|
||||
COALESCE((extra->>'quota_daily_used')::numeric, 0),
|
||||
COALESCE((extra->>'quota_daily_limit')::numeric, 0),
|
||||
COALESCE((extra->>'quota_weekly_used')::numeric, 0),
|
||||
COALESCE((extra->>'quota_weekly_limit')::numeric, 0)`,
|
||||
amount, accountID)
|
||||
COALESCE((extra->>'quota_weekly_limit')::numeric, 0)`
|
||||
|
||||
// accountQuotaIncrementSQLs 按 accountQuotaIncrementSQLIndex 存放账号配额累加语句。省略日或周维度的语句
|
||||
// 在 WHERE 中附加 accountQuotaExtraIsObjectCond 与被省略维度的未设置条件,条件不成立时命中 0 行;
|
||||
// 同时包含日、周维度的语句不附加这些条件,对任何账号配置都给出完整的累加结果。
|
||||
var accountQuotaIncrementSQLs = buildAccountQuotaIncrementSQLs()
|
||||
|
||||
func accountQuotaIncrementSQLIndex(daily, weekly bool) int {
|
||||
index := 0
|
||||
if daily {
|
||||
index |= 1
|
||||
}
|
||||
if weekly {
|
||||
index |= 2
|
||||
}
|
||||
return index
|
||||
}
|
||||
|
||||
func buildAccountQuotaIncrementSQLs() [4]string {
|
||||
var sqls [4]string
|
||||
for _, daily := range []bool{false, true} {
|
||||
for _, weekly := range []bool{false, true} {
|
||||
set := accountQuotaTotalIncrementExpr
|
||||
where := "id = $2 AND deleted_at IS NULL"
|
||||
if !daily || !weekly {
|
||||
where += "\n\t\t\tAND " + accountQuotaExtraIsObjectCond
|
||||
}
|
||||
if daily {
|
||||
set += accountQuotaDailyIncrementExpr
|
||||
} else {
|
||||
where += "\n\t\t\tAND " + accountQuotaDailyLimitUnsetCond
|
||||
}
|
||||
if weekly {
|
||||
set += accountQuotaWeeklyIncrementExpr
|
||||
} else {
|
||||
where += "\n\t\t\tAND " + accountQuotaWeeklyLimitUnsetCond
|
||||
}
|
||||
sqls[accountQuotaIncrementSQLIndex(daily, weekly)] = "UPDATE accounts SET extra = (\n\t\t\t" + set +
|
||||
"\n\t\t), updated_at = NOW()\n\t\tWHERE " + where + accountQuotaIncrementReturning
|
||||
}
|
||||
}
|
||||
return sqls
|
||||
}
|
||||
|
||||
// incrementUsageBillingAccountQuota 累加账号配额并返回累加后的状态。hasDaily/hasWeekly 是调用方所见的
|
||||
// 账号日/周上限设置,只决定先执行哪条语句;该语句的附加条件不成立而命中 0 行时,再执行同时包含日、周维度的语句。
|
||||
func incrementUsageBillingAccountQuota(ctx context.Context, tx *sql.Tx, accountID int64, amount float64, hasDaily, hasWeekly bool) (*service.AccountQuotaState, error) {
|
||||
index := accountQuotaIncrementSQLIndex(hasDaily, hasWeekly)
|
||||
fullIndex := accountQuotaIncrementSQLIndex(true, true)
|
||||
state, err := execAccountQuotaIncrement(ctx, tx, accountQuotaIncrementSQLs[index], accountID, amount)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var state service.AccountQuotaState
|
||||
if rows.Next() {
|
||||
if err := rows.Scan(
|
||||
&state.TotalUsed, &state.TotalLimit,
|
||||
&state.DailyUsed, &state.DailyLimit,
|
||||
&state.WeeklyUsed, &state.WeeklyLimit,
|
||||
); err != nil {
|
||||
_ = rows.Close()
|
||||
if state == nil && index != fullIndex {
|
||||
state, err = execAccountQuotaIncrement(ctx, tx, accountQuotaIncrementSQLs[fullIndex], accountID, amount)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
} else {
|
||||
if err := rows.Err(); err != nil {
|
||||
_ = rows.Close()
|
||||
return nil, err
|
||||
}
|
||||
_ = rows.Close()
|
||||
}
|
||||
if state == nil {
|
||||
return nil, service.ErrAccountNotFound
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
_ = rows.Close()
|
||||
return nil, err
|
||||
}
|
||||
// 必须在执行下一条 SQL 前显式关闭 rows:pq 驱动在同一连接上
|
||||
// 不允许前一条查询的结果集未耗尽时启动新查询,否则会返回
|
||||
// "unexpected Parse response" 错误。
|
||||
if err := rows.Close(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// 任意维度额度在本次递增中从"未超"跨越到"已超"时,必须刷新调度快照,
|
||||
// 否则 Redis 中缓存的 Account 仍显示旧的 used 值,后续请求会继续选中本账号,
|
||||
// 最终观察到 daily_used / weekly_used 大幅超过配置的 limit。
|
||||
@@ -556,5 +604,37 @@ func incrementUsageBillingAccountQuota(ctx context.Context, tx *sql.Tx, accountI
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return &state, nil
|
||||
return state, nil
|
||||
}
|
||||
|
||||
// execAccountQuotaIncrement 执行一条账号配额累加语句,未命中任何行时返回 nil 状态。
|
||||
func execAccountQuotaIncrement(ctx context.Context, tx *sql.Tx, query string, accountID int64, amount float64) (*service.AccountQuotaState, error) {
|
||||
rows, err := tx.QueryContext(ctx, query, amount, accountID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var state *service.AccountQuotaState
|
||||
if rows.Next() {
|
||||
state = &service.AccountQuotaState{}
|
||||
if err := rows.Scan(
|
||||
&state.TotalUsed, &state.TotalLimit,
|
||||
&state.DailyUsed, &state.DailyLimit,
|
||||
&state.WeeklyUsed, &state.WeeklyLimit,
|
||||
); err != nil {
|
||||
_ = rows.Close()
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
_ = rows.Close()
|
||||
return nil, err
|
||||
}
|
||||
// 必须在执行下一条 SQL 前显式关闭 rows:pq 驱动在同一连接上
|
||||
// 不允许前一条查询的结果集未耗尽时启动新查询,否则会返回
|
||||
// "unexpected Parse response" 错误。
|
||||
if err := rows.Close(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return state, nil
|
||||
}
|
||||
@@ -5,11 +5,13 @@ package repository
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"maps"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/lib/pq"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
@@ -217,6 +219,54 @@ func TestUsageBillingRepositoryApply_DeletedAPIKeyStillBillsBalance(t *testing.T
|
||||
require.Equal(t, 1, dedupCount)
|
||||
}
|
||||
|
||||
func TestUsageBillingRepositoryApply_DeletedAccountStillBillsBalance(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
client := testEntClient(t)
|
||||
repo := NewUsageBillingRepository(client, integrationDB)
|
||||
|
||||
user := mustCreateUser(t, client, &service.User{
|
||||
Email: fmt.Sprintf("usage-billing-deleted-account-user-%d@example.com", time.Now().UnixNano()),
|
||||
PasswordHash: "hash",
|
||||
Balance: 100,
|
||||
})
|
||||
apiKey := mustCreateApiKey(t, client, &service.APIKey{
|
||||
UserID: user.ID,
|
||||
Key: "sk-usage-billing-deleted-account-" + uuid.NewString(),
|
||||
Name: "billing-deleted-account",
|
||||
})
|
||||
account := mustCreateAccount(t, client, &service.Account{
|
||||
Name: "usage-billing-deleted-account-" + uuid.NewString(),
|
||||
Platform: service.PlatformGemini,
|
||||
Type: service.AccountTypeServiceAccount,
|
||||
})
|
||||
|
||||
_, err := integrationDB.ExecContext(ctx, "UPDATE accounts SET deleted_at = NOW() WHERE id = $1", account.ID)
|
||||
require.NoError(t, err)
|
||||
|
||||
requestID := uuid.NewString()
|
||||
result, err := repo.Apply(ctx, &service.UsageBillingCommand{
|
||||
RequestID: requestID,
|
||||
APIKeyID: apiKey.ID,
|
||||
UserID: user.ID,
|
||||
AccountID: account.ID,
|
||||
AccountType: service.AccountTypeServiceAccount,
|
||||
BalanceCost: 1.25,
|
||||
AccountQuotaCost: 1.25,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, result)
|
||||
require.True(t, result.Applied)
|
||||
require.Nil(t, result.QuotaState)
|
||||
|
||||
var balance float64
|
||||
require.NoError(t, integrationDB.QueryRowContext(ctx, "SELECT balance FROM users WHERE id = $1", user.ID).Scan(&balance))
|
||||
require.InDelta(t, 98.75, balance, 0.000001)
|
||||
|
||||
var dedupCount int
|
||||
require.NoError(t, integrationDB.QueryRowContext(ctx, "SELECT COUNT(*) FROM usage_billing_dedup WHERE request_id = $1 AND api_key_id = $2", requestID, apiKey.ID).Scan(&dedupCount))
|
||||
require.Equal(t, 1, dedupCount)
|
||||
}
|
||||
|
||||
func TestUsageBillingRepositoryApply_UpdatesAccountQuota(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
client := testEntClient(t)
|
||||
@@ -254,6 +304,60 @@ func TestUsageBillingRepositoryApply_UpdatesAccountQuota(t *testing.T) {
|
||||
require.InDelta(t, 3.5, quotaUsed, 0.000001)
|
||||
}
|
||||
|
||||
// service_account 只设总上限:累加 quota_used;日/周用量只在设置了对应 limit 时累加,未跨越上限不入队调度 outbox。
|
||||
func TestUsageBillingRepositoryApply_UpdatesServiceAccountQuota(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
client := testEntClient(t)
|
||||
repo := NewUsageBillingRepository(client, integrationDB)
|
||||
|
||||
user := mustCreateUser(t, client, &service.User{
|
||||
Email: fmt.Sprintf("usage-billing-sa-user-%d@example.com", time.Now().UnixNano()),
|
||||
PasswordHash: "hash",
|
||||
})
|
||||
apiKey := mustCreateApiKey(t, client, &service.APIKey{
|
||||
UserID: user.ID,
|
||||
Key: "sk-usage-billing-sa-" + uuid.NewString(),
|
||||
Name: "billing-sa",
|
||||
})
|
||||
account := mustCreateAccount(t, client, &service.Account{
|
||||
Name: "usage-billing-sa-quota-" + uuid.NewString(),
|
||||
Platform: service.PlatformGemini,
|
||||
Type: service.AccountTypeServiceAccount,
|
||||
Extra: map[string]any{
|
||||
"quota_limit": 100.0,
|
||||
},
|
||||
})
|
||||
|
||||
for _, cost := range []float64{2.25, 1.5} {
|
||||
_, err := repo.Apply(ctx, &service.UsageBillingCommand{
|
||||
RequestID: uuid.NewString(),
|
||||
APIKeyID: apiKey.ID,
|
||||
UserID: user.ID,
|
||||
AccountID: account.ID,
|
||||
AccountType: service.AccountTypeServiceAccount,
|
||||
AccountQuotaCost: cost,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
var quotaUsed float64
|
||||
var hasDailyUsed, hasWeeklyUsed bool
|
||||
require.NoError(t, integrationDB.QueryRowContext(ctx,
|
||||
"SELECT COALESCE((extra->>'quota_used')::numeric, 0), extra ? 'quota_daily_used', extra ? 'quota_weekly_used' FROM accounts WHERE id = $1",
|
||||
account.ID,
|
||||
).Scan("aUsed, &hasDailyUsed, &hasWeeklyUsed))
|
||||
require.InDelta(t, 3.75, quotaUsed, 0.000001)
|
||||
require.False(t, hasDailyUsed)
|
||||
require.False(t, hasWeeklyUsed)
|
||||
|
||||
var outboxCount int
|
||||
require.NoError(t, integrationDB.QueryRowContext(ctx,
|
||||
"SELECT COUNT(*) FROM scheduler_outbox WHERE event_type = $1 AND account_id = $2",
|
||||
service.SchedulerOutboxEventAccountChanged, account.ID,
|
||||
).Scan(&outboxCount))
|
||||
require.Zero(t, outboxCount, "service_account under its limit must not enqueue scheduler outbox")
|
||||
}
|
||||
|
||||
func TestUsageBillingRepositoryApply_EnqueuesSchedulerOutboxOnQuotaCrossing(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
client := testEntClient(t)
|
||||
@@ -340,6 +444,140 @@ func TestUsageBillingRepositoryApply_EnqueuesSchedulerOutboxOnQuotaCrossing(t *t
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 1, outboxCountFor(t, accountID), "single-shot crossing weekly limit should enqueue once")
|
||||
})
|
||||
|
||||
t.Run("total_first_crossing_enqueues", func(t *testing.T) {
|
||||
apiKeyID, accountID := newFixture(t, map[string]any{
|
||||
"quota_limit": 10.0,
|
||||
})
|
||||
_, err := repo.Apply(ctx, &service.UsageBillingCommand{
|
||||
RequestID: uuid.NewString(),
|
||||
APIKeyID: apiKeyID,
|
||||
AccountID: accountID,
|
||||
AccountType: service.AccountTypeAPIKey,
|
||||
AccountQuotaCost: 4,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 0, outboxCountFor(t, accountID), "below limit should not enqueue")
|
||||
|
||||
_, err = repo.Apply(ctx, &service.UsageBillingCommand{
|
||||
RequestID: uuid.NewString(),
|
||||
APIKeyID: apiKeyID,
|
||||
AccountID: accountID,
|
||||
AccountType: service.AccountTypeAPIKey,
|
||||
AccountQuotaCost: 8,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 1, outboxCountFor(t, accountID), "crossing total limit should enqueue once")
|
||||
})
|
||||
}
|
||||
|
||||
func TestIncrementUsageBillingAccountQuota_StatementVariantsMatchFullStatement(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
client := testEntClient(t)
|
||||
now := time.Now().UTC()
|
||||
at := func(offset time.Duration) string { return now.Add(offset).Format(time.RFC3339) }
|
||||
|
||||
// dailyUnset/weeklyUnset 为库中该维度视为未设置上限:省略该维度的语句在这些配置上命中,其余配置命中 0 行。
|
||||
configs := []struct {
|
||||
name string
|
||||
extra map[string]any
|
||||
rawExtra string
|
||||
dailyUnset bool
|
||||
weeklyUnset bool
|
||||
wantErr bool
|
||||
}{
|
||||
{name: "no_limits", extra: map[string]any{}, dailyUnset: true, weeklyUnset: true},
|
||||
{name: "total_only", extra: map[string]any{"quota_limit": 100.0, "quota_used": 3.0}, dailyUnset: true, weeklyUnset: true},
|
||||
{name: "zero_and_negative_period_limits", extra: map[string]any{"quota_limit": 5.0, "quota_daily_limit": 0.0, "quota_weekly_limit": -1.0}, dailyUnset: true, weeklyUnset: true},
|
||||
{name: "null_period_limits", extra: map[string]any{"quota_daily_limit": nil, "quota_weekly_limit": nil}, dailyUnset: true, weeklyUnset: true},
|
||||
{name: "string_period_limits", extra: map[string]any{"quota_daily_limit": "10", "quota_weekly_limit": "0"}},
|
||||
{name: "daily_rolling_active", extra: map[string]any{"quota_daily_limit": 10.0, "quota_daily_used": 4.0, "quota_daily_start": at(-time.Hour)}, weeklyUnset: true},
|
||||
{name: "daily_rolling_expired", extra: map[string]any{"quota_daily_limit": 10.0, "quota_daily_used": 9.0, "quota_daily_start": at(-30 * time.Hour)}, weeklyUnset: true},
|
||||
{name: "daily_fixed_expired", extra: map[string]any{
|
||||
"quota_daily_limit": 10.0, "quota_daily_used": 7.0, "quota_daily_reset_mode": "fixed",
|
||||
"quota_daily_reset_hour": 3, "quota_reset_timezone": "Asia/Shanghai", "quota_daily_reset_at": at(-2 * time.Hour),
|
||||
}, weeklyUnset: true},
|
||||
{name: "weekly_rolling_active", extra: map[string]any{"quota_weekly_limit": 50.0, "quota_weekly_used": 20.0, "quota_weekly_start": at(-48 * time.Hour)}, dailyUnset: true},
|
||||
{name: "weekly_fixed_expired", extra: map[string]any{
|
||||
"quota_weekly_limit": 50.0, "quota_weekly_used": 49.0, "quota_weekly_reset_mode": "fixed",
|
||||
"quota_weekly_reset_day": 1, "quota_weekly_reset_hour": 0, "quota_reset_timezone": "UTC", "quota_weekly_reset_at": at(-time.Hour),
|
||||
}, dailyUnset: true},
|
||||
{name: "daily_and_weekly", extra: map[string]any{
|
||||
"quota_limit": 100.0, "quota_daily_limit": 10.0, "quota_weekly_limit": 50.0,
|
||||
"quota_daily_used": 1.0, "quota_weekly_used": 2.0, "quota_daily_start": at(-time.Hour), "quota_weekly_start": at(-200 * time.Hour),
|
||||
}},
|
||||
{name: "array_extra", rawExtra: `[]`},
|
||||
{name: "scalar_extra", rawExtra: `"value"`},
|
||||
{name: "non_numeric_daily_limit", extra: map[string]any{"quota_daily_limit": "abc"}, weeklyUnset: true, wantErr: true},
|
||||
{name: "boolean_weekly_limit", extra: map[string]any{"quota_weekly_limit": true}, dailyUnset: true, wantErr: true},
|
||||
}
|
||||
|
||||
for _, cfg := range configs {
|
||||
for _, hints := range [][2]bool{{false, false}, {true, false}, {false, true}, {true, true}} {
|
||||
t.Run(fmt.Sprintf("%s/daily=%v/weekly=%v", cfg.name, hints[0], hints[1]), func(t *testing.T) {
|
||||
variant := mustCreateAccount(t, client, &service.Account{
|
||||
Name: "usage-billing-quota-variant-" + uuid.NewString(),
|
||||
Type: service.AccountTypeAPIKey,
|
||||
Extra: maps.Clone(cfg.extra),
|
||||
})
|
||||
reference := mustCreateAccount(t, client, &service.Account{
|
||||
Name: "usage-billing-quota-reference-" + uuid.NewString(),
|
||||
Type: service.AccountTypeAPIKey,
|
||||
Extra: maps.Clone(cfg.extra),
|
||||
})
|
||||
if cfg.rawExtra != "" {
|
||||
_, err := integrationDB.ExecContext(ctx, "UPDATE accounts SET extra = $1::jsonb WHERE id IN ($2, $3)", cfg.rawExtra, variant.ID, reference.ID)
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() {
|
||||
_, _ = integrationDB.ExecContext(ctx, "UPDATE accounts SET extra = '{}'::jsonb WHERE id IN ($1, $2)", variant.ID, reference.ID)
|
||||
})
|
||||
}
|
||||
|
||||
if cfg.wantErr {
|
||||
sqlState := func(accountID int64, daily, weekly bool) pq.ErrorCode {
|
||||
tx, err := integrationDB.BeginTx(ctx, nil)
|
||||
require.NoError(t, err)
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
_, err = incrementUsageBillingAccountQuota(ctx, tx, accountID, 2.5, daily, weekly)
|
||||
var pqErr *pq.Error
|
||||
require.ErrorAs(t, err, &pqErr)
|
||||
return pqErr.Code
|
||||
}
|
||||
require.Equal(t, sqlState(reference.ID, true, true), sqlState(variant.ID, hints[0], hints[1]))
|
||||
return
|
||||
}
|
||||
|
||||
tx, err := integrationDB.BeginTx(ctx, nil)
|
||||
require.NoError(t, err)
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
|
||||
isObject := cfg.rawExtra == ""
|
||||
wantHit := (hints[0] && hints[1]) || (isObject && (hints[0] || cfg.dailyUnset) && (hints[1] || cfg.weeklyUnset))
|
||||
_, err = tx.ExecContext(ctx, "SAVEPOINT quota_variant_probe")
|
||||
require.NoError(t, err)
|
||||
probe, err := execAccountQuotaIncrement(ctx, tx, accountQuotaIncrementSQLs[accountQuotaIncrementSQLIndex(hints[0], hints[1])], variant.ID, 2.5)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, wantHit, probe != nil, "variant statement hit")
|
||||
_, err = tx.ExecContext(ctx, "ROLLBACK TO SAVEPOINT quota_variant_probe")
|
||||
require.NoError(t, err)
|
||||
|
||||
got, err := incrementUsageBillingAccountQuota(ctx, tx, variant.ID, 2.5, hints[0], hints[1])
|
||||
require.NoError(t, err)
|
||||
want, err := incrementUsageBillingAccountQuota(ctx, tx, reference.ID, 2.5, true, true)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, *want, *got)
|
||||
|
||||
var gotExtra, wantExtra string
|
||||
var sameExtra, sameUpdatedAt bool
|
||||
require.NoError(t, tx.QueryRowContext(ctx,
|
||||
"SELECT v.extra::text, r.extra::text, v.extra = r.extra, v.updated_at = r.updated_at FROM accounts v, accounts r WHERE v.id = $1 AND r.id = $2",
|
||||
variant.ID, reference.ID,
|
||||
).Scan(&gotExtra, &wantExtra, &sameExtra, &sameUpdatedAt))
|
||||
require.True(t, sameExtra, "variant extra %s != reference extra %s", gotExtra, wantExtra)
|
||||
require.True(t, sameUpdatedAt)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDashboardAggregationRepositoryCleanupUsageBillingDedup_BatchDeletesOldRows(t *testing.T) {
|
||||
|
||||
@@ -5,6 +5,7 @@ package repository
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/DATA-DOG/go-sqlmock"
|
||||
@@ -22,6 +23,7 @@ const (
|
||||
userExistsForBillingSQL = `(?s)SELECT 1\s+FROM users\s+WHERE id = \$1 AND deleted_at IS NULL`
|
||||
apiKeyQuotaIncrementSQL = `(?s)UPDATE api_keys\s+SET quota_used = quota_used \+ \$1,.*WHERE id = \$2 AND deleted_at IS NULL\s+RETURNING`
|
||||
apiKeyRateLimitIncrementSQL = `(?s)UPDATE api_keys SET\s+usage_5h = .*WHERE id = \$2 AND deleted_at IS NULL`
|
||||
accountQuotaIncrementSQL = `(?s)UPDATE accounts SET extra = .*WHERE id = \$2 AND deleted_at IS NULL.*RETURNING`
|
||||
)
|
||||
|
||||
func TestDeductUsageBillingBalance_UsesSufficientBalanceGuard(t *testing.T) {
|
||||
@@ -137,6 +139,42 @@ func TestApplyUsageBillingEffects_DeletedAPIKeyStillBillsBalance(t *testing.T) {
|
||||
require.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
|
||||
func TestApplyUsageBillingEffects_DeletedAccountStillBillsBalance(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
db, mock, err := sqlmock.New()
|
||||
require.NoError(t, err)
|
||||
defer func() { _ = db.Close() }()
|
||||
|
||||
mock.ExpectBegin()
|
||||
tx, err := db.BeginTx(ctx, nil)
|
||||
require.NoError(t, err)
|
||||
mock.ExpectQuery(conditionalBalanceDeductSQL).
|
||||
WithArgs(10.0, int64(42)).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"balance"}).AddRow(90.0))
|
||||
mock.ExpectQuery(accountQuotaIncrementSQL).
|
||||
WithArgs(4.0, int64(9)).
|
||||
WillReturnRows(sqlmock.NewRows(accountQuotaStateColumns))
|
||||
mock.ExpectQuery(accountQuotaIncrementSQL).
|
||||
WithArgs(4.0, int64(9)).
|
||||
WillReturnRows(sqlmock.NewRows(accountQuotaStateColumns))
|
||||
mock.ExpectCommit()
|
||||
|
||||
result := &service.UsageBillingApplyResult{Applied: true}
|
||||
err = (&usageBillingRepository{}).applyUsageBillingEffects(ctx, tx, &service.UsageBillingCommand{
|
||||
UserID: 42,
|
||||
AccountID: 9,
|
||||
AccountType: service.AccountTypeServiceAccount,
|
||||
BalanceCost: 10,
|
||||
AccountQuotaCost: 4,
|
||||
}, result)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, result.NewBalance)
|
||||
require.InDelta(t, 90.0, *result.NewBalance, 0.000001)
|
||||
require.Nil(t, result.QuotaState)
|
||||
require.NoError(t, tx.Commit())
|
||||
require.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
|
||||
func TestApplyUsageBillingEffects_APIKeyCounterErrorStillFails(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
db, mock, err := sqlmock.New()
|
||||
@@ -184,6 +222,100 @@ func TestDeductUsageBillingBalance_ReturnsUserNotFoundWhenNoUserUpdated(t *testi
|
||||
require.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
|
||||
var accountQuotaStateColumns = []string{"quota_used", "quota_limit", "quota_daily_used", "quota_daily_limit", "quota_weekly_used", "quota_weekly_limit"}
|
||||
|
||||
func TestAccountQuotaIncrementSQLs_GuardOmittedDimensions(t *testing.T) {
|
||||
for _, daily := range []bool{false, true} {
|
||||
for _, weekly := range []bool{false, true} {
|
||||
query := accountQuotaIncrementSQLs[accountQuotaIncrementSQLIndex(daily, weekly)]
|
||||
set, where, ok := strings.Cut(query, "WHERE ")
|
||||
require.True(t, ok)
|
||||
require.Equal(t, !daily || !weekly, strings.Contains(where, accountQuotaExtraIsObjectCond), "daily=%v weekly=%v", daily, weekly)
|
||||
require.Equal(t, daily, strings.Contains(set, "'quota_daily_used'"), "daily=%v weekly=%v", daily, weekly)
|
||||
require.Equal(t, weekly, strings.Contains(set, "'quota_weekly_used'"), "daily=%v weekly=%v", daily, weekly)
|
||||
require.Equal(t, !daily, strings.Contains(where, accountQuotaDailyLimitUnsetCond), "daily=%v weekly=%v", daily, weekly)
|
||||
require.Equal(t, !weekly, strings.Contains(where, accountQuotaWeeklyLimitUnsetCond), "daily=%v weekly=%v", daily, weekly)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestIncrementUsageBillingAccountQuota_UsesStatementMatchingHints(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
db, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherEqual))
|
||||
require.NoError(t, err)
|
||||
defer func() { _ = db.Close() }()
|
||||
|
||||
mock.ExpectBegin()
|
||||
tx, err := db.BeginTx(ctx, nil)
|
||||
require.NoError(t, err)
|
||||
mock.ExpectQuery(accountQuotaIncrementSQLs[accountQuotaIncrementSQLIndex(true, false)]).
|
||||
WithArgs(2.5, int64(9)).
|
||||
WillReturnRows(sqlmock.NewRows(accountQuotaStateColumns).AddRow(12.5, 100.0, 2.5, 50.0, 0.0, 0.0))
|
||||
mock.ExpectCommit()
|
||||
|
||||
state, err := incrementUsageBillingAccountQuota(ctx, tx, 9, 2.5, true, false)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, state)
|
||||
require.InDelta(t, 12.5, state.TotalUsed, 0.000001)
|
||||
require.InDelta(t, 2.5, state.DailyUsed, 0.000001)
|
||||
require.NoError(t, tx.Commit())
|
||||
require.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
|
||||
func TestIncrementUsageBillingAccountQuota_FallsBackToFullStatementWhenGuardMisses(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
db, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherEqual))
|
||||
require.NoError(t, err)
|
||||
defer func() { _ = db.Close() }()
|
||||
|
||||
mock.ExpectBegin()
|
||||
tx, err := db.BeginTx(ctx, nil)
|
||||
require.NoError(t, err)
|
||||
mock.ExpectQuery(accountQuotaIncrementSQLs[accountQuotaIncrementSQLIndex(false, false)]).
|
||||
WithArgs(2.5, int64(9)).
|
||||
WillReturnRows(sqlmock.NewRows(accountQuotaStateColumns))
|
||||
mock.ExpectQuery(accountQuotaIncrementSQLs[accountQuotaIncrementSQLIndex(true, true)]).
|
||||
WithArgs(2.5, int64(9)).
|
||||
WillReturnRows(sqlmock.NewRows(accountQuotaStateColumns).AddRow(2.5, 0.0, 0.0, 0.0, 2.5, 20.0))
|
||||
mock.ExpectCommit()
|
||||
|
||||
state, err := incrementUsageBillingAccountQuota(ctx, tx, 9, 2.5, false, false)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, state)
|
||||
require.InDelta(t, 2.5, state.WeeklyUsed, 0.000001)
|
||||
require.InDelta(t, 20.0, state.WeeklyLimit, 0.000001)
|
||||
require.NoError(t, tx.Commit())
|
||||
require.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
|
||||
func TestIncrementUsageBillingAccountQuota_ReturnsNotFoundWhenFullStatementMisses(t *testing.T) {
|
||||
for _, hints := range [][2]bool{{false, false}, {true, false}, {false, true}, {true, true}} {
|
||||
ctx := context.Background()
|
||||
db, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherEqual))
|
||||
require.NoError(t, err)
|
||||
|
||||
mock.ExpectBegin()
|
||||
tx, err := db.BeginTx(ctx, nil)
|
||||
require.NoError(t, err)
|
||||
mock.ExpectQuery(accountQuotaIncrementSQLs[accountQuotaIncrementSQLIndex(hints[0], hints[1])]).
|
||||
WithArgs(2.5, int64(9)).
|
||||
WillReturnRows(sqlmock.NewRows(accountQuotaStateColumns))
|
||||
if !(hints[0] && hints[1]) {
|
||||
mock.ExpectQuery(accountQuotaIncrementSQLs[accountQuotaIncrementSQLIndex(true, true)]).
|
||||
WithArgs(2.5, int64(9)).
|
||||
WillReturnRows(sqlmock.NewRows(accountQuotaStateColumns))
|
||||
}
|
||||
mock.ExpectRollback()
|
||||
|
||||
state, err := incrementUsageBillingAccountQuota(ctx, tx, 9, 2.5, hints[0], hints[1])
|
||||
require.ErrorIs(t, err, service.ErrAccountNotFound, "hints=%v", hints)
|
||||
require.Nil(t, state)
|
||||
require.NoError(t, tx.Rollback())
|
||||
require.NoError(t, mock.ExpectationsWereMet(), "hints=%v", hints)
|
||||
_ = db.Close()
|
||||
}
|
||||
}
|
||||
|
||||
func TestReserveUsageBillingBatchImageBalance_MovesAvailableToFrozen(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
db, mock, err := sqlmock.New()
|
||||
|
||||
@@ -185,6 +185,53 @@ func TestCompositeTargetPlatformMiddlewareRewritesNestedLiveModel(t *testing.T)
|
||||
require.Equal(t, http.StatusNoContent, w.Code)
|
||||
}
|
||||
|
||||
// Scenario: 回归 —— openai OAuth 与 deepseek API Key 同时映射 gpt-6-astra 时,
|
||||
// 请求必须在路由层被拒绝,不能落到默认 Anthropic handler 后再按模型名猜平台。
|
||||
// 仅 API Key 的跨平台歧义保持原行为(放行且不解析平台)。
|
||||
func TestCompositeTargetPlatformMiddlewareRejectsOnlyOAuthAmbiguousOwnership(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
oauthClaimed bool
|
||||
wantStatus int
|
||||
}{
|
||||
{name: "oauth claimant", oauthClaimed: true, wantStatus: http.StatusBadRequest},
|
||||
{name: "apikey only", oauthClaimed: false, wantStatus: http.StatusNoContent},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
resolver := service.NewCompositeRouteResolver(nil)
|
||||
resolver.SetModelOwnershipResolver(func(context.Context, int64, string) (service.CompositeModelOwnership, error) {
|
||||
return service.CompositeModelOwnership{Ambiguous: true, OpenAIGatewayOAuthClaimed: tc.oauthClaimed}, nil
|
||||
})
|
||||
router := gin.New()
|
||||
router.Use(gin.HandlerFunc(servermiddleware.APIKeyAuthMiddleware(func(c *gin.Context) {
|
||||
groupID := int64(8)
|
||||
c.Set(string(servermiddleware.ContextKeyAPIKey), &service.APIKey{
|
||||
GroupID: &groupID,
|
||||
Group: &service.Group{ID: groupID, Platform: service.PlatformComposite},
|
||||
})
|
||||
c.Next()
|
||||
})))
|
||||
router.Use(compositeTargetPlatformMiddleware(resolver))
|
||||
router.POST("/v1/responses", func(c *gin.Context) {
|
||||
_, resolved := service.ResolvedTargetPlatformFromContext(c.Request.Context())
|
||||
require.False(t, resolved)
|
||||
c.Status(http.StatusNoContent)
|
||||
})
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/v1/responses", strings.NewReader(`{"model":"gpt-6-astra"}`))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, req)
|
||||
|
||||
require.Equal(t, tc.wantStatus, w.Code)
|
||||
if tc.oauthClaimed {
|
||||
require.Contains(t, w.Body.String(), "explicit composite route")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompositeRequestModelFromMultipartLiveSession(t *testing.T) {
|
||||
var body bytes.Buffer
|
||||
writer := multipart.NewWriter(&body)
|
||||
|
||||
@@ -586,6 +586,14 @@ func compositeTargetPlatformMiddleware(resolver *service.CompositeRouteResolver)
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
// 含 OAuth 账号的跨平台歧义是分组配置错误:拒绝而不是放行。否则未解析的
|
||||
// 请求落到默认 Anthropic handler,handler 再按模型名前缀另猜平台,
|
||||
// OAuth 凭据被送进不匹配的协议管线(如 ChatGPT token 发往 Anthropic)。
|
||||
if decision.OAuthAmbiguous() {
|
||||
service.MarkOpsClientBusinessLimited(c, service.OpsClientBusinessLimitedReasonLocalModelConfiguration)
|
||||
c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": gin.H{"type": "invalid_request_error", "message": decision.AmbiguousMessage()}})
|
||||
return
|
||||
}
|
||||
if decision.Matched {
|
||||
c.Request = c.Request.WithContext(service.WithCompositeRouteDecision(c.Request.Context(), decision))
|
||||
if upstreamModel := strings.TrimSpace(decision.UpstreamModel); upstreamModel != "" && upstreamModel != model && gjson.ValidBytes(body) {
|
||||
|
||||
@@ -27,6 +27,14 @@ func (r *pinnedModelsRoutesRepository) ListByGroup(context.Context, int64) ([]se
|
||||
return []service.Account{r.account}, nil
|
||||
}
|
||||
|
||||
func (r *pinnedModelsRoutesRepository) ListSchedulableByGroupID(context.Context, int64) ([]service.Account, error) {
|
||||
return []service.Account{r.account}, nil
|
||||
}
|
||||
|
||||
func (r *pinnedModelsRoutesRepository) ListModelAvailabilityCandidates(context.Context, *int64, []string, bool) ([]service.Account, error) {
|
||||
return []service.Account{r.account}, nil
|
||||
}
|
||||
|
||||
type pinnedModelsRoutesUpstream struct {
|
||||
service.HTTPUpstream
|
||||
ordinaryCalls atomic.Int32
|
||||
|
||||
@@ -4,10 +4,10 @@ package service
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"hash/fnv"
|
||||
"log/slog"
|
||||
"net/url"
|
||||
"reflect"
|
||||
"slices"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -75,6 +75,9 @@ type Account struct {
|
||||
modelMappingCacheRawLen int
|
||||
modelMappingCacheRawSig uint64
|
||||
modelMappingCacheRuntimeVersion uint64
|
||||
// modelMappingCacheShared 为 true 时缓存来自只读共享母本(见 PrepareSharedSnapshot),
|
||||
// 指针、长度与运行时版本匹配即直接复用预解析结果,不计算签名。
|
||||
modelMappingCacheShared bool
|
||||
|
||||
// header_overrides 热路径缓存(非持久化字段,同 model_mapping 缓存先例)
|
||||
headerOverrideCache map[string]string
|
||||
@@ -205,7 +208,7 @@ func (a *Account) IsSchedulable() bool {
|
||||
if a.TempUnschedulableUntil != nil && now.Before(*a.TempUnschedulableUntil) {
|
||||
return false
|
||||
}
|
||||
if a.IsAPIKeyOrBedrock() && a.IsQuotaExceeded() {
|
||||
if a.SupportsAccountQuota() && a.IsQuotaExceeded() {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
@@ -634,6 +637,9 @@ func (a *Account) GetModelMapping() map[string]string {
|
||||
a.modelMappingCacheRawPtr == rawPtr &&
|
||||
a.modelMappingCacheRawLen == rawLen &&
|
||||
a.modelMappingCacheRuntimeVersion == runtimeVersion {
|
||||
if a.modelMappingCacheShared {
|
||||
return a.modelMappingCache
|
||||
}
|
||||
rawSig = modelMappingSignature(rawMapping)
|
||||
rawSigReady = true
|
||||
if a.modelMappingCacheRawSig == rawSig {
|
||||
@@ -653,9 +659,24 @@ func (a *Account) GetModelMapping() map[string]string {
|
||||
a.modelMappingCacheRawLen = rawLen
|
||||
a.modelMappingCacheRawSig = rawSig
|
||||
a.modelMappingCacheRuntimeVersion = runtimeVersion
|
||||
a.modelMappingCacheShared = false
|
||||
return mapping
|
||||
}
|
||||
|
||||
// PrepareSharedSnapshot 预解析模型映射,并把账号标记为只读共享母本。
|
||||
// 母本按值复制出的副本与母本共用 Credentials 及其中 model_mapping 的同一 map:
|
||||
// 这些内层 map 在运行期不被原地修改,母本留在缓存期间持有这些 map,其地址不会被复用,
|
||||
// 因此副本在指针、长度与运行时版本都匹配时直接复用预解析结果,不计算签名;
|
||||
// 副本替换 Credentials 等导致任一项不匹配时回到普通的重建路径。
|
||||
// 只能由构造该账号的 goroutine 在其发布给其它 goroutine 之前调用,发布后母本不得再被修改。
|
||||
func (a *Account) PrepareSharedSnapshot() {
|
||||
if a == nil {
|
||||
return
|
||||
}
|
||||
a.GetModelMapping()
|
||||
a.modelMappingCacheShared = true
|
||||
}
|
||||
|
||||
func (a *Account) resolveModelMapping(rawMapping map[string]any) map[string]string {
|
||||
if a.Credentials == nil {
|
||||
// Antigravity 平台使用默认映射
|
||||
@@ -690,26 +711,7 @@ func (a *Account) resolveModelMapping(rawMapping map[string]any) map[string]stri
|
||||
}
|
||||
if len(result) > 0 {
|
||||
if a.Platform == domain.PlatformAntigravity {
|
||||
ensureAntigravityDefaultPassthroughs(result, []string{
|
||||
"gemini-3-flash",
|
||||
"gemini-3.1-pro-high",
|
||||
"gemini-3.1-pro-low",
|
||||
"gemini-3.6-flash",
|
||||
"gemini-3.6-flash-high",
|
||||
"gemini-3.6-flash-low",
|
||||
"gemini-3.6-flash-medium",
|
||||
"gemini-3.6-flash-tiered",
|
||||
"gemini-3.7-flash",
|
||||
"gemini-3.7-flash-high",
|
||||
"gemini-3.7-flash-low",
|
||||
"gemini-3.7-flash-medium",
|
||||
"gemini-3.7-flash-tiered",
|
||||
"gemini-3.8-flash",
|
||||
"gemini-3.8-flash-high",
|
||||
"gemini-3.8-flash-low",
|
||||
"gemini-3.8-flash-medium",
|
||||
"gemini-3.8-flash-tiered",
|
||||
})
|
||||
ensureAntigravityDefaultPassthroughs(result, antigravityDefaultPassthroughModels)
|
||||
applyAntigravityGemini31ProAliases(result)
|
||||
}
|
||||
return result
|
||||
@@ -735,28 +737,101 @@ func mapPtr(m map[string]any) uintptr {
|
||||
return reflect.ValueOf(m).Pointer()
|
||||
}
|
||||
|
||||
const (
|
||||
modelMappingSignatureFNVOffset = 14695981039346656037
|
||||
modelMappingSignatureFNVPrime = 1099511628211
|
||||
)
|
||||
|
||||
// modelMappingSignature 计算原始映射内容的进程内校验值,与 map 遍历顺序无关且不分配内存。
|
||||
// 每个条目把 key、分隔字节 0 与 value(string 写其字节,其它类型写标记字节 1)
|
||||
// 放进同一个 FNV-1a 哈希并经 fmix64 收尾,再对所有条目求和;
|
||||
// key 与 value 同在一个条目哈希里,交换两个 key 的 value 会改变结果。
|
||||
func modelMappingSignature(rawMapping map[string]any) uint64 {
|
||||
if len(rawMapping) == 0 {
|
||||
return 0
|
||||
}
|
||||
keys := make([]string, 0, len(rawMapping))
|
||||
for k := range rawMapping {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
|
||||
h := fnv.New64a()
|
||||
for _, k := range keys {
|
||||
_, _ = h.Write([]byte(k))
|
||||
_, _ = h.Write([]byte{0})
|
||||
if v, ok := rawMapping[k].(string); ok {
|
||||
_, _ = h.Write([]byte(v))
|
||||
var sum uint64
|
||||
for k, v := range rawMapping {
|
||||
h := uint64(modelMappingSignatureFNVOffset)
|
||||
h = fnv1aString(h, k)
|
||||
h = fnv1aByte(h, 0)
|
||||
if s, ok := v.(string); ok {
|
||||
h = fnv1aString(h, s)
|
||||
} else {
|
||||
_, _ = h.Write([]byte{1})
|
||||
h = fnv1aByte(h, 1)
|
||||
}
|
||||
_, _ = h.Write([]byte{0xff})
|
||||
sum += fmix64(h)
|
||||
}
|
||||
return h.Sum64()
|
||||
return sum
|
||||
}
|
||||
|
||||
func fnv1aString(h uint64, s string) uint64 {
|
||||
for i := 0; i < len(s); i++ {
|
||||
h ^= uint64(s[i])
|
||||
h *= modelMappingSignatureFNVPrime
|
||||
}
|
||||
return h
|
||||
}
|
||||
|
||||
func fnv1aByte(h uint64, b byte) uint64 {
|
||||
h ^= uint64(b)
|
||||
h *= modelMappingSignatureFNVPrime
|
||||
return h
|
||||
}
|
||||
|
||||
// fmix64 是 MurmurHash3 的 64 位收尾函数,使条目哈希各位充分混合后再求和。
|
||||
func fmix64(h uint64) uint64 {
|
||||
h ^= h >> 33
|
||||
h *= 0xff51afd7ed558ccd
|
||||
h ^= h >> 33
|
||||
h *= 0xc4ceb9fe1a85ec53
|
||||
h ^= h >> 33
|
||||
return h
|
||||
}
|
||||
|
||||
// antigravityDefaultPassthroughModels 是 Antigravity 显式 model_mapping 运行时补齐的默认透传条目:
|
||||
// 让新模型发布前保存的映射也能调用这些模型。
|
||||
var antigravityDefaultPassthroughModels = []string{
|
||||
"gemini-3-flash",
|
||||
"gemini-3.1-pro-high",
|
||||
"gemini-3.1-pro-low",
|
||||
"gemini-3.6-flash",
|
||||
"gemini-3.6-flash-high",
|
||||
"gemini-3.6-flash-low",
|
||||
"gemini-3.6-flash-medium",
|
||||
"gemini-3.6-flash-tiered",
|
||||
"gemini-3.7-flash",
|
||||
"gemini-3.7-flash-high",
|
||||
"gemini-3.7-flash-low",
|
||||
"gemini-3.7-flash-medium",
|
||||
"gemini-3.7-flash-tiered",
|
||||
"gemini-3.8-flash",
|
||||
"gemini-3.8-flash-high",
|
||||
"gemini-3.8-flash-low",
|
||||
"gemini-3.8-flash-medium",
|
||||
"gemini-3.8-flash-tiered",
|
||||
}
|
||||
|
||||
// isAntigravityInjectedDefaultPassthrough 判断 GetModelMapping 中的 key→target 是否仅由
|
||||
// resolveModelMapping 运行时补齐(管理员未写入 credentials.model_mapping)。
|
||||
func (a *Account) isAntigravityInjectedDefaultPassthrough(key, target string) bool {
|
||||
if a == nil || a.Platform != domain.PlatformAntigravity || key != target || !slices.Contains(antigravityDefaultPassthroughModels, key) {
|
||||
return false
|
||||
}
|
||||
rawMapping, _ := a.Credentials["model_mapping"].(map[string]any)
|
||||
hasExplicitEntry := false
|
||||
for _, v := range rawMapping {
|
||||
if _, ok := v.(string); ok {
|
||||
hasExplicitEntry = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !hasExplicitEntry {
|
||||
// 空映射走默认目录,不做运行时补齐。
|
||||
return false
|
||||
}
|
||||
_, configured := rawMapping[key].(string)
|
||||
return !configured
|
||||
}
|
||||
|
||||
func ensureAntigravityDefaultPassthrough(mapping map[string]string, model string) {
|
||||
@@ -887,6 +962,10 @@ func resolveRequestedModelInMapping(mapping map[string]string, requestedModel st
|
||||
// (isDeepseekServableModel)——未知模型名透传上游只会得到 404/400,并误触发
|
||||
// per-(账号,模型) 30 分钟冷却;带 [1m] 上下文后缀的写法先归一化再比对。
|
||||
func (a *Account) IsModelSupported(requestedModel string) bool {
|
||||
return supportsOpenAIRequestModel(a, requestedModel, false)
|
||||
}
|
||||
|
||||
func (a *Account) isModelMappingSupported(requestedModel string) bool {
|
||||
// 透传模式仅替换认证、模型语义完全交由上游决定,因此放行所有模型。
|
||||
// 该短路必须在 model_mapping 判定之前:账号从"白名单模式"切换到透传后,
|
||||
// credentials 里常残留旧的非空 model_mapping,若不在此放行,透传账号会被
|
||||
@@ -1347,11 +1426,26 @@ func (a *Account) IsBedrockAPIKey() bool {
|
||||
return a.IsBedrock() && a.GetCredential("auth_mode") == "apikey"
|
||||
}
|
||||
|
||||
// IsAPIKeyOrBedrock 返回账号类型是否支持配额和池模式等特性
|
||||
// IsAPIKeyOrBedrock 返回账号类型是否支持池模式等特性(账号配额判定见 SupportsAccountQuota)
|
||||
func (a *Account) IsAPIKeyOrBedrock() bool {
|
||||
return a.Type == AccountTypeAPIKey || a.Type == AccountTypeBedrock
|
||||
}
|
||||
|
||||
// AccountTypeSupportsQuota 返回账号类型是否支持账号配额(quota_limit 及日/周额度、quota_used 累加、超限停调度)。
|
||||
// 在 apikey/bedrock 之外额外放开 Vertex service_account;池模式等其它特性仍只看 IsAPIKeyOrBedrock。
|
||||
func AccountTypeSupportsQuota(accountType string) bool {
|
||||
switch strings.ToLower(accountType) {
|
||||
case AccountTypeAPIKey, AccountTypeBedrock, AccountTypeServiceAccount:
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// SupportsAccountQuota 返回账号是否支持账号配额,类型集合见 AccountTypeSupportsQuota。
|
||||
func (a *Account) SupportsAccountQuota() bool {
|
||||
return AccountTypeSupportsQuota(a.Type)
|
||||
}
|
||||
|
||||
func (a *Account) IsOpenAI() bool {
|
||||
return a.Platform == PlatformOpenAI
|
||||
}
|
||||
@@ -2316,7 +2410,10 @@ const (
|
||||
// 三态:default(跟随渠道)/ enabled(强制开启)/ disabled(强制关闭)。
|
||||
// 兼容旧 bool 值:true→enabled, false→default(并记录 debug 日志)。
|
||||
func (a *Account) GetWebSearchEmulationMode() string {
|
||||
if a == nil || a.Platform != PlatformAnthropic || a.Type != AccountTypeAPIKey || a.Extra == nil {
|
||||
// OpenAI API Key accounts reach this via /v1/messages; their upstreams
|
||||
// (DeepSeek etc. over Chat Completions) have no web_search tool.
|
||||
if a == nil || a.Type != AccountTypeAPIKey || a.Extra == nil ||
|
||||
(a.Platform != PlatformAnthropic && a.Platform != PlatformOpenAI) {
|
||||
return WebSearchModeDefault
|
||||
}
|
||||
raw := a.Extra[featureKeyWebSearchEmulation]
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
//go:build unit
|
||||
|
||||
package service
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestModelMappingSignature_IndependentOfInsertionOrder(t *testing.T) {
|
||||
const size = 64
|
||||
forward := make(map[string]any, size)
|
||||
backward := make(map[string]any, size)
|
||||
for i := 0; i < size; i++ {
|
||||
forward[fmt.Sprintf("model-%02d", i)] = fmt.Sprintf("upstream-%02d", i)
|
||||
}
|
||||
for i := size - 1; i >= 0; i-- {
|
||||
backward[fmt.Sprintf("model-%02d", i)] = fmt.Sprintf("upstream-%02d", i)
|
||||
}
|
||||
forward["non-string"] = 42
|
||||
backward["non-string"] = 42
|
||||
|
||||
want := modelMappingSignature(forward)
|
||||
require.NotZero(t, want)
|
||||
for i := 0; i < 20; i++ {
|
||||
require.Equal(t, want, modelMappingSignature(forward))
|
||||
require.Equal(t, want, modelMappingSignature(backward))
|
||||
}
|
||||
}
|
||||
|
||||
func TestModelMappingSignature_DetectsContentChanges(t *testing.T) {
|
||||
base := map[string]any{
|
||||
"claude-sonnet": "sonnet-a",
|
||||
"claude-opus": "opus-a",
|
||||
"gpt-5": "gpt-5-upstream",
|
||||
}
|
||||
baseSig := modelMappingSignature(base)
|
||||
|
||||
cases := map[string]map[string]any{
|
||||
"value changed": {
|
||||
"claude-sonnet": "sonnet-b",
|
||||
"claude-opus": "opus-a",
|
||||
"gpt-5": "gpt-5-upstream",
|
||||
},
|
||||
"key renamed": {
|
||||
"claude-sonnet-x": "sonnet-a",
|
||||
"claude-opus": "opus-a",
|
||||
"gpt-5": "gpt-5-upstream",
|
||||
},
|
||||
"values swapped between keys": {
|
||||
"claude-sonnet": "opus-a",
|
||||
"claude-opus": "sonnet-a",
|
||||
"gpt-5": "gpt-5-upstream",
|
||||
},
|
||||
"string value replaced by non-string": {
|
||||
"claude-sonnet": 1,
|
||||
"claude-opus": "opus-a",
|
||||
"gpt-5": "gpt-5-upstream",
|
||||
},
|
||||
"entry removed": {
|
||||
"claude-sonnet": "sonnet-a",
|
||||
"claude-opus": "opus-a",
|
||||
},
|
||||
}
|
||||
for name, changed := range cases {
|
||||
require.NotEqual(t, baseSig, modelMappingSignature(changed), name)
|
||||
}
|
||||
|
||||
// 非 string 的 value 统一按类型标记参与签名,具体取值不影响结果。
|
||||
require.Equal(t,
|
||||
modelMappingSignature(map[string]any{"m": 1}),
|
||||
modelMappingSignature(map[string]any{"m": true}),
|
||||
)
|
||||
}
|
||||
|
||||
func TestModelMappingSignature_EmptyIsZero(t *testing.T) {
|
||||
require.Zero(t, modelMappingSignature(nil))
|
||||
require.Zero(t, modelMappingSignature(map[string]any{}))
|
||||
}
|
||||
|
||||
func TestModelMappingSignature_DoesNotAllocate(t *testing.T) {
|
||||
mapping := map[string]any{
|
||||
"claude-sonnet": "sonnet-a",
|
||||
"claude-opus": "opus-a",
|
||||
"gpt-5": "gpt-5-upstream",
|
||||
"non-string": 3.14,
|
||||
}
|
||||
var sink uint64
|
||||
allocs := testing.AllocsPerRun(1000, func() {
|
||||
sink += modelMappingSignature(mapping)
|
||||
})
|
||||
require.Zero(t, allocs)
|
||||
require.NotZero(t, sink)
|
||||
}
|
||||
@@ -113,6 +113,48 @@ func TestAccountIsSchedulable_QuotaExceeded(t *testing.T) {
|
||||
},
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "service_account total quota exceeded",
|
||||
account: &Account{
|
||||
Status: StatusActive,
|
||||
Schedulable: true,
|
||||
Platform: PlatformGemini,
|
||||
Type: AccountTypeServiceAccount,
|
||||
Extra: map[string]any{
|
||||
"quota_limit": 50.0,
|
||||
"quota_used": 50.0,
|
||||
},
|
||||
},
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "service_account daily quota exceeded",
|
||||
account: &Account{
|
||||
Status: StatusActive,
|
||||
Schedulable: true,
|
||||
Platform: PlatformGemini,
|
||||
Type: AccountTypeServiceAccount,
|
||||
Extra: map[string]any{
|
||||
"quota_daily_limit": 10.0,
|
||||
"quota_daily_used": 12.0,
|
||||
"quota_daily_start": now.Add(-1 * time.Hour).Format(time.RFC3339),
|
||||
},
|
||||
},
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "service_account without limit stays schedulable regardless of quota_used",
|
||||
account: &Account{
|
||||
Status: StatusActive,
|
||||
Schedulable: true,
|
||||
Platform: PlatformGemini,
|
||||
Type: AccountTypeServiceAccount,
|
||||
Extra: map[string]any{
|
||||
"quota_used": 9999.0,
|
||||
},
|
||||
},
|
||||
want: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
|
||||
@@ -0,0 +1,204 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestAccountSupportsAccountQuota(t *testing.T) {
|
||||
tests := []struct {
|
||||
accountType string
|
||||
want bool
|
||||
}{
|
||||
{AccountTypeAPIKey, true},
|
||||
{AccountTypeBedrock, true},
|
||||
{AccountTypeServiceAccount, true},
|
||||
{AccountTypeOAuth, false},
|
||||
{AccountTypeSetupToken, false},
|
||||
{AccountTypeUpstream, false},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.accountType, func(t *testing.T) {
|
||||
account := &Account{Type: tt.accountType}
|
||||
require.Equal(t, tt.want, account.SupportsAccountQuota())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// 配额专用判定放开 service_account,不能连带放开池模式等其它 IsAPIKeyOrBedrock 特性。
|
||||
func TestServiceAccountQuotaDoesNotWidenPoolMode(t *testing.T) {
|
||||
account := &Account{
|
||||
Platform: PlatformGemini,
|
||||
Type: AccountTypeServiceAccount,
|
||||
Credentials: map[string]any{"pool_mode": true},
|
||||
}
|
||||
require.True(t, account.SupportsAccountQuota())
|
||||
require.False(t, account.IsAPIKeyOrBedrock())
|
||||
require.False(t, account.IsPoolMode())
|
||||
}
|
||||
|
||||
func TestShouldUpdateAccountQuota(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
account *Account
|
||||
totalCost float64
|
||||
want bool
|
||||
}{
|
||||
{
|
||||
name: "apikey without limit does not accumulate",
|
||||
account: &Account{Type: AccountTypeAPIKey, Extra: map[string]any{}},
|
||||
totalCost: 1.5,
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "apikey with total limit accumulates",
|
||||
account: &Account{Type: AccountTypeAPIKey, Extra: map[string]any{"quota_limit": 100.0}},
|
||||
totalCost: 1.5,
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "bedrock with daily limit accumulates",
|
||||
account: &Account{Type: AccountTypeBedrock, Extra: map[string]any{"quota_daily_limit": 10.0}},
|
||||
totalCost: 1.5,
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "service_account without limit does not accumulate",
|
||||
account: &Account{Platform: PlatformGemini, Type: AccountTypeServiceAccount, Extra: map[string]any{"quota_used": 30.0}},
|
||||
totalCost: 1.5,
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "service_account with limit accumulates",
|
||||
account: &Account{Platform: PlatformGemini, Type: AccountTypeServiceAccount, Extra: map[string]any{"quota_weekly_limit": 50.0}},
|
||||
totalCost: 1.5,
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "service_account zero cost does not accumulate",
|
||||
account: &Account{Platform: PlatformGemini, Type: AccountTypeServiceAccount, Extra: map[string]any{"quota_limit": 100.0}},
|
||||
totalCost: 0,
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "oauth with limit is not quota eligible",
|
||||
account: &Account{Type: AccountTypeOAuth, Extra: map[string]any{"quota_limit": 100.0}},
|
||||
totalCost: 1.5,
|
||||
want: false,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
p := &postUsageBillingParams{
|
||||
Cost: &CostBreakdown{TotalCost: tt.totalCost},
|
||||
Account: tt.account,
|
||||
}
|
||||
require.Equal(t, tt.want, p.shouldUpdateAccountQuota())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildUsageBillingCommandAccountQuotaCostForServiceAccount(t *testing.T) {
|
||||
build := func(account *Account) *UsageBillingCommand {
|
||||
return buildUsageBillingCommand("req-sa-quota", nil, &postUsageBillingParams{
|
||||
Cost: &CostBreakdown{TotalCost: 2, ActualCost: 3},
|
||||
User: &User{ID: 7},
|
||||
APIKey: &APIKey{ID: 13},
|
||||
Account: account,
|
||||
AccountRateMultiplier: 1.5,
|
||||
})
|
||||
}
|
||||
|
||||
// service_account 设了上限:AccountQuotaCost = TotalCost × 账号倍率
|
||||
cmd := build(&Account{ID: 9, Platform: PlatformGemini, Type: AccountTypeServiceAccount, Extra: map[string]any{"quota_limit": 100.0}})
|
||||
require.NotNil(t, cmd)
|
||||
require.Equal(t, AccountTypeServiceAccount, cmd.AccountType)
|
||||
require.InDelta(t, 3.0, cmd.AccountQuotaCost, 1e-9)
|
||||
|
||||
// service_account 不设上限:与 apikey 一致不累加
|
||||
cmd = build(&Account{ID: 10, Platform: PlatformGemini, Type: AccountTypeServiceAccount})
|
||||
require.NotNil(t, cmd)
|
||||
require.Zero(t, cmd.AccountQuotaCost)
|
||||
}
|
||||
|
||||
type accountQuotaIncrementRepoStub struct {
|
||||
AccountRepository
|
||||
calls []float64
|
||||
}
|
||||
|
||||
func (s *accountQuotaIncrementRepoStub) IncrementQuotaUsed(_ context.Context, _ int64, amount float64) error {
|
||||
s.calls = append(s.calls, amount)
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestPostUsageBillingLegacyAccumulatesServiceAccountQuota(t *testing.T) {
|
||||
repo := &accountQuotaIncrementRepoStub{}
|
||||
postUsageBilling(context.Background(), &postUsageBillingParams{
|
||||
Cost: &CostBreakdown{TotalCost: 2},
|
||||
User: &User{ID: 7},
|
||||
APIKey: &APIKey{ID: 13},
|
||||
Account: &Account{ID: 9, Platform: PlatformGemini, Type: AccountTypeServiceAccount, Extra: map[string]any{"quota_limit": 100.0}},
|
||||
AccountRateMultiplier: 1.25,
|
||||
}, &billingDeps{accountRepo: repo})
|
||||
|
||||
require.Len(t, repo.calls, 1)
|
||||
require.InDelta(t, 2.5, repo.calls[0], 1e-9)
|
||||
}
|
||||
|
||||
type settingGetValueCounter struct {
|
||||
SettingRepository
|
||||
calls int
|
||||
}
|
||||
|
||||
func (s *settingGetValueCounter) GetValue(context.Context, string) (string, error) {
|
||||
s.calls++
|
||||
return "false", nil
|
||||
}
|
||||
|
||||
// 未设任何上限的账号没有可跨越的阈值,不应逐请求读取通知设置。
|
||||
func TestNotifyAccountQuotaSkipsAccountWithoutLimit(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
account *Account
|
||||
wantCalls int
|
||||
}{
|
||||
{
|
||||
name: "service_account without limit",
|
||||
account: &Account{ID: 9, Platform: PlatformGemini, Type: AccountTypeServiceAccount},
|
||||
wantCalls: 0,
|
||||
},
|
||||
{
|
||||
name: "service_account with total limit",
|
||||
account: &Account{ID: 9, Platform: PlatformGemini, Type: AccountTypeServiceAccount, Extra: map[string]any{"quota_limit": 100.0}},
|
||||
wantCalls: 1,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
settings := &settingGetValueCounter{}
|
||||
notifyAccountQuota(&postUsageBillingParams{
|
||||
Cost: &CostBreakdown{TotalCost: 2},
|
||||
Account: tt.account,
|
||||
AccountRateMultiplier: 1,
|
||||
}, &billingDeps{
|
||||
balanceNotifyService: NewBalanceNotifyService(NewEmailService(settings, nil), settings, nil),
|
||||
}, nil)
|
||||
require.Equal(t, tt.wantCalls, settings.calls)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// 账号已删除时计数被跳过、无递增后状态,不应回退到快照做阈值判定。
|
||||
func TestNotifyAccountQuotaSkipsWhenQuotaIncrementSkipped(t *testing.T) {
|
||||
settings := &settingGetValueCounter{}
|
||||
notifyAccountQuota(&postUsageBillingParams{
|
||||
Cost: &CostBreakdown{TotalCost: 2},
|
||||
Account: &Account{ID: 9, Platform: PlatformGemini, Type: AccountTypeServiceAccount, Extra: map[string]any{"quota_limit": 100.0}},
|
||||
AccountRateMultiplier: 1,
|
||||
}, &billingDeps{
|
||||
balanceNotifyService: NewBalanceNotifyService(NewEmailService(settings, nil), settings, nil),
|
||||
}, &UsageBillingApplyResult{Applied: true})
|
||||
require.Zero(t, settings.calls)
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
//go:build unit
|
||||
|
||||
package service
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// 共享母本的副本命中预解析缓存时不计算签名:此处故意原地改写共享的原始映射,
|
||||
// 只用来观察副本走的是免签名路径(生产代码不会原地修改该 map)。
|
||||
func TestAccountPrepareSharedSnapshot_CopiesReusePreparedMappingWithoutSignature(t *testing.T) {
|
||||
rawMapping := map[string]any{"claude-sonnet": "sonnet-a"}
|
||||
master := &Account{
|
||||
Platform: PlatformAnthropic,
|
||||
Credentials: map[string]any{"model_mapping": rawMapping},
|
||||
}
|
||||
master.PrepareSharedSnapshot()
|
||||
|
||||
replica := *master
|
||||
require.Equal(t, map[string]string{"claude-sonnet": "sonnet-a"}, replica.GetModelMapping())
|
||||
|
||||
rawMapping["claude-sonnet"] = "sonnet-b"
|
||||
require.Equal(t, "sonnet-a", replica.GetModelMapping()["claude-sonnet"],
|
||||
"the shared fast path must not recompute the signature")
|
||||
require.Equal(t, "sonnet-a", replica.GetMappedModel("claude-sonnet"))
|
||||
|
||||
// 未标记为共享的账号仍按签名检出原地改写。
|
||||
plainRaw := map[string]any{"claude-sonnet": "sonnet-a"}
|
||||
plain := &Account{
|
||||
Platform: PlatformAnthropic,
|
||||
Credentials: map[string]any{"model_mapping": plainRaw},
|
||||
}
|
||||
require.Equal(t, "sonnet-a", plain.GetModelMapping()["claude-sonnet"])
|
||||
plainRaw["claude-sonnet"] = "sonnet-b"
|
||||
require.Equal(t, "sonnet-b", plain.GetModelMapping()["claude-sonnet"])
|
||||
}
|
||||
|
||||
func TestAccountPrepareSharedSnapshot_ReplacedCredentialsFallBackToSignaturePath(t *testing.T) {
|
||||
master := &Account{
|
||||
Platform: PlatformAnthropic,
|
||||
Credentials: map[string]any{"model_mapping": map[string]any{"claude-sonnet": "sonnet-a"}},
|
||||
}
|
||||
master.PrepareSharedSnapshot()
|
||||
|
||||
replica := *master
|
||||
replacedRaw := map[string]any{"claude-sonnet": "sonnet-b"}
|
||||
replica.Credentials = map[string]any{"model_mapping": replacedRaw}
|
||||
require.Equal(t, "sonnet-b", replica.GetModelMapping()["claude-sonnet"])
|
||||
|
||||
// 重建后副本回到普通路径:同一 map 的原地改写由签名检出。
|
||||
replacedRaw["claude-sonnet"] = "sonnet-c"
|
||||
require.Equal(t, "sonnet-c", replica.GetModelMapping()["claude-sonnet"])
|
||||
|
||||
// 母本不受副本重建影响。
|
||||
require.Equal(t, "sonnet-a", master.GetModelMapping()["claude-sonnet"])
|
||||
}
|
||||
|
||||
func TestAccountPrepareSharedSnapshot_MappingLengthChangeRebuilds(t *testing.T) {
|
||||
rawMapping := map[string]any{"claude-sonnet": "sonnet-a"}
|
||||
master := &Account{
|
||||
Platform: PlatformAnthropic,
|
||||
Credentials: map[string]any{"model_mapping": rawMapping},
|
||||
}
|
||||
master.PrepareSharedSnapshot()
|
||||
|
||||
replica := *master
|
||||
rawMapping["claude-opus"] = "opus-a"
|
||||
require.Equal(t, "opus-a", replica.GetModelMapping()["claude-opus"])
|
||||
}
|
||||
|
||||
func TestAccountPrepareSharedSnapshot_NilAccountAndNoMapping(t *testing.T) {
|
||||
var nilAccount *Account
|
||||
require.NotPanics(t, nilAccount.PrepareSharedSnapshot)
|
||||
|
||||
master := &Account{Platform: PlatformAnthropic}
|
||||
master.PrepareSharedSnapshot()
|
||||
replica := *master
|
||||
require.Nil(t, replica.GetModelMapping())
|
||||
require.Equal(t, "claude-sonnet", replica.GetMappedModel("claude-sonnet"))
|
||||
}
|
||||
@@ -2464,12 +2464,12 @@ func (s *AccountTestService) routeAntigravityTest(c *gin.Context, account *Accou
|
||||
}
|
||||
return s.testClaudeAccountConnection(c, account, modelID)
|
||||
}
|
||||
return s.testAntigravityAccountConnection(c, account, modelID)
|
||||
return s.testAntigravityAccountConnection(c, account, modelID, prompt)
|
||||
}
|
||||
|
||||
// testAntigravityAccountConnection tests an Antigravity account's connection
|
||||
// 支持 Claude 和 Gemini 两种协议,使用非流式请求
|
||||
func (s *AccountTestService) testAntigravityAccountConnection(c *gin.Context, account *Account, modelID string) error {
|
||||
func (s *AccountTestService) testAntigravityAccountConnection(c *gin.Context, account *Account, modelID string, prompt string) error {
|
||||
ctx := c.Request.Context()
|
||||
|
||||
testModelID := antigravityConnectionTestModel(modelID)
|
||||
@@ -2488,8 +2488,8 @@ func (s *AccountTestService) testAntigravityAccountConnection(c *gin.Context, ac
|
||||
// Send test_start event
|
||||
s.sendEvent(c, TestEvent{Type: "test_start", Model: testModelID})
|
||||
|
||||
// 调用 AntigravityGatewayService.TestConnection(复用协议转换逻辑)
|
||||
result, err := s.antigravityGatewayService.TestConnection(ctx, account, testModelID)
|
||||
// 调用 AntigravityGatewayService.TestConnectionWithPrompt(复用协议转换逻辑)
|
||||
result, err := s.antigravityGatewayService.TestConnectionWithPrompt(ctx, account, testModelID, prompt)
|
||||
if err != nil {
|
||||
return s.sendErrorAndEnd(c, err.Error())
|
||||
}
|
||||
@@ -2498,6 +2498,13 @@ func (s *AccountTestService) testAntigravityAccountConnection(c *gin.Context, ac
|
||||
if result.Text != "" {
|
||||
s.sendEvent(c, TestEvent{Type: "content", Text: result.Text})
|
||||
}
|
||||
for _, img := range result.Images {
|
||||
s.sendEvent(c, TestEvent{
|
||||
Type: "image",
|
||||
ImageURL: img.ImageURL,
|
||||
MimeType: img.MimeType,
|
||||
})
|
||||
}
|
||||
|
||||
s.sendEvent(c, TestEvent{Type: "test_complete", Success: true})
|
||||
return nil
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
@@ -14,3 +15,68 @@ func TestAntigravityConnectionTestModel(t *testing.T) {
|
||||
require.Equal(t, "claude-sonnet-4-6", antigravityConnectionTestModel(""))
|
||||
require.Equal(t, "gemini-3.1-pro-preview", antigravityConnectionTestModel("gemini-3.1-pro-preview"))
|
||||
}
|
||||
|
||||
func TestAntigravityBuildGeminiTestRequest_IncludesValidatedToolConfig(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
svc := &AntigravityGatewayService{}
|
||||
raw, err := svc.buildGeminiTestRequestWithPrompt("proj-123", "gemini-3.8-flash-high", "")
|
||||
require.NoError(t, err)
|
||||
|
||||
var v1Req map[string]any
|
||||
require.NoError(t, json.Unmarshal(raw, &v1Req))
|
||||
require.Equal(t, "proj-123", v1Req["project"])
|
||||
require.Equal(t, "gemini-3.8-flash-high", v1Req["model"])
|
||||
|
||||
inner, ok := v1Req["request"].(map[string]any)
|
||||
require.True(t, ok)
|
||||
toolCfg, ok := inner["toolConfig"].(map[string]any)
|
||||
require.True(t, ok, "expected toolConfig to be present in Gemini test request")
|
||||
fcCfg, ok := toolCfg["functionCallingConfig"].(map[string]any)
|
||||
require.True(t, ok)
|
||||
require.Equal(t, "VALIDATED", fcCfg["mode"])
|
||||
}
|
||||
|
||||
func TestAntigravityBuildGeminiTestRequestWithPrompt_ImageModel(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
svc := &AntigravityGatewayService{}
|
||||
raw, err := svc.buildGeminiTestRequestWithPrompt("proj-123", "gemini-3.1-flash-image", "a cute cat")
|
||||
require.NoError(t, err)
|
||||
|
||||
var v1Req map[string]any
|
||||
require.NoError(t, json.Unmarshal(raw, &v1Req))
|
||||
inner, ok := v1Req["request"].(map[string]any)
|
||||
require.True(t, ok)
|
||||
|
||||
genCfg, ok := inner["generationConfig"].(map[string]any)
|
||||
require.True(t, ok)
|
||||
require.Equal(t, []any{"TEXT", "IMAGE"}, genCfg["responseModalities"])
|
||||
|
||||
contents, ok := inner["contents"].([]any)
|
||||
require.True(t, ok)
|
||||
require.Len(t, contents, 1)
|
||||
firstContent := contents[0].(map[string]any)
|
||||
parts := firstContent["parts"].([]any)
|
||||
require.Equal(t, "a cute cat", parts[0].(map[string]any)["text"])
|
||||
}
|
||||
|
||||
func TestExtractContentFromSSEResponse_ExtractsTextAndInlineImages(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
sse := "data: {\"response\":{\"candidates\":[{\"content\":{\"parts\":[{\"text\":\"Here is your image\"},{\"inlineData\":{\"mimeType\":\"image/png\",\"data\":\"iVBORw0KGgo=\"}}]}}]}}\n\n"
|
||||
text, images := extractContentFromSSEResponse([]byte(sse))
|
||||
require.Equal(t, "Here is your image", text)
|
||||
require.Len(t, images, 1)
|
||||
require.Equal(t, "image/png", images[0].MimeType)
|
||||
require.Equal(t, "data:image/png;base64,iVBORw0KGgo=", images[0].ImageURL)
|
||||
}
|
||||
|
||||
func TestAntigravityShouldUseGeminiTestBuilder_UsesMappedModel(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
require.True(t, shouldUseAntigravityGeminiTestRequest("custom-alias", "gemini-2.5-flash"))
|
||||
require.True(t, shouldUseAntigravityGeminiTestRequest("gemini-3.1-pro", "gemini-pro-agent"))
|
||||
require.False(t, shouldUseAntigravityGeminiTestRequest("gemini-alias", "claude-sonnet-4-6"))
|
||||
require.False(t, shouldUseAntigravityGeminiTestRequest("claude-sonnet-4-6", "claude-sonnet-4-6"))
|
||||
}
|
||||
@@ -86,12 +86,30 @@ func TestGetWebSearchEmulationMode_MissingField(t *testing.T) {
|
||||
require.Equal(t, WebSearchModeDefault, a.GetWebSearchEmulationMode())
|
||||
}
|
||||
|
||||
func TestGetWebSearchEmulationMode_NonAnthropicPlatform(t *testing.T) {
|
||||
func TestGetWebSearchEmulationMode_OpenAIAPIKey(t *testing.T) {
|
||||
a := &Account{
|
||||
Platform: PlatformOpenAI,
|
||||
Type: AccountTypeAPIKey,
|
||||
Extra: map[string]any{featureKeyWebSearchEmulation: "enabled"},
|
||||
}
|
||||
require.Equal(t, WebSearchModeEnabled, a.GetWebSearchEmulationMode())
|
||||
}
|
||||
|
||||
func TestGetWebSearchEmulationMode_OpenAIOAuth(t *testing.T) {
|
||||
a := &Account{
|
||||
Platform: PlatformOpenAI,
|
||||
Type: AccountTypeOAuth,
|
||||
Extra: map[string]any{featureKeyWebSearchEmulation: "enabled"},
|
||||
}
|
||||
require.Equal(t, WebSearchModeDefault, a.GetWebSearchEmulationMode())
|
||||
}
|
||||
|
||||
func TestGetWebSearchEmulationMode_OtherPlatform(t *testing.T) {
|
||||
a := &Account{
|
||||
Platform: PlatformGemini,
|
||||
Type: AccountTypeAPIKey,
|
||||
Extra: map[string]any{featureKeyWebSearchEmulation: "enabled"},
|
||||
}
|
||||
require.Equal(t, WebSearchModeDefault, a.GetWebSearchEmulationMode())
|
||||
}
|
||||
|
||||
|
||||
@@ -311,10 +311,17 @@ func defaultModelsListCandidateIDs(platform string) []string {
|
||||
}
|
||||
}
|
||||
|
||||
func defaultAllowImageGenerationForPlatform(platform string) bool {
|
||||
// Grok image and video generation routes share the legacy image-generation gate.
|
||||
// Older clients send the false zero value, so Grok groups must default enabled.
|
||||
return platform == PlatformGrok
|
||||
// DefaultAllowImageGenerationForPlatform reports whether new groups on the platform allow
|
||||
// image generation. CreateGroup ORs the requested value with it, so a false in the create
|
||||
// request does not turn it off. Composite defaults disabled because the same switch also
|
||||
// gates OpenAI image generation there.
|
||||
func DefaultAllowImageGenerationForPlatform(platform string) bool {
|
||||
switch platform {
|
||||
case PlatformGrok, PlatformGemini, PlatformAntigravity:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func compositeDefaultModelsListCandidateIDs() []string {
|
||||
@@ -525,7 +532,7 @@ func (s *adminServiceImpl) CreateGroup(ctx context.Context, input *CreateGroupIn
|
||||
mcpXMLInject = *input.MCPXMLInject
|
||||
}
|
||||
|
||||
allowImageGeneration := input.AllowImageGeneration || defaultAllowImageGenerationForPlatform(platform)
|
||||
allowImageGeneration := input.AllowImageGeneration || DefaultAllowImageGenerationForPlatform(platform)
|
||||
allowBatchImageGeneration := input.AllowBatchImageGeneration && allowImageGeneration && platform == PlatformGemini
|
||||
|
||||
// 如果指定了复制账号的源分组,先获取账号 ID 列表
|
||||
|
||||
@@ -593,41 +593,47 @@ func TestAdminService_CreateGroup_DefaultsGrokMediaGenerationEnabled(t *testing.
|
||||
require.True(t, group.AllowImageGeneration)
|
||||
}
|
||||
|
||||
func TestAdminService_CreateGroup_PreservesNonGrokImageGenerationDisabled(t *testing.T) {
|
||||
repo := &groupRepoStubForAdmin{}
|
||||
svc := &adminServiceImpl{groupRepo: repo}
|
||||
func TestAdminService_CreateGroup_DefaultsGeminiFamilyImageGenerationEnabled(t *testing.T) {
|
||||
for _, platform := range []string{PlatformGemini, PlatformAntigravity} {
|
||||
t.Run(platform, func(t *testing.T) {
|
||||
repo := &groupRepoStubForAdmin{}
|
||||
svc := &adminServiceImpl{groupRepo: repo}
|
||||
|
||||
group, err := svc.CreateGroup(context.Background(), &CreateGroupInput{
|
||||
Name: "anthropic-text",
|
||||
Description: "Anthropic text group",
|
||||
Platform: PlatformAnthropic,
|
||||
RateMultiplier: 1.0,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, group)
|
||||
require.NotNil(t, repo.created)
|
||||
require.False(t, repo.created.AllowImageGeneration)
|
||||
require.False(t, group.AllowImageGeneration)
|
||||
group, err := svc.CreateGroup(context.Background(), &CreateGroupInput{
|
||||
Name: platform + "-images",
|
||||
Description: "Gemini family group",
|
||||
Platform: platform,
|
||||
RateMultiplier: 1.0,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, group)
|
||||
require.NotNil(t, repo.created)
|
||||
require.True(t, repo.created.AllowImageGeneration)
|
||||
require.True(t, group.AllowImageGeneration)
|
||||
require.False(t, repo.created.AllowBatchImageGeneration)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdminService_CreateGroup_DisablesBatchImageWhenImageGenerationDisabled(t *testing.T) {
|
||||
repo := &groupRepoStubForAdmin{}
|
||||
svc := &adminServiceImpl{groupRepo: repo}
|
||||
func TestAdminService_CreateGroup_PreservesImageGenerationDisabledWithoutPlatformDefault(t *testing.T) {
|
||||
for _, platform := range []string{PlatformAnthropic, PlatformComposite} {
|
||||
t.Run(platform, func(t *testing.T) {
|
||||
repo := &groupRepoStubForAdmin{}
|
||||
svc := &adminServiceImpl{groupRepo: repo}
|
||||
|
||||
group, err := svc.CreateGroup(context.Background(), &CreateGroupInput{
|
||||
Name: "gemini-no-image",
|
||||
Description: "Gemini group without image generation",
|
||||
Platform: PlatformGemini,
|
||||
RateMultiplier: 1.0,
|
||||
AllowImageGeneration: false,
|
||||
AllowBatchImageGeneration: true,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, group)
|
||||
require.NotNil(t, repo.created)
|
||||
require.False(t, repo.created.AllowImageGeneration)
|
||||
require.False(t, repo.created.AllowBatchImageGeneration)
|
||||
require.False(t, group.AllowBatchImageGeneration)
|
||||
group, err := svc.CreateGroup(context.Background(), &CreateGroupInput{
|
||||
Name: platform + "-text",
|
||||
Description: "Group without image default",
|
||||
Platform: platform,
|
||||
RateMultiplier: 1.0,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, group)
|
||||
require.NotNil(t, repo.created)
|
||||
require.False(t, repo.created.AllowImageGeneration)
|
||||
require.False(t, group.AllowImageGeneration)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdminService_CreateGroup_DisablesBatchImageForNonGeminiPlatform(t *testing.T) {
|
||||
|
||||
@@ -61,6 +61,9 @@ func (s *AntigravityGatewayService) Forward(ctx context.Context, c *gin.Context,
|
||||
// 应用 thinking 模式自动后缀:如果 thinking 开启且目标是 claude-sonnet-4-5,自动改为 thinking 版本
|
||||
thinkingEnabled := claudeReq.Thinking != nil && (claudeReq.Thinking.Type == "enabled" || claudeReq.Thinking.Type == "adaptive")
|
||||
mappedModel = applyThinkingModelSuffix(mappedModel, thinkingEnabled)
|
||||
if geminiImageGenerationDenied(c, nil, originalModel, mappedModel) {
|
||||
return nil, s.writeClaudeError(c, http.StatusBadRequest, "invalid_request_error", ImageGenerationPermissionMessage())
|
||||
}
|
||||
billingModel := mappedModel
|
||||
|
||||
// 获取 access_token
|
||||
|
||||
@@ -71,7 +71,7 @@ func (s *AntigravityGatewayService) ForwardAsChatCompletions(
|
||||
return nil, s.writeAntigravityCompatError(c, http.StatusBadRequest, "invalid_request_error", "model is required")
|
||||
}
|
||||
|
||||
responsesRequest, err := apicompat.ChatCompletionsToResponses(&request)
|
||||
responsesRequest, err := chatCompletionsToResponses(settingServiceConfig(s.settingService), &request)
|
||||
if err != nil {
|
||||
return nil, s.writeAntigravityCompatError(c, http.StatusBadRequest, "invalid_request_error", err.Error())
|
||||
}
|
||||
@@ -225,6 +225,9 @@ func (s *AntigravityGatewayService) prepareAntigravityCompatCall(
|
||||
thinkingEnabled := claudeRequest.Thinking != nil &&
|
||||
(claudeRequest.Thinking.Type == "enabled" || claudeRequest.Thinking.Type == "adaptive")
|
||||
mappedModel = applyThinkingModelSuffix(mappedModel, thinkingEnabled)
|
||||
if geminiImageGenerationDenied(c, nil, request.originalModel, mappedModel) {
|
||||
return nil, s.writeAntigravityCompatError(c, http.StatusBadRequest, "invalid_request_error", ImageGenerationPermissionMessage())
|
||||
}
|
||||
|
||||
if s.tokenProvider == nil {
|
||||
return nil, s.writeAntigravityCompatError(c, http.StatusBadGateway, "api_error", "Antigravity token provider not configured")
|
||||
|
||||
@@ -96,6 +96,9 @@ func (s *AntigravityGatewayService) ForwardGemini(ctx context.Context, c *gin.Co
|
||||
MarkOpsClientBusinessLimited(c, OpsClientBusinessLimitedReasonLocalFeatureGate)
|
||||
return nil, s.writeGoogleError(c, http.StatusForbidden, fmt.Sprintf("model %s not in whitelist", originalModel))
|
||||
}
|
||||
if geminiImageGenerationDenied(c, body, originalModel, mappedModel) {
|
||||
return nil, s.writeGoogleError(c, http.StatusBadRequest, ImageGenerationPermissionMessage())
|
||||
}
|
||||
forwardedModel := mappedModel
|
||||
|
||||
// 获取 access_token
|
||||
@@ -141,6 +144,8 @@ func (s *AntigravityGatewayService) ForwardGemini(ctx context.Context, c *gin.Co
|
||||
injectedBody = reconciled
|
||||
}
|
||||
|
||||
injectedBody = ensureGeminiFunctionCallThoughtSignatures(injectedBody)
|
||||
|
||||
// 包装请求
|
||||
wrappedBody, err := s.wrapV1InternalRequest(projectID, mappedModel, injectedBody)
|
||||
if err != nil {
|
||||
|
||||
@@ -78,12 +78,7 @@ func accountHasAntigravityPaidTier(account *Account) bool {
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
switch strings.ToLower(strings.TrimSpace(planType)) {
|
||||
case "pro", "ultra":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
return antigravity.IsPaidPlanType(planType)
|
||||
}
|
||||
|
||||
// smartRetryAction 智能重试的处理结果
|
||||
@@ -855,10 +850,12 @@ func sleepAntigravityBackoffWithContext(ctx context.Context, attempt int) bool {
|
||||
}
|
||||
}
|
||||
|
||||
// isSingleAccountRetry 检查 context 中是否设置了单账号退避重试标记
|
||||
// isSingleAccountRetry 检查是否处于单账号退避重试模式:显式标记优先,否则使用请求挂载的延迟判定。
|
||||
func isSingleAccountRetry(ctx context.Context) bool {
|
||||
v, _ := SingleAccountRetryFromContext(ctx)
|
||||
return v
|
||||
if v, ok := SingleAccountRetryFromContext(ctx); ok {
|
||||
return v
|
||||
}
|
||||
return singleAccountRetryProbeResult(ctx)
|
||||
}
|
||||
|
||||
// setModelRateLimitByModelName 使用官方模型 ID 设置模型级限流
|
||||
|
||||
@@ -344,16 +344,32 @@ func (s *AntigravityGatewayService) IsModelSupported(requestedModel string) bool
|
||||
strings.HasPrefix(requestedModel, "gemini-")
|
||||
}
|
||||
|
||||
// TestConnectionImage 测试连接返回的图片结果
|
||||
type TestConnectionImage struct {
|
||||
ImageURL string
|
||||
MimeType string
|
||||
}
|
||||
|
||||
// TestConnectionResult 测试连接结果
|
||||
type TestConnectionResult struct {
|
||||
Text string // 响应文本
|
||||
MappedModel string // 实际使用的模型
|
||||
Text string // 响应文本
|
||||
Images []TestConnectionImage // 响应图片(图片生成模型)
|
||||
MappedModel string // 实际使用的模型
|
||||
}
|
||||
|
||||
func shouldUseAntigravityGeminiTestRequest(_, mappedModel string) bool {
|
||||
return strings.HasPrefix(strings.ToLower(strings.TrimSpace(mappedModel)), "gemini-")
|
||||
}
|
||||
|
||||
// TestConnection 测试 Antigravity 账号连接。
|
||||
// 复用 antigravityRetryLoop 的完整重试 / credits overages / 智能重试逻辑,
|
||||
// 与真实调度行为一致。差异:不做账号切换(测试指定账号)、不记录 ops 错误。
|
||||
func (s *AntigravityGatewayService) TestConnection(ctx context.Context, account *Account, modelID string) (*TestConnectionResult, error) {
|
||||
return s.TestConnectionWithPrompt(ctx, account, modelID, "")
|
||||
}
|
||||
|
||||
// TestConnectionWithPrompt 测试 Antigravity 账号连接,支持为图片生成模型指定测试提示词。
|
||||
func (s *AntigravityGatewayService) TestConnectionWithPrompt(ctx context.Context, account *Account, modelID string, prompt string) (*TestConnectionResult, error) {
|
||||
|
||||
// 获取 token
|
||||
if s.tokenProvider == nil {
|
||||
@@ -377,8 +393,8 @@ func (s *AntigravityGatewayService) TestConnection(ctx context.Context, account
|
||||
|
||||
// 构建请求体
|
||||
var requestBody []byte
|
||||
if strings.HasPrefix(modelID, "gemini-") {
|
||||
requestBody, err = s.buildGeminiTestRequest(projectID, mappedModel)
|
||||
if shouldUseAntigravityGeminiTestRequest(modelID, mappedModel) {
|
||||
requestBody, err = s.buildGeminiTestRequestWithPrompt(projectID, mappedModel, prompt)
|
||||
} else {
|
||||
requestBody, err = s.buildClaudeTestRequest(projectID, mappedModel)
|
||||
}
|
||||
@@ -434,8 +450,8 @@ func (s *AntigravityGatewayService) TestConnection(ctx context.Context, account
|
||||
return nil, fmt.Errorf("API 返回 %d: %s", result.resp.StatusCode, string(respBody))
|
||||
}
|
||||
|
||||
text := extractTextFromSSEResponse(respBody)
|
||||
return &TestConnectionResult{Text: text, MappedModel: mappedModel}, nil
|
||||
text, images := extractContentFromSSEResponse(respBody)
|
||||
return &TestConnectionResult{Text: text, Images: images, MappedModel: mappedModel}, nil
|
||||
}
|
||||
|
||||
// testConnectionHandleError 是 TestConnection 使用的轻量 handleError 回调。
|
||||
@@ -451,9 +467,39 @@ func testConnectionHandleError(
|
||||
return nil
|
||||
}
|
||||
|
||||
// buildGeminiTestRequest 构建 Gemini 格式测试请求
|
||||
// 使用最小 token 消耗:输入 "." + maxOutputTokens: 1
|
||||
func (s *AntigravityGatewayService) buildGeminiTestRequest(projectID, model string) ([]byte, error) {
|
||||
// buildGeminiTestRequestWithPrompt 构建 Gemini 格式测试请求
|
||||
// 文本模型使用最小 token 消耗:输入 "." + maxOutputTokens: 1;图片模型使用图片生成配置
|
||||
func (s *AntigravityGatewayService) buildGeminiTestRequestWithPrompt(projectID, model, prompt string) ([]byte, error) {
|
||||
if isImageGenerationModel(model) {
|
||||
imagePrompt := strings.TrimSpace(prompt)
|
||||
if imagePrompt == "" {
|
||||
imagePrompt = defaultGeminiImageTestPrompt
|
||||
}
|
||||
payload := map[string]any{
|
||||
"contents": []map[string]any{
|
||||
{
|
||||
"role": "user",
|
||||
"parts": []map[string]any{
|
||||
{"text": imagePrompt},
|
||||
},
|
||||
},
|
||||
},
|
||||
"systemInstruction": map[string]any{
|
||||
"parts": []map[string]any{
|
||||
{"text": antigravity.GetDefaultIdentityPatch()},
|
||||
},
|
||||
},
|
||||
"generationConfig": map[string]any{
|
||||
"responseModalities": []string{"TEXT", "IMAGE"},
|
||||
"imageConfig": map[string]any{
|
||||
"aspectRatio": "1:1",
|
||||
},
|
||||
},
|
||||
}
|
||||
payloadBytes, _ := json.Marshal(payload)
|
||||
return s.wrapV1InternalRequest(projectID, model, payloadBytes)
|
||||
}
|
||||
|
||||
payload := map[string]any{
|
||||
"contents": []map[string]any{
|
||||
{
|
||||
@@ -472,6 +518,11 @@ func (s *AntigravityGatewayService) buildGeminiTestRequest(projectID, model stri
|
||||
"generationConfig": map[string]any{
|
||||
"maxOutputTokens": 1,
|
||||
},
|
||||
"toolConfig": map[string]any{
|
||||
"functionCallingConfig": map[string]any{
|
||||
"mode": "VALIDATED",
|
||||
},
|
||||
},
|
||||
}
|
||||
payloadBytes, _ := json.Marshal(payload)
|
||||
return s.wrapV1InternalRequest(projectID, model, payloadBytes)
|
||||
@@ -504,9 +555,10 @@ func (s *AntigravityGatewayService) getClaudeTransformOptions(ctx context.Contex
|
||||
return opts
|
||||
}
|
||||
|
||||
// extractTextFromSSEResponse 从 SSE 流式响应中提取文本
|
||||
func extractTextFromSSEResponse(respBody []byte) string {
|
||||
// extractContentFromSSEResponse 从 SSE 流式响应中提取文本和内联图片
|
||||
func extractContentFromSSEResponse(respBody []byte) (string, []TestConnectionImage) {
|
||||
var texts []string
|
||||
var images []TestConnectionImage
|
||||
lines := bytes.Split(respBody, []byte("\n"))
|
||||
|
||||
for _, line := range lines {
|
||||
@@ -532,7 +584,7 @@ func extractTextFromSSEResponse(respBody []byte) string {
|
||||
continue
|
||||
}
|
||||
|
||||
// 尝试从 response.candidates[0].content.parts[].text 提取
|
||||
// 尝试从 response.candidates[0].content.parts[] 提取
|
||||
response, ok := data["response"].(map[string]any)
|
||||
if !ok {
|
||||
// 尝试直接从 candidates 提取(某些响应格式)
|
||||
@@ -564,11 +616,21 @@ func extractTextFromSSEResponse(respBody []byte) string {
|
||||
if text, ok := partMap["text"].(string); ok && text != "" {
|
||||
texts = append(texts, text)
|
||||
}
|
||||
if inlineData, ok := partMap["inlineData"].(map[string]any); ok {
|
||||
mimeType, _ := inlineData["mimeType"].(string)
|
||||
b64Data, _ := inlineData["data"].(string)
|
||||
if strings.HasPrefix(strings.ToLower(mimeType), "image/") && b64Data != "" {
|
||||
images = append(images, TestConnectionImage{
|
||||
ImageURL: fmt.Sprintf("data:%s;base64,%s", mimeType, b64Data),
|
||||
MimeType: mimeType,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return strings.Join(texts, "")
|
||||
return strings.Join(texts, ""), images
|
||||
}
|
||||
|
||||
// injectIdentityPatchToGeminiRequest 为 Gemini 格式请求注入身份提示词
|
||||
|
||||
@@ -2012,3 +2012,175 @@ func generateLargeUnwrapJSON(minSize int) []byte {
|
||||
b, _ := json.Marshal(outer)
|
||||
return b
|
||||
}
|
||||
|
||||
func TestAntigravityGatewayService_ForwardGemini_NonStreamPreservesFunctionCallAndThoughtSignature(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
body := []byte(`{"contents":[{"role":"user","parts":[{"text":"Call get_weather for Tokyo."}]}],"tools":[{"functionDeclarations":[{"name":"get_weather","description":"Get weather","parameters":{"type":"object","properties":{"city":{"type":"string"}},"required":["city"]}}]}]}`)
|
||||
|
||||
writer := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(writer)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/v1beta/models/gemini-4-argon:generateContent", bytes.NewReader(body))
|
||||
|
||||
sseStream := strings.Join([]string{
|
||||
`data: {"response":{"candidates":[{"content":{"role":"model","parts":[{"thoughtSignature":"sig_fc_1","functionCall":{"name":"get_weather","args":{"city":"Tokyo"},"id":"call_1"}}]}}],"usageMetadata":{"promptTokenCount":300,"candidatesTokenCount":16,"totalTokenCount":328,"thoughtsTokenCount":12},"modelVersion":"gemini-4-argon","responseId":"resp_1"}}`,
|
||||
"",
|
||||
`data: {"response":{"candidates":[{"content":{"role":"model","parts":[{"text":""}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":300,"candidatesTokenCount":22,"totalTokenCount":334,"thoughtsTokenCount":12},"modelVersion":"gemini-4-argon","responseId":"resp_1"}}`,
|
||||
"",
|
||||
}, "\n")
|
||||
|
||||
upstream := &queuedHTTPUpstreamStub{
|
||||
responses: []*http.Response{{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: http.Header{"Content-Type": []string{"text/event-stream"}},
|
||||
Body: io.NopCloser(strings.NewReader(sseStream)),
|
||||
}},
|
||||
}
|
||||
svc := &AntigravityGatewayService{
|
||||
settingService: NewSettingService(&antigravitySettingRepoStub{}, &config.Config{Gateway: config.GatewayConfig{MaxLineSize: defaultMaxLineSize}}),
|
||||
tokenProvider: &AntigravityTokenProvider{},
|
||||
httpUpstream: upstream,
|
||||
}
|
||||
account := &Account{
|
||||
ID: 109,
|
||||
Name: "antigravity-fc-nonstream",
|
||||
Platform: PlatformAntigravity,
|
||||
Type: AccountTypeOAuth,
|
||||
Status: StatusActive,
|
||||
Concurrency: 1,
|
||||
Credentials: map[string]any{
|
||||
"access_token": "test-access-token",
|
||||
"project_id": "test-project",
|
||||
"model_mapping": map[string]any{
|
||||
"gemini-4-argon": "gemini-4-argon",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
result, err := svc.ForwardGemini(context.Background(), c, account, "gemini-4-argon", "generateContent", false, body, false)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, result)
|
||||
require.Equal(t, http.StatusOK, writer.Code)
|
||||
|
||||
var respPayload map[string]any
|
||||
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), &respPayload))
|
||||
candidates, ok := respPayload["candidates"].([]any)
|
||||
require.True(t, ok)
|
||||
require.Len(t, candidates, 1)
|
||||
candidate, ok := candidates[0].(map[string]any)
|
||||
require.True(t, ok)
|
||||
require.Equal(t, "STOP", candidate["finishReason"])
|
||||
|
||||
content, ok := candidate["content"].(map[string]any)
|
||||
require.True(t, ok)
|
||||
parts, ok := content["parts"].([]any)
|
||||
require.True(t, ok)
|
||||
require.Len(t, parts, 1, "trailing empty text part should not overwrite or pollute functionCall part")
|
||||
|
||||
part0, ok := parts[0].(map[string]any)
|
||||
require.True(t, ok)
|
||||
require.Equal(t, "sig_fc_1", part0["thoughtSignature"])
|
||||
fc, ok := part0["functionCall"].(map[string]any)
|
||||
require.True(t, ok)
|
||||
require.Equal(t, "get_weather", fc["name"])
|
||||
require.Equal(t, "call_1", fc["id"])
|
||||
require.Equal(t, map[string]any{"city": "Tokyo"}, fc["args"])
|
||||
}
|
||||
|
||||
func TestAntigravityGatewayService_ForwardGemini_StreamAndFunctionResponseFollowUp(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
// 1) Stream request with functionDeclarations returns unwrapped functionCall and thoughtSignature
|
||||
streamReqBody := []byte(`{"contents":[{"role":"user","parts":[{"text":"Call get_weather for Tokyo."}]}],"tools":[{"functionDeclarations":[{"name":"get_weather","parameters":{"type":"object","properties":{"city":{"type":"string"}}}}]}]}`)
|
||||
streamWriter := httptest.NewRecorder()
|
||||
streamCtx, _ := gin.CreateTestContext(streamWriter)
|
||||
streamCtx.Request = httptest.NewRequest(http.MethodPost, "/v1beta/models/gemini-4-argon:streamGenerateContent?alt=sse", bytes.NewReader(streamReqBody))
|
||||
|
||||
streamSSE := strings.Join([]string{
|
||||
`data: {"response":{"candidates":[{"content":{"role":"model","parts":[{"thoughtSignature":"sig_stream_1","functionCall":{"name":"get_weather","args":{"city":"Tokyo"},"id":"call_s1"}}]}}],"usageMetadata":{"promptTokenCount":10,"candidatesTokenCount":5}}}`,
|
||||
"",
|
||||
`data: {"response":{"candidates":[{"content":{"role":"model","parts":[{"text":""}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":10,"candidatesTokenCount":6}}}`,
|
||||
"",
|
||||
}, "\n")
|
||||
|
||||
// 2) Non-stream follow-up with functionCall (missing thoughtSignature) + functionResponse (with inlineData image)
|
||||
followUpReqBody := []byte(`{"contents":[{"role":"user","parts":[{"text":"Call get_weather for Tokyo."}]},{"role":"model","parts":[{"functionCall":{"name":"get_weather","args":{"city":"Tokyo"},"id":"call_s1"}}]},{"role":"user","parts":[{"functionResponse":{"name":"get_weather","id":"call_s1","response":{"weather":"Sunny"},"parts":[{"inlineData":{"mimeType":"image/png","data":"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="}}]}}]}],"tools":[{"functionDeclarations":[{"name":"get_weather","parameters":{"type":"object","properties":{"city":{"type":"string"}}}}]}]}`)
|
||||
followUpWriter := httptest.NewRecorder()
|
||||
followUpCtx, _ := gin.CreateTestContext(followUpWriter)
|
||||
followUpCtx.Request = httptest.NewRequest(http.MethodPost, "/v1beta/models/gemini-4-argon:generateContent", bytes.NewReader(followUpReqBody))
|
||||
|
||||
followUpSSE := strings.Join([]string{
|
||||
`data: {"response":{"candidates":[{"content":{"role":"model","parts":[{"text":"It is sunny in "}]}}],"usageMetadata":{"promptTokenCount":20,"candidatesTokenCount":4}}}`,
|
||||
"",
|
||||
`data: {"response":{"candidates":[{"content":{"role":"model","parts":[{"text":"Tokyo."}]}}],"usageMetadata":{"promptTokenCount":20,"candidatesTokenCount":6}}}`,
|
||||
"",
|
||||
`data: {"response":{"candidates":[{"content":{"role":"model","parts":[{"thoughtSignature":"sig_final","text":""}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":20,"candidatesTokenCount":8}}}`,
|
||||
"",
|
||||
}, "\n")
|
||||
|
||||
upstream := &queuedHTTPUpstreamStub{
|
||||
responses: []*http.Response{
|
||||
{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: http.Header{"Content-Type": []string{"text/event-stream"}},
|
||||
Body: io.NopCloser(strings.NewReader(streamSSE)),
|
||||
},
|
||||
{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: http.Header{"Content-Type": []string{"text/event-stream"}},
|
||||
Body: io.NopCloser(strings.NewReader(followUpSSE)),
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
svc := &AntigravityGatewayService{
|
||||
settingService: NewSettingService(&antigravitySettingRepoStub{}, &config.Config{Gateway: config.GatewayConfig{MaxLineSize: defaultMaxLineSize}}),
|
||||
tokenProvider: &AntigravityTokenProvider{},
|
||||
httpUpstream: upstream,
|
||||
}
|
||||
account := &Account{
|
||||
ID: 110,
|
||||
Name: "antigravity-fc-stream",
|
||||
Platform: PlatformAntigravity,
|
||||
Type: AccountTypeOAuth,
|
||||
Status: StatusActive,
|
||||
Concurrency: 1,
|
||||
Credentials: map[string]any{
|
||||
"access_token": "test-access-token",
|
||||
"project_id": "test-project",
|
||||
"model_mapping": map[string]any{
|
||||
"gemini-4-argon": "gemini-4-argon",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
res1, err := svc.ForwardGemini(context.Background(), streamCtx, account, "gemini-4-argon", "streamGenerateContent", true, streamReqBody, false)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, res1)
|
||||
require.Contains(t, streamWriter.Body.String(), `"functionCall":{"name":"get_weather","args":{"city":"Tokyo"},"id":"call_s1"}`)
|
||||
require.Contains(t, streamWriter.Body.String(), `"thoughtSignature":"sig_stream_1"`)
|
||||
|
||||
res2, err := svc.ForwardGemini(context.Background(), followUpCtx, account, "gemini-4-argon", "generateContent", false, followUpReqBody, false)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, res2)
|
||||
require.Len(t, upstream.requestBodies, 2)
|
||||
|
||||
// Verify follow-up request had dummy thoughtSignature injected on functionCall and preserved functionResponse image part
|
||||
secondSent := string(upstream.requestBodies[1])
|
||||
require.Contains(t, secondSent, `"thoughtSignature":"skip_thought_signature_validator"`)
|
||||
require.Contains(t, secondSent, `"mimeType":"image/png"`)
|
||||
|
||||
var followUpResp map[string]any
|
||||
require.NoError(t, json.Unmarshal(followUpWriter.Body.Bytes(), &followUpResp))
|
||||
cands, ok := followUpResp["candidates"].([]any)
|
||||
require.True(t, ok)
|
||||
cand0, ok := cands[0].(map[string]any)
|
||||
require.True(t, ok)
|
||||
content, ok := cand0["content"].(map[string]any)
|
||||
require.True(t, ok)
|
||||
parts, ok := content["parts"].([]any)
|
||||
require.True(t, ok)
|
||||
require.NotEmpty(t, parts)
|
||||
firstPart, ok := parts[0].(map[string]any)
|
||||
require.True(t, ok)
|
||||
require.Equal(t, "It is sunny in Tokyo.", firstPart["text"])
|
||||
}
|
||||
@@ -350,8 +350,7 @@ func (s *AntigravityGatewayService) handleGeminiStreamToNonStreaming(c *gin.Cont
|
||||
var firstTokenMs *int
|
||||
var last map[string]any
|
||||
var lastWithParts map[string]any
|
||||
var collectedImageParts []map[string]any // 收集所有包含图片的 parts
|
||||
var collectedTextParts []string // 收集所有文本片段
|
||||
var collectedParts []map[string]any // 收集所有 parts(text、thinking、functionCall、inlineData 等)
|
||||
|
||||
type scanEvent struct {
|
||||
line string
|
||||
@@ -467,19 +466,10 @@ func (s *AntigravityGatewayService) handleGeminiStreamToNonStreaming(c *gin.Cont
|
||||
}
|
||||
}
|
||||
|
||||
// 保留最后一个有 parts 的响应
|
||||
// 保留最后一个有 parts 的响应,并收集所有 parts
|
||||
if parts := extractGeminiParts(parsed); len(parts) > 0 {
|
||||
lastWithParts = parsed
|
||||
// 收集包含图片和文本的 parts
|
||||
for _, part := range parts {
|
||||
if inlineData, ok := part["inlineData"].(map[string]any); ok {
|
||||
collectedImageParts = append(collectedImageParts, part)
|
||||
_ = inlineData // 避免 unused 警告
|
||||
}
|
||||
if text, ok := part["text"].(string); ok && text != "" {
|
||||
collectedTextParts = append(collectedTextParts, text)
|
||||
}
|
||||
}
|
||||
collectedParts = append(collectedParts, parts...)
|
||||
}
|
||||
|
||||
case <-intervalCh:
|
||||
@@ -506,14 +496,9 @@ returnResponse:
|
||||
}
|
||||
}
|
||||
|
||||
// 如果收集到了图片 parts,需要合并到最终响应中
|
||||
if len(collectedImageParts) > 0 {
|
||||
finalResponse = mergeImagePartsToResponse(finalResponse, collectedImageParts)
|
||||
}
|
||||
|
||||
// 如果收集到了文本,需要合并到最终响应中
|
||||
if len(collectedTextParts) > 0 {
|
||||
finalResponse = mergeTextPartsToResponse(finalResponse, collectedTextParts)
|
||||
// 将收集的所有 parts 合并到最终响应中
|
||||
if len(collectedParts) > 0 {
|
||||
finalResponse = mergeCollectedPartsToResponse(finalResponse, collectedParts)
|
||||
}
|
||||
|
||||
respBody, err := json.Marshal(finalResponse)
|
||||
@@ -576,21 +561,27 @@ func mergeCollectedPartsToResponse(response map[string]any, collectedParts []map
|
||||
return response
|
||||
}
|
||||
|
||||
result, _, setParts := getOrCreateGeminiParts(response)
|
||||
result, existingParts, setParts := getOrCreateGeminiParts(response)
|
||||
|
||||
// 合并策略:
|
||||
// 1. 保持原始顺序
|
||||
// 2. 连续的普通 text parts 合并为一个
|
||||
// 2. 连续的普通 text parts 合并为一个,并保留关联的 thoughtSignature
|
||||
// 3. thinking、functionCall、inlineData 等保持原样
|
||||
var mergedParts []any
|
||||
var textBuffer strings.Builder
|
||||
var textSignature string
|
||||
|
||||
flushTextBuffer := func() {
|
||||
if textBuffer.Len() > 0 {
|
||||
mergedParts = append(mergedParts, map[string]any{
|
||||
if textBuffer.Len() > 0 || textSignature != "" {
|
||||
part := map[string]any{
|
||||
"text": textBuffer.String(),
|
||||
})
|
||||
}
|
||||
if textSignature != "" {
|
||||
part["thoughtSignature"] = textSignature
|
||||
}
|
||||
mergedParts = append(mergedParts, part)
|
||||
textBuffer.Reset()
|
||||
textSignature = ""
|
||||
}
|
||||
}
|
||||
|
||||
@@ -605,6 +596,9 @@ func mergeCollectedPartsToResponse(response map[string]any, collectedParts []map
|
||||
} else {
|
||||
// 普通 text,累积到 buffer
|
||||
_, _ = textBuffer.WriteString(text)
|
||||
if sig, ok := part["thoughtSignature"].(string); ok && sig != "" {
|
||||
textSignature = sig
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// 非 text part(functionCall、inlineData 等),先刷新 text buffer,然后保留原样
|
||||
@@ -616,76 +610,14 @@ func mergeCollectedPartsToResponse(response map[string]any, collectedParts []map
|
||||
// 刷新剩余的 text
|
||||
flushTextBuffer()
|
||||
|
||||
if len(mergedParts) == 0 {
|
||||
mergedParts = existingParts
|
||||
}
|
||||
|
||||
setParts(mergedParts)
|
||||
return result
|
||||
}
|
||||
|
||||
// mergeImagePartsToResponse 将收集到的图片 parts 合并到 Gemini 响应中
|
||||
func mergeImagePartsToResponse(response map[string]any, imageParts []map[string]any) map[string]any {
|
||||
if len(imageParts) == 0 {
|
||||
return response
|
||||
}
|
||||
|
||||
result, existingParts, setParts := getOrCreateGeminiParts(response)
|
||||
|
||||
// 检查现有 parts 中是否已经有图片
|
||||
for _, p := range existingParts {
|
||||
if pm, ok := p.(map[string]any); ok {
|
||||
if _, hasInline := pm["inlineData"]; hasInline {
|
||||
return result // 已有图片,不重复添加
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 添加收集到的图片 parts
|
||||
for _, imgPart := range imageParts {
|
||||
existingParts = append(existingParts, imgPart)
|
||||
}
|
||||
setParts(existingParts)
|
||||
return result
|
||||
}
|
||||
|
||||
// mergeTextPartsToResponse 将收集到的文本合并到 Gemini 响应中
|
||||
func mergeTextPartsToResponse(response map[string]any, textParts []string) map[string]any {
|
||||
if len(textParts) == 0 {
|
||||
return response
|
||||
}
|
||||
|
||||
mergedText := strings.Join(textParts, "")
|
||||
result, existingParts, setParts := getOrCreateGeminiParts(response)
|
||||
|
||||
// 查找并更新第一个 text part,或创建新的
|
||||
newParts := make([]any, 0, len(existingParts)+1)
|
||||
textUpdated := false
|
||||
|
||||
for _, p := range existingParts {
|
||||
pm, ok := p.(map[string]any)
|
||||
if !ok {
|
||||
newParts = append(newParts, p)
|
||||
continue
|
||||
}
|
||||
if _, hasText := pm["text"]; hasText && !textUpdated {
|
||||
// 用累积的文本替换
|
||||
newPart := make(map[string]any)
|
||||
for k, v := range pm {
|
||||
newPart[k] = v
|
||||
}
|
||||
newPart["text"] = mergedText
|
||||
newParts = append(newParts, newPart)
|
||||
textUpdated = true
|
||||
} else {
|
||||
newParts = append(newParts, pm)
|
||||
}
|
||||
}
|
||||
|
||||
if !textUpdated {
|
||||
newParts = append([]any{map[string]any{"text": mergedText}}, newParts...)
|
||||
}
|
||||
|
||||
setParts(newParts)
|
||||
return result
|
||||
}
|
||||
|
||||
// antigravityStatusClientClosed 是客户端在上游响应前断开时回写的状态码(499 client closed request)。
|
||||
const antigravityStatusClientClosed = 499
|
||||
|
||||
|
||||
@@ -108,17 +108,6 @@ func geminiThinkingLevelFromClaudeThinking(thinking *antigravity.ThinkingConfig)
|
||||
}
|
||||
}
|
||||
|
||||
// accountRawModelMappingHasKey 判断 key 是否由用户写在账号 credentials.model_mapping 里
|
||||
// (而不是 resolveModelMapping 运行时补进来的默认透传条目)。
|
||||
func accountRawModelMappingHasKey(account *Account, key string) bool {
|
||||
if account == nil || account.Credentials == nil {
|
||||
return false
|
||||
}
|
||||
raw, _ := account.Credentials["model_mapping"].(map[string]any)
|
||||
_, ok := raw[key]
|
||||
return ok
|
||||
}
|
||||
|
||||
// resolveGeminiThinkingVariant 为裸 Gemini 模型名挑选账号映射表里存在的思考深度变体。
|
||||
// 返回 (映射后的上游模型名, 是否命中)。未命中时调用方应回退到常规 getMappedModel 流程。
|
||||
func resolveGeminiThinkingVariant(account *Account, requestedModel string, body []byte) (string, bool) {
|
||||
@@ -140,16 +129,16 @@ func resolveGeminiThinkingVariantForLevel(account *Account, requestedModel strin
|
||||
if len(mapping) == 0 {
|
||||
return "", false
|
||||
}
|
||||
// 裸名本身已有"真正的"映射 → 尊重现有配置,不做推导。判定分两层:
|
||||
// 1. 映射目标不是自己(如 gemini-3.8-flash → gemini-3.8-flash-tiered):用户明确指定了目标;
|
||||
// 2. 映射目标是自己(原样透传):仅当这条是用户亲手写进 credentials.model_mapping 的才尊重。
|
||||
// resolveModelMapping 会给每个 Antigravity 账号自动补 gemini-3.x-flash 裸名自映射
|
||||
// (ensureAntigravityDefaultPassthroughs),而上游目录里并没有裸名模型,那条自映射
|
||||
// 正是导致 404 的来源,不能算作用户意图。
|
||||
if mapped, matched := resolveRequestedModelInMapping(mapping, model); matched {
|
||||
if strings.TrimSpace(mapped) != model || accountRawModelMappingHasKey(account, model) {
|
||||
return "", false
|
||||
}
|
||||
// 裸名本身若已映射到其他具体模型(如 gemini-3.8-flash → gemini-3.8-flash-tiered、
|
||||
// gemini-3.1-pro → gemini-pro-agent),尊重显式别名配置。
|
||||
// 若裸名映射目标是自己(如前端从 DefaultAntigravityModelMapping 拉取并持久化的
|
||||
// gemini-3.8-flash → gemini-3.8-flash,或 ensureAntigravityDefaultPassthroughs 注入的条目),
|
||||
// 当映射表中存在该模型的精确思考变体(-high/-medium/-low/-tiered)时继续解析变体,
|
||||
// 避免把上游不存在的裸名直接发出导致 404;而对已在映射表中的真实裸模型(如 gemini-2.5-flash),
|
||||
// 仅查找精确变体键以避免被通配符误匹配。
|
||||
mapped, modelMatched := resolveRequestedModelInMapping(mapping, model)
|
||||
if modelMatched && strings.TrimSpace(mapped) != model {
|
||||
return "", false
|
||||
}
|
||||
|
||||
if preferred == "" {
|
||||
@@ -163,8 +152,17 @@ func resolveGeminiThinkingVariantForLevel(account *Account, requestedModel strin
|
||||
}
|
||||
for _, level := range order {
|
||||
candidate := model + "-" + level
|
||||
if mapped, matched := resolveRequestedModelInMapping(mapping, candidate); matched && strings.TrimSpace(mapped) != "" {
|
||||
return mapped, true
|
||||
var (
|
||||
variantMapped string
|
||||
variantMatched bool
|
||||
)
|
||||
if modelMatched {
|
||||
variantMapped, variantMatched = mapping[candidate]
|
||||
} else {
|
||||
variantMapped, variantMatched = resolveRequestedModelInMapping(mapping, candidate)
|
||||
}
|
||||
if variantMatched && strings.TrimSpace(variantMapped) != "" {
|
||||
return variantMapped, true
|
||||
}
|
||||
}
|
||||
return "", false
|
||||
|
||||
@@ -74,10 +74,10 @@ func TestResolveGeminiThinkingVariant(t *testing.T) {
|
||||
{"agy low (1000) -> -low", catalog, "gemini-3.8-flash", budget("1000"), "gemini-3.8-flash-low", true},
|
||||
{"models/ prefix stripped", catalog, "models/gemini-3.8-flash", budget("1000"), "gemini-3.8-flash-low", true},
|
||||
{"no thinkingConfig -> -high", catalog, "gemini-3.8-flash", []byte(`{"contents":[]}`), "gemini-3.8-flash-high", true},
|
||||
// gemini-3.6/3.7/3.8-flash 的四个变体会被 resolveModelMapping 自动补齐,所以降级用一个不在默认表里的型号
|
||||
{"only -high exists: low request degrades to high", map[string]string{
|
||||
"gemini-3.5-flash-high": "gemini-3.5-flash-high",
|
||||
}, "gemini-3.5-flash", budget("1000"), "gemini-3.5-flash-high", true},
|
||||
// gemini-3.6/3.7/3.8-flash 的四个变体会被 resolveModelMapping 自动补齐(存量显式映射账号的兼容透传)。
|
||||
{"injected default variants are usable", catalog, "gemini-3.6-flash", budget("1000"), "gemini-3.6-flash-low", true},
|
||||
{"already suffixed: untouched", catalog, "gemini-3.8-flash-low", budget("-1"), "", false},
|
||||
{"bare name explicitly mapped: untouched", catalog, "gemini-2.5-flash", budget("-1"), "", false},
|
||||
@@ -90,16 +90,22 @@ func TestResolveGeminiThinkingVariant(t *testing.T) {
|
||||
{"variant value is itself a mapping target", map[string]string{
|
||||
"gemini-3.8-flash-high": "gemini-3.8-flash-tiered",
|
||||
}, "gemini-3.8-flash", budget("-1"), "gemini-3.8-flash-tiered", true},
|
||||
{"user-written bare identity passthrough: respected", map[string]string{
|
||||
// 前端持久化的默认目录含裸名自映射;-low 由默认透传补齐,按预算命中。
|
||||
{"persisted default bare identity passthrough still resolves when variants exist", map[string]string{
|
||||
"gemini-3.8-flash": "gemini-3.8-flash",
|
||||
"gemini-3.8-flash-high": "gemini-3.8-flash-high",
|
||||
}, "gemini-3.8-flash", budget("1000"), "", false},
|
||||
{"runtime-injected bare passthrough (not in credentials): still resolved", map[string]string{
|
||||
// resolveModelMapping 会补 gemini-3.7-flash → gemini-3.7-flash 的默认透传,
|
||||
// 但 credentials 里没有这条,应当继续推导变体。
|
||||
}, "gemini-3.8-flash", budget("1000"), "gemini-3.8-flash-low", true},
|
||||
{"bare identity passthrough resolves a configured variant outside the default passthroughs", map[string]string{
|
||||
"gemini-3.5-flash": "gemini-3.5-flash",
|
||||
"gemini-3.5-flash-high": "gemini-3.5-flash-high",
|
||||
}, "gemini-3.5-flash", budget("1000"), "gemini-3.5-flash-high", true},
|
||||
{"wildcard mapping does not fabricate variants for non-tiered bare model", map[string]string{
|
||||
"gemini-2.5*": "gemini-2.5-flash",
|
||||
}, "gemini-2.5-flash", budget("-1"), "", false},
|
||||
{"bare model absent from whitelist: configured variant still resolved", map[string]string{
|
||||
"gemini-3.7-flash-medium": "gemini-3.7-flash-medium",
|
||||
}, "gemini-3.7-flash", budget("4000"), "gemini-3.7-flash-medium", true},
|
||||
// 空 credentials 映射 → 走 DefaultAntigravityModelMapping,其中同样只有带后缀的 3.8 flash
|
||||
// 空 credentials 映射保留默认目录兼容行为。
|
||||
{"empty mapping falls back to default catalog", map[string]string{}, "gemini-3.8-flash", budget("-1"), "gemini-3.8-flash-high", true},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
|
||||
@@ -1093,6 +1093,15 @@ func TestResolveAntigravityForwardBaseURL(t *testing.T) {
|
||||
name: "ultra defaults to daily", account: &Account{Credentials: map[string]any{"plan_type": "ULTRA"}},
|
||||
want: dailyURL,
|
||||
},
|
||||
{
|
||||
name: "stored ultra tier id defaults to daily", account: &Account{Credentials: map[string]any{"plan_type": "g1-ultra-lite-tier"}},
|
||||
want: dailyURL,
|
||||
},
|
||||
{
|
||||
name: "stored pro tier id defaults to daily", account: &Account{Credentials: map[string]any{"plan_type": "g1-pro-tier"}},
|
||||
want: dailyURL,
|
||||
},
|
||||
{name: "free tier id defaults to prod", account: &Account{Credentials: map[string]any{"plan_type": "free-tier"}}, want: prodURL},
|
||||
{name: "free defaults to prod", account: &Account{Credentials: map[string]any{"plan_type": "free"}}, want: prodURL},
|
||||
{name: "abnormal defaults to prod", account: &Account{Credentials: map[string]any{"plan_type": "Abnormal"}}, want: prodURL},
|
||||
{name: "unknown defaults to prod", account: &Account{Credentials: map[string]any{"plan_type": "enterprise"}}, want: prodURL},
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/apicompat"
|
||||
)
|
||||
|
||||
func configuredMinOutputTokens(cfg *config.Config) int {
|
||||
if cfg != nil && cfg.Gateway.MinOutputTokens >= 16 {
|
||||
return cfg.Gateway.MinOutputTokens
|
||||
}
|
||||
return apicompat.DefaultMinMaxOutputTokens
|
||||
}
|
||||
|
||||
func chatCompletionsToResponses(cfg *config.Config, req *apicompat.ChatCompletionsRequest) (*apicompat.ResponsesRequest, error) {
|
||||
return apicompat.ChatCompletionsToResponsesWithMinOutputTokens(req, configuredMinOutputTokens(cfg))
|
||||
}
|
||||
|
||||
func anthropicToResponses(cfg *config.Config, req *apicompat.AnthropicRequest) (*apicompat.ResponsesRequest, error) {
|
||||
return apicompat.AnthropicToResponsesWithMinOutputTokens(req, configuredMinOutputTokens(cfg))
|
||||
}
|
||||
|
||||
func settingServiceConfig(settingService *SettingService) *config.Config {
|
||||
if settingService == nil {
|
||||
return nil
|
||||
}
|
||||
return settingService.cfg
|
||||
}
|
||||
@@ -524,6 +524,27 @@ func (s *BillingService) initFallbackPricing() {
|
||||
SupportsCacheBreakdown: false,
|
||||
}
|
||||
|
||||
// Gemini 4 Argon (Google AI pricing: $2 input / $10 output / $0.10 cached
|
||||
// input per MTok, promotional through 2026-11-30; official rates double to
|
||||
// $4/$20/$0.20 from 2026-12-01). One rate covers every prompt length.
|
||||
// Antigravity's -high/-low/-medium aliases are matched below so unavailable
|
||||
// remote pricing never records token-bearing requests at $0.
|
||||
s.fallbackPrices["gemini-4-argon"] = &ModelPricing{
|
||||
InputPricePerToken: 2e-6,
|
||||
OutputPricePerToken: 10e-6,
|
||||
CacheReadPricePerToken: 0.1e-6,
|
||||
SupportsCacheBreakdown: false,
|
||||
}
|
||||
|
||||
// Gemini 4 Argon Cyber Permissive (Vertex AI pricing: $4 input / $20 output /
|
||||
// $0.20 cached input per MTok). The Gemini 4 Argon promotion does not apply.
|
||||
s.fallbackPrices["gemini-4-argon-cyber-permissive"] = &ModelPricing{
|
||||
InputPricePerToken: 4e-6,
|
||||
OutputPricePerToken: 20e-6,
|
||||
CacheReadPricePerToken: 0.2e-6,
|
||||
SupportsCacheBreakdown: false,
|
||||
}
|
||||
|
||||
// OpenAI GPT-5.4(业务指定价格)
|
||||
s.fallbackPrices["gpt-5.4"] = &ModelPricing{
|
||||
InputPricePerToken: 2.5e-6, // $2.5 per MTok
|
||||
@@ -957,6 +978,20 @@ func (s *BillingService) initFallbackPricing() {
|
||||
LongContextOutputMultiplier: 2,
|
||||
}
|
||||
|
||||
// xAI Grok 4.7 Fast (Cursor and Grok Build only): the same model on faster
|
||||
// infrastructure at $4 input / $1 cached input / $12 output below 200k;
|
||||
// long-context rates are $6 / $1.50 / $18 (1.5x of the Fast base card).
|
||||
s.fallbackPrices["grok-4.7-fast"] = &ModelPricing{
|
||||
InputPricePerToken: 4e-6,
|
||||
OutputPricePerToken: 12e-6,
|
||||
CacheReadPricePerToken: 1e-6,
|
||||
SupportsCacheBreakdown: false,
|
||||
LongContextInputThreshold: 200000,
|
||||
LongContextThresholdInclusive: true,
|
||||
LongContextInputMultiplier: 1.5,
|
||||
LongContextOutputMultiplier: 1.5,
|
||||
}
|
||||
|
||||
// xAI Grok 4.3: $1.25 input / $0.20 cached / $2.50 output below 200k;
|
||||
// long-context rates are $2.50 / $0.40 / $5.
|
||||
s.fallbackPrices["grok-4.3"] = &ModelPricing{
|
||||
@@ -1014,7 +1049,7 @@ func (s *BillingService) initFallbackPricing() {
|
||||
|
||||
// getFallbackPricing 根据模型系列获取回退价格
|
||||
func (s *BillingService) getFallbackPricing(model string) *ModelPricing {
|
||||
modelLower := strings.ToLower(model)
|
||||
modelLower := normalizeAntigravityClaudeTierAlias(strings.ToLower(model))
|
||||
if modelLower == "jev-latest" {
|
||||
return s.fallbackPrices["jev-latest"]
|
||||
}
|
||||
@@ -1082,6 +1117,13 @@ func (s *BillingService) getFallbackPricing(model string) *ModelPricing {
|
||||
if strings.Contains(modelLower, "gemini-3.8-flash") || strings.Contains(modelLower, "gemini-3-8-flash") {
|
||||
return s.fallbackPrices["gemini-3.8-flash"]
|
||||
}
|
||||
// Cyber 变体不享受 Gemini 4 Argon 的优惠价,必须先于 "gemini-4-argon" 判。
|
||||
if strings.Contains(modelLower, "gemini-4-argon-cyber") {
|
||||
return s.fallbackPrices["gemini-4-argon-cyber-permissive"]
|
||||
}
|
||||
if strings.Contains(modelLower, "gemini-4-argon") {
|
||||
return s.fallbackPrices["gemini-4-argon"]
|
||||
}
|
||||
|
||||
// DeepSeek 系列:官方模型 V4 Pro/Flash(含 vision-exp)按各自价卡;
|
||||
// 其余 deepseek-*(含已停服的 deepseek-chat / deepseek-reasoner 与未知型号)
|
||||
@@ -1246,6 +1288,11 @@ func (s *BillingService) getFallbackPricing(model string) *ModelPricing {
|
||||
return s.fallbackPrices["grok-4.6"]
|
||||
case "grok-4.7", "grok-4.7-latest":
|
||||
return s.fallbackPrices["grok-4.7"]
|
||||
// Grok 4.7 Fast IDs (grok-4.7-fast, and the Grok Build ID
|
||||
// grok-4.7-build-fast). Without these cases both fall into the unknown-Grok
|
||||
// family card and bill at the standard 4.7 rate (#8119).
|
||||
case "grok-4.7-fast", "grok-4.7-build-fast":
|
||||
return s.fallbackPrices["grok-4.7-fast"]
|
||||
case "grok-4.5", "grok-4.5-latest":
|
||||
return s.fallbackPrices["grok-4.5"]
|
||||
case "grok-3-mini":
|
||||
|
||||
Loaded 100 of 245 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user