mirror of
https://github.com/Wei-Shaw/sub2api.git
synced 2026-12-04 23:51:08 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2d3e845205 | ||
|
|
c899c8cf37 | ||
|
|
4c4ff36380 | ||
|
|
1e08c4c56f | ||
|
|
2eb24814fe | ||
|
|
825ca7b1fc | ||
|
|
54a2bcfd15 | ||
|
|
27e8f69a9e | ||
|
|
684ab20a0b | ||
|
|
0173830df6 | ||
|
|
724565e4aa | ||
|
|
a03de418c8 | ||
|
|
61ebdbdd43 | ||
|
|
a1f1a0cc6b | ||
|
|
954d44c19c | ||
|
|
38081ef72e | ||
|
|
3c20f9a666 | ||
|
|
e1b76e2245 | ||
|
|
f970bd48c9 | ||
|
|
a0802f00b6 | ||
|
|
0b9f40e230 | ||
|
|
0b26acac07 | ||
|
|
7e2e9ba050 | ||
|
|
2a42833c4c | ||
|
|
c043c24774 | ||
|
|
11c1e944b9 | ||
|
|
d99ee72911 | ||
|
|
dec47e8fae | ||
|
|
fad2f215e8 | ||
|
|
20ad5ec506 | ||
|
|
0b6b4ea956 | ||
|
|
b0f5007f04 | ||
|
|
56f3d3c9b0 | ||
|
|
d60f4e442b | ||
|
|
b74024c786 | ||
|
|
21aacde0b3 | ||
|
|
ddf4c6fd81 | ||
|
|
f3a3d86845 | ||
|
|
b22f73e725 | ||
|
|
d6d53052f8 |
No files matched your search
@@ -1,6 +1,8 @@
|
||||
.PHONY: build build-backend build-frontend test test-backend test-frontend test-frontend-critical
|
||||
|
||||
FRONTEND_CRITICAL_VITEST := \
|
||||
src/api/__tests__/client.spec.ts \
|
||||
src/api/__tests__/tokenRefresh.spec.ts \
|
||||
src/views/auth/__tests__/LinuxDoCallbackView.spec.ts \
|
||||
src/views/auth/__tests__/WechatCallbackView.spec.ts \
|
||||
src/views/user/__tests__/PaymentView.spec.ts \
|
||||
|
||||
@@ -84,12 +84,6 @@ Please read the following carefully before using this project:
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://unity2.ai/register?source=sub2api"><img src="assets/partners/logos/unity2.png" alt="unity2" width="150"></a></td>
|
||||
<td>Thanks to Unity2 for sponsoring this project! <a href="https://unity2.ai/register?source=sub2api">Unity2</a> is a high-performance AI model API relay for individuals, teams, and enterprises, handling 30B+ tokens/day with 5000 RPM concurrency. One API Key works across Claude Code, Codex, OpenAI models, IDE plugins, and Agent workflows, with balance billing, bundled subscriptions, enterprise invoicing, and 1-on-1 support. <a href="https://unity2.ai/register?source=sub2api">Register</a> to claim $2 in balance, plus $10 more by joining the official group — up to $12 in free credit.
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://veilx.io/#/hello/SJRBRVDV"><img src="assets/partners/logos/veilx.png" alt="veilx" width="150"></a></td>
|
||||
<td>Thanks to Veilx for sponsoring this project! <a href="https://veilx.io/#/hello/SJRBRVDV">Veilx</a> CDN is purpose-built for large-scale AI API traffic, deeply optimized for relay services and call chains across OpenAI, Claude, Gemini, and scenarios like chat, image generation, embeddings, and streaming — delivering lower latency and higher stability under heavy concurrency. It also offers China three-network optimized return lines, making it ideal for global AI relay platforms, overseas AI SaaS, and cross-border high-concurrency deployments.
|
||||
|
||||
@@ -87,12 +87,6 @@
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://unity2.ai/register?source=sub2api"><img src="assets/partners/logos/unity2.png" alt="unity2" width="150"></a></td>
|
||||
<td>感谢 Unity2 赞助本项目! <a href="https://unity2.ai/register?source=sub2api">Unity2</a> 是面向个人开发者、团队、企业的高性能 AI 模型 API 中转平台,长期服务国内头部企业,日均承载超 300 亿 token 调用,支持 5000 RPM 级高并发。一个 API Key 即可适配 Claude Code、Codex、OpenAI 模型、IDE 插件和 Agent 工作流等场景。具备企业级稳定供应能力,在高并发、持续调用和团队集中采购场景下依然保持低延迟、高可用。同时支持余额计费、组合订阅、首充优惠、企业开票、专属 1v1 对接,适合个人高频使用和企业长期接入。现在注册 Unity2.ai 可领取 $2 余额,加入官方群再送 $10 余额,合计最高可领 $12 免费额度,适合先体验后长期使用。<a href="https://unity2.ai/register?source=sub2api">注册链接</a>
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://veilx.io/#/hello/SJRBRVDV"><img src="assets/partners/logos/veilx.png" alt="veilx" width="150"></a></td>
|
||||
<td>感谢 Veilx 赞助本项目! <a href="https://veilx.io/#/hello/SJRBRVDV">Veilx</a> CDN 专为超大规模 API 请求场景打造,针对 AI 中转站业务与 AI API 调用链路进行了深度优化,轻松应对高并发、高频请求与大流量传输,为开发者与企业提供更快、更稳、更低延迟的加速体验。无论是 OpenAI、Claude、Gemini 等 AI 接口中转,还是聊天、绘图、Embedding、流式输出等复杂场景,Veilx 都能显著提升响应速度与连接稳定性,有效降低网络波动带来的超时与失败问题。同时,Veilx 提供中国三网优化回国极速线路,大幅提升中国大陆地区访问海外 AI 服务的速度与稳定性,特别适合全球 AI 中转平台、海外 AI SaaS、跨境业务与高并发 API 系统部署。专为 AI API 而生,让你的 AI 中转服务更快、更稳、更省心。<a href="https://veilx.io/#/hello/SJRBRVDV">购买地址</a>
|
||||
|
||||
@@ -86,12 +86,6 @@
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://unity2.ai/register?source=sub2api"><img src="assets/partners/logos/unity2.png" alt="unity2" width="150"></a></td>
|
||||
<td>Unity2 のご支援に感謝します!<a href="https://unity2.ai/register?source=sub2api">Unity2</a> は個人開発者、チーム、企業向けの高性能 AI モデル API 中継プラットフォームです。中国の大手企業に長期にわたりサービスを提供しており、1日あたり 300 億以上のトークン呼び出しを処理し、5000 RPM 級の高並列性をサポートします。1つの API キーで Claude Code、Codex、OpenAI モデル、IDE プラグイン、Agent ワークフローなど様々なシナリオに対応できます。エンタープライズグレードの安定供給能力を備え、高並列・継続的な呼び出し・チームの集中購入シーンでも低レイテンシと高可用性を維持します。残高課金、組み合わせサブスクリプション、初回チャージ特典、企業向け請求書発行、専属 1v1 サポートにも対応しており、個人の頻繁な利用にも企業の長期導入にも適しています。今 Unity2.ai に登録すると $2 の残高、公式グループに参加するとさらに $10 の残高がもらえ、合計最大 $12 の無料クレジットを獲得できます — 試用後に長期利用したい方に最適です。<a href="https://unity2.ai/register?source=sub2api">登録リンク</a>
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://veilx.io/#/hello/SJRBRVDV"><img src="assets/partners/logos/veilx.png" alt="veilx" width="150"></a></td>
|
||||
<td>Veilx のご支援に感謝します!<a href="https://veilx.io/#/hello/SJRBRVDV">Veilx</a> CDN は超大規模 API リクエストシナリオ向けに設計されており、AI 中継サービスと AI API 呼び出しチェーンに対して深く最適化されています。高並列・高頻度リクエスト・大容量トラフィックに容易に対応し、開発者と企業により高速で安定した、低レイテンシの加速体験を提供します。OpenAI、Claude、Gemini などの AI インターフェース中継はもちろん、チャット、画像生成、Embedding、ストリーミング出力などの複雑なシナリオでも、Veilx は応答速度と接続安定性を大幅に向上させ、ネットワーク変動によるタイムアウトや失敗を効果的に削減します。さらに、Veilx は中国三大ネットワーク最適化の高速回線を提供しており、中国本土から海外 AI サービスへのアクセス速度と安定性を大幅に向上させます。グローバル AI 中継プラットフォーム、海外 AI SaaS、越境ビジネス、高並列 API システム展開に特に適しています。AI API のために生まれ、あなたの AI 中継サービスをより速く、より安定して、より安心に。<a href="https://veilx.io/#/hello/SJRBRVDV">購入リンク</a>
|
||||
|
||||
@@ -0,0 +1,237 @@
|
||||
// profit-preview 读取生产只读导出的 JSON(分组利润配置、账号倍率与探测状态、
|
||||
// 用户覆盖倍率、主力模型清单),复用线上 U/D/阈值判定做五平台离线预演。
|
||||
//
|
||||
// 用法:
|
||||
//
|
||||
// go run ./cmd/profit-preview -input dump.json [-assume-enabled] [-json]
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
)
|
||||
|
||||
type inputGroup struct {
|
||||
ID int64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Platform string `json:"platform"`
|
||||
RateMultiplier float64 `json:"rate_multiplier"`
|
||||
SubscriptionType string `json:"subscription_type"`
|
||||
ProfitControlEnabled bool `json:"profit_control_enabled"`
|
||||
ProfitMinMargin float64 `json:"profit_min_margin"`
|
||||
ProfitSafetyBuffer float64 `json:"profit_safety_buffer"`
|
||||
PeakRateEnabled bool `json:"peak_rate_enabled"`
|
||||
PeakStart string `json:"peak_start"`
|
||||
PeakEnd string `json:"peak_end"`
|
||||
PeakRateMultiplier float64 `json:"peak_rate_multiplier"`
|
||||
}
|
||||
|
||||
type inputAccount struct {
|
||||
ID int64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Platform string `json:"platform"`
|
||||
Type string `json:"type"`
|
||||
RateMultiplier *float64 `json:"rate_multiplier"`
|
||||
Extra map[string]any `json:"extra"`
|
||||
ModelMapping map[string]string `json:"model_mapping"`
|
||||
}
|
||||
|
||||
type inputEntry struct {
|
||||
Group inputGroup `json:"group"`
|
||||
Accounts []inputAccount `json:"accounts"`
|
||||
UserOverrides map[string]*float64 `json:"user_overrides"`
|
||||
Models []string `json:"models"`
|
||||
}
|
||||
|
||||
type inputDoc struct {
|
||||
Groups []inputEntry `json:"groups"`
|
||||
}
|
||||
|
||||
func main() {
|
||||
inputPath := flag.String("input", "", "生产只读导出 JSON 路径")
|
||||
assumeEnabled := flag.Bool("assume-enabled", false, "把当前关闭的支持平台分组按保存配置视为已启用")
|
||||
jsonOut := flag.Bool("json", false, "以 JSON 输出完整报告(默认输出可读表格)")
|
||||
flag.Parse()
|
||||
if *inputPath == "" {
|
||||
fmt.Fprintln(os.Stderr, "usage: profit-preview -input dump.json [-assume-enabled] [-json]")
|
||||
os.Exit(2)
|
||||
}
|
||||
raw, err := os.ReadFile(*inputPath)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "read input: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
inputs, err := parsePreviewInputs(raw, *assumeEnabled)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "parse input: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
evalAt := time.Now()
|
||||
reports := service.PreviewProfitAdmission(inputs, evalAt)
|
||||
if len(reports) == 0 {
|
||||
fmt.Fprintln(os.Stderr, "input produced no preview reports")
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
if *jsonOut {
|
||||
enc := json.NewEncoder(os.Stdout)
|
||||
enc.SetIndent("", " ")
|
||||
if err := enc.Encode(map[string]any{"evaluated_at": evalAt, "reports": reports}); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "write output: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
fmt.Printf("利润门预演 @ %s(U=账号倍率;探测状态仅告警)\n", evalAt.Format(time.RFC3339))
|
||||
for _, report := range reports {
|
||||
fmt.Printf("\n== 分组 %d %s [%s] ==\n", report.GroupID, report.GroupName, report.Platform)
|
||||
fmt.Printf(" 利润门生效=%v 假定启用=%v | 默认 D=%.4f 阈值=%.4f | 最低有效 D=%.4f 阈值=%.4f\n",
|
||||
report.EffectiveGate, report.AssumedEnabled,
|
||||
report.DefaultD, report.ThresholdDefault, report.MinEffectiveD, report.ThresholdMinD)
|
||||
counts := map[string]int{}
|
||||
for _, v := range report.Verdicts {
|
||||
counts[v.Class]++
|
||||
rate := "-"
|
||||
if v.AccountRate != nil {
|
||||
rate = fmt.Sprintf("%.4f", *v.AccountRate)
|
||||
}
|
||||
flags := make([]string, 0, 2)
|
||||
if v.RejectedUnderMinD {
|
||||
flags = append(flags, "最低有效D下拒绝")
|
||||
}
|
||||
if len(v.Warnings) > 0 {
|
||||
flags = append(flags, strings.Join(v.Warnings, ","))
|
||||
}
|
||||
suffix := ""
|
||||
if len(flags) > 0 {
|
||||
suffix = " [" + strings.Join(flags, "; ") + "]"
|
||||
}
|
||||
fmt.Printf(" 账号 %-4d %-24s 平台=%-12s U=%-8s 来源=%-19s %s%s\n",
|
||||
v.AccountID, v.Name, v.Platform, rate, v.RateSource, v.Class, suffix)
|
||||
}
|
||||
fmt.Printf(" 分类合计: 准入=%d 利润不足=%d 倍率非法=%d\n",
|
||||
counts[service.ProfitPreviewClassAdmitted],
|
||||
counts[service.ProfitPreviewClassRejectedThreshold],
|
||||
counts[service.ProfitPreviewClassRejectedInvalidRate])
|
||||
models := make([]string, 0, len(report.RemainingByModel))
|
||||
for model := range report.RemainingByModel {
|
||||
models = append(models, model)
|
||||
}
|
||||
sort.Strings(models)
|
||||
for _, model := range models {
|
||||
fmt.Printf(" 模型 %-20s 利润门准入账号: 默认D=%d 最低有效D=%d\n",
|
||||
model, report.RemainingByModel[model], report.RemainingByModelMinD[model])
|
||||
}
|
||||
for _, model := range modelsWithZeroRemaining(report) {
|
||||
fmt.Printf(" 警告: 模型 %s 启用后利润门准入账号为 0\n", model)
|
||||
}
|
||||
for _, model := range modelsWithZeroRemainingUnderMinD(report) {
|
||||
fmt.Printf(" 警告: 模型 %s 在最低有效D(存在低倍率用户覆盖)下利润门准入账号为 0\n", model)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func parsePreviewInputs(raw []byte, assumeEnabled bool) ([]service.ProfitPreviewGroupInput, error) {
|
||||
var doc inputDoc
|
||||
if err := json.Unmarshal(raw, &doc); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(doc.Groups) == 0 {
|
||||
return nil, fmt.Errorf("input contains no groups; check the export query and target configuration")
|
||||
}
|
||||
|
||||
inputs := make([]service.ProfitPreviewGroupInput, 0, len(doc.Groups))
|
||||
for i, entry := range doc.Groups {
|
||||
if entry.Group.ID <= 0 || strings.TrimSpace(entry.Group.Platform) == "" {
|
||||
return nil, fmt.Errorf("invalid group at index %d: id and platform are required", i)
|
||||
}
|
||||
group := &service.Group{
|
||||
ID: entry.Group.ID,
|
||||
Name: entry.Group.Name,
|
||||
Platform: entry.Group.Platform,
|
||||
Status: service.StatusActive,
|
||||
Hydrated: true,
|
||||
RateMultiplier: entry.Group.RateMultiplier,
|
||||
SubscriptionType: entry.Group.SubscriptionType,
|
||||
ProfitControlEnabled: entry.Group.ProfitControlEnabled,
|
||||
ProfitMinMargin: entry.Group.ProfitMinMargin,
|
||||
ProfitSafetyBuffer: entry.Group.ProfitSafetyBuffer,
|
||||
PeakRateEnabled: entry.Group.PeakRateEnabled,
|
||||
PeakStart: entry.Group.PeakStart,
|
||||
PeakEnd: entry.Group.PeakEnd,
|
||||
PeakRateMultiplier: entry.Group.PeakRateMultiplier,
|
||||
}
|
||||
accounts := make([]*service.Account, 0, len(entry.Accounts))
|
||||
for _, a := range entry.Accounts {
|
||||
account := &service.Account{
|
||||
ID: a.ID,
|
||||
Name: a.Name,
|
||||
Platform: a.Platform,
|
||||
Type: a.Type,
|
||||
RateMultiplier: a.RateMultiplier,
|
||||
Extra: a.Extra,
|
||||
}
|
||||
if len(a.ModelMapping) > 0 {
|
||||
mapping := make(map[string]any, len(a.ModelMapping))
|
||||
for k, v := range a.ModelMapping {
|
||||
mapping[k] = v
|
||||
}
|
||||
account.Credentials = map[string]any{"model_mapping": mapping}
|
||||
}
|
||||
accounts = append(accounts, account)
|
||||
}
|
||||
overrides := make(map[int64]float64, len(entry.UserOverrides))
|
||||
for userID, rate := range entry.UserOverrides {
|
||||
if rate == nil {
|
||||
continue
|
||||
}
|
||||
var id int64
|
||||
if _, err := fmt.Sscan(userID, &id); err == nil && id > 0 {
|
||||
overrides[id] = *rate
|
||||
}
|
||||
}
|
||||
inputs = append(inputs, service.ProfitPreviewGroupInput{
|
||||
Group: group,
|
||||
Accounts: accounts,
|
||||
UserOverrides: overrides,
|
||||
Models: entry.Models,
|
||||
AssumeEnabled: assumeEnabled,
|
||||
})
|
||||
}
|
||||
return inputs, nil
|
||||
}
|
||||
|
||||
func modelsWithZeroRemaining(report service.ProfitPreviewGroupReport) []string {
|
||||
var out []string
|
||||
for model, count := range report.RemainingByModel {
|
||||
if count == 0 {
|
||||
out = append(out, model)
|
||||
}
|
||||
}
|
||||
sort.Strings(out)
|
||||
return out
|
||||
}
|
||||
|
||||
// modelsWithZeroRemainingUnderMinD 返回默认 D 下仍有准入账号、但在最低有效 D
|
||||
// 下会归零的模型。最低有效 D 来自分组内最低的用户级倍率覆盖:这些模型对那部分
|
||||
// 用户是全黑的,而只看默认 D 的告警完全看不出来。
|
||||
// 两档都为 0 的模型由 modelsWithZeroRemaining 报告,这里不重复。
|
||||
func modelsWithZeroRemainingUnderMinD(report service.ProfitPreviewGroupReport) []string {
|
||||
var out []string
|
||||
for model, count := range report.RemainingByModelMinD {
|
||||
if count == 0 && report.RemainingByModel[model] > 0 {
|
||||
out = append(out, model)
|
||||
}
|
||||
}
|
||||
sort.Strings(out)
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestParsePreviewInputsIgnoresNullUserOverride(t *testing.T) {
|
||||
raw := []byte(`{
|
||||
"groups": [{
|
||||
"group": {
|
||||
"id": 50,
|
||||
"name": "preview",
|
||||
"platform": "openai",
|
||||
"rate_multiplier": 0.5,
|
||||
"subscription_type": "standard",
|
||||
"profit_control_enabled": false,
|
||||
"profit_min_margin": 0.1,
|
||||
"profit_safety_buffer": 0
|
||||
},
|
||||
"accounts": [{
|
||||
"id": 1,
|
||||
"name": "cheap",
|
||||
"platform": "openai",
|
||||
"type": "apikey",
|
||||
"rate_multiplier": 0.2
|
||||
}],
|
||||
"user_overrides": {"40": null, "41": 0.4},
|
||||
"models": ["gpt-test"]
|
||||
}]
|
||||
}`)
|
||||
|
||||
inputs, err := parsePreviewInputs(raw, true)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, inputs, 1)
|
||||
require.Equal(t, map[int64]float64{41: 0.4}, inputs[0].UserOverrides)
|
||||
require.True(t, inputs[0].AssumeEnabled)
|
||||
|
||||
report := service.PreviewProfitAdmission(inputs, time.Date(2026, 1, 15, 8, 30, 0, 0, time.UTC))[0]
|
||||
require.InDelta(t, 0.4, report.MinEffectiveD, 1e-12, "null 覆盖不能被解码成 0 倍率")
|
||||
require.InDelta(t, 0.36, report.ThresholdMinD, 1e-12)
|
||||
}
|
||||
|
||||
func TestParsePreviewInputsRejectsEmptyGroups(t *testing.T) {
|
||||
for _, raw := range [][]byte{
|
||||
[]byte(`{"groups":null}`),
|
||||
[]byte(`{"groups":[]}`),
|
||||
} {
|
||||
inputs, err := parsePreviewInputs(raw, false)
|
||||
require.ErrorContains(t, err, "input contains no groups")
|
||||
require.Nil(t, inputs)
|
||||
}
|
||||
}
|
||||
|
||||
// TestModelsWithZeroRemainingWarnings 钉死两档 D 的归零告警分工:
|
||||
// 默认 D 归零由 modelsWithZeroRemaining 报告;默认 D 仍有账号但最低有效 D
|
||||
// (分组内存在更低的用户级倍率覆盖)归零的模型必须单独告警——那些用户的该
|
||||
// 模型会全黑,只看默认 D 完全看不出来。两档都为 0 时不重复告警。
|
||||
func TestModelsWithZeroRemainingWarnings(t *testing.T) {
|
||||
report := service.ProfitPreviewGroupReport{
|
||||
RemainingByModel: map[string]int{
|
||||
"both-zero": 0,
|
||||
"min-d-zero": 2,
|
||||
"healthy": 3,
|
||||
"min-d-zero-alt": 1,
|
||||
},
|
||||
RemainingByModelMinD: map[string]int{
|
||||
"both-zero": 0,
|
||||
"min-d-zero": 0,
|
||||
"healthy": 3,
|
||||
"min-d-zero-alt": 0,
|
||||
},
|
||||
}
|
||||
|
||||
if got := modelsWithZeroRemaining(report); len(got) != 1 || got[0] != "both-zero" {
|
||||
t.Fatalf("默认D归零告警应只覆盖 both-zero,got %v", got)
|
||||
}
|
||||
|
||||
got := modelsWithZeroRemainingUnderMinD(report)
|
||||
want := []string{"min-d-zero", "min-d-zero-alt"}
|
||||
if len(got) != len(want) {
|
||||
t.Fatalf("最低有效D归零告警不符: got %v want %v", got, want)
|
||||
}
|
||||
for i := range want {
|
||||
if got[i] != want[i] {
|
||||
t.Fatalf("最低有效D归零告警不符(应按模型名排序): got %v want %v", got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1 +1 @@
|
||||
0.1.169
|
||||
0.1.170
|
||||
@@ -88,6 +88,7 @@ func provideCleanup(
|
||||
schedulerSnapshot *service.SchedulerSnapshotService,
|
||||
tokenRefresh *service.TokenRefreshService,
|
||||
accountExpiry *service.AccountExpiryService,
|
||||
codexVersionSync *service.OpenAICodexVersionSyncService,
|
||||
proxyExpiry *service.ProxyExpiryService,
|
||||
subscriptionExpiry *service.SubscriptionExpiryService,
|
||||
usageCleanup *service.UsageCleanupService,
|
||||
@@ -236,6 +237,10 @@ func provideCleanup(
|
||||
accountExpiry.Stop()
|
||||
return nil
|
||||
}},
|
||||
{"OpenAICodexVersionSyncService", func() error {
|
||||
codexVersionSync.Stop()
|
||||
return nil
|
||||
}},
|
||||
{"ProxyExpiryService", func() error {
|
||||
proxyExpiry.Stop()
|
||||
return nil
|
||||
|
||||
@@ -206,7 +206,7 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
|
||||
imageStorageSettingService := service.ProvideImageStorageSettingService(settingRepository, secretEncryptor, backupService, imageStorageFactory, configConfig)
|
||||
backupHandler := admin.NewBackupHandler(backupService, userService, imageStorageSettingService)
|
||||
oAuthHandler := admin.NewOAuthHandler(oAuthService)
|
||||
openAIOAuthHandler := admin.NewOpenAIOAuthHandler(openAIOAuthService, adminService, openAIQuotaService)
|
||||
openAIOAuthHandler := admin.NewOpenAIOAuthHandler(openAIOAuthService, adminService, openAIQuotaService, rateLimitService)
|
||||
geminiOAuthHandler := admin.NewGeminiOAuthHandler(geminiOAuthService)
|
||||
antigravityOAuthHandler := admin.NewAntigravityOAuthHandler(antigravityOAuthService)
|
||||
tokenRefreshService := service.ProvideTokenRefreshService(accountRepository, oAuthService, openAIOAuthService, geminiOAuthService, antigravityOAuthService, grokOAuthService, compositeTokenCacheInvalidator, schedulerCache, configConfig, tempUnschedCache, privacyClientFactory, proxyRepository, oAuthRefreshAPI, openAIGatewayService)
|
||||
@@ -320,6 +320,7 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
|
||||
opsScheduledReportService := service.ProvideOpsScheduledReportService(opsService, userService, emailService, redisClient, configConfig)
|
||||
opsIngressRejectAggregator := service.ProvideOpsIngressRejectAggregator(opsRepository, opsService)
|
||||
accountExpiryService := service.ProvideAccountExpiryService(accountRepository)
|
||||
openAICodexVersionSyncService := service.ProvideOpenAICodexVersionSyncService(settingRepository, settingService, gitHubReleaseClient)
|
||||
proxyExpiryService := service.ProvideProxyExpiryService(proxyRepository)
|
||||
subscriptionExpiryService := service.ProvideSubscriptionExpiryService(userSubscriptionRepository, settingRepository, notificationEmailService, leaderLockCache, db)
|
||||
batchImageWorkerRuntime := service.ProvideBatchImageWorkerRuntime(batchImageRepository, accountRepository, batchImageQueue, usageBillingRepository, usageLogRepository, batchImageModelPricingResolver, apiKeyAuthCacheInvalidator, configConfig)
|
||||
@@ -327,7 +328,7 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
|
||||
paymentOrderExpiryService := service.ProvidePaymentOrderExpiryService(paymentService, leaderLockCache, db)
|
||||
channelMonitorRunner := service.ProvideChannelMonitorRunner(channelMonitorService, settingService)
|
||||
userPlatformQuotaUsageFlusher := service.ProvideUserPlatformQuotaUsageFlusher(configConfig, billingCache, serviceUserPlatformQuotaRepository, timingWheelService)
|
||||
v := provideCleanup(client, redisClient, opsMetricsCollector, opsAggregationService, opsAlertEvaluatorService, opsCleanupService, opsScheduledReportService, opsSystemLogSink, opsService, opsIngressRejectAggregator, apiKeyService, authCacheInvalidationWorker, schedulerSnapshotService, tokenRefreshService, accountExpiryService, proxyExpiryService, subscriptionExpiryService, usageCleanupService, idempotencyCleanupService, batchImageCleanupService, batchImageWorkerRuntime, pricingService, emailQueueService, billingCacheService, usageRecordWorkerPool, subscriptionService, oAuthService, openAIOAuthService, geminiOAuthService, antigravityOAuthService, grokOAuthService, openAIGatewayService, scheduledTestRunnerService, backupService, paymentOrderExpiryService, channelMonitorRunner, userPlatformQuotaUsageFlusher, upstreamBillingProbeService, ollamaCloudUsageService, auditLogService, promptService)
|
||||
v := provideCleanup(client, redisClient, opsMetricsCollector, opsAggregationService, opsAlertEvaluatorService, opsCleanupService, opsScheduledReportService, opsSystemLogSink, opsService, opsIngressRejectAggregator, apiKeyService, authCacheInvalidationWorker, schedulerSnapshotService, tokenRefreshService, accountExpiryService, openAICodexVersionSyncService, proxyExpiryService, subscriptionExpiryService, usageCleanupService, idempotencyCleanupService, batchImageCleanupService, batchImageWorkerRuntime, pricingService, emailQueueService, billingCacheService, usageRecordWorkerPool, subscriptionService, oAuthService, openAIOAuthService, geminiOAuthService, antigravityOAuthService, grokOAuthService, openAIGatewayService, scheduledTestRunnerService, backupService, paymentOrderExpiryService, channelMonitorRunner, userPlatformQuotaUsageFlusher, upstreamBillingProbeService, ollamaCloudUsageService, auditLogService, promptService)
|
||||
application := &Application{
|
||||
Server: httpServer,
|
||||
PromptAudit: promptService,
|
||||
@@ -371,6 +372,7 @@ func provideCleanup(
|
||||
schedulerSnapshot *service.SchedulerSnapshotService,
|
||||
tokenRefresh *service.TokenRefreshService,
|
||||
accountExpiry *service.AccountExpiryService,
|
||||
codexVersionSync *service.OpenAICodexVersionSyncService,
|
||||
proxyExpiry *service.ProxyExpiryService,
|
||||
subscriptionExpiry *service.SubscriptionExpiryService,
|
||||
usageCleanup *service.UsageCleanupService,
|
||||
@@ -518,6 +520,10 @@ func provideCleanup(
|
||||
accountExpiry.Stop()
|
||||
return nil
|
||||
}},
|
||||
{"OpenAICodexVersionSyncService", func() error {
|
||||
codexVersionSync.Stop()
|
||||
return nil
|
||||
}},
|
||||
{"ProxyExpiryService", func() error {
|
||||
proxyExpiry.Stop()
|
||||
return nil
|
||||
|
||||
@@ -40,6 +40,7 @@ func TestProvideCleanup_WithMinimalDependencies_NoPanic(t *testing.T) {
|
||||
nil,
|
||||
)
|
||||
accountExpirySvc := service.NewAccountExpiryService(nil, time.Second)
|
||||
codexVersionSyncSvc := service.NewOpenAICodexVersionSyncService(nil, nil, nil, time.Second)
|
||||
proxyExpirySvc := service.NewProxyExpiryService(nil, time.Second)
|
||||
subscriptionExpirySvc := service.NewSubscriptionExpiryService(nil, time.Second)
|
||||
pricingSvc := service.NewPricingService(cfg, nil)
|
||||
@@ -65,6 +66,7 @@ func TestProvideCleanup_WithMinimalDependencies_NoPanic(t *testing.T) {
|
||||
schedulerSnapshotSvc,
|
||||
tokenRefreshSvc,
|
||||
accountExpirySvc,
|
||||
codexVersionSyncSvc,
|
||||
proxyExpirySvc,
|
||||
subscriptionExpirySvc,
|
||||
&service.UsageCleanupService{},
|
||||
|
||||
+14
-14
@@ -6828,25 +6828,25 @@ type (
|
||||
APIKey, Account, AccountGroup, Announcement, AnnouncementRead, AuthIdentity,
|
||||
AuthIdentityChannel, BatchImageEvent, BatchImageItem, BatchImageJob,
|
||||
ChannelMonitor, ChannelMonitorDailyRollup, ChannelMonitorHistory,
|
||||
ChannelMonitorRequestTemplate, CompositeModelRoute,
|
||||
ErrorPassthroughRule, Group, IdempotencyRecord, IdentityAdoptionDecision,
|
||||
PaymentAuditLog, PaymentOrder, PaymentProviderInstance, PendingAuthSession,
|
||||
PromoCode, PromoCodeUsage, Proxy, RedeemCode, SecuritySecret, Setting,
|
||||
SubscriptionPlan, TLSFingerprintProfile, UsageCleanupTask, UsageLog, User,
|
||||
UserAllowedGroup, UserAttributeDefinition, UserAttributeValue,
|
||||
UserPlatformQuota, UserSubscription []ent.Hook
|
||||
ChannelMonitorRequestTemplate, CompositeModelRoute, ErrorPassthroughRule,
|
||||
Group, IdempotencyRecord, IdentityAdoptionDecision, PaymentAuditLog,
|
||||
PaymentOrder, PaymentProviderInstance, PendingAuthSession, PromoCode,
|
||||
PromoCodeUsage, Proxy, RedeemCode, SecuritySecret, Setting, SubscriptionPlan,
|
||||
TLSFingerprintProfile, UsageCleanupTask, UsageLog, User, UserAllowedGroup,
|
||||
UserAttributeDefinition, UserAttributeValue, UserPlatformQuota,
|
||||
UserSubscription []ent.Hook
|
||||
}
|
||||
inters struct {
|
||||
APIKey, Account, AccountGroup, Announcement, AnnouncementRead, AuthIdentity,
|
||||
AuthIdentityChannel, BatchImageEvent, BatchImageItem, BatchImageJob,
|
||||
ChannelMonitor, ChannelMonitorDailyRollup, ChannelMonitorHistory,
|
||||
ChannelMonitorRequestTemplate, CompositeModelRoute,
|
||||
ErrorPassthroughRule, Group, IdempotencyRecord, IdentityAdoptionDecision,
|
||||
PaymentAuditLog, PaymentOrder, PaymentProviderInstance, PendingAuthSession,
|
||||
PromoCode, PromoCodeUsage, Proxy, RedeemCode, SecuritySecret, Setting,
|
||||
SubscriptionPlan, TLSFingerprintProfile, UsageCleanupTask, UsageLog, User,
|
||||
UserAllowedGroup, UserAttributeDefinition, UserAttributeValue,
|
||||
UserPlatformQuota, UserSubscription []ent.Interceptor
|
||||
ChannelMonitorRequestTemplate, CompositeModelRoute, ErrorPassthroughRule,
|
||||
Group, IdempotencyRecord, IdentityAdoptionDecision, PaymentAuditLog,
|
||||
PaymentOrder, PaymentProviderInstance, PendingAuthSession, PromoCode,
|
||||
PromoCodeUsage, Proxy, RedeemCode, SecuritySecret, Setting, SubscriptionPlan,
|
||||
TLSFingerprintProfile, UsageCleanupTask, UsageLog, User, UserAllowedGroup,
|
||||
UserAttributeDefinition, UserAttributeValue, UserPlatformQuota,
|
||||
UserSubscription []ent.Interceptor
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
+35
-2
@@ -123,6 +123,12 @@ type Group struct {
|
||||
MaxReasoningEffort string `json:"max_reasoning_effort,omitempty"`
|
||||
// OpenAI reasoning effort 自定义精确映射;先映射再应用上限
|
||||
ReasoningEffortMappings []domain.ReasoningEffortMapping `json:"reasoning_effort_mappings,omitempty"`
|
||||
// 是否启用利润控制:调度时仅允许账号计费倍率满足毛利率要求的账号进入候选池
|
||||
ProfitControlEnabled bool `json:"profit_control_enabled,omitempty"`
|
||||
// 最低毛利率,小数(0.30=30%);账号准入条件为 U <= D*(1-margin-buffer)
|
||||
ProfitMinMargin float64 `json:"profit_min_margin,omitempty"`
|
||||
// 安全缓冲,小数;与 margin 相加后从下游倍率中扣除,默认 0
|
||||
ProfitSafetyBuffer float64 `json:"profit_safety_buffer,omitempty"`
|
||||
// Edges holds the relations/edges for other nodes in the graph.
|
||||
// The values are being populated by the GroupQuery when eager-loading is set.
|
||||
Edges GroupEdges `json:"edges"`
|
||||
@@ -231,9 +237,9 @@ func (*Group) scanValues(columns []string) ([]any, error) {
|
||||
switch columns[i] {
|
||||
case group.FieldModelRouting, group.FieldSupportedModelScopes, group.FieldMessagesDispatchModelConfig, group.FieldModelsListConfig, group.FieldReasoningEffortMappings:
|
||||
values[i] = new([]byte)
|
||||
case group.FieldPeakRateEnabled, group.FieldIsExclusive, group.FieldAllowImageGeneration, group.FieldAllowBatchImageGeneration, group.FieldImageRateIndependent, group.FieldVideoRateIndependent, group.FieldClaudeCodeOnly, group.FieldModelRoutingEnabled, group.FieldMcpXMLInject, group.FieldAllowMessagesDispatch, group.FieldAllowLive, group.FieldRequireOauthOnly, group.FieldRequirePrivacySet:
|
||||
case group.FieldPeakRateEnabled, group.FieldIsExclusive, group.FieldAllowImageGeneration, group.FieldAllowBatchImageGeneration, group.FieldImageRateIndependent, group.FieldVideoRateIndependent, group.FieldClaudeCodeOnly, group.FieldModelRoutingEnabled, group.FieldMcpXMLInject, group.FieldAllowMessagesDispatch, group.FieldAllowLive, group.FieldRequireOauthOnly, group.FieldRequirePrivacySet, group.FieldProfitControlEnabled:
|
||||
values[i] = new(sql.NullBool)
|
||||
case group.FieldRateMultiplier, group.FieldPeakRateMultiplier, group.FieldDailyLimitUsd, group.FieldWeeklyLimitUsd, group.FieldMonthlyLimitUsd, group.FieldImageRateMultiplier, group.FieldImagePrice1k, group.FieldImagePrice2k, group.FieldImagePrice4k, group.FieldBatchImageDiscountMultiplier, group.FieldBatchImageHoldMultiplier, group.FieldVideoRateMultiplier, group.FieldVideoPrice480p, group.FieldVideoPrice720p, group.FieldVideoPrice1080p, group.FieldWebSearchPricePerCall:
|
||||
case group.FieldRateMultiplier, group.FieldPeakRateMultiplier, group.FieldDailyLimitUsd, group.FieldWeeklyLimitUsd, group.FieldMonthlyLimitUsd, group.FieldImageRateMultiplier, group.FieldImagePrice1k, group.FieldImagePrice2k, group.FieldImagePrice4k, group.FieldBatchImageDiscountMultiplier, group.FieldBatchImageHoldMultiplier, group.FieldVideoRateMultiplier, group.FieldVideoPrice480p, group.FieldVideoPrice720p, group.FieldVideoPrice1080p, group.FieldWebSearchPricePerCall, group.FieldProfitMinMargin, group.FieldProfitSafetyBuffer:
|
||||
values[i] = new(sql.NullFloat64)
|
||||
case group.FieldID, group.FieldDefaultValidityDays, group.FieldFallbackGroupID, group.FieldFallbackGroupIDOnInvalidRequest, group.FieldSortOrder, group.FieldRpmLimit:
|
||||
values[i] = new(sql.NullInt64)
|
||||
@@ -599,6 +605,24 @@ func (_m *Group) assignValues(columns []string, values []any) error {
|
||||
return fmt.Errorf("unmarshal field reasoning_effort_mappings: %w", err)
|
||||
}
|
||||
}
|
||||
case group.FieldProfitControlEnabled:
|
||||
if value, ok := values[i].(*sql.NullBool); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field profit_control_enabled", values[i])
|
||||
} else if value.Valid {
|
||||
_m.ProfitControlEnabled = value.Bool
|
||||
}
|
||||
case group.FieldProfitMinMargin:
|
||||
if value, ok := values[i].(*sql.NullFloat64); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field profit_min_margin", values[i])
|
||||
} else if value.Valid {
|
||||
_m.ProfitMinMargin = value.Float64
|
||||
}
|
||||
case group.FieldProfitSafetyBuffer:
|
||||
if value, ok := values[i].(*sql.NullFloat64); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field profit_safety_buffer", values[i])
|
||||
} else if value.Valid {
|
||||
_m.ProfitSafetyBuffer = value.Float64
|
||||
}
|
||||
default:
|
||||
_m.selectValues.Set(columns[i], values[i])
|
||||
}
|
||||
@@ -860,6 +884,15 @@ func (_m *Group) String() string {
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("reasoning_effort_mappings=")
|
||||
builder.WriteString(fmt.Sprintf("%v", _m.ReasoningEffortMappings))
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("profit_control_enabled=")
|
||||
builder.WriteString(fmt.Sprintf("%v", _m.ProfitControlEnabled))
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("profit_min_margin=")
|
||||
builder.WriteString(fmt.Sprintf("%v", _m.ProfitMinMargin))
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("profit_safety_buffer=")
|
||||
builder.WriteString(fmt.Sprintf("%v", _m.ProfitSafetyBuffer))
|
||||
builder.WriteByte(')')
|
||||
return builder.String()
|
||||
}
|
||||
|
||||
@@ -120,6 +120,12 @@ const (
|
||||
FieldMaxReasoningEffort = "max_reasoning_effort"
|
||||
// FieldReasoningEffortMappings holds the string denoting the reasoning_effort_mappings field in the database.
|
||||
FieldReasoningEffortMappings = "reasoning_effort_mappings"
|
||||
// FieldProfitControlEnabled holds the string denoting the profit_control_enabled field in the database.
|
||||
FieldProfitControlEnabled = "profit_control_enabled"
|
||||
// FieldProfitMinMargin holds the string denoting the profit_min_margin field in the database.
|
||||
FieldProfitMinMargin = "profit_min_margin"
|
||||
// FieldProfitSafetyBuffer holds the string denoting the profit_safety_buffer field in the database.
|
||||
FieldProfitSafetyBuffer = "profit_safety_buffer"
|
||||
// EdgeAPIKeys holds the string denoting the api_keys edge name in mutations.
|
||||
EdgeAPIKeys = "api_keys"
|
||||
// EdgeRedeemCodes holds the string denoting the redeem_codes edge name in mutations.
|
||||
@@ -247,6 +253,9 @@ var Columns = []string{
|
||||
FieldRpmLimit,
|
||||
FieldMaxReasoningEffort,
|
||||
FieldReasoningEffortMappings,
|
||||
FieldProfitControlEnabled,
|
||||
FieldProfitMinMargin,
|
||||
FieldProfitSafetyBuffer,
|
||||
}
|
||||
|
||||
var (
|
||||
@@ -366,6 +375,12 @@ var (
|
||||
MaxReasoningEffortValidator func(string) error
|
||||
// DefaultReasoningEffortMappings holds the default value on creation for the "reasoning_effort_mappings" field.
|
||||
DefaultReasoningEffortMappings []domain.ReasoningEffortMapping
|
||||
// DefaultProfitControlEnabled holds the default value on creation for the "profit_control_enabled" field.
|
||||
DefaultProfitControlEnabled bool
|
||||
// DefaultProfitMinMargin holds the default value on creation for the "profit_min_margin" field.
|
||||
DefaultProfitMinMargin float64
|
||||
// DefaultProfitSafetyBuffer holds the default value on creation for the "profit_safety_buffer" field.
|
||||
DefaultProfitSafetyBuffer float64
|
||||
)
|
||||
|
||||
// OrderOption defines the ordering options for the Group queries.
|
||||
@@ -611,6 +626,21 @@ func ByMaxReasoningEffort(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldMaxReasoningEffort, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByProfitControlEnabled orders the results by the profit_control_enabled field.
|
||||
func ByProfitControlEnabled(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldProfitControlEnabled, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByProfitMinMargin orders the results by the profit_min_margin field.
|
||||
func ByProfitMinMargin(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldProfitMinMargin, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByProfitSafetyBuffer orders the results by the profit_safety_buffer field.
|
||||
func ByProfitSafetyBuffer(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldProfitSafetyBuffer, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByAPIKeysCount orders the results by api_keys count.
|
||||
func ByAPIKeysCount(opts ...sql.OrderTermOption) OrderOption {
|
||||
return func(s *sql.Selector) {
|
||||
|
||||
@@ -290,6 +290,21 @@ func MaxReasoningEffort(v string) predicate.Group {
|
||||
return predicate.Group(sql.FieldEQ(FieldMaxReasoningEffort, v))
|
||||
}
|
||||
|
||||
// ProfitControlEnabled applies equality check predicate on the "profit_control_enabled" field. It's identical to ProfitControlEnabledEQ.
|
||||
func ProfitControlEnabled(v bool) predicate.Group {
|
||||
return predicate.Group(sql.FieldEQ(FieldProfitControlEnabled, v))
|
||||
}
|
||||
|
||||
// ProfitMinMargin applies equality check predicate on the "profit_min_margin" field. It's identical to ProfitMinMarginEQ.
|
||||
func ProfitMinMargin(v float64) predicate.Group {
|
||||
return predicate.Group(sql.FieldEQ(FieldProfitMinMargin, v))
|
||||
}
|
||||
|
||||
// ProfitSafetyBuffer applies equality check predicate on the "profit_safety_buffer" field. It's identical to ProfitSafetyBufferEQ.
|
||||
func ProfitSafetyBuffer(v float64) predicate.Group {
|
||||
return predicate.Group(sql.FieldEQ(FieldProfitSafetyBuffer, v))
|
||||
}
|
||||
|
||||
// CreatedAtEQ applies the EQ predicate on the "created_at" field.
|
||||
func CreatedAtEQ(v time.Time) predicate.Group {
|
||||
return predicate.Group(sql.FieldEQ(FieldCreatedAt, v))
|
||||
@@ -2190,6 +2205,96 @@ func MaxReasoningEffortContainsFold(v string) predicate.Group {
|
||||
return predicate.Group(sql.FieldContainsFold(FieldMaxReasoningEffort, v))
|
||||
}
|
||||
|
||||
// ProfitControlEnabledEQ applies the EQ predicate on the "profit_control_enabled" field.
|
||||
func ProfitControlEnabledEQ(v bool) predicate.Group {
|
||||
return predicate.Group(sql.FieldEQ(FieldProfitControlEnabled, v))
|
||||
}
|
||||
|
||||
// ProfitControlEnabledNEQ applies the NEQ predicate on the "profit_control_enabled" field.
|
||||
func ProfitControlEnabledNEQ(v bool) predicate.Group {
|
||||
return predicate.Group(sql.FieldNEQ(FieldProfitControlEnabled, v))
|
||||
}
|
||||
|
||||
// ProfitMinMarginEQ applies the EQ predicate on the "profit_min_margin" field.
|
||||
func ProfitMinMarginEQ(v float64) predicate.Group {
|
||||
return predicate.Group(sql.FieldEQ(FieldProfitMinMargin, v))
|
||||
}
|
||||
|
||||
// ProfitMinMarginNEQ applies the NEQ predicate on the "profit_min_margin" field.
|
||||
func ProfitMinMarginNEQ(v float64) predicate.Group {
|
||||
return predicate.Group(sql.FieldNEQ(FieldProfitMinMargin, v))
|
||||
}
|
||||
|
||||
// ProfitMinMarginIn applies the In predicate on the "profit_min_margin" field.
|
||||
func ProfitMinMarginIn(vs ...float64) predicate.Group {
|
||||
return predicate.Group(sql.FieldIn(FieldProfitMinMargin, vs...))
|
||||
}
|
||||
|
||||
// ProfitMinMarginNotIn applies the NotIn predicate on the "profit_min_margin" field.
|
||||
func ProfitMinMarginNotIn(vs ...float64) predicate.Group {
|
||||
return predicate.Group(sql.FieldNotIn(FieldProfitMinMargin, vs...))
|
||||
}
|
||||
|
||||
// ProfitMinMarginGT applies the GT predicate on the "profit_min_margin" field.
|
||||
func ProfitMinMarginGT(v float64) predicate.Group {
|
||||
return predicate.Group(sql.FieldGT(FieldProfitMinMargin, v))
|
||||
}
|
||||
|
||||
// ProfitMinMarginGTE applies the GTE predicate on the "profit_min_margin" field.
|
||||
func ProfitMinMarginGTE(v float64) predicate.Group {
|
||||
return predicate.Group(sql.FieldGTE(FieldProfitMinMargin, v))
|
||||
}
|
||||
|
||||
// ProfitMinMarginLT applies the LT predicate on the "profit_min_margin" field.
|
||||
func ProfitMinMarginLT(v float64) predicate.Group {
|
||||
return predicate.Group(sql.FieldLT(FieldProfitMinMargin, v))
|
||||
}
|
||||
|
||||
// ProfitMinMarginLTE applies the LTE predicate on the "profit_min_margin" field.
|
||||
func ProfitMinMarginLTE(v float64) predicate.Group {
|
||||
return predicate.Group(sql.FieldLTE(FieldProfitMinMargin, v))
|
||||
}
|
||||
|
||||
// ProfitSafetyBufferEQ applies the EQ predicate on the "profit_safety_buffer" field.
|
||||
func ProfitSafetyBufferEQ(v float64) predicate.Group {
|
||||
return predicate.Group(sql.FieldEQ(FieldProfitSafetyBuffer, v))
|
||||
}
|
||||
|
||||
// ProfitSafetyBufferNEQ applies the NEQ predicate on the "profit_safety_buffer" field.
|
||||
func ProfitSafetyBufferNEQ(v float64) predicate.Group {
|
||||
return predicate.Group(sql.FieldNEQ(FieldProfitSafetyBuffer, v))
|
||||
}
|
||||
|
||||
// ProfitSafetyBufferIn applies the In predicate on the "profit_safety_buffer" field.
|
||||
func ProfitSafetyBufferIn(vs ...float64) predicate.Group {
|
||||
return predicate.Group(sql.FieldIn(FieldProfitSafetyBuffer, vs...))
|
||||
}
|
||||
|
||||
// ProfitSafetyBufferNotIn applies the NotIn predicate on the "profit_safety_buffer" field.
|
||||
func ProfitSafetyBufferNotIn(vs ...float64) predicate.Group {
|
||||
return predicate.Group(sql.FieldNotIn(FieldProfitSafetyBuffer, vs...))
|
||||
}
|
||||
|
||||
// ProfitSafetyBufferGT applies the GT predicate on the "profit_safety_buffer" field.
|
||||
func ProfitSafetyBufferGT(v float64) predicate.Group {
|
||||
return predicate.Group(sql.FieldGT(FieldProfitSafetyBuffer, v))
|
||||
}
|
||||
|
||||
// ProfitSafetyBufferGTE applies the GTE predicate on the "profit_safety_buffer" field.
|
||||
func ProfitSafetyBufferGTE(v float64) predicate.Group {
|
||||
return predicate.Group(sql.FieldGTE(FieldProfitSafetyBuffer, v))
|
||||
}
|
||||
|
||||
// ProfitSafetyBufferLT applies the LT predicate on the "profit_safety_buffer" field.
|
||||
func ProfitSafetyBufferLT(v float64) predicate.Group {
|
||||
return predicate.Group(sql.FieldLT(FieldProfitSafetyBuffer, v))
|
||||
}
|
||||
|
||||
// ProfitSafetyBufferLTE applies the LTE predicate on the "profit_safety_buffer" field.
|
||||
func ProfitSafetyBufferLTE(v float64) predicate.Group {
|
||||
return predicate.Group(sql.FieldLTE(FieldProfitSafetyBuffer, v))
|
||||
}
|
||||
|
||||
// HasAPIKeys applies the HasEdge predicate on the "api_keys" edge.
|
||||
func HasAPIKeys() predicate.Group {
|
||||
return predicate.Group(func(s *sql.Selector) {
|
||||
|
||||
@@ -725,6 +725,48 @@ func (_c *GroupCreate) SetReasoningEffortMappings(v []domain.ReasoningEffortMapp
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetProfitControlEnabled sets the "profit_control_enabled" field.
|
||||
func (_c *GroupCreate) SetProfitControlEnabled(v bool) *GroupCreate {
|
||||
_c.mutation.SetProfitControlEnabled(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetNillableProfitControlEnabled sets the "profit_control_enabled" field if the given value is not nil.
|
||||
func (_c *GroupCreate) SetNillableProfitControlEnabled(v *bool) *GroupCreate {
|
||||
if v != nil {
|
||||
_c.SetProfitControlEnabled(*v)
|
||||
}
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetProfitMinMargin sets the "profit_min_margin" field.
|
||||
func (_c *GroupCreate) SetProfitMinMargin(v float64) *GroupCreate {
|
||||
_c.mutation.SetProfitMinMargin(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetNillableProfitMinMargin sets the "profit_min_margin" field if the given value is not nil.
|
||||
func (_c *GroupCreate) SetNillableProfitMinMargin(v *float64) *GroupCreate {
|
||||
if v != nil {
|
||||
_c.SetProfitMinMargin(*v)
|
||||
}
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetProfitSafetyBuffer sets the "profit_safety_buffer" field.
|
||||
func (_c *GroupCreate) SetProfitSafetyBuffer(v float64) *GroupCreate {
|
||||
_c.mutation.SetProfitSafetyBuffer(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetNillableProfitSafetyBuffer sets the "profit_safety_buffer" field if the given value is not nil.
|
||||
func (_c *GroupCreate) SetNillableProfitSafetyBuffer(v *float64) *GroupCreate {
|
||||
if v != nil {
|
||||
_c.SetProfitSafetyBuffer(*v)
|
||||
}
|
||||
return _c
|
||||
}
|
||||
|
||||
// AddAPIKeyIDs adds the "api_keys" edge to the APIKey entity by IDs.
|
||||
func (_c *GroupCreate) AddAPIKeyIDs(ids ...int64) *GroupCreate {
|
||||
_c.mutation.AddAPIKeyIDs(ids...)
|
||||
@@ -998,6 +1040,18 @@ func (_c *GroupCreate) defaults() error {
|
||||
v := group.DefaultReasoningEffortMappings
|
||||
_c.mutation.SetReasoningEffortMappings(v)
|
||||
}
|
||||
if _, ok := _c.mutation.ProfitControlEnabled(); !ok {
|
||||
v := group.DefaultProfitControlEnabled
|
||||
_c.mutation.SetProfitControlEnabled(v)
|
||||
}
|
||||
if _, ok := _c.mutation.ProfitMinMargin(); !ok {
|
||||
v := group.DefaultProfitMinMargin
|
||||
_c.mutation.SetProfitMinMargin(v)
|
||||
}
|
||||
if _, ok := _c.mutation.ProfitSafetyBuffer(); !ok {
|
||||
v := group.DefaultProfitSafetyBuffer
|
||||
_c.mutation.SetProfitSafetyBuffer(v)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -1156,6 +1210,15 @@ func (_c *GroupCreate) check() error {
|
||||
if _, ok := _c.mutation.ReasoningEffortMappings(); !ok {
|
||||
return &ValidationError{Name: "reasoning_effort_mappings", err: errors.New(`ent: missing required field "Group.reasoning_effort_mappings"`)}
|
||||
}
|
||||
if _, ok := _c.mutation.ProfitControlEnabled(); !ok {
|
||||
return &ValidationError{Name: "profit_control_enabled", err: errors.New(`ent: missing required field "Group.profit_control_enabled"`)}
|
||||
}
|
||||
if _, ok := _c.mutation.ProfitMinMargin(); !ok {
|
||||
return &ValidationError{Name: "profit_min_margin", err: errors.New(`ent: missing required field "Group.profit_min_margin"`)}
|
||||
}
|
||||
if _, ok := _c.mutation.ProfitSafetyBuffer(); !ok {
|
||||
return &ValidationError{Name: "profit_safety_buffer", err: errors.New(`ent: missing required field "Group.profit_safety_buffer"`)}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -1391,6 +1454,18 @@ func (_c *GroupCreate) createSpec() (*Group, *sqlgraph.CreateSpec) {
|
||||
_spec.SetField(group.FieldReasoningEffortMappings, field.TypeJSON, value)
|
||||
_node.ReasoningEffortMappings = value
|
||||
}
|
||||
if value, ok := _c.mutation.ProfitControlEnabled(); ok {
|
||||
_spec.SetField(group.FieldProfitControlEnabled, field.TypeBool, value)
|
||||
_node.ProfitControlEnabled = value
|
||||
}
|
||||
if value, ok := _c.mutation.ProfitMinMargin(); ok {
|
||||
_spec.SetField(group.FieldProfitMinMargin, field.TypeFloat64, value)
|
||||
_node.ProfitMinMargin = value
|
||||
}
|
||||
if value, ok := _c.mutation.ProfitSafetyBuffer(); ok {
|
||||
_spec.SetField(group.FieldProfitSafetyBuffer, field.TypeFloat64, value)
|
||||
_node.ProfitSafetyBuffer = value
|
||||
}
|
||||
if nodes := _c.mutation.APIKeysIDs(); len(nodes) > 0 {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2M,
|
||||
@@ -2363,6 +2438,54 @@ func (u *GroupUpsert) UpdateReasoningEffortMappings() *GroupUpsert {
|
||||
return u
|
||||
}
|
||||
|
||||
// SetProfitControlEnabled sets the "profit_control_enabled" field.
|
||||
func (u *GroupUpsert) SetProfitControlEnabled(v bool) *GroupUpsert {
|
||||
u.Set(group.FieldProfitControlEnabled, v)
|
||||
return u
|
||||
}
|
||||
|
||||
// UpdateProfitControlEnabled sets the "profit_control_enabled" field to the value that was provided on create.
|
||||
func (u *GroupUpsert) UpdateProfitControlEnabled() *GroupUpsert {
|
||||
u.SetExcluded(group.FieldProfitControlEnabled)
|
||||
return u
|
||||
}
|
||||
|
||||
// SetProfitMinMargin sets the "profit_min_margin" field.
|
||||
func (u *GroupUpsert) SetProfitMinMargin(v float64) *GroupUpsert {
|
||||
u.Set(group.FieldProfitMinMargin, v)
|
||||
return u
|
||||
}
|
||||
|
||||
// UpdateProfitMinMargin sets the "profit_min_margin" field to the value that was provided on create.
|
||||
func (u *GroupUpsert) UpdateProfitMinMargin() *GroupUpsert {
|
||||
u.SetExcluded(group.FieldProfitMinMargin)
|
||||
return u
|
||||
}
|
||||
|
||||
// AddProfitMinMargin adds v to the "profit_min_margin" field.
|
||||
func (u *GroupUpsert) AddProfitMinMargin(v float64) *GroupUpsert {
|
||||
u.Add(group.FieldProfitMinMargin, v)
|
||||
return u
|
||||
}
|
||||
|
||||
// SetProfitSafetyBuffer sets the "profit_safety_buffer" field.
|
||||
func (u *GroupUpsert) SetProfitSafetyBuffer(v float64) *GroupUpsert {
|
||||
u.Set(group.FieldProfitSafetyBuffer, v)
|
||||
return u
|
||||
}
|
||||
|
||||
// UpdateProfitSafetyBuffer sets the "profit_safety_buffer" field to the value that was provided on create.
|
||||
func (u *GroupUpsert) UpdateProfitSafetyBuffer() *GroupUpsert {
|
||||
u.SetExcluded(group.FieldProfitSafetyBuffer)
|
||||
return u
|
||||
}
|
||||
|
||||
// AddProfitSafetyBuffer adds v to the "profit_safety_buffer" field.
|
||||
func (u *GroupUpsert) AddProfitSafetyBuffer(v float64) *GroupUpsert {
|
||||
u.Add(group.FieldProfitSafetyBuffer, v)
|
||||
return u
|
||||
}
|
||||
|
||||
// UpdateNewValues updates the mutable fields using the new values that were set on create.
|
||||
// Using this option is equivalent to using:
|
||||
//
|
||||
@@ -3363,6 +3486,62 @@ func (u *GroupUpsertOne) UpdateReasoningEffortMappings() *GroupUpsertOne {
|
||||
})
|
||||
}
|
||||
|
||||
// SetProfitControlEnabled sets the "profit_control_enabled" field.
|
||||
func (u *GroupUpsertOne) SetProfitControlEnabled(v bool) *GroupUpsertOne {
|
||||
return u.Update(func(s *GroupUpsert) {
|
||||
s.SetProfitControlEnabled(v)
|
||||
})
|
||||
}
|
||||
|
||||
// UpdateProfitControlEnabled sets the "profit_control_enabled" field to the value that was provided on create.
|
||||
func (u *GroupUpsertOne) UpdateProfitControlEnabled() *GroupUpsertOne {
|
||||
return u.Update(func(s *GroupUpsert) {
|
||||
s.UpdateProfitControlEnabled()
|
||||
})
|
||||
}
|
||||
|
||||
// SetProfitMinMargin sets the "profit_min_margin" field.
|
||||
func (u *GroupUpsertOne) SetProfitMinMargin(v float64) *GroupUpsertOne {
|
||||
return u.Update(func(s *GroupUpsert) {
|
||||
s.SetProfitMinMargin(v)
|
||||
})
|
||||
}
|
||||
|
||||
// AddProfitMinMargin adds v to the "profit_min_margin" field.
|
||||
func (u *GroupUpsertOne) AddProfitMinMargin(v float64) *GroupUpsertOne {
|
||||
return u.Update(func(s *GroupUpsert) {
|
||||
s.AddProfitMinMargin(v)
|
||||
})
|
||||
}
|
||||
|
||||
// UpdateProfitMinMargin sets the "profit_min_margin" field to the value that was provided on create.
|
||||
func (u *GroupUpsertOne) UpdateProfitMinMargin() *GroupUpsertOne {
|
||||
return u.Update(func(s *GroupUpsert) {
|
||||
s.UpdateProfitMinMargin()
|
||||
})
|
||||
}
|
||||
|
||||
// SetProfitSafetyBuffer sets the "profit_safety_buffer" field.
|
||||
func (u *GroupUpsertOne) SetProfitSafetyBuffer(v float64) *GroupUpsertOne {
|
||||
return u.Update(func(s *GroupUpsert) {
|
||||
s.SetProfitSafetyBuffer(v)
|
||||
})
|
||||
}
|
||||
|
||||
// AddProfitSafetyBuffer adds v to the "profit_safety_buffer" field.
|
||||
func (u *GroupUpsertOne) AddProfitSafetyBuffer(v float64) *GroupUpsertOne {
|
||||
return u.Update(func(s *GroupUpsert) {
|
||||
s.AddProfitSafetyBuffer(v)
|
||||
})
|
||||
}
|
||||
|
||||
// UpdateProfitSafetyBuffer sets the "profit_safety_buffer" field to the value that was provided on create.
|
||||
func (u *GroupUpsertOne) UpdateProfitSafetyBuffer() *GroupUpsertOne {
|
||||
return u.Update(func(s *GroupUpsert) {
|
||||
s.UpdateProfitSafetyBuffer()
|
||||
})
|
||||
}
|
||||
|
||||
// Exec executes the query.
|
||||
func (u *GroupUpsertOne) Exec(ctx context.Context) error {
|
||||
if len(u.create.conflict) == 0 {
|
||||
@@ -4529,6 +4708,62 @@ func (u *GroupUpsertBulk) UpdateReasoningEffortMappings() *GroupUpsertBulk {
|
||||
})
|
||||
}
|
||||
|
||||
// SetProfitControlEnabled sets the "profit_control_enabled" field.
|
||||
func (u *GroupUpsertBulk) SetProfitControlEnabled(v bool) *GroupUpsertBulk {
|
||||
return u.Update(func(s *GroupUpsert) {
|
||||
s.SetProfitControlEnabled(v)
|
||||
})
|
||||
}
|
||||
|
||||
// UpdateProfitControlEnabled sets the "profit_control_enabled" field to the value that was provided on create.
|
||||
func (u *GroupUpsertBulk) UpdateProfitControlEnabled() *GroupUpsertBulk {
|
||||
return u.Update(func(s *GroupUpsert) {
|
||||
s.UpdateProfitControlEnabled()
|
||||
})
|
||||
}
|
||||
|
||||
// SetProfitMinMargin sets the "profit_min_margin" field.
|
||||
func (u *GroupUpsertBulk) SetProfitMinMargin(v float64) *GroupUpsertBulk {
|
||||
return u.Update(func(s *GroupUpsert) {
|
||||
s.SetProfitMinMargin(v)
|
||||
})
|
||||
}
|
||||
|
||||
// AddProfitMinMargin adds v to the "profit_min_margin" field.
|
||||
func (u *GroupUpsertBulk) AddProfitMinMargin(v float64) *GroupUpsertBulk {
|
||||
return u.Update(func(s *GroupUpsert) {
|
||||
s.AddProfitMinMargin(v)
|
||||
})
|
||||
}
|
||||
|
||||
// UpdateProfitMinMargin sets the "profit_min_margin" field to the value that was provided on create.
|
||||
func (u *GroupUpsertBulk) UpdateProfitMinMargin() *GroupUpsertBulk {
|
||||
return u.Update(func(s *GroupUpsert) {
|
||||
s.UpdateProfitMinMargin()
|
||||
})
|
||||
}
|
||||
|
||||
// SetProfitSafetyBuffer sets the "profit_safety_buffer" field.
|
||||
func (u *GroupUpsertBulk) SetProfitSafetyBuffer(v float64) *GroupUpsertBulk {
|
||||
return u.Update(func(s *GroupUpsert) {
|
||||
s.SetProfitSafetyBuffer(v)
|
||||
})
|
||||
}
|
||||
|
||||
// AddProfitSafetyBuffer adds v to the "profit_safety_buffer" field.
|
||||
func (u *GroupUpsertBulk) AddProfitSafetyBuffer(v float64) *GroupUpsertBulk {
|
||||
return u.Update(func(s *GroupUpsert) {
|
||||
s.AddProfitSafetyBuffer(v)
|
||||
})
|
||||
}
|
||||
|
||||
// UpdateProfitSafetyBuffer sets the "profit_safety_buffer" field to the value that was provided on create.
|
||||
func (u *GroupUpsertBulk) UpdateProfitSafetyBuffer() *GroupUpsertBulk {
|
||||
return u.Update(func(s *GroupUpsert) {
|
||||
s.UpdateProfitSafetyBuffer()
|
||||
})
|
||||
}
|
||||
|
||||
// Exec executes the query.
|
||||
func (u *GroupUpsertBulk) Exec(ctx context.Context) error {
|
||||
if u.create.err != nil {
|
||||
|
||||
@@ -953,6 +953,62 @@ func (_u *GroupUpdate) AppendReasoningEffortMappings(v []domain.ReasoningEffortM
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetProfitControlEnabled sets the "profit_control_enabled" field.
|
||||
func (_u *GroupUpdate) SetProfitControlEnabled(v bool) *GroupUpdate {
|
||||
_u.mutation.SetProfitControlEnabled(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableProfitControlEnabled sets the "profit_control_enabled" field if the given value is not nil.
|
||||
func (_u *GroupUpdate) SetNillableProfitControlEnabled(v *bool) *GroupUpdate {
|
||||
if v != nil {
|
||||
_u.SetProfitControlEnabled(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetProfitMinMargin sets the "profit_min_margin" field.
|
||||
func (_u *GroupUpdate) SetProfitMinMargin(v float64) *GroupUpdate {
|
||||
_u.mutation.ResetProfitMinMargin()
|
||||
_u.mutation.SetProfitMinMargin(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableProfitMinMargin sets the "profit_min_margin" field if the given value is not nil.
|
||||
func (_u *GroupUpdate) SetNillableProfitMinMargin(v *float64) *GroupUpdate {
|
||||
if v != nil {
|
||||
_u.SetProfitMinMargin(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// AddProfitMinMargin adds value to the "profit_min_margin" field.
|
||||
func (_u *GroupUpdate) AddProfitMinMargin(v float64) *GroupUpdate {
|
||||
_u.mutation.AddProfitMinMargin(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetProfitSafetyBuffer sets the "profit_safety_buffer" field.
|
||||
func (_u *GroupUpdate) SetProfitSafetyBuffer(v float64) *GroupUpdate {
|
||||
_u.mutation.ResetProfitSafetyBuffer()
|
||||
_u.mutation.SetProfitSafetyBuffer(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableProfitSafetyBuffer sets the "profit_safety_buffer" field if the given value is not nil.
|
||||
func (_u *GroupUpdate) SetNillableProfitSafetyBuffer(v *float64) *GroupUpdate {
|
||||
if v != nil {
|
||||
_u.SetProfitSafetyBuffer(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// AddProfitSafetyBuffer adds value to the "profit_safety_buffer" field.
|
||||
func (_u *GroupUpdate) AddProfitSafetyBuffer(v float64) *GroupUpdate {
|
||||
_u.mutation.AddProfitSafetyBuffer(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// AddAPIKeyIDs adds the "api_keys" edge to the APIKey entity by IDs.
|
||||
func (_u *GroupUpdate) AddAPIKeyIDs(ids ...int64) *GroupUpdate {
|
||||
_u.mutation.AddAPIKeyIDs(ids...)
|
||||
@@ -1544,6 +1600,21 @@ func (_u *GroupUpdate) sqlSave(ctx context.Context) (_node int, err error) {
|
||||
sqljson.Append(u, group.FieldReasoningEffortMappings, value)
|
||||
})
|
||||
}
|
||||
if value, ok := _u.mutation.ProfitControlEnabled(); ok {
|
||||
_spec.SetField(group.FieldProfitControlEnabled, field.TypeBool, value)
|
||||
}
|
||||
if value, ok := _u.mutation.ProfitMinMargin(); ok {
|
||||
_spec.SetField(group.FieldProfitMinMargin, field.TypeFloat64, value)
|
||||
}
|
||||
if value, ok := _u.mutation.AddedProfitMinMargin(); ok {
|
||||
_spec.AddField(group.FieldProfitMinMargin, field.TypeFloat64, value)
|
||||
}
|
||||
if value, ok := _u.mutation.ProfitSafetyBuffer(); ok {
|
||||
_spec.SetField(group.FieldProfitSafetyBuffer, field.TypeFloat64, value)
|
||||
}
|
||||
if value, ok := _u.mutation.AddedProfitSafetyBuffer(); ok {
|
||||
_spec.AddField(group.FieldProfitSafetyBuffer, field.TypeFloat64, value)
|
||||
}
|
||||
if _u.mutation.APIKeysCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2M,
|
||||
@@ -2775,6 +2846,62 @@ func (_u *GroupUpdateOne) AppendReasoningEffortMappings(v []domain.ReasoningEffo
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetProfitControlEnabled sets the "profit_control_enabled" field.
|
||||
func (_u *GroupUpdateOne) SetProfitControlEnabled(v bool) *GroupUpdateOne {
|
||||
_u.mutation.SetProfitControlEnabled(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableProfitControlEnabled sets the "profit_control_enabled" field if the given value is not nil.
|
||||
func (_u *GroupUpdateOne) SetNillableProfitControlEnabled(v *bool) *GroupUpdateOne {
|
||||
if v != nil {
|
||||
_u.SetProfitControlEnabled(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetProfitMinMargin sets the "profit_min_margin" field.
|
||||
func (_u *GroupUpdateOne) SetProfitMinMargin(v float64) *GroupUpdateOne {
|
||||
_u.mutation.ResetProfitMinMargin()
|
||||
_u.mutation.SetProfitMinMargin(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableProfitMinMargin sets the "profit_min_margin" field if the given value is not nil.
|
||||
func (_u *GroupUpdateOne) SetNillableProfitMinMargin(v *float64) *GroupUpdateOne {
|
||||
if v != nil {
|
||||
_u.SetProfitMinMargin(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// AddProfitMinMargin adds value to the "profit_min_margin" field.
|
||||
func (_u *GroupUpdateOne) AddProfitMinMargin(v float64) *GroupUpdateOne {
|
||||
_u.mutation.AddProfitMinMargin(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetProfitSafetyBuffer sets the "profit_safety_buffer" field.
|
||||
func (_u *GroupUpdateOne) SetProfitSafetyBuffer(v float64) *GroupUpdateOne {
|
||||
_u.mutation.ResetProfitSafetyBuffer()
|
||||
_u.mutation.SetProfitSafetyBuffer(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableProfitSafetyBuffer sets the "profit_safety_buffer" field if the given value is not nil.
|
||||
func (_u *GroupUpdateOne) SetNillableProfitSafetyBuffer(v *float64) *GroupUpdateOne {
|
||||
if v != nil {
|
||||
_u.SetProfitSafetyBuffer(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// AddProfitSafetyBuffer adds value to the "profit_safety_buffer" field.
|
||||
func (_u *GroupUpdateOne) AddProfitSafetyBuffer(v float64) *GroupUpdateOne {
|
||||
_u.mutation.AddProfitSafetyBuffer(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// AddAPIKeyIDs adds the "api_keys" edge to the APIKey entity by IDs.
|
||||
func (_u *GroupUpdateOne) AddAPIKeyIDs(ids ...int64) *GroupUpdateOne {
|
||||
_u.mutation.AddAPIKeyIDs(ids...)
|
||||
@@ -3396,6 +3523,21 @@ func (_u *GroupUpdateOne) sqlSave(ctx context.Context) (_node *Group, err error)
|
||||
sqljson.Append(u, group.FieldReasoningEffortMappings, value)
|
||||
})
|
||||
}
|
||||
if value, ok := _u.mutation.ProfitControlEnabled(); ok {
|
||||
_spec.SetField(group.FieldProfitControlEnabled, field.TypeBool, value)
|
||||
}
|
||||
if value, ok := _u.mutation.ProfitMinMargin(); ok {
|
||||
_spec.SetField(group.FieldProfitMinMargin, field.TypeFloat64, value)
|
||||
}
|
||||
if value, ok := _u.mutation.AddedProfitMinMargin(); ok {
|
||||
_spec.AddField(group.FieldProfitMinMargin, field.TypeFloat64, value)
|
||||
}
|
||||
if value, ok := _u.mutation.ProfitSafetyBuffer(); ok {
|
||||
_spec.SetField(group.FieldProfitSafetyBuffer, field.TypeFloat64, value)
|
||||
}
|
||||
if value, ok := _u.mutation.AddedProfitSafetyBuffer(); ok {
|
||||
_spec.AddField(group.FieldProfitSafetyBuffer, field.TypeFloat64, value)
|
||||
}
|
||||
if _u.mutation.APIKeysCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2M,
|
||||
|
||||
@@ -947,6 +947,9 @@ var (
|
||||
{Name: "rpm_limit", Type: field.TypeInt, Default: 0},
|
||||
{Name: "max_reasoning_effort", Type: field.TypeString, Size: 20, Default: ""},
|
||||
{Name: "reasoning_effort_mappings", Type: field.TypeJSON, SchemaType: map[string]string{"postgres": "jsonb"}},
|
||||
{Name: "profit_control_enabled", Type: field.TypeBool, Default: false},
|
||||
{Name: "profit_min_margin", Type: field.TypeFloat64, Default: 0, SchemaType: map[string]string{"postgres": "decimal(10,4)"}},
|
||||
{Name: "profit_safety_buffer", Type: field.TypeFloat64, Default: 0, SchemaType: map[string]string{"postgres": "decimal(10,4)"}},
|
||||
}
|
||||
// GroupsTable holds the schema information for the "groups" table.
|
||||
GroupsTable = &schema.Table{
|
||||
|
||||
+229
-1
@@ -21922,6 +21922,11 @@ type GroupMutation struct {
|
||||
max_reasoning_effort *string
|
||||
reasoning_effort_mappings *[]domain.ReasoningEffortMapping
|
||||
appendreasoning_effort_mappings []domain.ReasoningEffortMapping
|
||||
profit_control_enabled *bool
|
||||
profit_min_margin *float64
|
||||
addprofit_min_margin *float64
|
||||
profit_safety_buffer *float64
|
||||
addprofit_safety_buffer *float64
|
||||
clearedFields map[string]struct{}
|
||||
api_keys map[int64]struct{}
|
||||
removedapi_keys map[int64]struct{}
|
||||
@@ -24586,6 +24591,154 @@ func (m *GroupMutation) ResetReasoningEffortMappings() {
|
||||
m.appendreasoning_effort_mappings = nil
|
||||
}
|
||||
|
||||
// SetProfitControlEnabled sets the "profit_control_enabled" field.
|
||||
func (m *GroupMutation) SetProfitControlEnabled(b bool) {
|
||||
m.profit_control_enabled = &b
|
||||
}
|
||||
|
||||
// ProfitControlEnabled returns the value of the "profit_control_enabled" field in the mutation.
|
||||
func (m *GroupMutation) ProfitControlEnabled() (r bool, exists bool) {
|
||||
v := m.profit_control_enabled
|
||||
if v == nil {
|
||||
return
|
||||
}
|
||||
return *v, true
|
||||
}
|
||||
|
||||
// OldProfitControlEnabled returns the old "profit_control_enabled" field's value of the Group entity.
|
||||
// If the Group object wasn't provided to the builder, the object is fetched from the database.
|
||||
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
|
||||
func (m *GroupMutation) OldProfitControlEnabled(ctx context.Context) (v bool, err error) {
|
||||
if !m.op.Is(OpUpdateOne) {
|
||||
return v, errors.New("OldProfitControlEnabled is only allowed on UpdateOne operations")
|
||||
}
|
||||
if m.id == nil || m.oldValue == nil {
|
||||
return v, errors.New("OldProfitControlEnabled requires an ID field in the mutation")
|
||||
}
|
||||
oldValue, err := m.oldValue(ctx)
|
||||
if err != nil {
|
||||
return v, fmt.Errorf("querying old value for OldProfitControlEnabled: %w", err)
|
||||
}
|
||||
return oldValue.ProfitControlEnabled, nil
|
||||
}
|
||||
|
||||
// ResetProfitControlEnabled resets all changes to the "profit_control_enabled" field.
|
||||
func (m *GroupMutation) ResetProfitControlEnabled() {
|
||||
m.profit_control_enabled = nil
|
||||
}
|
||||
|
||||
// SetProfitMinMargin sets the "profit_min_margin" field.
|
||||
func (m *GroupMutation) SetProfitMinMargin(f float64) {
|
||||
m.profit_min_margin = &f
|
||||
m.addprofit_min_margin = nil
|
||||
}
|
||||
|
||||
// ProfitMinMargin returns the value of the "profit_min_margin" field in the mutation.
|
||||
func (m *GroupMutation) ProfitMinMargin() (r float64, exists bool) {
|
||||
v := m.profit_min_margin
|
||||
if v == nil {
|
||||
return
|
||||
}
|
||||
return *v, true
|
||||
}
|
||||
|
||||
// OldProfitMinMargin returns the old "profit_min_margin" field's value of the Group entity.
|
||||
// If the Group object wasn't provided to the builder, the object is fetched from the database.
|
||||
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
|
||||
func (m *GroupMutation) OldProfitMinMargin(ctx context.Context) (v float64, err error) {
|
||||
if !m.op.Is(OpUpdateOne) {
|
||||
return v, errors.New("OldProfitMinMargin is only allowed on UpdateOne operations")
|
||||
}
|
||||
if m.id == nil || m.oldValue == nil {
|
||||
return v, errors.New("OldProfitMinMargin requires an ID field in the mutation")
|
||||
}
|
||||
oldValue, err := m.oldValue(ctx)
|
||||
if err != nil {
|
||||
return v, fmt.Errorf("querying old value for OldProfitMinMargin: %w", err)
|
||||
}
|
||||
return oldValue.ProfitMinMargin, nil
|
||||
}
|
||||
|
||||
// AddProfitMinMargin adds f to the "profit_min_margin" field.
|
||||
func (m *GroupMutation) AddProfitMinMargin(f float64) {
|
||||
if m.addprofit_min_margin != nil {
|
||||
*m.addprofit_min_margin += f
|
||||
} else {
|
||||
m.addprofit_min_margin = &f
|
||||
}
|
||||
}
|
||||
|
||||
// AddedProfitMinMargin returns the value that was added to the "profit_min_margin" field in this mutation.
|
||||
func (m *GroupMutation) AddedProfitMinMargin() (r float64, exists bool) {
|
||||
v := m.addprofit_min_margin
|
||||
if v == nil {
|
||||
return
|
||||
}
|
||||
return *v, true
|
||||
}
|
||||
|
||||
// ResetProfitMinMargin resets all changes to the "profit_min_margin" field.
|
||||
func (m *GroupMutation) ResetProfitMinMargin() {
|
||||
m.profit_min_margin = nil
|
||||
m.addprofit_min_margin = nil
|
||||
}
|
||||
|
||||
// SetProfitSafetyBuffer sets the "profit_safety_buffer" field.
|
||||
func (m *GroupMutation) SetProfitSafetyBuffer(f float64) {
|
||||
m.profit_safety_buffer = &f
|
||||
m.addprofit_safety_buffer = nil
|
||||
}
|
||||
|
||||
// ProfitSafetyBuffer returns the value of the "profit_safety_buffer" field in the mutation.
|
||||
func (m *GroupMutation) ProfitSafetyBuffer() (r float64, exists bool) {
|
||||
v := m.profit_safety_buffer
|
||||
if v == nil {
|
||||
return
|
||||
}
|
||||
return *v, true
|
||||
}
|
||||
|
||||
// OldProfitSafetyBuffer returns the old "profit_safety_buffer" field's value of the Group entity.
|
||||
// If the Group object wasn't provided to the builder, the object is fetched from the database.
|
||||
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
|
||||
func (m *GroupMutation) OldProfitSafetyBuffer(ctx context.Context) (v float64, err error) {
|
||||
if !m.op.Is(OpUpdateOne) {
|
||||
return v, errors.New("OldProfitSafetyBuffer is only allowed on UpdateOne operations")
|
||||
}
|
||||
if m.id == nil || m.oldValue == nil {
|
||||
return v, errors.New("OldProfitSafetyBuffer requires an ID field in the mutation")
|
||||
}
|
||||
oldValue, err := m.oldValue(ctx)
|
||||
if err != nil {
|
||||
return v, fmt.Errorf("querying old value for OldProfitSafetyBuffer: %w", err)
|
||||
}
|
||||
return oldValue.ProfitSafetyBuffer, nil
|
||||
}
|
||||
|
||||
// AddProfitSafetyBuffer adds f to the "profit_safety_buffer" field.
|
||||
func (m *GroupMutation) AddProfitSafetyBuffer(f float64) {
|
||||
if m.addprofit_safety_buffer != nil {
|
||||
*m.addprofit_safety_buffer += f
|
||||
} else {
|
||||
m.addprofit_safety_buffer = &f
|
||||
}
|
||||
}
|
||||
|
||||
// AddedProfitSafetyBuffer returns the value that was added to the "profit_safety_buffer" field in this mutation.
|
||||
func (m *GroupMutation) AddedProfitSafetyBuffer() (r float64, exists bool) {
|
||||
v := m.addprofit_safety_buffer
|
||||
if v == nil {
|
||||
return
|
||||
}
|
||||
return *v, true
|
||||
}
|
||||
|
||||
// ResetProfitSafetyBuffer resets all changes to the "profit_safety_buffer" field.
|
||||
func (m *GroupMutation) ResetProfitSafetyBuffer() {
|
||||
m.profit_safety_buffer = nil
|
||||
m.addprofit_safety_buffer = nil
|
||||
}
|
||||
|
||||
// AddAPIKeyIDs adds the "api_keys" edge to the APIKey entity by ids.
|
||||
func (m *GroupMutation) AddAPIKeyIDs(ids ...int64) {
|
||||
if m.api_keys == nil {
|
||||
@@ -24944,7 +25097,7 @@ func (m *GroupMutation) Type() string {
|
||||
// order to get all numeric fields that were incremented/decremented, call
|
||||
// AddedFields().
|
||||
func (m *GroupMutation) Fields() []string {
|
||||
fields := make([]string, 0, 52)
|
||||
fields := make([]string, 0, 55)
|
||||
if m.created_at != nil {
|
||||
fields = append(fields, group.FieldCreatedAt)
|
||||
}
|
||||
@@ -25101,6 +25254,15 @@ func (m *GroupMutation) Fields() []string {
|
||||
if m.reasoning_effort_mappings != nil {
|
||||
fields = append(fields, group.FieldReasoningEffortMappings)
|
||||
}
|
||||
if m.profit_control_enabled != nil {
|
||||
fields = append(fields, group.FieldProfitControlEnabled)
|
||||
}
|
||||
if m.profit_min_margin != nil {
|
||||
fields = append(fields, group.FieldProfitMinMargin)
|
||||
}
|
||||
if m.profit_safety_buffer != nil {
|
||||
fields = append(fields, group.FieldProfitSafetyBuffer)
|
||||
}
|
||||
return fields
|
||||
}
|
||||
|
||||
@@ -25213,6 +25375,12 @@ func (m *GroupMutation) Field(name string) (ent.Value, bool) {
|
||||
return m.MaxReasoningEffort()
|
||||
case group.FieldReasoningEffortMappings:
|
||||
return m.ReasoningEffortMappings()
|
||||
case group.FieldProfitControlEnabled:
|
||||
return m.ProfitControlEnabled()
|
||||
case group.FieldProfitMinMargin:
|
||||
return m.ProfitMinMargin()
|
||||
case group.FieldProfitSafetyBuffer:
|
||||
return m.ProfitSafetyBuffer()
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
@@ -25326,6 +25494,12 @@ func (m *GroupMutation) OldField(ctx context.Context, name string) (ent.Value, e
|
||||
return m.OldMaxReasoningEffort(ctx)
|
||||
case group.FieldReasoningEffortMappings:
|
||||
return m.OldReasoningEffortMappings(ctx)
|
||||
case group.FieldProfitControlEnabled:
|
||||
return m.OldProfitControlEnabled(ctx)
|
||||
case group.FieldProfitMinMargin:
|
||||
return m.OldProfitMinMargin(ctx)
|
||||
case group.FieldProfitSafetyBuffer:
|
||||
return m.OldProfitSafetyBuffer(ctx)
|
||||
}
|
||||
return nil, fmt.Errorf("unknown Group field %s", name)
|
||||
}
|
||||
@@ -25699,6 +25873,27 @@ func (m *GroupMutation) SetField(name string, value ent.Value) error {
|
||||
}
|
||||
m.SetReasoningEffortMappings(v)
|
||||
return nil
|
||||
case group.FieldProfitControlEnabled:
|
||||
v, ok := value.(bool)
|
||||
if !ok {
|
||||
return fmt.Errorf("unexpected type %T for field %s", value, name)
|
||||
}
|
||||
m.SetProfitControlEnabled(v)
|
||||
return nil
|
||||
case group.FieldProfitMinMargin:
|
||||
v, ok := value.(float64)
|
||||
if !ok {
|
||||
return fmt.Errorf("unexpected type %T for field %s", value, name)
|
||||
}
|
||||
m.SetProfitMinMargin(v)
|
||||
return nil
|
||||
case group.FieldProfitSafetyBuffer:
|
||||
v, ok := value.(float64)
|
||||
if !ok {
|
||||
return fmt.Errorf("unexpected type %T for field %s", value, name)
|
||||
}
|
||||
m.SetProfitSafetyBuffer(v)
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("unknown Group field %s", name)
|
||||
}
|
||||
@@ -25770,6 +25965,12 @@ func (m *GroupMutation) AddedFields() []string {
|
||||
if m.addrpm_limit != nil {
|
||||
fields = append(fields, group.FieldRpmLimit)
|
||||
}
|
||||
if m.addprofit_min_margin != nil {
|
||||
fields = append(fields, group.FieldProfitMinMargin)
|
||||
}
|
||||
if m.addprofit_safety_buffer != nil {
|
||||
fields = append(fields, group.FieldProfitSafetyBuffer)
|
||||
}
|
||||
return fields
|
||||
}
|
||||
|
||||
@@ -25820,6 +26021,10 @@ func (m *GroupMutation) AddedField(name string) (ent.Value, bool) {
|
||||
return m.AddedSortOrder()
|
||||
case group.FieldRpmLimit:
|
||||
return m.AddedRpmLimit()
|
||||
case group.FieldProfitMinMargin:
|
||||
return m.AddedProfitMinMargin()
|
||||
case group.FieldProfitSafetyBuffer:
|
||||
return m.AddedProfitSafetyBuffer()
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
@@ -25976,6 +26181,20 @@ func (m *GroupMutation) AddField(name string, value ent.Value) error {
|
||||
}
|
||||
m.AddRpmLimit(v)
|
||||
return nil
|
||||
case group.FieldProfitMinMargin:
|
||||
v, ok := value.(float64)
|
||||
if !ok {
|
||||
return fmt.Errorf("unexpected type %T for field %s", value, name)
|
||||
}
|
||||
m.AddProfitMinMargin(v)
|
||||
return nil
|
||||
case group.FieldProfitSafetyBuffer:
|
||||
v, ok := value.(float64)
|
||||
if !ok {
|
||||
return fmt.Errorf("unexpected type %T for field %s", value, name)
|
||||
}
|
||||
m.AddProfitSafetyBuffer(v)
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("unknown Group numeric field %s", name)
|
||||
}
|
||||
@@ -26258,6 +26477,15 @@ func (m *GroupMutation) ResetField(name string) error {
|
||||
case group.FieldReasoningEffortMappings:
|
||||
m.ResetReasoningEffortMappings()
|
||||
return nil
|
||||
case group.FieldProfitControlEnabled:
|
||||
m.ResetProfitControlEnabled()
|
||||
return nil
|
||||
case group.FieldProfitMinMargin:
|
||||
m.ResetProfitMinMargin()
|
||||
return nil
|
||||
case group.FieldProfitSafetyBuffer:
|
||||
m.ResetProfitSafetyBuffer()
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("unknown Group field %s", name)
|
||||
}
|
||||
|
||||
@@ -1181,6 +1181,18 @@ func init() {
|
||||
groupDescReasoningEffortMappings := groupFields[48].Descriptor()
|
||||
// group.DefaultReasoningEffortMappings holds the default value on creation for the reasoning_effort_mappings field.
|
||||
group.DefaultReasoningEffortMappings = groupDescReasoningEffortMappings.Default.([]domain.ReasoningEffortMapping)
|
||||
// groupDescProfitControlEnabled is the schema descriptor for profit_control_enabled field.
|
||||
groupDescProfitControlEnabled := groupFields[49].Descriptor()
|
||||
// group.DefaultProfitControlEnabled holds the default value on creation for the profit_control_enabled field.
|
||||
group.DefaultProfitControlEnabled = groupDescProfitControlEnabled.Default.(bool)
|
||||
// groupDescProfitMinMargin is the schema descriptor for profit_min_margin field.
|
||||
groupDescProfitMinMargin := groupFields[50].Descriptor()
|
||||
// group.DefaultProfitMinMargin holds the default value on creation for the profit_min_margin field.
|
||||
group.DefaultProfitMinMargin = groupDescProfitMinMargin.Default.(float64)
|
||||
// groupDescProfitSafetyBuffer is the schema descriptor for profit_safety_buffer field.
|
||||
groupDescProfitSafetyBuffer := groupFields[51].Descriptor()
|
||||
// group.DefaultProfitSafetyBuffer holds the default value on creation for the profit_safety_buffer field.
|
||||
group.DefaultProfitSafetyBuffer = groupDescProfitSafetyBuffer.Default.(float64)
|
||||
idempotencyrecordMixin := schema.IdempotencyRecord{}.Mixin()
|
||||
idempotencyrecordMixinFields0 := idempotencyrecordMixin[0].Fields()
|
||||
_ = idempotencyrecordMixinFields0
|
||||
|
||||
@@ -234,6 +234,20 @@ func (Group) Fields() []ent.Field {
|
||||
Default([]domain.ReasoningEffortMapping{}).
|
||||
SchemaType(map[string]string{dialect.Postgres: "jsonb"}).
|
||||
Comment("OpenAI reasoning effort 自定义精确映射;先映射再应用上限"),
|
||||
|
||||
// 分组利润控制(migration 192/193):openai/anthropic/gemini/grok/antigravity
|
||||
// 的 token 分组可启用,composite 分组不能直接启用。
|
||||
field.Bool("profit_control_enabled").
|
||||
Default(false).
|
||||
Comment("是否启用利润控制:调度时仅允许账号计费倍率满足毛利率要求的账号进入候选池"),
|
||||
field.Float("profit_min_margin").
|
||||
SchemaType(map[string]string{dialect.Postgres: "decimal(10,4)"}).
|
||||
Default(0).
|
||||
Comment("最低毛利率,小数(0.30=30%);账号准入条件为 U <= D*(1-margin-buffer)"),
|
||||
field.Float("profit_safety_buffer").
|
||||
SchemaType(map[string]string{dialect.Postgres: "decimal(10,4)"}).
|
||||
Default(0).
|
||||
Comment("安全缓冲,小数;与 margin 相加后从下游倍率中扣除,默认 0"),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -907,6 +907,18 @@ type GatewayConfig struct {
|
||||
// ForceCodexCLI: 强制将 OpenAI `/v1/responses` 请求按 Codex CLI 处理。
|
||||
// 用于网关未透传/改写 User-Agent 时的兼容兜底(默认关闭,避免影响其他客户端)。
|
||||
ForceCodexCLI bool `mapstructure:"force_codex_cli"`
|
||||
// DisableCodexIdentityEnforcement: 关闭「强制统一 Codex 出站身份」。上游 /backend-api/codex
|
||||
// 在容量紧张时按客户端身份分优先级降载,被降载的请求会拿到 HTTP 200 + 流内
|
||||
// server_is_overloaded,该次请求失败。默认强制统一出口:所有 OAuth 出站的
|
||||
// User-Agent / originator / version 都改写为网关规范身份,确保没有请求带着第三方或陈旧身份
|
||||
// 出站。置 true 后退回「仅按最终 User-Agent 配对 originator」的收口语义,供上游策略变动时回滚。
|
||||
//
|
||||
// 取反义命名是为了让零值安全:该开关会发布为进程级快照,未经 viper 加载而手工构造的
|
||||
// Config(测试、工具)其零值必须落在「强制统一开启」这一侧,否则会静默丢掉这层保护。
|
||||
DisableCodexIdentityEnforcement bool `mapstructure:"disable_codex_identity_enforcement"`
|
||||
// DisableCodexOriginatorNormalization: 已废弃,等价于 DisableCodexIdentityEnforcement。
|
||||
// 保留以兼容既有配置文件;加载时会折叠进新键,不要在新代码里直接读取。
|
||||
DisableCodexOriginatorNormalization bool `mapstructure:"disable_codex_originator_normalization"`
|
||||
// CodexImageGenerationBridgeEnabled: 是否为 Codex `/v1/responses` 自动注入 image_generation 工具和桥接指令。
|
||||
// 默认关闭,避免纯文本 Codex 请求被意外改写;显式携带 image_generation 工具的请求仍按分组能力转发。
|
||||
CodexImageGenerationBridgeEnabled bool `mapstructure:"codex_image_generation_bridge_enabled"`
|
||||
@@ -1766,6 +1778,13 @@ func load(allowMissingJWTSecret bool) (*Config, error) {
|
||||
cfg.Gateway.ForcedCodexInstructionsTemplate = string(content)
|
||||
}
|
||||
|
||||
// 兼容旧键 gateway.disable_codex_originator_normalization:语义已被
|
||||
// disable_codex_identity_enforcement 取代(身份改写升级为强制统一出口),
|
||||
// 任一为 true 即关闭强制统一。
|
||||
if cfg.Gateway.DisableCodexOriginatorNormalization {
|
||||
cfg.Gateway.DisableCodexIdentityEnforcement = true
|
||||
}
|
||||
|
||||
// 兼容旧键 gateway.openai_ws.sticky_previous_response_ttl_seconds。
|
||||
// 新键未配置(<=0)时回退旧键;新键优先。
|
||||
if cfg.Gateway.OpenAIWS.StickyResponseIDTTLSeconds <= 0 && cfg.Gateway.OpenAIWS.StickyPreviousResponseTTLSeconds > 0 {
|
||||
@@ -2217,6 +2236,8 @@ func setDefaults() {
|
||||
viper.SetDefault("gateway.max_account_switches", 10)
|
||||
viper.SetDefault("gateway.max_account_switches_gemini", 3)
|
||||
viper.SetDefault("gateway.force_codex_cli", false)
|
||||
viper.SetDefault("gateway.disable_codex_identity_enforcement", false)
|
||||
viper.SetDefault("gateway.disable_codex_originator_normalization", false)
|
||||
viper.SetDefault("gateway.codex_image_generation_bridge_enabled", false)
|
||||
viper.SetDefault("gateway.openai_passthrough_allow_timeout_headers", false)
|
||||
viper.SetDefault("gateway.openai_compact_model", "gpt-5.4")
|
||||
|
||||
@@ -147,6 +147,8 @@ type UpdateAccountRequest struct {
|
||||
GroupIDs *[]int64 `json:"group_ids"`
|
||||
ExpiresAt *int64 `json:"expires_at"`
|
||||
AutoPauseOnExpired *bool `json:"auto_pause_on_expired"`
|
||||
ProbeEnabled *bool `json:"upstream_billing_probe_enabled"`
|
||||
RateSyncEnabled *bool `json:"upstream_billing_rate_sync_enabled"`
|
||||
ConfirmMixedChannelRisk *bool `json:"confirm_mixed_channel_risk"` // 用户确认混合渠道风险
|
||||
}
|
||||
|
||||
@@ -987,6 +989,8 @@ func (h *AccountHandler) Update(c *gin.Context) {
|
||||
GroupIDs: req.GroupIDs,
|
||||
ExpiresAt: req.ExpiresAt,
|
||||
AutoPauseOnExpired: req.AutoPauseOnExpired,
|
||||
ProbeEnabled: req.ProbeEnabled,
|
||||
RateSyncEnabled: req.RateSyncEnabled,
|
||||
SkipMixedChannelCheck: skipCheck,
|
||||
})
|
||||
if err != nil {
|
||||
|
||||
@@ -144,7 +144,7 @@ func TestApplyOAuthCredentialsRejectsMalformedOpenAILongContextBillingBeforeMuta
|
||||
|
||||
func TestOpenAIOAuthCodexPATBoundaryRejectsMalformedOpenAILongContextBillingValueBeforeTokenValidation(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
handler := NewOpenAIOAuthHandler(nil, newStubAdminService(), nil)
|
||||
handler := NewOpenAIOAuthHandler(nil, newStubAdminService(), nil, nil)
|
||||
router := gin.New()
|
||||
router.Use(gin.Recovery())
|
||||
router.POST("/openai/create-from-codex-pat", handler.CreateAccountFromCodexPAT)
|
||||
|
||||
@@ -147,6 +147,28 @@ func TestAccountHandlerUpdateMixedChannelConflictSimplifiedResponse(t *testing.T
|
||||
require.False(t, hasRequireConfirmation)
|
||||
}
|
||||
|
||||
func TestAccountHandlerUpdateMapsUpstreamBillingRateSyncSettings(t *testing.T) {
|
||||
adminSvc := newStubAdminService()
|
||||
router := setupAccountMixedChannelRouter(adminSvc)
|
||||
body, _ := json.Marshal(map[string]any{
|
||||
"name": "gemini-key",
|
||||
"upstream_billing_probe_enabled": true,
|
||||
"upstream_billing_rate_sync_enabled": true,
|
||||
})
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodPut, "/api/v1/admin/accounts/42", bytes.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
router.ServeHTTP(rec, req)
|
||||
|
||||
require.Equal(t, http.StatusOK, rec.Code)
|
||||
require.NotNil(t, adminSvc.lastUpdateAccountInput)
|
||||
require.NotNil(t, adminSvc.lastUpdateAccountInput.ProbeEnabled)
|
||||
require.True(t, *adminSvc.lastUpdateAccountInput.ProbeEnabled)
|
||||
require.NotNil(t, adminSvc.lastUpdateAccountInput.RateSyncEnabled)
|
||||
require.True(t, *adminSvc.lastUpdateAccountInput.RateSyncEnabled)
|
||||
}
|
||||
|
||||
func TestAccountHandlerBulkUpdateMixedChannelConflict(t *testing.T) {
|
||||
adminSvc := newStubAdminService()
|
||||
adminSvc.bulkUpdateAccountErr = &service.MixedChannelError{
|
||||
|
||||
@@ -32,6 +32,7 @@ type stubAdminService struct {
|
||||
createAccountErr error
|
||||
createSparkShadowErr error
|
||||
updateAccountErr error
|
||||
lastUpdateAccountInput *service.UpdateAccountInput
|
||||
bulkUpdateAccountErr error
|
||||
lastBulkUpdateAccountInput *service.BulkUpdateAccountsInput
|
||||
getAccountResult *service.Account
|
||||
@@ -501,6 +502,7 @@ func (s *stubAdminService) RecoverDuplicateAccount(ctx context.Context, id int64
|
||||
|
||||
func (s *stubAdminService) UpdateAccount(ctx context.Context, id int64, input *service.UpdateAccountInput) (*service.Account, error) {
|
||||
s.updateAccountCalls++
|
||||
s.lastUpdateAccountInput = input
|
||||
if s.updateAccountErr != nil {
|
||||
return nil, s.updateAccountErr
|
||||
}
|
||||
|
||||
@@ -118,6 +118,9 @@ type CreateGroupRequest struct {
|
||||
PeakStart string `json:"peak_start"`
|
||||
PeakEnd string `json:"peak_end"`
|
||||
PeakRateMultiplier *float64 `json:"peak_rate_multiplier"`
|
||||
ProfitControlEnabled bool `json:"profit_control_enabled"`
|
||||
ProfitMinMargin *float64 `json:"profit_min_margin"`
|
||||
ProfitSafetyBuffer *float64 `json:"profit_safety_buffer"`
|
||||
ImagePrice1K *float64 `json:"image_price_1k"`
|
||||
ImagePrice2K *float64 `json:"image_price_2k"`
|
||||
ImagePrice4K *float64 `json:"image_price_4k"`
|
||||
@@ -177,6 +180,9 @@ type UpdateGroupRequest struct {
|
||||
PeakStart *string `json:"peak_start"`
|
||||
PeakEnd *string `json:"peak_end"`
|
||||
PeakRateMultiplier *float64 `json:"peak_rate_multiplier"`
|
||||
ProfitControlEnabled *bool `json:"profit_control_enabled"`
|
||||
ProfitMinMargin *float64 `json:"profit_min_margin"`
|
||||
ProfitSafetyBuffer *float64 `json:"profit_safety_buffer"`
|
||||
ImagePrice1K *float64 `json:"image_price_1k"`
|
||||
ImagePrice2K *float64 `json:"image_price_2k"`
|
||||
ImagePrice4K *float64 `json:"image_price_4k"`
|
||||
@@ -475,6 +481,13 @@ func (h *GroupHandler) Create(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
// platform 是 omitempty:预校验必须用与 CreateGroup 落库一致的归一化平台,
|
||||
// 否则省略 platform 的请求会被误判成「平台不支持利润控制」。
|
||||
if err := service.ValidateProfitControlConfig(service.NormalizeGroupPlatform(req.Platform), req.ProfitControlEnabled, float64ValueOrDefault(req.ProfitMinMargin, 0), float64ValueOrDefault(req.ProfitSafetyBuffer, 0)); err != nil {
|
||||
response.BadRequest(c, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
group, err := h.adminService.CreateGroup(c.Request.Context(), &service.CreateGroupInput{
|
||||
Name: req.Name,
|
||||
Description: req.Description,
|
||||
@@ -497,6 +510,9 @@ func (h *GroupHandler) Create(c *gin.Context) {
|
||||
PeakStart: req.PeakStart,
|
||||
PeakEnd: req.PeakEnd,
|
||||
PeakRateMultiplier: req.PeakRateMultiplier,
|
||||
ProfitControlEnabled: req.ProfitControlEnabled,
|
||||
ProfitMinMargin: req.ProfitMinMargin,
|
||||
ProfitSafetyBuffer: req.ProfitSafetyBuffer,
|
||||
ImagePrice1K: req.ImagePrice1K,
|
||||
ImagePrice2K: req.ImagePrice2K,
|
||||
ImagePrice4K: req.ImagePrice4K,
|
||||
@@ -616,6 +632,9 @@ func (h *GroupHandler) Update(c *gin.Context) {
|
||||
PeakStart: req.PeakStart,
|
||||
PeakEnd: req.PeakEnd,
|
||||
PeakRateMultiplier: req.PeakRateMultiplier,
|
||||
ProfitControlEnabled: req.ProfitControlEnabled,
|
||||
ProfitMinMargin: req.ProfitMinMargin,
|
||||
ProfitSafetyBuffer: req.ProfitSafetyBuffer,
|
||||
ImagePrice1K: req.ImagePrice1K,
|
||||
ImagePrice2K: req.ImagePrice2K,
|
||||
ImagePrice4K: req.ImagePrice4K,
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
package admin
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -17,7 +20,61 @@ import (
|
||||
type OpenAIOAuthHandler struct {
|
||||
openaiOAuthService *service.OpenAIOAuthService
|
||||
adminService service.AdminService
|
||||
quotaService *service.OpenAIQuotaService
|
||||
quotaService openAIQuotaService
|
||||
rateLimitService openAIAccountStateRecoverer
|
||||
}
|
||||
|
||||
type openAIQuotaService interface {
|
||||
QueryUsage(ctx context.Context, accountID int64) (*service.OpenAIQuotaUsage, error)
|
||||
CacheResetCreditsSnapshot(ctx context.Context, accountID int64, credits *service.OpenAIRateLimitResetCredits) error
|
||||
ResetCredit(ctx context.Context, accountID int64) (*service.OpenAIQuotaResetResult, error)
|
||||
}
|
||||
|
||||
type openAIAccountStateRecoverer interface {
|
||||
RecoverAccountState(ctx context.Context, accountID int64, options service.AccountRecoveryOptions) (*service.SuccessfulTestRecoveryResult, error)
|
||||
}
|
||||
|
||||
const (
|
||||
openAIQuotaResetWarningCacheRefreshFailed = "reset_credit_cache_refresh_failed"
|
||||
openAIQuotaResetWarningAccountRecoveryFailed = "account_state_recovery_failed"
|
||||
openAIQuotaResetWarningAccountRefreshFailed = "account_state_refresh_failed"
|
||||
)
|
||||
|
||||
// openAIQuotaResetPostProcessTimeout bounds the work performed AFTER the
|
||||
// (non-refundable) reset credit has already been consumed upstream. The whole
|
||||
// request must stay comfortably inside the panel HTTP client timeout, otherwise
|
||||
// the browser aborts a mutation that already succeeded and the operator retries
|
||||
// it — spending a second credit.
|
||||
const openAIQuotaResetPostProcessTimeout = 8 * time.Second
|
||||
|
||||
type openAIQuotaResetResponse struct {
|
||||
service.OpenAIQuotaResetResult
|
||||
Quota *service.OpenAIQuotaUsage `json:"quota,omitempty"`
|
||||
Account *dto.Account `json:"account,omitempty"`
|
||||
CacheRefreshed bool `json:"cache_refreshed"`
|
||||
AccountStateRecovered bool `json:"account_state_recovered"`
|
||||
WarningCode string `json:"warning_code,omitempty"`
|
||||
}
|
||||
|
||||
// openAIQuotaRefreshResponse is the reset-credit-persisting variant of the quota
|
||||
// query. The usage payload is embedded so the shape stays identical to the plain
|
||||
// query; cache_persisted reports whether the snapshot write succeeded, because a
|
||||
// failed display-cache write must never discard a successful upstream read.
|
||||
type openAIQuotaRefreshResponse struct {
|
||||
service.OpenAIQuotaUsage
|
||||
CachePersisted bool `json:"cache_persisted"`
|
||||
}
|
||||
|
||||
// openAIQuotaResetPostProcessContext detaches the post-reset bookkeeping from the
|
||||
// client connection. The credit is already spent at that point, so account-state
|
||||
// recovery must complete even if the operator closes the tab (mirrors
|
||||
// systemUpdateContext, added for the same reason in #4504).
|
||||
func openAIQuotaResetPostProcessContext(ctx context.Context) (context.Context, context.CancelFunc) {
|
||||
base := context.Background()
|
||||
if ctx != nil {
|
||||
base = context.WithoutCancel(ctx)
|
||||
}
|
||||
return context.WithTimeout(base, openAIQuotaResetPostProcessTimeout)
|
||||
}
|
||||
|
||||
func oauthPlatformFromPath(c *gin.Context) string {
|
||||
@@ -29,12 +86,22 @@ func NewOpenAIOAuthHandler(
|
||||
openaiOAuthService *service.OpenAIOAuthService,
|
||||
adminService service.AdminService,
|
||||
quotaService *service.OpenAIQuotaService,
|
||||
rateLimitService *service.RateLimitService,
|
||||
) *OpenAIOAuthHandler {
|
||||
return &OpenAIOAuthHandler{
|
||||
h := &OpenAIOAuthHandler{
|
||||
openaiOAuthService: openaiOAuthService,
|
||||
adminService: adminService,
|
||||
quotaService: quotaService,
|
||||
}
|
||||
// Assign through explicit nil checks: storing a nil *Service in an interface
|
||||
// field yields a non-nil interface, which would silently defeat the
|
||||
// `== nil` capability guards below and panic instead of returning 400.
|
||||
if quotaService != nil {
|
||||
h.quotaService = quotaService
|
||||
}
|
||||
if rateLimitService != nil {
|
||||
h.rateLimitService = rateLimitService
|
||||
}
|
||||
return h
|
||||
}
|
||||
|
||||
// OpenAIGenerateAuthURLRequest represents the request for generating OpenAI auth URL
|
||||
@@ -420,6 +487,7 @@ func (h *OpenAIOAuthHandler) QueryQuota(c *gin.Context) {
|
||||
response.BadRequest(c, "openai quota service is not enabled")
|
||||
return
|
||||
}
|
||||
|
||||
usage, err := h.quotaService.QueryUsage(c.Request.Context(), accountID)
|
||||
if err != nil {
|
||||
response.ErrorFrom(c, err)
|
||||
@@ -428,6 +496,47 @@ func (h *OpenAIOAuthHandler) QueryQuota(c *gin.Context) {
|
||||
response.Success(c, usage)
|
||||
}
|
||||
|
||||
// RefreshQuota queries the rate-limit / quota usage AND persists the reset-credit
|
||||
// snapshot so the card can be rehydrated without an upstream round-trip.
|
||||
// POST /api/v1/admin/openai/accounts/:id/quota/refresh
|
||||
//
|
||||
// It is a POST (not a GET with a side-effect flag) because it writes account
|
||||
// state: the audit middleware only records mutating verbs, so a persisting GET
|
||||
// would mutate the database without an audit trail.
|
||||
func (h *OpenAIOAuthHandler) RefreshQuota(c *gin.Context) {
|
||||
accountID, err := strconv.ParseInt(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
response.BadRequest(c, "Invalid account ID")
|
||||
return
|
||||
}
|
||||
if h.quotaService == nil {
|
||||
response.BadRequest(c, "openai quota service is not enabled")
|
||||
return
|
||||
}
|
||||
|
||||
usage, err := h.quotaService.QueryUsage(c.Request.Context(), accountID)
|
||||
if err != nil {
|
||||
response.ErrorFrom(c, err)
|
||||
return
|
||||
}
|
||||
if usage == nil {
|
||||
response.Error(c, http.StatusInternalServerError, "openai quota query returned an empty result")
|
||||
return
|
||||
}
|
||||
|
||||
refreshResponse := openAIQuotaRefreshResponse{OpenAIQuotaUsage: *usage}
|
||||
// A failed snapshot write leaves the previous cache intact — report it as a
|
||||
// partial success instead of discarding the usage payload we just fetched,
|
||||
// which would leave the card without a credit count at all.
|
||||
if err := h.quotaService.CacheResetCreditsSnapshot(c.Request.Context(), accountID, usage.RateLimitResetCredits); err != nil {
|
||||
slog.Warn("openai_quota_reset_credit_cache_persist_failed", "account_id", accountID, "error", err)
|
||||
response.Success(c, refreshResponse)
|
||||
return
|
||||
}
|
||||
refreshResponse.CachePersisted = true
|
||||
response.Success(c, refreshResponse)
|
||||
}
|
||||
|
||||
// CreateShadowRequest is the request body for CreateShadow.
|
||||
type CreateShadowRequest struct {
|
||||
Name string `json:"name"`
|
||||
@@ -482,5 +591,63 @@ func (h *OpenAIOAuthHandler) ResetQuota(c *gin.Context) {
|
||||
response.ErrorFrom(c, err)
|
||||
return
|
||||
}
|
||||
response.Success(c, result)
|
||||
if result == nil {
|
||||
response.Error(c, http.StatusInternalServerError, "openai quota reset returned an empty result")
|
||||
return
|
||||
}
|
||||
|
||||
resetResponse := openAIQuotaResetResponse{OpenAIQuotaResetResult: *result}
|
||||
postCtx, cancelPost := openAIQuotaResetPostProcessContext(c.Request.Context())
|
||||
defer cancelPost()
|
||||
|
||||
// Step 1 — unblocking the account is the whole point of consuming a credit
|
||||
// (#3672 / #3740), so it runs FIRST and is never gated on the display cache.
|
||||
// Recovery is DB-only and leaves the manual `schedulable` switch untouched.
|
||||
if h.rateLimitService == nil {
|
||||
resetResponse.WarningCode = openAIQuotaResetWarningAccountRecoveryFailed
|
||||
response.Success(c, resetResponse)
|
||||
return
|
||||
}
|
||||
if _, err := h.rateLimitService.RecoverAccountState(postCtx, accountID, service.AccountRecoveryOptions{
|
||||
InvalidateToken: true,
|
||||
}); err != nil {
|
||||
// Recovery failures are almost always storage-level; the remaining steps
|
||||
// share that dependency, so stop here instead of compounding the failure.
|
||||
slog.Warn("openai_quota_reset_account_recovery_failed", "account_id", accountID, "error", err)
|
||||
resetResponse.WarningCode = openAIQuotaResetWarningAccountRecoveryFailed
|
||||
response.Success(c, resetResponse)
|
||||
return
|
||||
}
|
||||
resetResponse.AccountStateRecovered = true
|
||||
|
||||
// Step 2 — refresh the reset-credit display cache. A failure here is reported
|
||||
// but must not hide the recovered account row produced by step 3.
|
||||
usage, usageErr := h.quotaService.QueryUsage(postCtx, accountID)
|
||||
switch {
|
||||
case usageErr != nil || usage == nil:
|
||||
slog.Warn("openai_quota_reset_cache_refresh_failed", "account_id", accountID, "error", usageErr)
|
||||
resetResponse.WarningCode = openAIQuotaResetWarningCacheRefreshFailed
|
||||
default:
|
||||
if err := h.quotaService.CacheResetCreditsSnapshot(postCtx, accountID, usage.RateLimitResetCredits); err != nil {
|
||||
slog.Warn("openai_quota_reset_cache_refresh_failed", "account_id", accountID, "error", err)
|
||||
resetResponse.WarningCode = openAIQuotaResetWarningCacheRefreshFailed
|
||||
} else {
|
||||
resetResponse.Quota = usage
|
||||
resetResponse.CacheRefreshed = true
|
||||
}
|
||||
}
|
||||
|
||||
// Step 3 — hand back the post-recovery account row so the list drops the
|
||||
// stale rate-limit badge without waiting for the next poll.
|
||||
account, err := h.adminService.GetAccount(postCtx, accountID)
|
||||
if err != nil {
|
||||
slog.Warn("openai_quota_reset_account_refresh_failed", "account_id", accountID, "error", err)
|
||||
if resetResponse.WarningCode == "" {
|
||||
resetResponse.WarningCode = openAIQuotaResetWarningAccountRefreshFailed
|
||||
}
|
||||
response.Success(c, resetResponse)
|
||||
return
|
||||
}
|
||||
resetResponse.Account = dto.AccountFromService(account)
|
||||
response.Success(c, resetResponse)
|
||||
}
|
||||
@@ -0,0 +1,486 @@
|
||||
//go:build unit
|
||||
|
||||
package admin
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
)
|
||||
|
||||
type openAIQuotaWorkflowStub struct {
|
||||
resetResult *service.OpenAIQuotaResetResult
|
||||
resetErr error
|
||||
queryResult *service.OpenAIQuotaUsage
|
||||
queryErr error
|
||||
cacheErr error
|
||||
|
||||
resetCalls int
|
||||
queryCalls int
|
||||
cacheCalls int
|
||||
|
||||
queryCtxErr error
|
||||
cacheCtxErr error
|
||||
}
|
||||
|
||||
func (s *openAIQuotaWorkflowStub) ResetCredit(context.Context, int64) (*service.OpenAIQuotaResetResult, error) {
|
||||
s.resetCalls++
|
||||
return s.resetResult, s.resetErr
|
||||
}
|
||||
|
||||
func (s *openAIQuotaWorkflowStub) QueryUsage(ctx context.Context, _ int64) (*service.OpenAIQuotaUsage, error) {
|
||||
s.queryCalls++
|
||||
s.queryCtxErr = ctx.Err()
|
||||
return s.queryResult, s.queryErr
|
||||
}
|
||||
|
||||
func (s *openAIQuotaWorkflowStub) CacheResetCreditsSnapshot(ctx context.Context, _ int64, _ *service.OpenAIRateLimitResetCredits) error {
|
||||
s.cacheCalls++
|
||||
s.cacheCtxErr = ctx.Err()
|
||||
return s.cacheErr
|
||||
}
|
||||
|
||||
type openAIAccountStateRecovererStub struct {
|
||||
err error
|
||||
calls int
|
||||
accountID int64
|
||||
lastOptions service.AccountRecoveryOptions
|
||||
lastCtxErr error
|
||||
}
|
||||
|
||||
func (s *openAIAccountStateRecovererStub) RecoverAccountState(ctx context.Context, accountID int64, options service.AccountRecoveryOptions) (*service.SuccessfulTestRecoveryResult, error) {
|
||||
s.calls++
|
||||
s.accountID = accountID
|
||||
s.lastOptions = options
|
||||
s.lastCtxErr = ctx.Err()
|
||||
return &service.SuccessfulTestRecoveryResult{}, s.err
|
||||
}
|
||||
|
||||
type openAIResetAdminServiceStub struct {
|
||||
service.AdminService
|
||||
account *service.Account
|
||||
err error
|
||||
calls int
|
||||
}
|
||||
|
||||
func (s *openAIResetAdminServiceStub) GetAccount(context.Context, int64) (*service.Account, error) {
|
||||
s.calls++
|
||||
return s.account, s.err
|
||||
}
|
||||
|
||||
type openAIQuotaResetEnvelope struct {
|
||||
Code int `json:"code"`
|
||||
Data openAIQuotaResetResponse `json:"data"`
|
||||
}
|
||||
|
||||
type openAIQuotaRefreshEnvelope struct {
|
||||
Code int `json:"code"`
|
||||
Data openAIQuotaRefreshResponse `json:"data"`
|
||||
}
|
||||
|
||||
func performOpenAIQuotaResetRequest(t *testing.T, handler *OpenAIOAuthHandler) (int, openAIQuotaResetEnvelope) {
|
||||
t.Helper()
|
||||
return performOpenAIQuotaResetRequestWithContext(t, handler, nil)
|
||||
}
|
||||
|
||||
// performOpenAIQuotaResetRequestWithContext drives the reset endpoint, optionally
|
||||
// with an already-canceled request context (client disconnect simulation).
|
||||
func performOpenAIQuotaResetRequestWithContext(t *testing.T, handler *OpenAIOAuthHandler, ctx context.Context) (int, openAIQuotaResetEnvelope) {
|
||||
t.Helper()
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
router := gin.New()
|
||||
router.POST("/api/v1/admin/openai/accounts/:id/reset-quota", handler.ResetQuota)
|
||||
recorder := httptest.NewRecorder()
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/admin/openai/accounts/42/reset-quota", nil)
|
||||
if ctx != nil {
|
||||
request = request.WithContext(ctx)
|
||||
}
|
||||
router.ServeHTTP(recorder, request)
|
||||
|
||||
var envelope openAIQuotaResetEnvelope
|
||||
require.NoError(t, json.Unmarshal(recorder.Body.Bytes(), &envelope))
|
||||
return recorder.Code, envelope
|
||||
}
|
||||
|
||||
func performOpenAIQuotaRefreshRequest(t *testing.T, handler *OpenAIOAuthHandler) (int, openAIQuotaRefreshEnvelope) {
|
||||
t.Helper()
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
router := gin.New()
|
||||
router.POST("/api/v1/admin/openai/accounts/:id/quota/refresh", handler.RefreshQuota)
|
||||
recorder := httptest.NewRecorder()
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/admin/openai/accounts/42/quota/refresh", nil)
|
||||
router.ServeHTTP(recorder, request)
|
||||
|
||||
var envelope openAIQuotaRefreshEnvelope
|
||||
require.NoError(t, json.Unmarshal(recorder.Body.Bytes(), &envelope))
|
||||
return recorder.Code, envelope
|
||||
}
|
||||
|
||||
func successfulOpenAIQuotaWorkflowStub() *openAIQuotaWorkflowStub {
|
||||
return &openAIQuotaWorkflowStub{
|
||||
resetResult: &service.OpenAIQuotaResetResult{
|
||||
Code: "success",
|
||||
WindowsReset: 1,
|
||||
},
|
||||
queryResult: &service.OpenAIQuotaUsage{
|
||||
FetchedAt: 123,
|
||||
RateLimitResetCredits: &service.OpenAIRateLimitResetCredits{
|
||||
AvailableCount: 0,
|
||||
Credits: []service.OpenAIRateLimitResetCreditDetail{},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func recoveredAccountStub() *openAIResetAdminServiceStub {
|
||||
return &openAIResetAdminServiceStub{account: &service.Account{
|
||||
ID: 42,
|
||||
Name: "recovered",
|
||||
Platform: service.PlatformOpenAI,
|
||||
Type: service.AccountTypeOAuth,
|
||||
Status: service.StatusActive,
|
||||
Schedulable: false,
|
||||
}}
|
||||
}
|
||||
|
||||
func TestOpenAIResetQuota_ResetFailureStopsWorkflow(t *testing.T) {
|
||||
quota := &openAIQuotaWorkflowStub{resetErr: errors.New("upstream reset failed")}
|
||||
recoverer := &openAIAccountStateRecovererStub{}
|
||||
handler := &OpenAIOAuthHandler{
|
||||
adminService: &openAIResetAdminServiceStub{},
|
||||
quotaService: quota,
|
||||
rateLimitService: recoverer,
|
||||
}
|
||||
|
||||
status, _ := performOpenAIQuotaResetRequest(t, handler)
|
||||
|
||||
require.Equal(t, http.StatusInternalServerError, status)
|
||||
require.Equal(t, 1, quota.resetCalls)
|
||||
require.Zero(t, quota.queryCalls)
|
||||
require.Zero(t, quota.cacheCalls)
|
||||
require.Zero(t, recoverer.calls)
|
||||
}
|
||||
|
||||
// Account-state recovery is the reason the credit was spent (#3672 / #3740), so it
|
||||
// must run before — and independently of — the reset-credit display cache.
|
||||
func TestOpenAIResetQuota_RecoversAccountStateBeforeRefreshingCache(t *testing.T) {
|
||||
quota := successfulOpenAIQuotaWorkflowStub()
|
||||
recoverer := &openAIAccountStateRecovererStub{}
|
||||
adminService := recoveredAccountStub()
|
||||
handler := &OpenAIOAuthHandler{
|
||||
adminService: adminService,
|
||||
quotaService: quota,
|
||||
rateLimitService: recoverer,
|
||||
}
|
||||
|
||||
status, envelope := performOpenAIQuotaResetRequest(t, handler)
|
||||
|
||||
require.Equal(t, http.StatusOK, status)
|
||||
require.Empty(t, envelope.Data.WarningCode)
|
||||
require.True(t, envelope.Data.AccountStateRecovered)
|
||||
require.True(t, envelope.Data.CacheRefreshed)
|
||||
require.NotNil(t, envelope.Data.Quota)
|
||||
require.NotNil(t, envelope.Data.Account)
|
||||
require.Equal(t, int64(42), envelope.Data.Account.ID)
|
||||
require.False(t, envelope.Data.Account.Schedulable, "manual scheduling switch must not be flipped")
|
||||
require.Equal(t, int64(42), recoverer.accountID)
|
||||
require.True(t, recoverer.lastOptions.InvalidateToken)
|
||||
require.Equal(t, 1, quota.resetCalls)
|
||||
require.Equal(t, 1, quota.queryCalls)
|
||||
require.Equal(t, 1, quota.cacheCalls)
|
||||
require.Equal(t, 1, recoverer.calls)
|
||||
require.Equal(t, 1, adminService.calls)
|
||||
}
|
||||
|
||||
func TestOpenAIResetQuota_RecoveryFailureStopsWorkflow(t *testing.T) {
|
||||
quota := successfulOpenAIQuotaWorkflowStub()
|
||||
recoverer := &openAIAccountStateRecovererStub{err: errors.New("recovery failed")}
|
||||
adminService := recoveredAccountStub()
|
||||
handler := &OpenAIOAuthHandler{
|
||||
adminService: adminService,
|
||||
quotaService: quota,
|
||||
rateLimitService: recoverer,
|
||||
}
|
||||
|
||||
status, envelope := performOpenAIQuotaResetRequest(t, handler)
|
||||
|
||||
require.Equal(t, http.StatusOK, status)
|
||||
require.Equal(t, openAIQuotaResetWarningAccountRecoveryFailed, envelope.Data.WarningCode)
|
||||
require.False(t, envelope.Data.AccountStateRecovered)
|
||||
require.False(t, envelope.Data.CacheRefreshed)
|
||||
require.Nil(t, envelope.Data.Quota)
|
||||
require.Nil(t, envelope.Data.Account)
|
||||
require.Equal(t, 1, recoverer.calls)
|
||||
require.Zero(t, quota.queryCalls)
|
||||
require.Zero(t, quota.cacheCalls)
|
||||
require.Zero(t, adminService.calls)
|
||||
}
|
||||
|
||||
func TestOpenAIResetQuota_MissingRecovererReportsRecoveryFailure(t *testing.T) {
|
||||
quota := successfulOpenAIQuotaWorkflowStub()
|
||||
adminService := recoveredAccountStub()
|
||||
handler := &OpenAIOAuthHandler{
|
||||
adminService: adminService,
|
||||
quotaService: quota,
|
||||
}
|
||||
|
||||
status, envelope := performOpenAIQuotaResetRequest(t, handler)
|
||||
|
||||
require.Equal(t, http.StatusOK, status)
|
||||
require.Equal(t, openAIQuotaResetWarningAccountRecoveryFailed, envelope.Data.WarningCode)
|
||||
require.False(t, envelope.Data.AccountStateRecovered)
|
||||
require.Zero(t, quota.queryCalls)
|
||||
require.Zero(t, adminService.calls)
|
||||
}
|
||||
|
||||
// A failed cache refresh must not hide the recovered account row: the operator
|
||||
// still needs the list to drop the stale rate-limit badge.
|
||||
func TestOpenAIResetQuota_QueryFailureStillRecoversAndReturnsAccount(t *testing.T) {
|
||||
quota := successfulOpenAIQuotaWorkflowStub()
|
||||
quota.queryResult = nil
|
||||
quota.queryErr = errors.New("upstream query failed")
|
||||
recoverer := &openAIAccountStateRecovererStub{}
|
||||
adminService := recoveredAccountStub()
|
||||
handler := &OpenAIOAuthHandler{
|
||||
adminService: adminService,
|
||||
quotaService: quota,
|
||||
rateLimitService: recoverer,
|
||||
}
|
||||
|
||||
status, envelope := performOpenAIQuotaResetRequest(t, handler)
|
||||
|
||||
require.Equal(t, http.StatusOK, status)
|
||||
require.Equal(t, openAIQuotaResetWarningCacheRefreshFailed, envelope.Data.WarningCode)
|
||||
require.True(t, envelope.Data.AccountStateRecovered)
|
||||
require.False(t, envelope.Data.CacheRefreshed)
|
||||
require.Nil(t, envelope.Data.Quota)
|
||||
require.NotNil(t, envelope.Data.Account)
|
||||
require.Equal(t, 1, quota.queryCalls)
|
||||
require.Zero(t, quota.cacheCalls)
|
||||
require.Equal(t, 1, recoverer.calls)
|
||||
require.Equal(t, 1, adminService.calls)
|
||||
}
|
||||
|
||||
func TestOpenAIResetQuota_CacheFailureStillRecoversAndReturnsAccount(t *testing.T) {
|
||||
quota := successfulOpenAIQuotaWorkflowStub()
|
||||
quota.cacheErr = errors.New("cache write failed")
|
||||
recoverer := &openAIAccountStateRecovererStub{}
|
||||
adminService := recoveredAccountStub()
|
||||
handler := &OpenAIOAuthHandler{
|
||||
adminService: adminService,
|
||||
quotaService: quota,
|
||||
rateLimitService: recoverer,
|
||||
}
|
||||
|
||||
status, envelope := performOpenAIQuotaResetRequest(t, handler)
|
||||
|
||||
require.Equal(t, http.StatusOK, status)
|
||||
require.Equal(t, openAIQuotaResetWarningCacheRefreshFailed, envelope.Data.WarningCode)
|
||||
require.True(t, envelope.Data.AccountStateRecovered)
|
||||
require.False(t, envelope.Data.CacheRefreshed)
|
||||
require.Nil(t, envelope.Data.Quota)
|
||||
require.NotNil(t, envelope.Data.Account)
|
||||
require.Equal(t, 1, quota.cacheCalls)
|
||||
require.Equal(t, 1, adminService.calls)
|
||||
}
|
||||
|
||||
func TestOpenAIResetQuota_AccountRefreshFailureReportsRecoveredState(t *testing.T) {
|
||||
quota := successfulOpenAIQuotaWorkflowStub()
|
||||
recoverer := &openAIAccountStateRecovererStub{}
|
||||
adminService := &openAIResetAdminServiceStub{err: errors.New("account refresh failed")}
|
||||
handler := &OpenAIOAuthHandler{
|
||||
adminService: adminService,
|
||||
quotaService: quota,
|
||||
rateLimitService: recoverer,
|
||||
}
|
||||
|
||||
status, envelope := performOpenAIQuotaResetRequest(t, handler)
|
||||
|
||||
require.Equal(t, http.StatusOK, status)
|
||||
require.Equal(t, openAIQuotaResetWarningAccountRefreshFailed, envelope.Data.WarningCode)
|
||||
require.True(t, envelope.Data.CacheRefreshed)
|
||||
require.True(t, envelope.Data.AccountStateRecovered)
|
||||
require.NotNil(t, envelope.Data.Quota)
|
||||
require.Nil(t, envelope.Data.Account)
|
||||
require.Equal(t, 1, adminService.calls)
|
||||
}
|
||||
|
||||
// The first (most actionable) failure wins so the UI never downgrades a cache
|
||||
// problem into a cosmetic "could not reload the row" message.
|
||||
func TestOpenAIResetQuota_CacheAndAccountFailureKeepsFirstWarning(t *testing.T) {
|
||||
quota := successfulOpenAIQuotaWorkflowStub()
|
||||
quota.cacheErr = errors.New("cache write failed")
|
||||
recoverer := &openAIAccountStateRecovererStub{}
|
||||
adminService := &openAIResetAdminServiceStub{err: errors.New("account refresh failed")}
|
||||
handler := &OpenAIOAuthHandler{
|
||||
adminService: adminService,
|
||||
quotaService: quota,
|
||||
rateLimitService: recoverer,
|
||||
}
|
||||
|
||||
status, envelope := performOpenAIQuotaResetRequest(t, handler)
|
||||
|
||||
require.Equal(t, http.StatusOK, status)
|
||||
require.Equal(t, openAIQuotaResetWarningCacheRefreshFailed, envelope.Data.WarningCode)
|
||||
require.True(t, envelope.Data.AccountStateRecovered)
|
||||
require.Nil(t, envelope.Data.Account)
|
||||
}
|
||||
|
||||
// The credit is non-refundable once consumed, so post-reset bookkeeping must
|
||||
// survive a client disconnect instead of leaving the account rate-limited.
|
||||
func TestOpenAIResetQuota_PostProcessingSurvivesClientCancellation(t *testing.T) {
|
||||
quota := successfulOpenAIQuotaWorkflowStub()
|
||||
recoverer := &openAIAccountStateRecovererStub{}
|
||||
adminService := recoveredAccountStub()
|
||||
handler := &OpenAIOAuthHandler{
|
||||
adminService: adminService,
|
||||
quotaService: quota,
|
||||
rateLimitService: recoverer,
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
|
||||
status, _ := performOpenAIQuotaResetRequestWithContext(t, handler, ctx)
|
||||
|
||||
require.Equal(t, http.StatusOK, status)
|
||||
require.Equal(t, 1, recoverer.calls)
|
||||
require.NoError(t, recoverer.lastCtxErr, "recovery must not inherit the canceled client context")
|
||||
require.NoError(t, quota.queryCtxErr)
|
||||
require.NoError(t, quota.cacheCtxErr)
|
||||
require.Equal(t, 1, adminService.calls)
|
||||
}
|
||||
|
||||
func TestOpenAIRefreshQuota_PersistsSnapshot(t *testing.T) {
|
||||
quota := successfulOpenAIQuotaWorkflowStub()
|
||||
handler := &OpenAIOAuthHandler{
|
||||
adminService: &openAIResetAdminServiceStub{},
|
||||
quotaService: quota,
|
||||
}
|
||||
|
||||
status, envelope := performOpenAIQuotaRefreshRequest(t, handler)
|
||||
|
||||
require.Equal(t, http.StatusOK, status)
|
||||
require.True(t, envelope.Data.CachePersisted)
|
||||
require.Equal(t, int64(123), envelope.Data.FetchedAt)
|
||||
require.Equal(t, 1, quota.queryCalls)
|
||||
require.Equal(t, 1, quota.cacheCalls)
|
||||
require.Zero(t, quota.resetCalls)
|
||||
}
|
||||
|
||||
// A rejected snapshot write must never discard the usage payload: otherwise the
|
||||
// card loses its credit count and the reset button stays disabled forever.
|
||||
func TestOpenAIRefreshQuota_PersistFailureStillReturnsUsage(t *testing.T) {
|
||||
quota := successfulOpenAIQuotaWorkflowStub()
|
||||
quota.queryResult = &service.OpenAIQuotaUsage{
|
||||
FetchedAt: 456,
|
||||
RateLimitResetCredits: &service.OpenAIRateLimitResetCredits{
|
||||
AvailableCount: 2,
|
||||
},
|
||||
}
|
||||
quota.cacheErr = errors.New("expiration details unavailable")
|
||||
handler := &OpenAIOAuthHandler{
|
||||
adminService: &openAIResetAdminServiceStub{},
|
||||
quotaService: quota,
|
||||
}
|
||||
|
||||
status, envelope := performOpenAIQuotaRefreshRequest(t, handler)
|
||||
|
||||
require.Equal(t, http.StatusOK, status)
|
||||
require.False(t, envelope.Data.CachePersisted)
|
||||
require.Equal(t, int64(456), envelope.Data.FetchedAt)
|
||||
require.NotNil(t, envelope.Data.RateLimitResetCredits)
|
||||
require.Equal(t, 2, envelope.Data.RateLimitResetCredits.AvailableCount)
|
||||
require.Equal(t, 1, quota.cacheCalls)
|
||||
}
|
||||
|
||||
// An empty-but-successful upstream read must not be dereferenced blindly.
|
||||
func TestOpenAIQuotaEmptyUsageIsHandledWithoutPanic(t *testing.T) {
|
||||
t.Run("refresh reports an internal error", func(t *testing.T) {
|
||||
quota := successfulOpenAIQuotaWorkflowStub()
|
||||
quota.queryResult = nil
|
||||
handler := &OpenAIOAuthHandler{
|
||||
adminService: &openAIResetAdminServiceStub{},
|
||||
quotaService: quota,
|
||||
}
|
||||
|
||||
status, envelope := performOpenAIQuotaRefreshRequest(t, handler)
|
||||
|
||||
require.Equal(t, http.StatusInternalServerError, status)
|
||||
require.False(t, envelope.Data.CachePersisted)
|
||||
require.Zero(t, quota.cacheCalls)
|
||||
})
|
||||
|
||||
t.Run("reset degrades to a cache warning", func(t *testing.T) {
|
||||
quota := successfulOpenAIQuotaWorkflowStub()
|
||||
quota.queryResult = nil
|
||||
recoverer := &openAIAccountStateRecovererStub{}
|
||||
adminService := recoveredAccountStub()
|
||||
handler := &OpenAIOAuthHandler{
|
||||
adminService: adminService,
|
||||
quotaService: quota,
|
||||
rateLimitService: recoverer,
|
||||
}
|
||||
|
||||
status, envelope := performOpenAIQuotaResetRequest(t, handler)
|
||||
|
||||
require.Equal(t, http.StatusOK, status)
|
||||
require.Equal(t, openAIQuotaResetWarningCacheRefreshFailed, envelope.Data.WarningCode)
|
||||
require.True(t, envelope.Data.AccountStateRecovered)
|
||||
require.NotNil(t, envelope.Data.Account)
|
||||
require.Zero(t, quota.cacheCalls)
|
||||
})
|
||||
}
|
||||
|
||||
func TestOpenAIRefreshQuota_QueryFailureIsReported(t *testing.T) {
|
||||
quota := &openAIQuotaWorkflowStub{queryErr: errors.New("upstream query failed")}
|
||||
handler := &OpenAIOAuthHandler{
|
||||
adminService: &openAIResetAdminServiceStub{},
|
||||
quotaService: quota,
|
||||
}
|
||||
|
||||
status, _ := performOpenAIQuotaRefreshRequest(t, handler)
|
||||
|
||||
require.Equal(t, http.StatusInternalServerError, status)
|
||||
require.Equal(t, 1, quota.queryCalls)
|
||||
require.Zero(t, quota.cacheCalls)
|
||||
}
|
||||
|
||||
// Storing a nil *Service in an interface field would make the capability guards
|
||||
// non-nil and panic on the first call; the constructor must keep them nil.
|
||||
func TestNewOpenAIOAuthHandlerKeepsNilQuotaCapabilitiesGuarded(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
handler := NewOpenAIOAuthHandler(nil, newStubAdminService(), nil, nil)
|
||||
require.Nil(t, handler.quotaService)
|
||||
require.Nil(t, handler.rateLimitService)
|
||||
|
||||
router := gin.New()
|
||||
router.Use(gin.Recovery())
|
||||
router.GET("/openai/accounts/:id/quota", handler.QueryQuota)
|
||||
router.POST("/openai/accounts/:id/quota/refresh", handler.RefreshQuota)
|
||||
router.POST("/openai/accounts/:id/reset-quota", handler.ResetQuota)
|
||||
|
||||
for _, tc := range []struct {
|
||||
method string
|
||||
path string
|
||||
}{
|
||||
{http.MethodGet, "/openai/accounts/42/quota"},
|
||||
{http.MethodPost, "/openai/accounts/42/quota/refresh"},
|
||||
{http.MethodPost, "/openai/accounts/42/reset-quota"},
|
||||
} {
|
||||
recorder := httptest.NewRecorder()
|
||||
router.ServeHTTP(recorder, httptest.NewRequest(tc.method, tc.path, nil))
|
||||
require.Equal(t, http.StatusBadRequest, recorder.Code, "%s %s", tc.method, tc.path)
|
||||
}
|
||||
}
|
||||
@@ -20,7 +20,7 @@ func TestCreateShadow_ReturnsCreatedShadow(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
stub := &stubAdminService{}
|
||||
h := NewOpenAIOAuthHandler(nil, stub, nil)
|
||||
h := NewOpenAIOAuthHandler(nil, stub, nil, nil)
|
||||
|
||||
router := gin.New()
|
||||
router.POST("/api/v1/admin/accounts/:id/shadow", h.CreateShadow)
|
||||
@@ -54,7 +54,7 @@ func TestCreateShadow_ReturnsCreatedShadow(t *testing.T) {
|
||||
func TestCreateShadow_InvalidID(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
h := NewOpenAIOAuthHandler(nil, &stubAdminService{}, nil)
|
||||
h := NewOpenAIOAuthHandler(nil, &stubAdminService{}, nil, nil)
|
||||
|
||||
router := gin.New()
|
||||
router.POST("/api/v1/admin/accounts/:id/shadow", h.CreateShadow)
|
||||
@@ -72,7 +72,7 @@ func TestCreateShadow_ServiceError(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
stub := &stubAdminService{createSparkShadowErr: errors.New("database unavailable")}
|
||||
h := NewOpenAIOAuthHandler(nil, stub, nil)
|
||||
h := NewOpenAIOAuthHandler(nil, stub, nil, nil)
|
||||
|
||||
router := gin.New()
|
||||
router.POST("/api/v1/admin/accounts/:id/shadow", h.CreateShadow)
|
||||
@@ -91,7 +91,7 @@ func TestCreateShadow_ServiceError(t *testing.T) {
|
||||
func TestCreateShadow_BadBody(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
h := NewOpenAIOAuthHandler(nil, &stubAdminService{}, nil)
|
||||
h := NewOpenAIOAuthHandler(nil, &stubAdminService{}, nil, nil)
|
||||
|
||||
router := gin.New()
|
||||
router.POST("/api/v1/admin/accounts/:id/shadow", h.CreateShadow)
|
||||
|
||||
@@ -279,6 +279,9 @@ func (h *SettingHandler) GetSettings(c *gin.Context) {
|
||||
EnableClientDatelineNormalization: settings.EnableClientDatelineNormalization,
|
||||
AntigravityUserAgentVersion: settings.AntigravityUserAgentVersion,
|
||||
OpenAICodexUserAgent: settings.OpenAICodexUserAgent,
|
||||
OpenAICodexClientVersion: settings.OpenAICodexClientVersion,
|
||||
OpenAICodexClientVersionSynced: settings.OpenAICodexClientVersionSynced,
|
||||
OpenAICodexVersionAutoSyncEnabled: settings.OpenAICodexVersionAutoSyncEnabled,
|
||||
MinCodexVersion: settings.MinCodexVersion,
|
||||
MaxCodexVersion: settings.MaxCodexVersion,
|
||||
CodexCLIOnlyBlacklist: settings.CodexCLIOnlyBlacklist,
|
||||
|
||||
@@ -443,6 +443,12 @@ func diffSettings(before *service.SystemSettings, after *service.SystemSettings,
|
||||
if before.OpenAICodexUserAgent != after.OpenAICodexUserAgent {
|
||||
changed = append(changed, "openai_codex_user_agent")
|
||||
}
|
||||
if before.OpenAICodexClientVersion != after.OpenAICodexClientVersion {
|
||||
changed = append(changed, "openai_codex_client_version")
|
||||
}
|
||||
if before.OpenAICodexVersionAutoSyncEnabled != after.OpenAICodexVersionAutoSyncEnabled {
|
||||
changed = append(changed, "openai_codex_version_auto_sync_enabled")
|
||||
}
|
||||
if before.PaymentVisibleMethodAlipaySource != after.PaymentVisibleMethodAlipaySource {
|
||||
changed = append(changed, "payment_visible_method_alipay_source")
|
||||
}
|
||||
|
||||
@@ -236,6 +236,8 @@ type UpdateSettingsRequest struct {
|
||||
EnableClientDatelineNormalization *bool `json:"enable_client_dateline_normalization"`
|
||||
AntigravityUserAgentVersion *string `json:"antigravity_user_agent_version"`
|
||||
OpenAICodexUserAgent *string `json:"openai_codex_user_agent"`
|
||||
OpenAICodexClientVersion *string `json:"openai_codex_client_version"`
|
||||
OpenAICodexVersionAutoSyncEnabled *bool `json:"openai_codex_version_auto_sync_enabled"`
|
||||
|
||||
// codex_cli_only 加固(global-only)
|
||||
MinCodexVersion string `json:"min_codex_version"`
|
||||
@@ -1276,6 +1278,15 @@ func (h *SettingHandler) UpdateSettings(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
}
|
||||
if req.OpenAICodexClientVersion != nil {
|
||||
// 该值会被拼进出站 User-Agent 与 version 头,必须是合法版本号;空串表示跟随自动同步。
|
||||
normalized := strings.TrimSpace(*req.OpenAICodexClientVersion)
|
||||
if normalized != "" && service.NormalizeCodexClientVersion(normalized) == "" {
|
||||
response.Error(c, http.StatusBadRequest, "openai_codex_client_version must be empty or a valid version (e.g. 0.146.0)")
|
||||
return
|
||||
}
|
||||
req.OpenAICodexClientVersion = &normalized
|
||||
}
|
||||
|
||||
// codex_cli_only 加固:最低/最高 Codex 版本(空=禁用,或合法 semver;max>=min)
|
||||
if req.MinCodexVersion != "" && !semverPattern.MatchString(req.MinCodexVersion) {
|
||||
@@ -1555,6 +1566,20 @@ func (h *SettingHandler) UpdateSettings(c *gin.Context) {
|
||||
}
|
||||
return previousSettings.OpenAICodexUserAgent
|
||||
}(),
|
||||
OpenAICodexClientVersion: func() string {
|
||||
if req.OpenAICodexClientVersion != nil {
|
||||
return *req.OpenAICodexClientVersion
|
||||
}
|
||||
return previousSettings.OpenAICodexClientVersion
|
||||
}(),
|
||||
// 同步值由自动同步任务独占写入,面板保存时原样带回,避免被清空。
|
||||
OpenAICodexClientVersionSynced: previousSettings.OpenAICodexClientVersionSynced,
|
||||
OpenAICodexVersionAutoSyncEnabled: func() bool {
|
||||
if req.OpenAICodexVersionAutoSyncEnabled != nil {
|
||||
return *req.OpenAICodexVersionAutoSyncEnabled
|
||||
}
|
||||
return previousSettings.OpenAICodexVersionAutoSyncEnabled
|
||||
}(),
|
||||
MinCodexVersion: strings.TrimSpace(req.MinCodexVersion),
|
||||
MaxCodexVersion: strings.TrimSpace(req.MaxCodexVersion),
|
||||
CodexCLIOnlyBlacklist: strings.TrimSpace(req.CodexCLIOnlyBlacklist),
|
||||
@@ -2027,6 +2052,9 @@ func (h *SettingHandler) UpdateSettings(c *gin.Context) {
|
||||
EnableClientDatelineNormalization: updatedSettings.EnableClientDatelineNormalization,
|
||||
AntigravityUserAgentVersion: updatedSettings.AntigravityUserAgentVersion,
|
||||
OpenAICodexUserAgent: updatedSettings.OpenAICodexUserAgent,
|
||||
OpenAICodexClientVersion: updatedSettings.OpenAICodexClientVersion,
|
||||
OpenAICodexClientVersionSynced: updatedSettings.OpenAICodexClientVersionSynced,
|
||||
OpenAICodexVersionAutoSyncEnabled: updatedSettings.OpenAICodexVersionAutoSyncEnabled,
|
||||
MinCodexVersion: updatedSettings.MinCodexVersion,
|
||||
MaxCodexVersion: updatedSettings.MaxCodexVersion,
|
||||
CodexCLIOnlyBlacklist: updatedSettings.CodexCLIOnlyBlacklist,
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
func ensureCompositeTargetPlatform(c *gin.Context, apiKey *service.APIKey, model string) {
|
||||
@@ -55,3 +58,42 @@ func effectiveAPIKeyPlatform(c *gin.Context, apiKey *service.APIKey) string {
|
||||
}
|
||||
return apiKey.Group.Platform
|
||||
}
|
||||
|
||||
func openAIReasoningEffortPolicyForRequest(c *gin.Context, apiKey *service.APIKey) (string, []service.ReasoningEffortMapping, bool) {
|
||||
if apiKey == nil || apiKey.Group == nil {
|
||||
return "", nil, false
|
||||
}
|
||||
if apiKey.Group.Platform != service.PlatformOpenAI && apiKey.Group.Platform != service.PlatformComposite {
|
||||
return "", nil, false
|
||||
}
|
||||
if effectiveAPIKeyPlatform(c, apiKey) != service.PlatformOpenAI {
|
||||
return "", nil, false
|
||||
}
|
||||
return apiKey.Group.MaxReasoningEffort, apiKey.Group.ReasoningEffortMappings, true
|
||||
}
|
||||
|
||||
func applyOpenAIReasoningEffortPolicyForRequest(c *gin.Context, apiKey *service.APIKey, body []byte) ([]byte, bool) {
|
||||
maxEffort, mappings, ok := openAIReasoningEffortPolicyForRequest(c, apiKey)
|
||||
if !ok {
|
||||
return body, false
|
||||
}
|
||||
return service.ApplyOpenAIReasoningEffortPolicy(body, maxEffort, mappings)
|
||||
}
|
||||
|
||||
func bindOpenAIReasoningEffortPolicyForMessagesRequest(c *gin.Context, apiKey *service.APIKey, body []byte) {
|
||||
if c == nil || c.Request == nil {
|
||||
return
|
||||
}
|
||||
// The Messages bridge synthesizes a default OpenAI effort when
|
||||
// output_config.effort is omitted. Bind the group policy only for an
|
||||
// explicit client value so the ceiling does not alter that default.
|
||||
effort := gjson.GetBytes(body, "output_config.effort")
|
||||
if !effort.Exists() || effort.Type != gjson.String || strings.TrimSpace(effort.String()) == "" {
|
||||
return
|
||||
}
|
||||
maxEffort, mappings, ok := openAIReasoningEffortPolicyForRequest(c, apiKey)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
c.Request = c.Request.WithContext(service.WithOpenAIReasoningEffortPolicy(c.Request.Context(), maxEffort, mappings))
|
||||
}
|
||||
@@ -77,6 +77,46 @@ func TestCompositeTargetPlatformResolvedAllowsConcreteGroupWithoutResolution(t *
|
||||
require.True(t, compositeTargetPlatformResolved(c, apiKey, "llama-4-maverick"))
|
||||
}
|
||||
|
||||
func TestOpenAIReasoningEffortPolicyForCompositeTarget(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
group := &service.Group{
|
||||
Platform: service.PlatformComposite,
|
||||
MaxReasoningEffort: "medium",
|
||||
ReasoningEffortMappings: []service.ReasoningEffortMapping{
|
||||
{From: "max", To: "xhigh"},
|
||||
},
|
||||
}
|
||||
apiKey := &service.APIKey{Group: group}
|
||||
body := []byte(`{"reasoning":{"effort":"max"}}`)
|
||||
|
||||
openAICtx, _ := gin.CreateTestContext(httptest.NewRecorder())
|
||||
openAICtx.Request = httptest.NewRequest("POST", "/v1/responses", nil)
|
||||
openAICtx.Request = openAICtx.Request.WithContext(service.WithResolvedTargetPlatform(openAICtx.Request.Context(), service.PlatformOpenAI))
|
||||
got, changed := applyOpenAIReasoningEffortPolicyForRequest(openAICtx, apiKey, body)
|
||||
require.True(t, changed)
|
||||
require.JSONEq(t, `{"reasoning":{"effort":"medium"}}`, string(got))
|
||||
|
||||
bindOpenAIReasoningEffortPolicyForMessagesRequest(openAICtx, apiKey, []byte(`{"output_config":{"effort":"max"}}`))
|
||||
bound, changed := service.ApplyOpenAIReasoningEffortPolicyFromContext(openAICtx.Request.Context(), body)
|
||||
require.True(t, changed)
|
||||
require.JSONEq(t, `{"reasoning":{"effort":"medium"}}`, string(bound))
|
||||
|
||||
omittedCtx, _ := gin.CreateTestContext(httptest.NewRecorder())
|
||||
omittedCtx.Request = httptest.NewRequest("POST", "/v1/messages", nil)
|
||||
omittedCtx.Request = omittedCtx.Request.WithContext(service.WithResolvedTargetPlatform(omittedCtx.Request.Context(), service.PlatformOpenAI))
|
||||
bindOpenAIReasoningEffortPolicyForMessagesRequest(omittedCtx, apiKey, []byte(`{"model":"gpt-5"}`))
|
||||
omitted, changed := service.ApplyOpenAIReasoningEffortPolicyFromContext(omittedCtx.Request.Context(), body)
|
||||
require.False(t, changed)
|
||||
require.Equal(t, body, omitted)
|
||||
|
||||
grokCtx, _ := gin.CreateTestContext(httptest.NewRecorder())
|
||||
grokCtx.Request = httptest.NewRequest("POST", "/v1/responses", nil)
|
||||
grokCtx.Request = grokCtx.Request.WithContext(service.WithResolvedTargetPlatform(grokCtx.Request.Context(), service.PlatformGrok))
|
||||
got, changed = applyOpenAIReasoningEffortPolicyForRequest(grokCtx, apiKey, body)
|
||||
require.False(t, changed)
|
||||
require.Equal(t, body, got)
|
||||
}
|
||||
|
||||
func TestClientRequestedModelUsesCompositePublicModel(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
c, _ := gin.CreateTestContext(httptest.NewRecorder())
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
)
|
||||
|
||||
// profitControlJSONFields 是分组利润控制的三个 JSON 字段。它们与同响应中的
|
||||
// rate_multiplier 相乘即可反推出运营方的上游采购成本上限,属于内部经营信息,
|
||||
// 只能出现在管理员 DTO 中。
|
||||
var profitControlJSONFields = []string{
|
||||
"profit_control_enabled",
|
||||
"profit_min_margin",
|
||||
"profit_safety_buffer",
|
||||
}
|
||||
|
||||
func profitControlServiceGroup() *service.Group {
|
||||
return &service.Group{
|
||||
ID: 7,
|
||||
Name: "profit-gated",
|
||||
Platform: service.PlatformAnthropic,
|
||||
RateMultiplier: 2.0,
|
||||
Status: service.StatusActive,
|
||||
ProfitControlEnabled: true,
|
||||
ProfitMinMargin: 0.3,
|
||||
ProfitSafetyBuffer: 0.05,
|
||||
}
|
||||
}
|
||||
|
||||
func marshalToMap(t *testing.T, v any) map[string]any {
|
||||
t.Helper()
|
||||
raw, err := json.Marshal(v)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal: %v", err)
|
||||
}
|
||||
var out map[string]any
|
||||
if err := json.Unmarshal(raw, &out); err != nil {
|
||||
t.Fatalf("unmarshal: %v", err)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// TestGroupFromServiceOmitsProfitControl 钉死普通用户侧的分组 DTO 不泄露利润控制配置。
|
||||
func TestGroupFromServiceOmitsProfitControl(t *testing.T) {
|
||||
for name, got := range map[string]any{
|
||||
"GroupFromService": GroupFromService(profitControlServiceGroup()),
|
||||
"GroupFromServiceShallow": GroupFromServiceShallow(profitControlServiceGroup()),
|
||||
} {
|
||||
fields := marshalToMap(t, got)
|
||||
for _, f := range profitControlJSONFields {
|
||||
if _, ok := fields[f]; ok {
|
||||
t.Errorf("%s: 普通用户 DTO 不得包含 %q", name, f)
|
||||
}
|
||||
}
|
||||
if _, ok := fields["rate_multiplier"]; !ok {
|
||||
t.Errorf("%s: 应仍返回 rate_multiplier", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestGroupFromServiceAdminIncludesProfitControl 钉死管理端仍能读写利润控制配置。
|
||||
func TestGroupFromServiceAdminIncludesProfitControl(t *testing.T) {
|
||||
admin := GroupFromServiceAdmin(profitControlServiceGroup())
|
||||
if admin.ProfitControlEnabled != true || admin.ProfitMinMargin != 0.3 || admin.ProfitSafetyBuffer != 0.05 {
|
||||
t.Fatalf("管理员 DTO 未透传利润控制配置: %+v", admin)
|
||||
}
|
||||
fields := marshalToMap(t, admin)
|
||||
for _, f := range profitControlJSONFields {
|
||||
if _, ok := fields[f]; !ok {
|
||||
t.Errorf("管理员 DTO 应包含 %q", f)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -146,6 +146,9 @@ func GroupFromServiceAdmin(g *service.Group) *AdminGroup {
|
||||
}
|
||||
out := &AdminGroup{
|
||||
Group: groupFromServiceBase(g),
|
||||
ProfitControlEnabled: g.ProfitControlEnabled,
|
||||
ProfitMinMargin: g.ProfitMinMargin,
|
||||
ProfitSafetyBuffer: g.ProfitSafetyBuffer,
|
||||
ModelRouting: g.ModelRouting,
|
||||
ModelRoutingEnabled: g.ModelRoutingEnabled,
|
||||
MCPXMLInject: g.MCPXMLInject,
|
||||
|
||||
@@ -199,6 +199,9 @@ type SystemSettings struct {
|
||||
EnableClientDatelineNormalization bool `json:"enable_client_dateline_normalization"`
|
||||
AntigravityUserAgentVersion string `json:"antigravity_user_agent_version"`
|
||||
OpenAICodexUserAgent string `json:"openai_codex_user_agent"`
|
||||
OpenAICodexClientVersion string `json:"openai_codex_client_version"`
|
||||
OpenAICodexClientVersionSynced string `json:"openai_codex_client_version_synced"`
|
||||
OpenAICodexVersionAutoSyncEnabled bool `json:"openai_codex_version_auto_sync_enabled"`
|
||||
|
||||
// codex_cli_only 加固
|
||||
MinCodexVersion string `json:"min_codex_version"`
|
||||
|
||||
@@ -155,6 +155,13 @@ type Group struct {
|
||||
type AdminGroup struct {
|
||||
Group
|
||||
|
||||
// 分组利润控制(五个 token 平台分组可启用;margin/buffer 为小数存储)。
|
||||
// 仅管理员可见:这三个字段与同响应中的 rate_multiplier 相乘即可反推出
|
||||
// 运营方的上游成本上限,属于内部经营信息,不得下放到 dto.Group。
|
||||
ProfitControlEnabled bool `json:"profit_control_enabled"`
|
||||
ProfitMinMargin float64 `json:"profit_min_margin"`
|
||||
ProfitSafetyBuffer float64 `json:"profit_safety_buffer"`
|
||||
|
||||
// 模型路由配置(仅 anthropic 平台使用)
|
||||
ModelRouting map[string][]int64 `json:"model_routing"`
|
||||
ModelRoutingEnabled bool `json:"model_routing_enabled"`
|
||||
|
||||
@@ -40,8 +40,18 @@ const (
|
||||
// Service 层在 SingleAccountRetry 模式下已做充分原地重试(最多 3 次、总等待 30s),
|
||||
// Handler 层只需短暂间隔后重新进入 Service 层即可。
|
||||
singleAccountBackoffDelay = 2 * time.Second
|
||||
// maxProfitVetoAttempts 单次请求内允许的分组利润门终检否决次数上限。
|
||||
// 利润否决不产生上游请求,因此不会推进 SwitchCount;没有独立上限的话,
|
||||
// 「选号 → 终检否决 → 重选」在候选池与账号快照短暂不一致时可以空转很久。
|
||||
// 取值与 maxAccountSwitches 默认值一致:混合定价的大分组仍有充分重选机会,
|
||||
// 同时把整池越线时的无谓选号开销限制在常数级。
|
||||
maxProfitVetoAttempts = 10
|
||||
)
|
||||
|
||||
// profitVetoExhaustedMessage 是利润否决次数耗尽时返回给客户端的文案。
|
||||
// 语义上等同于「无可用账号」:候选账号都不满足分组的利润约束。
|
||||
const profitVetoExhaustedMessage = "No available accounts: all candidates rejected by group profit control"
|
||||
|
||||
// FailoverState 跨循环迭代共享的 failover 状态
|
||||
type FailoverState struct {
|
||||
SwitchCount int
|
||||
@@ -51,18 +61,64 @@ type FailoverState struct {
|
||||
LastFailoverErr *service.UpstreamFailoverError
|
||||
ForceCacheBilling bool
|
||||
hasBoundSession bool
|
||||
|
||||
// profitVetoedAccountIDs 记录被分组利润门终检否决的账号,是 FailedAccountIDs
|
||||
// 的子集。之所以单独维护:HandleSelectionExhausted 的 503 退避分支会清空
|
||||
// FailedAccountIDs,而利润否决在同一请求内的判定不会改变(下游倍率 D 已在
|
||||
// 请求开始冻结),被清空的账号会被立即重选并再次否决,形成没有任何上游请求、
|
||||
// SwitchCount 也不前进的活锁。清空后必须把它们放回排除集。
|
||||
profitVetoedAccountIDs map[int64]struct{}
|
||||
// profitVetoCount 本次请求累计的利润否决次数,用于 maxProfitVetoAttempts 上限。
|
||||
profitVetoCount int
|
||||
}
|
||||
|
||||
// NewFailoverState 创建 failover 状态
|
||||
func NewFailoverState(maxSwitches int, hasBoundSession bool) *FailoverState {
|
||||
return &FailoverState{
|
||||
MaxSwitches: maxSwitches,
|
||||
FailedAccountIDs: make(map[int64]struct{}),
|
||||
SameAccountRetryCount: make(map[int64]int),
|
||||
hasBoundSession: hasBoundSession,
|
||||
MaxSwitches: maxSwitches,
|
||||
FailedAccountIDs: make(map[int64]struct{}),
|
||||
SameAccountRetryCount: make(map[int64]int),
|
||||
hasBoundSession: hasBoundSession,
|
||||
profitVetoedAccountIDs: make(map[int64]struct{}),
|
||||
}
|
||||
}
|
||||
|
||||
// RecordProfitVeto 记录一次分组利润门终检否决:把账号加入排除列表(同时登记到
|
||||
// 利润否决集,使其不被 503 退避分支清掉)并递增否决计数。
|
||||
//
|
||||
// 返回 FailoverContinue 表示调用方可以继续重选下一个账号;返回 FailoverExhausted
|
||||
// 表示本次请求的利润否决次数已达上限,调用方应按「无可用账号」终止,
|
||||
// 不得继续 continue。
|
||||
func (s *FailoverState) RecordProfitVeto(accountID int64) FailoverAction {
|
||||
s.FailedAccountIDs[accountID] = struct{}{}
|
||||
if s.profitVetoedAccountIDs == nil {
|
||||
s.profitVetoedAccountIDs = make(map[int64]struct{})
|
||||
}
|
||||
s.profitVetoedAccountIDs[accountID] = struct{}{}
|
||||
s.profitVetoCount++
|
||||
if s.profitVetoCount >= maxProfitVetoAttempts {
|
||||
return FailoverExhausted
|
||||
}
|
||||
return FailoverContinue
|
||||
}
|
||||
|
||||
// ProfitVetoCount 返回本次请求累计的利润否决次数(供日志使用)。
|
||||
func (s *FailoverState) ProfitVetoCount() int { return s.profitVetoCount }
|
||||
|
||||
// allExclusionsAreProfitVetoed 判断排除列表是否已全部由利润门否决贡献。
|
||||
// 此时清空 FailedAccountIDs 会被原样恢复,退避重试不会带来任何新候选。
|
||||
func (s *FailoverState) allExclusionsAreProfitVetoed() bool {
|
||||
if len(s.profitVetoedAccountIDs) == 0 || len(s.FailedAccountIDs) == 0 {
|
||||
return false
|
||||
}
|
||||
for id := range s.FailedAccountIDs {
|
||||
if _, ok := s.profitVetoedAccountIDs[id]; !ok {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// HandleFailoverError 处理 UpstreamFailoverError,返回下一步动作。
|
||||
// 包含:缓存计费判断、同账号重试、临时封禁、切换计数、Antigravity 延时。
|
||||
func (s *FailoverState) HandleFailoverError(
|
||||
@@ -156,6 +212,17 @@ func (s *FailoverState) HandleSelectionExhausted(ctx context.Context) FailoverAc
|
||||
s.LastFailoverErr.StatusCode == http.StatusServiceUnavailable &&
|
||||
s.SwitchCount <= s.MaxSwitches {
|
||||
|
||||
// 排除列表全由利润门否决贡献时,清空后会被原样恢复:退避重试拿不到
|
||||
// 任何新候选,而利润否决不推进 SwitchCount,退避条件将永远成立。
|
||||
// 这里直接判定耗尽,避免每 2s 空转一轮的活锁。
|
||||
if s.allExclusionsAreProfitVetoed() {
|
||||
logger.FromContext(ctx).Warn("gateway.failover_selection_exhausted_by_profit_veto",
|
||||
zap.Int("profit_veto_count", s.profitVetoCount),
|
||||
zap.Int("excluded_accounts", len(s.FailedAccountIDs)),
|
||||
)
|
||||
return FailoverExhausted
|
||||
}
|
||||
|
||||
logger.FromContext(ctx).Warn("gateway.failover_single_account_backoff",
|
||||
zap.Duration("backoff_delay", singleAccountBackoffDelay),
|
||||
zap.Int("switch_count", s.SwitchCount),
|
||||
@@ -169,6 +236,11 @@ func (s *FailoverState) HandleSelectionExhausted(ctx context.Context) FailoverAc
|
||||
zap.Int("max_switches", s.MaxSwitches),
|
||||
)
|
||||
s.FailedAccountIDs = make(map[int64]struct{})
|
||||
// 利润门否决的账号不参与退避重试的解除:判定依据(冻结的下游倍率)在
|
||||
// 同一请求内不变,放它们回池只会被再次否决。
|
||||
for id := range s.profitVetoedAccountIDs {
|
||||
s.FailedAccountIDs[id] = struct{}{}
|
||||
}
|
||||
return FailoverContinue
|
||||
}
|
||||
return FailoverExhausted
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// profitVetoLoopResult 记录一次模拟选号循环的终止方式与步数。
|
||||
type profitVetoLoopResult struct {
|
||||
outcome string // "forwarded" | "exhausted" | "budget_exceeded"
|
||||
forwardedID int64
|
||||
iterations int
|
||||
backoffRetries int
|
||||
}
|
||||
|
||||
// runProfitVetoLoop 模拟 handler 的「选号 → 利润终检 → 重选」循环,只保留与
|
||||
// 活锁相关的状态机(FailoverState + 排除列表 + HandleSelectionExhausted),
|
||||
// 不涉及真实调度器与上游转发。
|
||||
//
|
||||
// pool 按顺序给出候选账号;vetoed 中的账号每次终检都被利润门否决——这对应
|
||||
// 「候选池快照与 per-account 快照短暂不一致」时门的确定性判定。
|
||||
// maxIterations 是测试自身的预算:循环超过它即视为活锁。
|
||||
func runProfitVetoLoop(t *testing.T, fs *FailoverState, pool []int64, vetoed map[int64]bool, maxIterations int) profitVetoLoopResult {
|
||||
t.Helper()
|
||||
res := profitVetoLoopResult{}
|
||||
for res.iterations = 1; res.iterations <= maxIterations; res.iterations++ {
|
||||
// 选号:返回第一个不在排除列表中的账号。
|
||||
var picked int64
|
||||
for _, id := range pool {
|
||||
if _, excluded := fs.FailedAccountIDs[id]; !excluded {
|
||||
picked = id
|
||||
break
|
||||
}
|
||||
}
|
||||
if picked == 0 {
|
||||
// 选号耗尽,交给退避决策。
|
||||
switch fs.HandleSelectionExhausted(context.Background()) {
|
||||
case FailoverContinue:
|
||||
res.backoffRetries++
|
||||
continue
|
||||
default:
|
||||
res.outcome = "exhausted"
|
||||
return res
|
||||
}
|
||||
}
|
||||
if vetoed[picked] {
|
||||
if fs.RecordProfitVeto(picked) == FailoverExhausted {
|
||||
res.outcome = "exhausted"
|
||||
return res
|
||||
}
|
||||
continue
|
||||
}
|
||||
res.outcome = "forwarded"
|
||||
res.forwardedID = picked
|
||||
return res
|
||||
}
|
||||
res.outcome = "budget_exceeded"
|
||||
return res
|
||||
}
|
||||
|
||||
// TestProfitVetoAfter503DoesNotLivelock 钉死 #4925 引入的活锁回归:
|
||||
// 一次真实 503 之后,若调度器持续返回会被利润门否决的账号,
|
||||
// 「选号 → 否决 → 排除 → 选号耗尽 → 清空排除 → 睡 2s → 选号」会无限循环,
|
||||
// 因为利润否决不推进 SwitchCount,退避条件永远成立。
|
||||
func TestProfitVetoAfter503DoesNotLivelock(t *testing.T) {
|
||||
fs := NewFailoverState(10, false)
|
||||
// 已经历一次真实 503(Antigravity 单账号分组 MODEL_CAPACITY_EXHAUSTED 是设计内路径)。
|
||||
fs.LastFailoverErr = newTestFailoverErr(503, false, false)
|
||||
fs.SwitchCount = 1
|
||||
fs.FailedAccountIDs[1] = struct{}{}
|
||||
|
||||
start := time.Now()
|
||||
res := runProfitVetoLoop(t, fs, []int64{1}, map[int64]bool{1: true}, 50)
|
||||
elapsed := time.Since(start)
|
||||
|
||||
require.Equal(t, "exhausted", res.outcome, "整池被利润门否决时必须有限步终止")
|
||||
require.LessOrEqual(t, res.backoffRetries, 1, "被否决的账号不得被退避分支复活并反复重选")
|
||||
require.Less(t, elapsed, 10*time.Second, "不得每 2s 空转一轮")
|
||||
}
|
||||
|
||||
// TestProfitVetoKeepsBackoffUsefulForHealthyAccount 钉死修复没有削弱既有的
|
||||
// 503 退避语义:排除列表里仍有非利润否决的账号时,退避照常清空并重试,
|
||||
// 只是被利润门否决的账号不再复活。
|
||||
func TestProfitVetoKeepsBackoffUsefulForHealthyAccount(t *testing.T) {
|
||||
fs := NewFailoverState(10, false)
|
||||
fs.LastFailoverErr = newTestFailoverErr(503, false, false)
|
||||
fs.SwitchCount = 1
|
||||
// 账号 1 因真实 503 被排除;账号 2 会被利润门否决。
|
||||
fs.FailedAccountIDs[1] = struct{}{}
|
||||
|
||||
res := runProfitVetoLoop(t, fs, []int64{2, 1}, map[int64]bool{2: true}, 50)
|
||||
|
||||
require.Equal(t, "forwarded", res.outcome)
|
||||
require.Equal(t, int64(1), res.forwardedID, "退避清空后应重新可选账号 1")
|
||||
require.Equal(t, 1, res.backoffRetries, "应发生且只发生一次退避重试")
|
||||
require.Contains(t, fs.FailedAccountIDs, int64(2), "利润否决的账号在退避清空后必须被放回排除集")
|
||||
}
|
||||
|
||||
// TestProfitVetoAttemptsCapped 钉死没有 503 参与时,大分组整池越线也会在
|
||||
// 常数步内终止,而不是把整池逐个选一遍。
|
||||
func TestProfitVetoAttemptsCapped(t *testing.T) {
|
||||
fs := NewFailoverState(10, false)
|
||||
pool := make([]int64, 0, 64)
|
||||
vetoed := make(map[int64]bool, 64)
|
||||
for id := int64(1); id <= 64; id++ {
|
||||
pool = append(pool, id)
|
||||
vetoed[id] = true
|
||||
}
|
||||
|
||||
res := runProfitVetoLoop(t, fs, pool, vetoed, 200)
|
||||
|
||||
require.Equal(t, "exhausted", res.outcome)
|
||||
require.Equal(t, maxProfitVetoAttempts, fs.ProfitVetoCount())
|
||||
require.Equal(t, maxProfitVetoAttempts, res.iterations, "达到上限即终止,不应继续遍历候选池")
|
||||
}
|
||||
|
||||
// TestRecordProfitVetoExcludesAccount 钉死 RecordProfitVeto 仍然把账号加入
|
||||
// 调度排除列表(选号入参用的就是 FailedAccountIDs)。
|
||||
func TestRecordProfitVetoExcludesAccount(t *testing.T) {
|
||||
fs := NewFailoverState(10, false)
|
||||
require.Equal(t, FailoverContinue, fs.RecordProfitVeto(42))
|
||||
require.Contains(t, fs.FailedAccountIDs, int64(42))
|
||||
require.Equal(t, 1, fs.ProfitVetoCount())
|
||||
}
|
||||
|
||||
// TestHandleSelectionExhaustedUnaffectedWithoutProfitVeto 钉死未启用利润控制的
|
||||
// 请求(无任何利润否决)走的仍是原有退避语义:清空排除列表并重试。
|
||||
func TestHandleSelectionExhaustedUnaffectedWithoutProfitVeto(t *testing.T) {
|
||||
fs := NewFailoverState(3, false)
|
||||
fs.LastFailoverErr = newTestFailoverErr(503, false, false)
|
||||
fs.SwitchCount = 1
|
||||
fs.FailedAccountIDs[100] = struct{}{}
|
||||
|
||||
require.Equal(t, FailoverContinue, fs.HandleSelectionExhausted(context.Background()))
|
||||
require.Empty(t, fs.FailedAccountIDs, "无利润否决时排除列表应被完全清空")
|
||||
}
|
||||
@@ -196,6 +196,8 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
|
||||
|
||||
setOpsRequestContext(c, reqModel, reqStream)
|
||||
setOpsEndpointContext(c, "", int16(service.RequestTypeFromLegacy(reqStream, false)))
|
||||
pricingCtx, pricingAt := service.WithGatewayTokenRequestPricing(c.Request.Context())
|
||||
c.Request = c.Request.WithContext(pricingCtx)
|
||||
|
||||
// 验证 model 必填
|
||||
if reqModel == "" {
|
||||
@@ -421,8 +423,30 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
|
||||
}
|
||||
// Slot acquired: no longer waiting in queue.
|
||||
releaseWait()
|
||||
if err := h.gatewayService.BindStickySession(c.Request.Context(), apiKey.GroupID, sessionKey, account.ID); err != nil {
|
||||
reqLog.Warn("gateway.bind_sticky_session_failed", zap.Int64("account_id", account.ID), zap.Error(err))
|
||||
}
|
||||
// 终检与准入后绑定使用选号结果携带的门(见 responses 同名注释)。
|
||||
admissionCtx := service.ContextWithSelectionProfitGate(c.Request.Context(), selection)
|
||||
latest, vetoed, reason := h.gatewayService.GatewayProfitControlVetoLatest(admissionCtx, account)
|
||||
if vetoed {
|
||||
if accountReleaseFunc != nil {
|
||||
accountReleaseFunc()
|
||||
}
|
||||
reqLog.Debug("gateway.account_slot_profit_vetoed", zap.Int64("account_id", account.ID), zap.String("reason", reason))
|
||||
if fs.RecordProfitVeto(account.ID) == FailoverExhausted {
|
||||
reqLog.Warn("gateway.profit_veto_attempts_exhausted", zap.Int("profit_veto_count", fs.ProfitVetoCount()))
|
||||
markOpsRoutingCapacityLimited(c)
|
||||
h.handleStreamingAwareError(c, http.StatusServiceUnavailable, "api_error", profitVetoExhaustedMessage, streamStarted)
|
||||
return
|
||||
}
|
||||
continue
|
||||
}
|
||||
account = latest
|
||||
selection.Account = latest
|
||||
// 等待路径保持既有 eager 绑定(无门时 helper 直接绑定);调度器已
|
||||
// 抢槽的直达路径无门时由选号内部绑定,这里只在门下补准入后绑定。
|
||||
if selection.ProfitGateActive() || !selection.Acquired {
|
||||
if err := h.gatewayService.BindStickySessionAfterProfitAdmission(admissionCtx, apiKey.GroupID, sessionKey, account.ID); err != nil {
|
||||
reqLog.Warn("gateway.bind_sticky_session_after_profit_admission_failed", zap.Int64("account_id", account.ID), zap.Error(err))
|
||||
}
|
||||
}
|
||||
// 账号槽位/等待计数需要在超时或断开时安全回收
|
||||
@@ -544,6 +568,7 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
|
||||
User: apiKey.User,
|
||||
Account: account,
|
||||
Subscription: subscription,
|
||||
PricingAt: pricingAt,
|
||||
InboundEndpoint: inboundEndpoint,
|
||||
UpstreamEndpoint: upstreamEndpoint,
|
||||
UserAgent: userAgent,
|
||||
@@ -721,12 +746,30 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
|
||||
}
|
||||
// Slot acquired: no longer waiting in queue.
|
||||
releaseWait()
|
||||
reqLog.Info("sticky.bind_after_wait",
|
||||
zap.String("session_key", sessionKey),
|
||||
zap.Int64("account_id", account.ID),
|
||||
)
|
||||
if err := h.gatewayService.BindStickySession(c.Request.Context(), currentAPIKey.GroupID, sessionKey, account.ID); err != nil {
|
||||
reqLog.Warn("gateway.bind_sticky_session_failed", zap.Int64("account_id", account.ID), zap.Error(err))
|
||||
}
|
||||
// 终检与准入后绑定使用选号结果携带的门(见 responses 同名注释)。
|
||||
admissionCtx := service.ContextWithSelectionProfitGate(c.Request.Context(), selection)
|
||||
latest, vetoed, reason := h.gatewayService.GatewayProfitControlVetoLatest(admissionCtx, account)
|
||||
if vetoed {
|
||||
if accountReleaseFunc != nil {
|
||||
accountReleaseFunc()
|
||||
}
|
||||
reqLog.Debug("gateway.account_slot_profit_vetoed", zap.Int64("account_id", account.ID), zap.String("reason", reason))
|
||||
if fs.RecordProfitVeto(account.ID) == FailoverExhausted {
|
||||
reqLog.Warn("gateway.profit_veto_attempts_exhausted", zap.Int("profit_veto_count", fs.ProfitVetoCount()))
|
||||
markOpsRoutingCapacityLimited(c)
|
||||
h.handleStreamingAwareError(c, http.StatusServiceUnavailable, "api_error", profitVetoExhaustedMessage, streamStarted)
|
||||
return
|
||||
}
|
||||
continue
|
||||
}
|
||||
account = latest
|
||||
selection.Account = latest
|
||||
// 等待路径保持既有 eager 绑定(无门时 helper 直接绑定);调度器已
|
||||
// 抢槽的直达路径无门时由选号内部绑定,这里只在门下补准入后绑定。
|
||||
if selection.ProfitGateActive() || !selection.Acquired {
|
||||
if err := h.gatewayService.BindStickySessionAfterProfitAdmission(admissionCtx, currentAPIKey.GroupID, sessionKey, account.ID); err != nil {
|
||||
reqLog.Warn("gateway.bind_sticky_session_after_profit_admission_failed", zap.Int64("account_id", account.ID), zap.Error(err))
|
||||
}
|
||||
}
|
||||
// 账号槽位/等待计数需要在超时或断开时安全回收
|
||||
@@ -864,6 +907,7 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
|
||||
User: currentAPIKey.User,
|
||||
Account: account,
|
||||
Subscription: currentSubscription,
|
||||
PricingAt: pricingAt,
|
||||
InboundEndpoint: inboundEndpoint,
|
||||
UpstreamEndpoint: upstreamEndpoint,
|
||||
UserAgent: userAgent,
|
||||
|
||||
@@ -93,6 +93,8 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) {
|
||||
|
||||
setOpsRequestContext(c, reqModel, reqStream)
|
||||
setOpsEndpointContext(c, "", int16(service.RequestTypeFromLegacy(reqStream, false)))
|
||||
pricingCtx, pricingAt := service.WithGatewayTokenRequestPricing(c.Request.Context())
|
||||
c.Request = c.Request.WithContext(pricingCtx)
|
||||
|
||||
// 解析渠道级模型映射
|
||||
channelMapping, _ := h.gatewayService.ResolveChannelMappingAndRestrict(c.Request.Context(), apiKey.GroupID, reqModel)
|
||||
@@ -157,7 +159,6 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) {
|
||||
if groupPlatform == service.PlatformGemini && selectionSessionHash != "" {
|
||||
selectionSessionHash = "gemini:" + selectionSessionHash
|
||||
}
|
||||
|
||||
// 3. Account selection + failover loop
|
||||
fs := NewFailoverState(h.maxAccountSwitches, false)
|
||||
if groupPlatform == service.PlatformGemini {
|
||||
@@ -223,6 +224,28 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
}
|
||||
// 终检与准入后绑定使用选号结果携带的门(见 responses 同名注释)。
|
||||
admissionCtx := service.ContextWithSelectionProfitGate(c.Request.Context(), selection)
|
||||
latest, vetoed, reason := h.gatewayService.GatewayProfitControlVetoLatest(admissionCtx, account)
|
||||
if vetoed {
|
||||
if accountReleaseFunc != nil {
|
||||
accountReleaseFunc()
|
||||
}
|
||||
reqLog.Debug("gateway.cc.account_slot_profit_vetoed", zap.Int64("account_id", account.ID), zap.String("reason", reason))
|
||||
if fs.RecordProfitVeto(account.ID) == FailoverExhausted {
|
||||
reqLog.Warn("gateway.cc.profit_veto_attempts_exhausted", zap.Int("profit_veto_count", fs.ProfitVetoCount()))
|
||||
h.chatCompletionsErrorResponse(c, http.StatusServiceUnavailable, "api_error", profitVetoExhaustedMessage)
|
||||
return
|
||||
}
|
||||
continue
|
||||
}
|
||||
account = latest
|
||||
selection.Account = latest
|
||||
if selection.ProfitGateActive() {
|
||||
if err := h.gatewayService.BindStickySessionAfterProfitAdmission(admissionCtx, apiKey.GroupID, selectionSessionHash, account.ID); err != nil {
|
||||
reqLog.Warn("gateway.cc.bind_sticky_session_after_profit_admission_failed", zap.Int64("account_id", account.ID), zap.Error(err))
|
||||
}
|
||||
}
|
||||
accountReleaseFunc = wrapReleaseOnDone(c.Request.Context(), accountReleaseFunc)
|
||||
|
||||
if groupPlatform == service.PlatformGemini && account.Platform != service.PlatformGemini {
|
||||
@@ -318,6 +341,7 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) {
|
||||
User: apiKey.User,
|
||||
Account: account,
|
||||
Subscription: subscription,
|
||||
PricingAt: pricingAt,
|
||||
InboundEndpoint: inboundEndpoint,
|
||||
UpstreamEndpoint: upstreamEndpoint,
|
||||
UserAgent: userAgent,
|
||||
|
||||
@@ -90,9 +90,15 @@ func (h *GatewayHandler) Responses(c *gin.Context) {
|
||||
setOpsRequestContext(c, reqModel, reqStream)
|
||||
setOpsEndpointContext(c, "", int16(service.RequestTypeFromLegacy(reqStream, false)))
|
||||
requestCtx := c.Request.Context()
|
||||
// 定价上下文无条件装配:/v1/responses 是 token 计费端点,声明生图工具的
|
||||
// 混合请求同样按 token 计费(外加图片部分),其 token 利润保护不因请求体
|
||||
// 里的任何工具声明(含 Codex 被动 image_gen namespace)而关闭。生图意图
|
||||
// 仅用于能力路由与图片计费;独立图片/视频端点才在利润门范围之外。
|
||||
requestCtx, pricingAt := service.WithGatewayTokenRequestPricing(requestCtx)
|
||||
if service.IsImageGenerationIntentForPlatform("/v1/responses", reqModel, body, openAICompatibleRequestPlatform(c.Request.Context(), apiKey)) {
|
||||
requestCtx = service.WithOpenAIImageGenerationIntent(requestCtx)
|
||||
}
|
||||
c.Request = c.Request.WithContext(requestCtx)
|
||||
|
||||
// 解析渠道级模型映射
|
||||
channelMapping, _ := h.gatewayService.ResolveChannelMappingAndRestrict(requestCtx, apiKey.GroupID, reqModel)
|
||||
@@ -220,6 +226,30 @@ func (h *GatewayHandler) Responses(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
}
|
||||
// 终检与准入后绑定必须使用选号结果携带的门:门安装在调度栈的局部
|
||||
// ctx 上(composite/fallback 还可能解析出与入口分组不同的门),直接用
|
||||
// requestCtx 会退化为空操作。
|
||||
admissionCtx := service.ContextWithSelectionProfitGate(requestCtx, selection)
|
||||
latest, vetoed, reason := h.gatewayService.GatewayProfitControlVetoLatest(admissionCtx, account)
|
||||
if vetoed {
|
||||
if accountReleaseFunc != nil {
|
||||
accountReleaseFunc()
|
||||
}
|
||||
reqLog.Debug("gateway.responses.account_slot_profit_vetoed", zap.Int64("account_id", account.ID), zap.String("reason", reason))
|
||||
if fs.RecordProfitVeto(account.ID) == FailoverExhausted {
|
||||
reqLog.Warn("gateway.responses.profit_veto_attempts_exhausted", zap.Int("profit_veto_count", fs.ProfitVetoCount()))
|
||||
h.responsesErrorResponse(c, http.StatusServiceUnavailable, "api_error", profitVetoExhaustedMessage)
|
||||
return
|
||||
}
|
||||
continue
|
||||
}
|
||||
account = latest
|
||||
selection.Account = latest
|
||||
if selection.ProfitGateActive() {
|
||||
if err := h.gatewayService.BindStickySessionAfterProfitAdmission(admissionCtx, apiKey.GroupID, sessionHash, account.ID); err != nil {
|
||||
reqLog.Warn("gateway.responses.bind_sticky_session_after_profit_admission_failed", zap.Int64("account_id", account.ID), zap.Error(err))
|
||||
}
|
||||
}
|
||||
accountReleaseFunc = wrapReleaseOnDone(c.Request.Context(), accountReleaseFunc)
|
||||
|
||||
// 5. Forward request
|
||||
@@ -299,6 +329,7 @@ func (h *GatewayHandler) Responses(c *gin.Context) {
|
||||
User: apiKey.User,
|
||||
Account: account,
|
||||
Subscription: subscription,
|
||||
PricingAt: pricingAt,
|
||||
InboundEndpoint: inboundEndpoint,
|
||||
UpstreamEndpoint: upstreamEndpoint,
|
||||
UserAgent: userAgent,
|
||||
|
||||
@@ -204,6 +204,8 @@ func (h *GatewayHandler) GeminiV1BetaModels(c *gin.Context) {
|
||||
|
||||
setOpsRequestContext(c, modelName, stream)
|
||||
setOpsEndpointContext(c, "", int16(service.RequestTypeFromLegacy(stream, false)))
|
||||
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 {
|
||||
googleSecurityAuditError(c, decision)
|
||||
@@ -466,8 +468,30 @@ func (h *GatewayHandler) GeminiV1BetaModels(c *gin.Context) {
|
||||
geminiConcurrency.DecrementAccountWaitCount(c.Request.Context(), account.ID)
|
||||
accountWaitCounted = false
|
||||
}
|
||||
if err := h.gatewayService.BindStickySession(c.Request.Context(), apiKey.GroupID, sessionKey, account.ID); err != nil {
|
||||
reqLog.Warn("gemini.bind_sticky_session_failed", zap.Int64("account_id", account.ID), zap.Error(err))
|
||||
}
|
||||
// 终检与准入后绑定使用选号结果携带的门(见 responses 同名注释)。
|
||||
admissionCtx := service.ContextWithSelectionProfitGate(c.Request.Context(), selection)
|
||||
latest, vetoed, reason := h.gatewayService.GatewayProfitControlVetoLatest(admissionCtx, account)
|
||||
if vetoed {
|
||||
if accountReleaseFunc != nil {
|
||||
accountReleaseFunc()
|
||||
}
|
||||
reqLog.Debug("gemini.account_slot_profit_vetoed", zap.Int64("account_id", account.ID), zap.String("reason", reason))
|
||||
if fs.RecordProfitVeto(account.ID) == FailoverExhausted {
|
||||
reqLog.Warn("gemini.profit_veto_attempts_exhausted", zap.Int("profit_veto_count", fs.ProfitVetoCount()))
|
||||
markOpsRoutingCapacityLimited(c)
|
||||
googleError(c, http.StatusServiceUnavailable, profitVetoExhaustedMessage)
|
||||
return
|
||||
}
|
||||
continue
|
||||
}
|
||||
account = latest
|
||||
selection.Account = latest
|
||||
// 等待路径保持既有 eager 绑定(无门时 helper 直接绑定);调度器已抢槽
|
||||
// 的直达路径无门时由选号内部绑定,这里只在门下补准入后绑定。
|
||||
if selection.ProfitGateActive() || !selection.Acquired {
|
||||
if err := h.gatewayService.BindStickySessionAfterProfitAdmission(admissionCtx, apiKey.GroupID, sessionKey, account.ID); err != nil {
|
||||
reqLog.Warn("gemini.bind_sticky_session_after_profit_admission_failed", zap.Int64("account_id", account.ID), zap.Error(err))
|
||||
}
|
||||
}
|
||||
// 账号槽位/等待计数需要在超时或断开时安全回收
|
||||
@@ -553,6 +577,7 @@ func (h *GatewayHandler) GeminiV1BetaModels(c *gin.Context) {
|
||||
User: apiKey.User,
|
||||
Account: account,
|
||||
Subscription: subscription,
|
||||
PricingAt: pricingAt,
|
||||
InboundEndpoint: inboundEndpoint,
|
||||
UpstreamEndpoint: upstreamEndpoint,
|
||||
UserAgent: userAgent,
|
||||
|
||||
@@ -177,7 +177,11 @@ func (h *OpenAIGatewayHandler) handleGrokMedia(c *gin.Context, endpoint service.
|
||||
return
|
||||
}
|
||||
}
|
||||
requestCtx := c.Request.Context()
|
||||
// Grok 媒体(图片/视频生成与视频查询)按媒体倍率计费,不在 token 利润门
|
||||
// 范围内:显式豁免,防止 service 层防御性装门按文本 D 误过滤媒体请求,
|
||||
// 也防止已计费的在途视频任务因绑定账号被门排除而查询返回伪 404。
|
||||
requestCtx := service.WithOpenAIProfitControlSuppressed(c.Request.Context())
|
||||
profitVetoCount := 0
|
||||
failedAccountIDs := make(map[int64]struct{})
|
||||
sameAccountRetryCount := make(map[int64]int)
|
||||
var lastFailoverErr *service.UpstreamFailoverError
|
||||
@@ -293,8 +297,17 @@ func (h *OpenAIGatewayHandler) handleGrokMedia(c *gin.Context, endpoint service.
|
||||
sessionHash = ensureOpenAIPoolModeSessionHash(sessionHash, account)
|
||||
setOpsSelectedAccount(c, account.ID, account.Platform)
|
||||
|
||||
accountReleaseFunc, accountAcquired := h.acquireResponsesAccountSlot(c, apiKey.GroupID, sessionHash, selection, false, &streamStarted, reqLog)
|
||||
if !accountAcquired {
|
||||
accountReleaseFunc, slotResult := h.acquireResponsesAccountSlot(c, apiKey.GroupID, sessionHash, selection, false, &streamStarted, reqLog)
|
||||
if slotResult == openAISlotAcquireProfitVetoed {
|
||||
// 媒体路径已显式豁免利润门(suppress 标记),此分支仅防御性兜底,
|
||||
// 同样受否决上限约束。
|
||||
if !recordOpenAIProfitVeto(failedAccountIDs, account.ID, &profitVetoCount) {
|
||||
h.handleOpenAIProfitVetoExhausted(c, streamStarted, reqLog, profitVetoCount)
|
||||
return
|
||||
}
|
||||
continue
|
||||
}
|
||||
if slotResult != openAISlotAcquireOK {
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
@@ -107,12 +107,18 @@ func (h *OpenAIGatewayHandler) AlphaSearch(c *gin.Context) {
|
||||
|
||||
searchID := strings.TrimSpace(gjson.GetBytes(body, "id").String())
|
||||
sessionHash := h.gatewayService.GenerateSessionHashWithFallback(c, nil, searchID)
|
||||
profitVetoCount := 0
|
||||
failedAccountIDs := make(map[int64]struct{})
|
||||
var lastFailoverErr *service.UpstreamFailoverError
|
||||
switchCount := 0
|
||||
var oauth429FailoverState service.OpenAIOAuth429FailoverState
|
||||
routingStart := time.Now()
|
||||
|
||||
// 分组利润控制:alpha search 文本入口请求级装门并固定 pricingAt
|
||||
//(记录路径经 service.OpenAIPricingAtFromContext 从请求 ctx 回读)。
|
||||
asPricingCtx, _ := h.gatewayService.WithOpenAIRequestPricingContext(c.Request.Context(), apiKey.GroupID)
|
||||
c.Request = c.Request.WithContext(asPricingCtx)
|
||||
|
||||
for {
|
||||
selection, _, err := h.gatewayService.SelectAccountWithSchedulerForCapability(
|
||||
c.Request.Context(),
|
||||
@@ -151,8 +157,16 @@ func (h *OpenAIGatewayHandler) AlphaSearch(c *gin.Context) {
|
||||
|
||||
account := selection.Account
|
||||
setOpsSelectedAccount(c, account.ID, account.Platform)
|
||||
accountRelease, acquired := h.acquireResponsesAccountSlot(c, apiKey.GroupID, sessionHash, selection, false, &streamStarted, reqLog)
|
||||
if !acquired {
|
||||
accountRelease, slotResult := h.acquireResponsesAccountSlot(c, apiKey.GroupID, sessionHash, selection, false, &streamStarted, reqLog)
|
||||
if slotResult == openAISlotAcquireProfitVetoed {
|
||||
// 利润终检否决:排除该账号重新选号;否决次数达上限则按无可用账号终止。
|
||||
if !recordOpenAIProfitVeto(failedAccountIDs, account.ID, &profitVetoCount) {
|
||||
h.handleOpenAIProfitVetoExhausted(c, streamStarted, reqLog, profitVetoCount)
|
||||
return
|
||||
}
|
||||
continue
|
||||
}
|
||||
if slotResult != openAISlotAcquireOK {
|
||||
return
|
||||
}
|
||||
service.SetOpsLatencyMs(c, service.OpsRoutingLatencyMsKey, time.Since(routingStart).Milliseconds())
|
||||
@@ -255,6 +269,7 @@ func (h *OpenAIGatewayHandler) recordAlphaSearchUsage(
|
||||
QuotaPlatform: quotaPlatform,
|
||||
SessionID: sessionID,
|
||||
ChannelUsageFields: channelMapping.ToUsageFields(requestedModel, result.UpstreamModel),
|
||||
PricingAt: service.OpenAIPricingAtFromContext(c.Request.Context()),
|
||||
}); err != nil {
|
||||
logger.L().With(
|
||||
zap.String("component", "handler.openai_gateway.alpha_search"),
|
||||
|
||||
@@ -80,10 +80,8 @@ func (h *OpenAIGatewayHandler) ChatCompletions(c *gin.Context) {
|
||||
h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", "Model is not supported by this OpenAI-compatible endpoint for composite groups")
|
||||
return
|
||||
}
|
||||
if apiKey.Group != nil && apiKey.Group.Platform == service.PlatformOpenAI {
|
||||
if cappedBody, changed := service.ApplyOpenAIReasoningEffortPolicy(body, apiKey.Group.MaxReasoningEffort, apiKey.Group.ReasoningEffortMappings); changed {
|
||||
body = cappedBody
|
||||
}
|
||||
if cappedBody, changed := applyOpenAIReasoningEffortPolicyForRequest(c, apiKey, body); changed {
|
||||
body = cappedBody
|
||||
}
|
||||
reqStream, ok := parseOpenAICompatibleStream(body)
|
||||
if !ok {
|
||||
@@ -144,11 +142,16 @@ func (h *OpenAIGatewayHandler) ChatCompletions(c *gin.Context) {
|
||||
|
||||
maxAccountSwitches := h.maxAccountSwitches
|
||||
switchCount := 0
|
||||
profitVetoCount := 0
|
||||
failedAccountIDs := make(map[int64]struct{})
|
||||
sameAccountRetryCount := make(map[int64]int)
|
||||
var lastFailoverErr *service.UpstreamFailoverError
|
||||
var oauth429FailoverState service.OpenAIOAuth429FailoverState
|
||||
|
||||
// 分组利润控制:chat completions 文本入口请求级装门并固定 pricingAt。
|
||||
ccPricingCtx, pricingAt := h.gatewayService.WithOpenAIRequestPricingContext(c.Request.Context(), apiKey.GroupID)
|
||||
c.Request = c.Request.WithContext(ccPricingCtx)
|
||||
|
||||
for {
|
||||
if failoverClientGone(c) {
|
||||
return
|
||||
@@ -207,8 +210,16 @@ func (h *OpenAIGatewayHandler) ChatCompletions(c *gin.Context) {
|
||||
_ = scheduleDecision
|
||||
setOpsSelectedAccount(c, account.ID, account.Platform)
|
||||
|
||||
accountReleaseFunc, acquired := h.acquireResponsesAccountSlot(c, apiKey.GroupID, sessionHash, selection, reqStream, &streamStarted, reqLog)
|
||||
if !acquired {
|
||||
accountReleaseFunc, slotResult := h.acquireResponsesAccountSlot(c, apiKey.GroupID, sessionHash, selection, reqStream, &streamStarted, reqLog)
|
||||
if slotResult == openAISlotAcquireProfitVetoed {
|
||||
// 利润终检否决:排除该账号重新选号;否决次数达上限则按无可用账号终止。
|
||||
if !recordOpenAIProfitVeto(failedAccountIDs, account.ID, &profitVetoCount) {
|
||||
h.handleOpenAIProfitVetoExhausted(c, streamStarted, reqLog, profitVetoCount)
|
||||
return
|
||||
}
|
||||
continue
|
||||
}
|
||||
if slotResult != openAISlotAcquireOK {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -358,6 +369,7 @@ func (h *OpenAIGatewayHandler) ChatCompletions(c *gin.Context) {
|
||||
QuotaPlatform: quotaPlatform,
|
||||
SessionID: sessionID,
|
||||
ChannelUsageFields: clientRequestedUsageFields(c, channelMapping, reqModel, result.UpstreamModel),
|
||||
PricingAt: pricingAt,
|
||||
CyberBlocked: cyberBlocked,
|
||||
}); err != nil {
|
||||
logger.L().With(
|
||||
|
||||
@@ -107,6 +107,7 @@ func (h *OpenAIGatewayHandler) Embeddings(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
profitVetoCount := 0
|
||||
failedAccountIDs := make(map[int64]struct{})
|
||||
var lastFailoverErr *service.UpstreamFailoverError
|
||||
switchCount := 0
|
||||
@@ -116,6 +117,10 @@ func (h *OpenAIGatewayHandler) Embeddings(c *gin.Context) {
|
||||
}
|
||||
routingStart := time.Now()
|
||||
|
||||
// 分组利润控制:embeddings 文本入口请求级装门并固定 pricingAt。
|
||||
embPricingCtx, pricingAt := h.gatewayService.WithOpenAIRequestPricingContext(c.Request.Context(), apiKey.GroupID)
|
||||
c.Request = c.Request.WithContext(embPricingCtx)
|
||||
|
||||
for {
|
||||
selection, _, err := h.gatewayService.SelectAccountWithSchedulerForCapability(
|
||||
c.Request.Context(),
|
||||
@@ -165,8 +170,16 @@ func (h *OpenAIGatewayHandler) Embeddings(c *gin.Context) {
|
||||
account := selection.Account
|
||||
setOpsSelectedAccount(c, account.ID, account.Platform)
|
||||
|
||||
accountReleaseFunc, accountAcquired := h.acquireResponsesAccountSlot(c, apiKey.GroupID, "", selection, false, &streamStarted, reqLog)
|
||||
if !accountAcquired {
|
||||
accountReleaseFunc, slotResult := h.acquireResponsesAccountSlot(c, apiKey.GroupID, "", selection, false, &streamStarted, reqLog)
|
||||
if slotResult == openAISlotAcquireProfitVetoed {
|
||||
// 利润终检否决:排除该账号重新选号;否决次数达上限则按无可用账号终止。
|
||||
if !recordOpenAIProfitVeto(failedAccountIDs, account.ID, &profitVetoCount) {
|
||||
h.handleOpenAIProfitVetoExhausted(c, streamStarted, reqLog, profitVetoCount)
|
||||
return
|
||||
}
|
||||
continue
|
||||
}
|
||||
if slotResult != openAISlotAcquireOK {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -260,6 +273,7 @@ func (h *OpenAIGatewayHandler) Embeddings(c *gin.Context) {
|
||||
QuotaPlatform: quotaPlatform,
|
||||
SessionID: sessionID,
|
||||
ChannelUsageFields: clientRequestedUsageFields(c, channelMapping, reqModel, result.UpstreamModel),
|
||||
PricingAt: pricingAt,
|
||||
}); err != nil {
|
||||
logger.L().With(
|
||||
zap.String("component", "handler.openai_gateway.embeddings"),
|
||||
|
||||
@@ -143,6 +143,9 @@ func (h *OpenAIGatewayHandler) CountTokens(c *gin.Context) {
|
||||
}
|
||||
|
||||
requestStart := time.Now()
|
||||
// count_tokens 不计费:显式豁免利润门,避免高倍率账号池被门排除后连
|
||||
// token 计数都返回 no available accounts。
|
||||
c.Request = c.Request.WithContext(service.WithOpenAIProfitControlSuppressed(c.Request.Context()))
|
||||
sessionHash := h.gatewayService.GenerateSessionHash(c, body)
|
||||
currentRoutingModel := routingModel
|
||||
if preferredMappedModel != "" {
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"runtime/debug"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
@@ -312,10 +313,8 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) {
|
||||
h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", "Model is not supported by this OpenAI-compatible endpoint for composite groups")
|
||||
return
|
||||
}
|
||||
if apiKey.Group != nil && apiKey.Group.Platform == service.PlatformOpenAI {
|
||||
if cappedBody, changed := service.ApplyOpenAIReasoningEffortPolicy(body, apiKey.Group.MaxReasoningEffort, apiKey.Group.ReasoningEffortMappings); changed {
|
||||
body = cappedBody
|
||||
}
|
||||
if cappedBody, changed := applyOpenAIReasoningEffortPolicyForRequest(c, apiKey, body); changed {
|
||||
body = cappedBody
|
||||
}
|
||||
|
||||
reqStream, ok := parseOpenAICompatibleStream(body)
|
||||
@@ -426,6 +425,7 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) {
|
||||
maxAccountSwitches := h.maxAccountSwitches
|
||||
switchCount := 0
|
||||
firstOutputTimeoutSwitchCount := 0
|
||||
profitVetoCount := 0
|
||||
failedAccountIDs := make(map[int64]struct{})
|
||||
sameAccountRetryCount := make(map[int64]int)
|
||||
var lastFailoverErr *service.UpstreamFailoverError
|
||||
@@ -439,6 +439,13 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) {
|
||||
// 该判断已排除 Codex 被动 image_gen namespace,避免 CC-only 账号被误过滤(#4476)。
|
||||
requiredCapability := openAIResponsesRequiredCapability(imageIntent, requestPlatform)
|
||||
|
||||
// 分组利润控制:请求级装配定价上下文——pricingAt 固定本请求的
|
||||
// D 与计费高峰因子,选号、槽位终检与全部 failover 重入共用同一门与阈值。
|
||||
// 生图意图只影响能力路由与图片计费,不关门:混合 /v1/responses 请求的
|
||||
// token 计费部分仍受利润门保护,独立图片/视频端点才在门外。
|
||||
pricingCtx, pricingAt := h.gatewayService.WithOpenAIRequestPricingContext(c.Request.Context(), apiKey.GroupID)
|
||||
c.Request = c.Request.WithContext(pricingCtx)
|
||||
|
||||
for {
|
||||
// Streaming Forward intentionally detaches the upstream request so usage can
|
||||
// be drained after a disconnect. Re-check the client context before every
|
||||
@@ -516,8 +523,17 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) {
|
||||
reqLog.Debug("openai.account_selected", zap.Int64("account_id", account.ID), zap.String("account_name", account.Name))
|
||||
setOpsSelectedAccount(c, account.ID, account.Platform)
|
||||
|
||||
accountReleaseFunc, acquired := h.acquireResponsesAccountSlot(c, apiKey.GroupID, sessionHash, selection, reqStream, &streamStarted, reqLog)
|
||||
if !acquired {
|
||||
accountReleaseFunc, slotResult := h.acquireResponsesAccountSlot(c, apiKey.GroupID, sessionHash, selection, reqStream, &streamStarted, reqLog)
|
||||
if slotResult == openAISlotAcquireProfitVetoed {
|
||||
// 利润终检否决:排除该账号重新选号,全池耗尽由下一轮选号报错;
|
||||
// 否决次数达上限则直接终止,避免排队抢槽后才终检的延迟放大。
|
||||
if !recordOpenAIProfitVeto(failedAccountIDs, account.ID, &profitVetoCount) {
|
||||
h.handleOpenAIProfitVetoExhausted(c, streamStarted, reqLog, profitVetoCount)
|
||||
return
|
||||
}
|
||||
continue
|
||||
}
|
||||
if slotResult != openAISlotAcquireOK {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -696,6 +712,7 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) {
|
||||
QuotaPlatform: quotaPlatform,
|
||||
SessionID: sessionID,
|
||||
ChannelUsageFields: clientRequestedUsageFields(c, channelMapping, reqModel, result.UpstreamModel),
|
||||
PricingAt: pricingAt,
|
||||
CyberBlocked: cyberBlocked,
|
||||
}); err != nil {
|
||||
logger.L().With(
|
||||
@@ -932,6 +949,7 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) {
|
||||
h.anthropicErrorResponse(c, http.StatusBadRequest, "invalid_request_error", "Model is not supported by this OpenAI-compatible endpoint for composite groups")
|
||||
return
|
||||
}
|
||||
bindOpenAIReasoningEffortPolicyForMessagesRequest(c, apiKey, body)
|
||||
routingModel := service.NormalizeOpenAICompatRequestedModel(reqModel)
|
||||
preferredMappedModel := resolveOpenAIMessagesDispatchMappedModel(apiKey, reqModel)
|
||||
reqStream := gjson.GetBytes(body, "stream").Bool()
|
||||
@@ -988,12 +1006,17 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) {
|
||||
|
||||
maxAccountSwitches := h.maxAccountSwitches
|
||||
switchCount := 0
|
||||
profitVetoCount := 0
|
||||
failedAccountIDs := make(map[int64]struct{})
|
||||
sameAccountRetryCount := make(map[int64]int)
|
||||
var lastFailoverErr *service.UpstreamFailoverError
|
||||
var oauth429FailoverState service.OpenAIOAuth429FailoverState
|
||||
effectiveMappedModel := preferredMappedModel
|
||||
|
||||
// 分组利润控制:Messages 文本入口同样请求级装门并固定 pricingAt。
|
||||
msgPricingCtx, pricingAt := h.gatewayService.WithOpenAIRequestPricingContext(c.Request.Context(), apiKey.GroupID)
|
||||
c.Request = c.Request.WithContext(msgPricingCtx)
|
||||
|
||||
for {
|
||||
if failoverClientGone(c) {
|
||||
return
|
||||
@@ -1058,8 +1081,17 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) {
|
||||
_ = scheduleDecision
|
||||
setOpsSelectedAccount(c, account.ID, account.Platform)
|
||||
|
||||
accountReleaseFunc, acquired := h.acquireResponsesAccountSlot(c, apiKey.GroupID, sessionHash, selection, reqStream, &streamStarted, reqLog)
|
||||
if !acquired {
|
||||
accountReleaseFunc, slotResult := h.acquireResponsesAccountSlot(c, apiKey.GroupID, sessionHash, selection, reqStream, &streamStarted, reqLog)
|
||||
if slotResult == openAISlotAcquireProfitVetoed {
|
||||
// 利润终检否决:排除该账号重新选号,全池耗尽由下一轮选号报错;
|
||||
// 否决次数达上限则直接终止,避免排队抢槽后才终检的延迟放大。
|
||||
if !recordOpenAIProfitVeto(failedAccountIDs, account.ID, &profitVetoCount) {
|
||||
h.handleOpenAIProfitVetoExhausted(c, streamStarted, reqLog, profitVetoCount)
|
||||
return
|
||||
}
|
||||
continue
|
||||
}
|
||||
if slotResult != openAISlotAcquireOK {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -1208,6 +1240,7 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) {
|
||||
QuotaPlatform: quotaPlatform,
|
||||
SessionID: sessionID,
|
||||
ChannelUsageFields: clientRequestedUsageFields(c, channelMappingMsg, reqModel, result.UpstreamModel),
|
||||
PricingAt: pricingAt,
|
||||
CyberBlocked: cyberBlocked,
|
||||
}); err != nil {
|
||||
logger.L().With(
|
||||
@@ -1348,6 +1381,74 @@ func (h *OpenAIGatewayHandler) acquireResponsesUserSlot(
|
||||
return wrapReleaseOnDone(ctx, userReleaseFunc), true
|
||||
}
|
||||
|
||||
// openAISlotAcquireResult 是账号槽位获取的三态结果。
|
||||
type openAISlotAcquireResult int
|
||||
|
||||
const (
|
||||
openAISlotAcquireOK openAISlotAcquireResult = iota
|
||||
// openAISlotAcquireFailed:错误响应已写出,调用方直接 return。
|
||||
openAISlotAcquireFailed
|
||||
// openAISlotAcquireProfitVetoed:槽位获取成功后利润终检否决。槽位已释放、
|
||||
// 未写任何响应;调用方应经 recordOpenAIProfitVeto 把该账号加入本请求排除集
|
||||
// 后重新选号,全池耗尽由下一轮选号返回标准 no available accounts。
|
||||
openAISlotAcquireProfitVetoed
|
||||
)
|
||||
|
||||
// openAIWSTurnPricing 持有 WebSocket 连接内「当前 turn」的计费定价时刻。
|
||||
// 由 BeforeTurn 在每个 turn 开始时冻结,AfterTurn 的用量提交读取它;turn 在
|
||||
// 连接内串行推进,互斥锁只为跨用量提交 goroutine 的读取安全。
|
||||
//
|
||||
// 零值语义(重要):ws_v2 passthrough ingress 只实现了 AfterTurn,没有任何
|
||||
// turn 起始回调,BeforeTurn 永远不会被调用。此时本值保持零,RecordUsage 经
|
||||
// openAIUsagePricingAt 回退到记录时刻——与引入分组利润控制前的基线一致。
|
||||
// 绝不能用建连时刻初始化:那会把透传连接的所有 turn 钉死在建连时的高峰因子,
|
||||
// 客户端只要峰前一分钟建连并保活,整条连接就能全程按谷价结算,正是利润控制
|
||||
// 想堵的漏洞。透传 ingress 目前不做 turn 级利润复核,只有建连时的准入门。
|
||||
type openAIWSTurnPricing struct {
|
||||
mu sync.Mutex
|
||||
at time.Time
|
||||
}
|
||||
|
||||
func (p *openAIWSTurnPricing) freeze(at time.Time) {
|
||||
p.mu.Lock()
|
||||
p.at = at
|
||||
p.mu.Unlock()
|
||||
}
|
||||
|
||||
func (p *openAIWSTurnPricing) current() time.Time {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
return p.at
|
||||
}
|
||||
|
||||
// recordOpenAIProfitVeto 记录 OpenAI 侧选号循环的一次利润门终检否决:把账号
|
||||
// 加入本请求排除集并递增否决计数。返回 false 表示否决次数已达
|
||||
// maxProfitVetoAttempts,调用方必须停止重选并按「无可用账号」终止。
|
||||
//
|
||||
// OpenAI 路径用的是各自的 failedAccountIDs map + for 循环(不是 FailoverState),
|
||||
// 这里用一个独立计数器复用同一上限语义。上限是必需的:WaitPlan 分支先阻塞
|
||||
// 排队(sticky 45s / fallback 30s)拿到槽位才终检,无上限重选会把单次请求的
|
||||
// 延迟放大到 N × WaitPlan.Timeout。
|
||||
func recordOpenAIProfitVeto(failedAccountIDs map[int64]struct{}, accountID int64, vetoCount *int) bool {
|
||||
failedAccountIDs[accountID] = struct{}{}
|
||||
*vetoCount++
|
||||
return *vetoCount < maxProfitVetoAttempts
|
||||
}
|
||||
|
||||
// handleOpenAIProfitVetoExhausted 在利润否决预算耗尽时写出错误响应。
|
||||
// 与 acquireResponsesAccountSlot 内部的 no-available-accounts 失败分支同形,
|
||||
// 保证同一调用方在两条路径上拿到一致的响应格式。
|
||||
func (h *OpenAIGatewayHandler) handleOpenAIProfitVetoExhausted(
|
||||
c *gin.Context,
|
||||
streamStarted bool,
|
||||
reqLog *zap.Logger,
|
||||
vetoCount int,
|
||||
) {
|
||||
reqLog.Warn("openai.profit_veto_attempts_exhausted", zap.Int("profit_veto_count", vetoCount))
|
||||
markOpsRoutingCapacityLimited(c)
|
||||
h.handleStreamingAwareError(c, http.StatusServiceUnavailable, "api_error", profitVetoExhaustedMessage, streamStarted)
|
||||
}
|
||||
|
||||
func (h *OpenAIGatewayHandler) acquireResponsesAccountSlot(
|
||||
c *gin.Context,
|
||||
groupID *int64,
|
||||
@@ -1356,22 +1457,41 @@ func (h *OpenAIGatewayHandler) acquireResponsesAccountSlot(
|
||||
reqStream bool,
|
||||
streamStarted *bool,
|
||||
reqLog *zap.Logger,
|
||||
) (func(), bool) {
|
||||
) (func(), openAISlotAcquireResult) {
|
||||
if selection == nil || selection.Account == nil {
|
||||
markOpsRoutingCapacityLimited(c)
|
||||
h.handleStreamingAwareError(c, http.StatusServiceUnavailable, "api_error", "No available accounts", *streamStarted)
|
||||
return nil, false
|
||||
return nil, openAISlotAcquireFailed
|
||||
}
|
||||
|
||||
ctx := c.Request.Context()
|
||||
// 终检与准入后绑定使用选号结果携带的门:composite 等跨分组调度解析出的
|
||||
// 门只存在于调度栈的局部 ctx,必须经选号结果重放到本函数的 ctx 上。
|
||||
ctx := service.ContextWithSelectionProfitGate(c.Request.Context(), selection)
|
||||
account := selection.Account
|
||||
if selection.Acquired {
|
||||
return wrapReleaseOnDone(ctx, selection.ReleaseFunc), true
|
||||
latest, vetoed, reason := h.gatewayService.ProfitControlVetoLatest(ctx, account)
|
||||
if vetoed {
|
||||
if selection.ReleaseFunc != nil {
|
||||
selection.ReleaseFunc()
|
||||
}
|
||||
reqLog.Debug("openai.account_slot_profit_vetoed", zap.Int64("account_id", account.ID), zap.String("reason", reason))
|
||||
return nil, openAISlotAcquireProfitVetoed
|
||||
}
|
||||
account = latest
|
||||
selection.Account = latest
|
||||
// 调度器已抢槽路径无门时由选号内部完成 eager 绑定;门下选号内部
|
||||
// 推迟绑定,这里在终检通过后补准入后绑定。
|
||||
if selection.ProfitGateActive() {
|
||||
if err := h.gatewayService.BindStickySessionAfterProfitAdmission(ctx, groupID, sessionHash, account.ID); err != nil {
|
||||
reqLog.Warn("openai.bind_sticky_session_after_profit_admission_failed", zap.Int64("account_id", account.ID), zap.Error(err))
|
||||
}
|
||||
}
|
||||
return wrapReleaseOnDone(ctx, selection.ReleaseFunc), openAISlotAcquireOK
|
||||
}
|
||||
if selection.WaitPlan == nil {
|
||||
markOpsRoutingCapacityLimited(c)
|
||||
h.handleStreamingAwareError(c, http.StatusServiceUnavailable, "api_error", "No available accounts", *streamStarted)
|
||||
return nil, false
|
||||
return nil, openAISlotAcquireFailed
|
||||
}
|
||||
|
||||
fastReleaseFunc, fastAcquired, err := h.concurrencyHelper.TryAcquireAccountSlot(
|
||||
@@ -1382,13 +1502,25 @@ func (h *OpenAIGatewayHandler) acquireResponsesAccountSlot(
|
||||
if err != nil {
|
||||
reqLog.Warn("openai.account_slot_quick_acquire_failed", zap.Int64("account_id", account.ID), zap.Error(err))
|
||||
h.handleConcurrencyError(c, err, "account", *streamStarted)
|
||||
return nil, false
|
||||
return nil, openAISlotAcquireFailed
|
||||
}
|
||||
if fastAcquired {
|
||||
if err := h.gatewayService.BindStickySession(ctx, groupID, sessionHash, account.ID); err != nil {
|
||||
reqLog.Warn("openai.bind_sticky_session_failed", zap.Int64("account_id", account.ID), zap.Error(err))
|
||||
// 分组利润控制:快速抢槽成功后终检。选号与抢槽之间账号
|
||||
// 倍率可能刷新,越线则释放槽位交由调用方排除重选,不绑定粘连。
|
||||
latest, vetoed, reason := h.gatewayService.ProfitControlVetoLatest(ctx, account)
|
||||
if vetoed {
|
||||
if fastReleaseFunc != nil {
|
||||
fastReleaseFunc()
|
||||
}
|
||||
reqLog.Debug("openai.account_slot_profit_vetoed", zap.Int64("account_id", account.ID), zap.String("reason", reason))
|
||||
return nil, openAISlotAcquireProfitVetoed
|
||||
}
|
||||
return wrapReleaseOnDone(ctx, fastReleaseFunc), true
|
||||
account = latest
|
||||
selection.Account = latest
|
||||
if err := h.gatewayService.BindStickySessionAfterProfitAdmission(ctx, groupID, sessionHash, account.ID); err != nil {
|
||||
reqLog.Warn("openai.bind_sticky_session_after_profit_admission_failed", zap.Int64("account_id", account.ID), zap.Error(err))
|
||||
}
|
||||
return wrapReleaseOnDone(ctx, fastReleaseFunc), openAISlotAcquireOK
|
||||
}
|
||||
|
||||
canWait, waitErr := h.concurrencyHelper.IncrementAccountWaitCount(ctx, account.ID, selection.WaitPlan.MaxWaiting)
|
||||
@@ -1400,7 +1532,7 @@ func (h *OpenAIGatewayHandler) acquireResponsesAccountSlot(
|
||||
zap.Int("max_waiting", selection.WaitPlan.MaxWaiting),
|
||||
)
|
||||
h.handleStreamingAwareError(c, http.StatusTooManyRequests, "rate_limit_error", "Too many pending requests, please retry later", *streamStarted)
|
||||
return nil, false
|
||||
return nil, openAISlotAcquireFailed
|
||||
}
|
||||
|
||||
accountWaitCounted := waitErr == nil && canWait
|
||||
@@ -1423,15 +1555,27 @@ func (h *OpenAIGatewayHandler) acquireResponsesAccountSlot(
|
||||
if err != nil {
|
||||
reqLog.Warn("openai.account_slot_acquire_failed", zap.Int64("account_id", account.ID), zap.Error(err))
|
||||
h.handleConcurrencyError(c, err, "account", *streamStarted)
|
||||
return nil, false
|
||||
return nil, openAISlotAcquireFailed
|
||||
}
|
||||
|
||||
// Slot acquired: no longer waiting in queue.
|
||||
releaseWait()
|
||||
if err := h.gatewayService.BindStickySession(ctx, groupID, sessionHash, account.ID); err != nil {
|
||||
reqLog.Warn("openai.bind_sticky_session_failed", zap.Int64("account_id", account.ID), zap.Error(err))
|
||||
// 分组利润控制:WaitPlan 排队成功后终检。排队期间账号倍率
|
||||
// 可能上调,越线则释放槽位交由调用方排除重选,不绑定粘连。
|
||||
latest, vetoed, reason := h.gatewayService.ProfitControlVetoLatest(ctx, account)
|
||||
if vetoed {
|
||||
if accountReleaseFunc != nil {
|
||||
accountReleaseFunc()
|
||||
}
|
||||
reqLog.Debug("openai.account_slot_profit_vetoed", zap.Int64("account_id", account.ID), zap.String("reason", reason))
|
||||
return nil, openAISlotAcquireProfitVetoed
|
||||
}
|
||||
return wrapReleaseOnDone(ctx, accountReleaseFunc), true
|
||||
account = latest
|
||||
selection.Account = latest
|
||||
if err := h.gatewayService.BindStickySessionAfterProfitAdmission(ctx, groupID, sessionHash, account.ID); err != nil {
|
||||
reqLog.Warn("openai.bind_sticky_session_after_profit_admission_failed", zap.Int64("account_id", account.ID), zap.Error(err))
|
||||
}
|
||||
return wrapReleaseOnDone(ctx, accountReleaseFunc), openAISlotAcquireOK
|
||||
}
|
||||
|
||||
// ResponsesWebSocket handles OpenAI Responses API WebSocket ingress endpoint
|
||||
@@ -1667,6 +1811,7 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) {
|
||||
)
|
||||
maxAccountSwitches := h.maxAccountSwitches
|
||||
switchCount := 0
|
||||
profitVetoCount := 0
|
||||
failedAccountIDs := make(map[int64]struct{})
|
||||
var lastFailoverErr *service.UpstreamFailoverError
|
||||
var oauth429FailoverState service.OpenAIOAuth429FailoverState
|
||||
@@ -1717,6 +1862,14 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) {
|
||||
requiredCapability = service.OpenAIEndpointCapabilityResponses
|
||||
}
|
||||
|
||||
// 分组利润控制:WS 桥按连接装配定价上下文并装门(选号与抢槽共用该
|
||||
// ctx)。连接内不重选号,但每个 turn 开始经 BeforeTurn 重新冻结 pricingAt
|
||||
// 并按最新门复核当前账号(准入与计费同源),峰前建连保活不能让后续 turn
|
||||
// 继续按建连时刻的谷价计费。生图意图只影响能力路由与图片计费,不关门。
|
||||
// 建连时刻只用于选号/准入,不作为任何 turn 的计费定价时刻。
|
||||
wsPricingCtx, _ := h.gatewayService.WithOpenAIRequestPricingContext(ctx, apiKey.GroupID)
|
||||
ctx = wsPricingCtx
|
||||
|
||||
for {
|
||||
if ctx.Err() != nil {
|
||||
return
|
||||
@@ -1762,7 +1915,28 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) {
|
||||
if selection.WaitPlan != nil && selection.WaitPlan.MaxConcurrency > 0 {
|
||||
accountMaxConcurrency = selection.WaitPlan.MaxConcurrency
|
||||
}
|
||||
// 终检、准入后绑定与后续 turn 级复核都使用选号结果携带的门(composite
|
||||
// 等跨分组调度的门只存在于调度栈局部 ctx);准入成功后并入连接 ctx。
|
||||
admissionCtx := service.ContextWithSelectionProfitGate(ctx, selection)
|
||||
accountReleaseFunc := selection.ReleaseFunc
|
||||
if selection.Acquired {
|
||||
// 调度器已抢槽路径同样终检:选号与抢槽之间账号倍率可能刷新。
|
||||
latest, vetoed, reason := h.gatewayService.ProfitControlVetoLatest(admissionCtx, account)
|
||||
if vetoed {
|
||||
if accountReleaseFunc != nil {
|
||||
accountReleaseFunc()
|
||||
}
|
||||
reqLog.Debug("openai.websocket_account_slot_profit_vetoed", zap.Int64("account_id", account.ID), zap.String("reason", reason))
|
||||
if !recordOpenAIProfitVeto(failedAccountIDs, account.ID, &profitVetoCount) {
|
||||
reqLog.Warn("openai.websocket_profit_veto_attempts_exhausted", zap.Int("profit_veto_count", profitVetoCount))
|
||||
closeOpenAIClientWS(wsConn, coderws.StatusTryAgainLater, "no available account")
|
||||
return
|
||||
}
|
||||
continue
|
||||
}
|
||||
account = latest
|
||||
selection.Account = latest
|
||||
}
|
||||
if !selection.Acquired {
|
||||
if selection.WaitPlan == nil {
|
||||
closeOpenAIClientWS(wsConn, coderws.StatusTryAgainLater, "account is busy, please retry later")
|
||||
@@ -1782,11 +1956,30 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) {
|
||||
closeOpenAIClientWS(wsConn, coderws.StatusTryAgainLater, "account is busy, please retry later")
|
||||
return
|
||||
}
|
||||
// 分组利润控制:WS 快速抢槽成功后终检,越线则释放
|
||||
// 槽位、排除该账号重新选号,全池耗尽由下一轮选号关闭连接。
|
||||
latest, vetoed, reason := h.gatewayService.ProfitControlVetoLatest(admissionCtx, account)
|
||||
if vetoed {
|
||||
if fastReleaseFunc != nil {
|
||||
fastReleaseFunc()
|
||||
}
|
||||
reqLog.Debug("openai.websocket_account_slot_profit_vetoed", zap.Int64("account_id", account.ID), zap.String("reason", reason))
|
||||
if !recordOpenAIProfitVeto(failedAccountIDs, account.ID, &profitVetoCount) {
|
||||
reqLog.Warn("openai.websocket_profit_veto_attempts_exhausted", zap.Int("profit_veto_count", profitVetoCount))
|
||||
closeOpenAIClientWS(wsConn, coderws.StatusTryAgainLater, "no available account")
|
||||
return
|
||||
}
|
||||
continue
|
||||
}
|
||||
account = latest
|
||||
selection.Account = latest
|
||||
accountReleaseFunc = fastReleaseFunc
|
||||
}
|
||||
// 准入完成:门并入连接 ctx,turn 级复核与 failover 重选共用。
|
||||
ctx = admissionCtx
|
||||
currentAccountRelease = wrapReleaseOnDone(ctx, accountReleaseFunc)
|
||||
if err := h.gatewayService.BindStickySession(ctx, apiKey.GroupID, sessionHash, account.ID); err != nil {
|
||||
reqLog.Warn("openai.websocket_bind_sticky_session_failed", zap.Int64("account_id", account.ID), zap.Error(err))
|
||||
if err := h.gatewayService.BindStickySessionAfterProfitAdmission(ctx, apiKey.GroupID, sessionHash, account.ID); err != nil {
|
||||
reqLog.Warn("openai.websocket_bind_sticky_session_after_profit_admission_failed", zap.Int64("account_id", account.ID), zap.Error(err))
|
||||
}
|
||||
|
||||
token, _, err := h.gatewayService.GetRequestCredential(ctx, c, account)
|
||||
@@ -1813,17 +2006,16 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) {
|
||||
zap.Int("candidate_count", scheduleDecision.CandidateCount),
|
||||
)
|
||||
|
||||
maxReasoningEffort := ""
|
||||
var reasoningEffortMappings []service.ReasoningEffortMapping
|
||||
if apiKey.Group != nil && apiKey.Group.Platform == service.PlatformOpenAI {
|
||||
maxReasoningEffort = apiKey.Group.MaxReasoningEffort
|
||||
reasoningEffortMappings = apiKey.Group.ReasoningEffortMappings
|
||||
}
|
||||
maxReasoningEffort, reasoningEffortMappings, _ := openAIReasoningEffortPolicyForRequest(c, apiKey)
|
||||
var requestPayloadHash string
|
||||
// Passthrough rejects overlapping response.create frames, so one immutable
|
||||
// turn-tagged slot preserves the exact mapping used for the in-flight request.
|
||||
var turnChannelMapping atomic.Pointer[openAIWSTurnChannelMappingSnapshot]
|
||||
turnChannelMapping.Store(&openAIWSTurnChannelMappingSnapshot{turn: 1, mapping: channelMappingWS})
|
||||
// turn 级定价:BeforeTurn 重新冻结 pricingAt 并按最新门复核当前账号,
|
||||
// AfterTurn 的计费读取所属 turn 的时刻。零值起步的语义见
|
||||
// openAIWSTurnPricing 的注释——绝不能用建连时刻初始化。
|
||||
var turnPricing openAIWSTurnPricing
|
||||
hooks := &service.OpenAIWSIngressHooks{
|
||||
InitialRequestModel: reqModel,
|
||||
MaxReasoningEffort: maxReasoningEffort,
|
||||
@@ -1869,6 +2061,18 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) {
|
||||
if cyberBlockedThisConn {
|
||||
return service.NewOpenAIWSClientCloseError(coderws.StatusPolicyViolation, cyberSessionBlockedClientMsg, nil)
|
||||
}
|
||||
// 长连接跨峰谷/倍率刷新防护:每个 turn 按当前时刻重装门并复核
|
||||
// 当前账号,越线即要求客户端重连重选(连接绑定单一上游账号,
|
||||
// 无法中途换号)。本 turn 的准入与计费共用同一 pricingAt。
|
||||
turnCtx, turnAt := h.gatewayService.WithOpenAITurnPricingContext(ctx, apiKey.GroupID)
|
||||
if _, vetoed, reason := h.gatewayService.ProfitControlVetoLatest(turnCtx, account); vetoed {
|
||||
reqLog.Info("openai.websocket_turn_profit_vetoed",
|
||||
zap.Int("turn", turn),
|
||||
zap.Int64("account_id", account.ID),
|
||||
zap.String("reason", reason))
|
||||
return service.NewOpenAIWSClientCloseError(coderws.StatusTryAgainLater, "account is no longer eligible for this connection, please reconnect", nil)
|
||||
}
|
||||
turnPricing.freeze(turnAt)
|
||||
if turn == 1 {
|
||||
return nil
|
||||
}
|
||||
@@ -1967,6 +2171,7 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) {
|
||||
upstreamEndpoint := resolveOpenAIUpstreamEndpoint(c, account, result)
|
||||
quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey)
|
||||
sessionID := service.ExtractClientSessionID(c)
|
||||
turnRecordPricingAt := turnPricing.current()
|
||||
cyberBlocked := service.GetOpsCyberPolicy(c) != nil
|
||||
h.submitOpenAIUsageRecordTask(ctx, result, func(taskCtx context.Context) {
|
||||
if err := h.gatewayService.RecordUsage(taskCtx, &service.OpenAIRecordUsageInput{
|
||||
@@ -1984,6 +2189,7 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) {
|
||||
QuotaPlatform: quotaPlatform,
|
||||
SessionID: sessionID,
|
||||
ChannelUsageFields: turnUsageFields,
|
||||
PricingAt: turnRecordPricingAt,
|
||||
CyberBlocked: cyberBlocked,
|
||||
}); err != nil {
|
||||
reqLog.Error("openai.websocket_record_usage_failed",
|
||||
|
||||
@@ -148,6 +148,7 @@ func (h *OpenAIGatewayHandler) Images(c *gin.Context) {
|
||||
|
||||
maxAccountSwitches := h.maxAccountSwitches
|
||||
switchCount := 0
|
||||
profitVetoCount := 0
|
||||
failedAccountIDs := make(map[int64]struct{})
|
||||
sameAccountRetryCount := make(map[int64]int)
|
||||
var lastFailoverErr *service.UpstreamFailoverError
|
||||
@@ -221,8 +222,16 @@ func (h *OpenAIGatewayHandler) Images(c *gin.Context) {
|
||||
reqLog.Debug("openai.images.account_selected", zap.Int64("account_id", account.ID), zap.String("account_name", account.Name))
|
||||
setOpsSelectedAccount(c, account.ID, account.Platform)
|
||||
|
||||
accountReleaseFunc, acquired := h.acquireResponsesAccountSlot(c, apiKey.GroupID, sessionHash, selection, parsed.Stream, &streamStarted, reqLog)
|
||||
if !acquired {
|
||||
accountReleaseFunc, slotResult := h.acquireResponsesAccountSlot(c, apiKey.GroupID, sessionHash, selection, parsed.Stream, &streamStarted, reqLog)
|
||||
if slotResult == openAISlotAcquireProfitVetoed {
|
||||
// Images 调度不装利润门,此分支实际不可达;防御性排除重选并受同一否决上限约束。
|
||||
if !recordOpenAIProfitVeto(failedAccountIDs, account.ID, &profitVetoCount) {
|
||||
h.handleOpenAIProfitVetoExhausted(c, streamStarted, reqLog, profitVetoCount)
|
||||
return
|
||||
}
|
||||
continue
|
||||
}
|
||||
if slotResult != openAISlotAcquireOK {
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
//go:build unit
|
||||
|
||||
package handler
|
||||
|
||||
// 槽位终检与生图跳门回归(handler 半程):
|
||||
// - 槽位获取成功后的利润终检:越线账号释放槽位并要求调用方排除重选,
|
||||
// 不写响应、不绑定粘连;
|
||||
// - openAIResponsesRequiredCapability 的生图意图映射钉死(scheduler 的
|
||||
// 跳门条件依赖 CapabilityResponses ⇔ 显式生图意图这一耦合)。
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http/httptest"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey"
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/require"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
type profitCountingConcurrencyCache struct {
|
||||
fakeConcurrencyCache
|
||||
accountReleases atomic.Int64
|
||||
}
|
||||
|
||||
func (c *profitCountingConcurrencyCache) ReleaseAccountSlot(context.Context, int64, string) error {
|
||||
c.accountReleases.Add(1)
|
||||
return nil
|
||||
}
|
||||
|
||||
func profitSlotTestAccount(id int64, rate float64) *service.Account {
|
||||
now := time.Now()
|
||||
return &service.Account{
|
||||
ID: id,
|
||||
Platform: service.PlatformOpenAI,
|
||||
Type: service.AccountTypeAPIKey,
|
||||
Status: service.StatusActive,
|
||||
Schedulable: true,
|
||||
Concurrency: 2,
|
||||
RateMultiplier: &rate,
|
||||
Extra: map[string]any{
|
||||
"upstream_billing_probe": map[string]any{
|
||||
"status": service.UpstreamBillingProbeStatusOK,
|
||||
"received_at": now.Add(-time.Minute),
|
||||
"fresh_until": now.Add(30 * time.Minute),
|
||||
"data": map[string]any{
|
||||
"billing_scope": "token",
|
||||
"resolved_rate_multiplier": rate,
|
||||
"peak_rate_enabled": false,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func profitSlotTestContext(t *testing.T, gw *service.OpenAIGatewayService, groupID int64, suppress bool) context.Context {
|
||||
t.Helper()
|
||||
group := &service.Group{
|
||||
ID: groupID,
|
||||
Platform: service.PlatformOpenAI,
|
||||
Status: service.StatusActive,
|
||||
Hydrated: true,
|
||||
RateMultiplier: 1.0,
|
||||
SubscriptionType: service.SubscriptionTypeStandard,
|
||||
ProfitControlEnabled: true,
|
||||
ProfitMinMargin: 0.5,
|
||||
}
|
||||
base := context.WithValue(context.Background(), ctxkey.Group, group)
|
||||
if suppress {
|
||||
base = service.WithOpenAIProfitControlSuppressed(base)
|
||||
}
|
||||
ctx, pricingAt := gw.WithOpenAIRequestPricingContext(base, &groupID)
|
||||
require.False(t, pricingAt.IsZero())
|
||||
return ctx
|
||||
}
|
||||
|
||||
func TestAcquireResponsesAccountSlotProfitRecheck(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
gw := &service.OpenAIGatewayService{}
|
||||
groupID := int64(50)
|
||||
|
||||
newHandler := func(cache *profitCountingConcurrencyCache) *OpenAIGatewayHandler {
|
||||
return &OpenAIGatewayHandler{
|
||||
gatewayService: gw,
|
||||
concurrencyHelper: NewConcurrencyHelper(service.NewConcurrencyService(cache), SSEPingFormatClaude, 0),
|
||||
}
|
||||
}
|
||||
newSelection := func(account *service.Account) *service.AccountSelectionResult {
|
||||
return &service.AccountSelectionResult{
|
||||
Account: account,
|
||||
Acquired: false,
|
||||
WaitPlan: &service.AccountWaitPlan{AccountID: account.ID, MaxConcurrency: 2, Timeout: time.Second, MaxWaiting: 2},
|
||||
}
|
||||
}
|
||||
|
||||
t.Run("veto releases slot and requests reschedule without writing response", func(t *testing.T) {
|
||||
cache := &profitCountingConcurrencyCache{}
|
||||
h := newHandler(cache)
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
c.Request = httptest.NewRequest("POST", "/v1/responses", nil).WithContext(profitSlotTestContext(t, gw, groupID, false))
|
||||
streamStarted := false
|
||||
|
||||
release, result := h.acquireResponsesAccountSlot(c, &groupID, "", newSelection(profitSlotTestAccount(1, 0.8)), false, &streamStarted, zap.NewNop())
|
||||
require.Equal(t, openAISlotAcquireProfitVetoed, result)
|
||||
require.Nil(t, release)
|
||||
require.Zero(t, w.Body.Len(), "利润终检否决不得写出任何响应")
|
||||
require.Equal(t, int64(1), cache.accountReleases.Load(), "否决后必须立即释放已获取的槽位")
|
||||
})
|
||||
|
||||
t.Run("qualifying account acquires normally", func(t *testing.T) {
|
||||
cache := &profitCountingConcurrencyCache{}
|
||||
h := newHandler(cache)
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
c.Request = httptest.NewRequest("POST", "/v1/responses", nil).WithContext(profitSlotTestContext(t, gw, groupID, false))
|
||||
streamStarted := false
|
||||
|
||||
release, result := h.acquireResponsesAccountSlot(c, &groupID, "", newSelection(profitSlotTestAccount(2, 0.3)), false, &streamStarted, zap.NewNop())
|
||||
require.Equal(t, openAISlotAcquireOK, result)
|
||||
require.NotNil(t, release)
|
||||
release()
|
||||
})
|
||||
|
||||
t.Run("image intent suppression keeps official behavior", func(t *testing.T) {
|
||||
cache := &profitCountingConcurrencyCache{}
|
||||
h := newHandler(cache)
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
c.Request = httptest.NewRequest("POST", "/v1/responses", nil).WithContext(profitSlotTestContext(t, gw, groupID, true))
|
||||
streamStarted := false
|
||||
|
||||
release, result := h.acquireResponsesAccountSlot(c, &groupID, "", newSelection(profitSlotTestAccount(3, 0.8)), false, &streamStarted, zap.NewNop())
|
||||
require.Equal(t, openAISlotAcquireOK, result, "生图意图跳门:过贵账号照常获取(图片边界不装门)")
|
||||
require.NotNil(t, release)
|
||||
release()
|
||||
})
|
||||
}
|
||||
|
||||
// scheduler 跳门条件依赖"CapabilityResponses 仅在显式生图意图时被要求"这一
|
||||
// 映射;后续若扩展该 capability 的用途,本测试失败提示同步收窄跳门条件。
|
||||
func TestOpenAIResponsesRequiredCapabilityPinsImageIntentMapping(t *testing.T) {
|
||||
require.Equal(t, service.OpenAIEndpointCapabilityResponses, openAIResponsesRequiredCapability(true, service.PlatformOpenAI))
|
||||
require.Equal(t, service.OpenAIEndpointCapabilityChatCompletions, openAIResponsesRequiredCapability(false, service.PlatformOpenAI))
|
||||
require.Equal(t, service.OpenAIEndpointCapabilityChatCompletions, openAIResponsesRequiredCapability(true, service.PlatformGrok))
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// TestRecordOpenAIProfitVetoBounded 钉死 OpenAI 侧选号循环的利润否决预算:
|
||||
// 账号被加入排除集,且第 maxProfitVetoAttempts 次否决返回 false 要求终止。
|
||||
//
|
||||
// 上限是必需的:acquireResponsesAccountSlot 的 WaitPlan 分支先阻塞排队
|
||||
// (sticky 45s / fallback 30s)拿到槽位才做利润终检,无上限重选会把单次请求
|
||||
// 的延迟放大到 N × WaitPlan.Timeout。
|
||||
func TestRecordOpenAIProfitVetoBounded(t *testing.T) {
|
||||
failed := make(map[int64]struct{})
|
||||
count := 0
|
||||
|
||||
for i := int64(1); i < int64(maxProfitVetoAttempts); i++ {
|
||||
require.True(t, recordOpenAIProfitVeto(failed, i, &count), "第 %d 次否决应允许继续重选", i)
|
||||
require.Contains(t, failed, i, "否决的账号必须进入本请求排除集")
|
||||
}
|
||||
|
||||
require.False(t,
|
||||
recordOpenAIProfitVeto(failed, int64(maxProfitVetoAttempts), &count),
|
||||
"第 %d 次否决应耗尽预算并要求终止", maxProfitVetoAttempts)
|
||||
require.Equal(t, maxProfitVetoAttempts, count)
|
||||
require.Len(t, failed, maxProfitVetoAttempts)
|
||||
}
|
||||
|
||||
// TestOpenAIProfitVetoLoopTerminates 模拟「选号 → 抢槽 → 利润终检否决 → 重选」
|
||||
// 循环:整池越线时必须在常数步内终止,而不是把候选池逐个排队一遍。
|
||||
func TestOpenAIProfitVetoLoopTerminates(t *testing.T) {
|
||||
failed := make(map[int64]struct{})
|
||||
count := 0
|
||||
terminated := false
|
||||
iterations := 0
|
||||
|
||||
// 候选池远大于否决上限:无上限时会对每个账号各排队一次。
|
||||
for accountID := int64(1); accountID <= 500; accountID++ {
|
||||
iterations++
|
||||
if _, excluded := failed[accountID]; excluded {
|
||||
continue
|
||||
}
|
||||
if !recordOpenAIProfitVeto(failed, accountID, &count) {
|
||||
terminated = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
require.True(t, terminated, "整池越线时循环必须由否决预算终止")
|
||||
require.Equal(t, maxProfitVetoAttempts, iterations)
|
||||
}
|
||||
|
||||
// TestProfitVetoBudgetSharedWithFailoverState 钉死两条路径(FailoverState 与
|
||||
// OpenAI 独立计数器)使用同一上限语义,避免日后单边漂移。
|
||||
func TestProfitVetoBudgetSharedWithFailoverState(t *testing.T) {
|
||||
fs := NewFailoverState(10, false)
|
||||
failed := make(map[int64]struct{})
|
||||
count := 0
|
||||
|
||||
var fsStoppedAt, openAIStoppedAt int
|
||||
for i := int64(1); i <= int64(maxProfitVetoAttempts)+5; i++ {
|
||||
if fsStoppedAt == 0 && fs.RecordProfitVeto(i) == FailoverExhausted {
|
||||
fsStoppedAt = fs.ProfitVetoCount()
|
||||
}
|
||||
if openAIStoppedAt == 0 && !recordOpenAIProfitVeto(failed, i, &count) {
|
||||
openAIStoppedAt = count
|
||||
}
|
||||
}
|
||||
|
||||
require.Equal(t, maxProfitVetoAttempts, fsStoppedAt)
|
||||
require.Equal(t, fsStoppedAt, openAIStoppedAt, "两条路径的利润否决上限必须一致")
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// TestOpenAIWSTurnPricingZeroValue 钉死 WS turn 定价的零值语义:
|
||||
// 没有 turn 起始回调的 ingress 模式(ws_v2 passthrough 只实现 AfterTurn)
|
||||
// 必须让 pricingAt 保持零,由 RecordUsage 回退到记录时刻。
|
||||
//
|
||||
// 反例(本 PR 引入的回归):用建连时刻初始化,会把透传连接的所有 turn 钉死在
|
||||
// 建连时的高峰因子——客户端峰前一分钟建连并保活,整条连接就按谷价结算。
|
||||
func TestOpenAIWSTurnPricingZeroValue(t *testing.T) {
|
||||
var p openAIWSTurnPricing
|
||||
require.True(t, p.current().IsZero(),
|
||||
"未经 turn 起始回调冻结时必须保持零值,交由 RecordUsage 回退记录时刻")
|
||||
}
|
||||
|
||||
// TestOpenAIWSTurnPricingFreezePerTurn 钉死每个 turn 的 BeforeTurn 都会覆盖
|
||||
// 上一个 turn 的定价时刻:长连接跨峰谷时后续 turn 不得沿用旧时刻。
|
||||
func TestOpenAIWSTurnPricingFreezePerTurn(t *testing.T) {
|
||||
var p openAIWSTurnPricing
|
||||
turn1 := time.Now().Add(-time.Hour)
|
||||
turn2 := time.Now()
|
||||
|
||||
p.freeze(turn1)
|
||||
require.Equal(t, turn1, p.current())
|
||||
|
||||
p.freeze(turn2)
|
||||
require.Equal(t, turn2, p.current(), "后续 turn 必须使用自己的定价时刻")
|
||||
}
|
||||
@@ -230,6 +230,7 @@ func (s *Stripe) Refund(ctx context.Context, req payment.RefundRequest) (*paymen
|
||||
Amount: stripe.Int64(amountInMinorUnit),
|
||||
Reason: stripe.String(string(stripe.RefundReasonRequestedByCustomer)),
|
||||
}
|
||||
params.SetIdempotencyKey(fmt.Sprintf("re-%s-%d", req.OrderID, amountInMinorUnit))
|
||||
params.Context = ctx
|
||||
|
||||
r, err := s.sc.V1Refunds.Create(ctx, params)
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
//go:build unit
|
||||
|
||||
package provider
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/payment"
|
||||
"github.com/stretchr/testify/require"
|
||||
stripe "github.com/stripe/stripe-go/v85"
|
||||
)
|
||||
|
||||
type stripeRefundBackend struct {
|
||||
params []*stripe.RefundCreateParams
|
||||
}
|
||||
|
||||
func (b *stripeRefundBackend) Call(_ string, _ string, _ string, params stripe.ParamsContainer, v stripe.LastResponseSetter) error {
|
||||
b.params = append(b.params, params.(*stripe.RefundCreateParams))
|
||||
refund := v.(*stripe.Refund)
|
||||
refund.ID = "re_123"
|
||||
refund.Status = stripe.RefundStatusSucceeded
|
||||
return nil
|
||||
}
|
||||
|
||||
func (*stripeRefundBackend) CallStreaming(string, string, string, stripe.ParamsContainer, stripe.StreamingLastResponseSetter) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (*stripeRefundBackend) CallRaw(string, string, string, []byte, *stripe.Params, stripe.LastResponseSetter) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (*stripeRefundBackend) CallMultipart(string, string, string, string, *bytes.Buffer, *stripe.Params, stripe.LastResponseSetter) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (*stripeRefundBackend) SetMaxNetworkRetries(int64) {}
|
||||
|
||||
func TestStripeRefundUsesStableAmountSpecificIdempotencyKey(t *testing.T) {
|
||||
backend := &stripeRefundBackend{}
|
||||
client := stripe.NewClient("sk_test", stripe.WithBackends(&stripe.Backends{API: backend}))
|
||||
provider := &Stripe{
|
||||
config: map[string]string{"currency": "CNY"},
|
||||
initialized: true,
|
||||
sc: client,
|
||||
}
|
||||
|
||||
refund := func(amount string) {
|
||||
_, err := provider.Refund(context.Background(), payment.RefundRequest{
|
||||
TradeNo: "pi_123",
|
||||
OrderID: "sub2_order_456",
|
||||
Amount: amount,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
refund("12.34")
|
||||
refund("12.34")
|
||||
refund("12.35")
|
||||
|
||||
require.Len(t, backend.params, 3)
|
||||
require.Equal(t, int64(1234), *backend.params[0].Amount)
|
||||
require.Equal(t, "re-sub2_order_456-1234", *backend.params[0].IdempotencyKey)
|
||||
require.Equal(t, backend.params[0].IdempotencyKey, backend.params[1].IdempotencyKey)
|
||||
require.Equal(t, int64(1235), *backend.params[2].Amount)
|
||||
require.Equal(t, "re-sub2_order_456-1235", *backend.params[2].IdempotencyKey)
|
||||
require.NotEqual(t, *backend.params[0].IdempotencyKey, *backend.params[2].IdempotencyKey)
|
||||
}
|
||||
@@ -57,17 +57,6 @@ var codexOfficialClientOriginators = map[string]bool{
|
||||
"codex_sdk_ts": true, // TypeScript SDK
|
||||
}
|
||||
|
||||
// IsBrowserUserAgent 判断 User-Agent 是否来自浏览器(Chrome/Firefox/Safari/Edge/Opera 等)。
|
||||
// 所有现代浏览器的 UA 均以 "Mozilla/" 作为前缀,CLI 工具(codex/claude/curl/postman/python-requests 等)不会。
|
||||
// 该判定用于避免 Cloudflare 对浏览器型 UA 在 OpenAI 上游接口上触发 JS 质询。
|
||||
func IsBrowserUserAgent(userAgent string) bool {
|
||||
ua := strings.TrimSpace(userAgent)
|
||||
if ua == "" {
|
||||
return false
|
||||
}
|
||||
return strings.HasPrefix(strings.ToLower(ua), "mozilla/")
|
||||
}
|
||||
|
||||
// IsCodexCLIRequest checks if the User-Agent indicates a Codex CLI request
|
||||
func IsCodexCLIRequest(userAgent string) bool {
|
||||
ua := normalizeCodexClientHeader(userAgent)
|
||||
@@ -255,6 +244,83 @@ func canonicalizeCodexOriginator(name string) string {
|
||||
return name
|
||||
}
|
||||
|
||||
// CodexCLIOriginator 官方 Codex CLI 默认 originator(codex-rs DEFAULT_ORIGINATOR),
|
||||
// 也是身份归一化的目标身份。
|
||||
const CodexCLIOriginator = "codex_cli_rs"
|
||||
|
||||
// CodexUserAgentVersion 提取 Codex UA 的完整版本段,即 `{client}/{version} (...` 中的 version。
|
||||
// 与 ParseCodexEngineVersion 的区别:后者只取三段数字用于引擎版本比较(会丢掉 -alpha.4
|
||||
// 之类的预发布后缀),本函数保留原样,因为出站 version 头必须与 UA 版本段逐字一致。
|
||||
// 取不到(非 Codex 形态 UA)时返回空串。
|
||||
func CodexUserAgentVersion(userAgent string) string {
|
||||
ua := strings.TrimSpace(userAgent)
|
||||
slash := strings.IndexByte(ua, '/')
|
||||
if slash <= 0 {
|
||||
return ""
|
||||
}
|
||||
rest := ua[slash+1:]
|
||||
if space := strings.IndexByte(rest, ' '); space >= 0 {
|
||||
rest = rest[:space]
|
||||
}
|
||||
return strings.TrimSpace(rest)
|
||||
}
|
||||
|
||||
// SetCodexUserAgentVersion 用 version 重建 Codex 形态 UA 中的版本声明,其余部分
|
||||
// (客户端名、OS / 架构 / 终端指纹)原样保留;UA 不是 `{client}/{version}` 形态时返回空串,
|
||||
// 由调用方决定整体回退。
|
||||
//
|
||||
// 尾部官方客户端标识组 `(name; version)` 与首段是同一个版本声明的两个出口
|
||||
// (CODEX_INTERNAL_ORIGINATOR_OVERRIDE 场景,如 `cccc/0.142.0 ... (codex-tui; 0.142.0)`),
|
||||
// 必须一并更新,否则会拼出首段声明新版本、尾部仍是旧版本的自相矛盾身份。
|
||||
// 仅在括号组确为官方客户端标识时才改写,避免误伤 OS 组(如 `(Ubuntu 22.4.0; x86_64)`)。
|
||||
func SetCodexUserAgentVersion(userAgent, version string) string {
|
||||
ua := strings.TrimSpace(userAgent)
|
||||
version = strings.TrimSpace(version)
|
||||
if version == "" {
|
||||
return ""
|
||||
}
|
||||
slash := strings.IndexByte(ua, '/')
|
||||
if slash <= 0 {
|
||||
return ""
|
||||
}
|
||||
client := strings.TrimSpace(ua[:slash])
|
||||
if client == "" {
|
||||
return ""
|
||||
}
|
||||
rest := ua[slash+1:]
|
||||
tail := ""
|
||||
if space := strings.IndexByte(rest, ' '); space >= 0 {
|
||||
tail = rest[space:]
|
||||
} else if strings.TrimSpace(rest) == "" {
|
||||
// `client/` 没有版本段,不是可重建的 Codex 形态。
|
||||
return ""
|
||||
}
|
||||
return rewriteCodexUATrailerVersion(client+"/"+version+tail, version)
|
||||
}
|
||||
|
||||
// rewriteCodexUATrailerVersion 把尾部官方客户端标识组 `(name; version)` 的版本改成 version。
|
||||
// 括号组缺少 `;` 分隔的版本、或 name 不是官方 originator 时原样返回。
|
||||
func rewriteCodexUATrailerVersion(ua, version string) string {
|
||||
open := strings.LastIndex(ua, "(")
|
||||
if open < 0 {
|
||||
return ua
|
||||
}
|
||||
closeIdx := strings.Index(ua[open+1:], ")")
|
||||
if closeIdx < 0 {
|
||||
return ua
|
||||
}
|
||||
inner := ua[open+1 : open+1+closeIdx]
|
||||
semi := strings.Index(inner, ";")
|
||||
if semi < 0 {
|
||||
return ua
|
||||
}
|
||||
name := strings.TrimSpace(inner[:semi])
|
||||
if name == "" || !IsCodexOfficialClientOriginator(name) {
|
||||
return ua
|
||||
}
|
||||
return ua[:open+1] + name + "; " + version + ua[open+1+closeIdx:]
|
||||
}
|
||||
|
||||
// codexEngineVersionPattern 提取版本段开头的三段数字 X.Y.Z(忽略 -alpha 等后缀)。
|
||||
var codexEngineVersionPattern = regexp.MustCompile(`^(\d+\.\d+\.\d+)`)
|
||||
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
package openai
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestCodexUserAgentVersion(t *testing.T) {
|
||||
require.Equal(t, "0.146.0", CodexUserAgentVersion("codex_cli_rs/0.146.0 (Ubuntu 22.4.0; x86_64) xterm-256color"))
|
||||
require.Equal(t, "0.146.0", CodexUserAgentVersion(" codex_cli_rs/0.146.0 "))
|
||||
// 预发布后缀原样保留:出站 version 头必须与 UA 版本段逐字一致。
|
||||
require.Equal(t, "0.147.0-alpha.4", CodexUserAgentVersion("codex-tui/0.147.0-alpha.4 (Mac OS X 14.0; arm64) iTerm"))
|
||||
// 非 `{client}/{version}` 形态取不到版本段。
|
||||
require.Empty(t, CodexUserAgentVersion("curl 8.7.1"))
|
||||
require.Empty(t, CodexUserAgentVersion("/0.146.0"))
|
||||
require.Empty(t, CodexUserAgentVersion(""))
|
||||
}
|
||||
|
||||
// 管理员在面板 / 账号上配置的 UA 填写于某个历史版本,逐字沿用会把出站身份钉死在陈旧版本上。
|
||||
// 重建只动版本声明,OS / 架构 / 终端指纹必须原样保留——那是该配置项唯一不可替代的价值。
|
||||
func TestSetCodexUserAgentVersion(t *testing.T) {
|
||||
require.Equal(t,
|
||||
"codex_cli_rs/0.146.0 (Ubuntu 22.4.0; x86_64) xterm-256color",
|
||||
SetCodexUserAgentVersion("codex_cli_rs/0.125.0 (Ubuntu 22.4.0; x86_64) xterm-256color", "0.146.0"),
|
||||
)
|
||||
require.Equal(t, "codex_cli_rs/0.146.0", SetCodexUserAgentVersion("codex_cli_rs/0.1.0", "0.146.0"))
|
||||
|
||||
// 尾部官方客户端标识组与首段是同一个版本声明的两个出口,必须一并更新,
|
||||
// 否则拼出首段声明新版本、尾部仍是旧版本的自相矛盾身份。
|
||||
require.Equal(t,
|
||||
"cccc/0.146.0 (Ubuntu 22.4.0; x86_64) screen (codex-tui; 0.146.0)",
|
||||
SetCodexUserAgentVersion("cccc/0.142.0 (Ubuntu 22.4.0; x86_64) screen (codex-tui; 0.142.0)", "0.146.0"),
|
||||
)
|
||||
// OS 括号组不是客户端标识,不得被误改。
|
||||
require.Equal(t,
|
||||
"codex_cli_rs/0.146.0 (Ubuntu 22.4.0; x86_64)",
|
||||
SetCodexUserAgentVersion("codex_cli_rs/0.125.0 (Ubuntu 22.4.0; x86_64)", "0.146.0"),
|
||||
)
|
||||
|
||||
// 无法重建时返回空串,由调用方决定整体回退,绝不拼出畸形身份。
|
||||
require.Empty(t, SetCodexUserAgentVersion("not-a-codex-client", "0.146.0"))
|
||||
require.Empty(t, SetCodexUserAgentVersion("codex_cli_rs/", "0.146.0"))
|
||||
require.Empty(t, SetCodexUserAgentVersion("/0.1.0", "0.146.0"))
|
||||
require.Empty(t, SetCodexUserAgentVersion("codex_cli_rs/0.1.0", ""))
|
||||
}
|
||||
@@ -56,8 +56,10 @@ var schedulerNeutralExtraKeyPrefixes = []string{
|
||||
"codex_secondary_",
|
||||
"codex_5h_",
|
||||
"codex_7d_",
|
||||
"codex_reset_credit_",
|
||||
"passive_usage_",
|
||||
"upstream_billing_probe",
|
||||
"upstream_billing_rate_sync",
|
||||
"ollama_cloud_usage",
|
||||
}
|
||||
|
||||
@@ -397,16 +399,29 @@ func (r *accountRepository) ListCRSAccountIDs(ctx context.Context) (map[string]i
|
||||
}
|
||||
|
||||
func (r *accountRepository) Update(ctx context.Context, account *service.Account) error {
|
||||
return r.updateAccount(ctx, account, nil)
|
||||
return r.updateAccount(ctx, account, nil, nil, account.RateMultiplier)
|
||||
}
|
||||
|
||||
// UpdateWithUpstreamBillingProbeEnabled applies an explicit probe switch in the
|
||||
// same row-lock transaction as the rest of an admin account edit.
|
||||
func (r *accountRepository) UpdateWithUpstreamBillingProbeEnabled(ctx context.Context, account *service.Account, enabled bool) error {
|
||||
return r.updateAccount(ctx, account, &enabled)
|
||||
// UpdateWithAccountBillingSettings applies an admin account edit while
|
||||
// preserving a concurrently probe-synchronized rate unless the request
|
||||
// explicitly includes a manual rate.
|
||||
func (r *accountRepository) UpdateWithAccountBillingSettings(
|
||||
ctx context.Context,
|
||||
account *service.Account,
|
||||
probeEnabled *bool,
|
||||
rateSyncEnabled *bool,
|
||||
rateMultiplier *float64,
|
||||
) error {
|
||||
return r.updateAccount(ctx, account, probeEnabled, rateSyncEnabled, rateMultiplier)
|
||||
}
|
||||
|
||||
func (r *accountRepository) updateAccount(ctx context.Context, account *service.Account, explicitProbeEnabled *bool) error {
|
||||
func (r *accountRepository) updateAccount(
|
||||
ctx context.Context,
|
||||
account *service.Account,
|
||||
explicitProbeEnabled *bool,
|
||||
explicitRateSyncEnabled *bool,
|
||||
explicitRateMultiplier *float64,
|
||||
) error {
|
||||
if account == nil {
|
||||
return nil
|
||||
}
|
||||
@@ -430,7 +445,14 @@ func (r *accountRepository) updateAccount(ctx context.Context, account *service.
|
||||
}
|
||||
}
|
||||
|
||||
updated, err := r.updateLockedAccount(ctx, client, account, explicitProbeEnabled)
|
||||
updated, err := r.updateLockedAccount(
|
||||
ctx,
|
||||
client,
|
||||
account,
|
||||
explicitProbeEnabled,
|
||||
explicitRateSyncEnabled,
|
||||
explicitRateMultiplier,
|
||||
)
|
||||
if err != nil {
|
||||
return translatePersistenceError(err, service.ErrAccountNotFound, nil)
|
||||
}
|
||||
@@ -452,8 +474,15 @@ func (r *accountRepository) updateAccount(ctx context.Context, account *service.
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *accountRepository) updateLockedAccount(ctx context.Context, client *dbent.Client, account *service.Account, explicitProbeEnabled *bool) (*dbent.Account, error) {
|
||||
extra, err := lockAndMergeAccountProbeExtra(ctx, client, account, explicitProbeEnabled)
|
||||
func (r *accountRepository) updateLockedAccount(
|
||||
ctx context.Context,
|
||||
client *dbent.Client,
|
||||
account *service.Account,
|
||||
explicitProbeEnabled *bool,
|
||||
explicitRateSyncEnabled *bool,
|
||||
explicitRateMultiplier *float64,
|
||||
) (*dbent.Account, error) {
|
||||
extra, err := lockAndMergeAccountProbeExtra(ctx, client, account, explicitProbeEnabled, explicitRateSyncEnabled)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -478,8 +507,8 @@ func (r *accountRepository) updateLockedAccount(ctx context.Context, client *dbe
|
||||
SetSchedulable(schedulable).
|
||||
SetAutoPauseOnExpired(account.AutoPauseOnExpired)
|
||||
|
||||
if account.RateMultiplier != nil {
|
||||
builder.SetRateMultiplier(*account.RateMultiplier)
|
||||
if explicitRateMultiplier != nil {
|
||||
builder.SetRateMultiplier(*explicitRateMultiplier)
|
||||
}
|
||||
if account.LoadFactor != nil {
|
||||
builder.SetLoadFactor(*account.LoadFactor)
|
||||
@@ -542,7 +571,13 @@ func (r *accountRepository) updateLockedAccount(ctx context.Context, client *dbe
|
||||
return builder.Save(ctx)
|
||||
}
|
||||
|
||||
func lockAndMergeAccountProbeExtra(ctx context.Context, client *dbent.Client, account *service.Account, explicitProbeEnabled *bool) (map[string]any, error) {
|
||||
func lockAndMergeAccountProbeExtra(
|
||||
ctx context.Context,
|
||||
client *dbent.Client,
|
||||
account *service.Account,
|
||||
explicitProbeEnabled *bool,
|
||||
explicitRateSyncEnabled *bool,
|
||||
) (map[string]any, error) {
|
||||
credentials, err := json.Marshal(normalizeJSONMap(account.Credentials))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -569,6 +604,7 @@ func lockAndMergeAccountProbeExtra(ctx context.Context, client *dbent.Client, ac
|
||||
),
|
||||
proxy_id IS NOT DISTINCT FROM $5,
|
||||
extra -> 'upstream_billing_probe_enabled',
|
||||
extra -> 'upstream_billing_rate_sync_enabled',
|
||||
extra -> 'upstream_billing_probe',
|
||||
extra -> 'ollama_cloud_usage_session',
|
||||
extra -> 'ollama_cloud_usage_auto_refresh',
|
||||
@@ -593,6 +629,7 @@ func lockAndMergeAccountProbeExtra(ctx context.Context, client *dbent.Client, ac
|
||||
ollamaGroupIdentityUnchanged bool
|
||||
ollamaProxyIdentityUnchanged bool
|
||||
currentEnabled []byte
|
||||
currentRateSyncEnabled []byte
|
||||
currentSnapshot []byte
|
||||
currentOllamaSession []byte
|
||||
currentOllamaAutoRefresh []byte
|
||||
@@ -603,6 +640,7 @@ func lockAndMergeAccountProbeExtra(ctx context.Context, client *dbent.Client, ac
|
||||
&ollamaGroupIdentityUnchanged,
|
||||
&ollamaProxyIdentityUnchanged,
|
||||
¤tEnabled,
|
||||
¤tRateSyncEnabled,
|
||||
¤tSnapshot,
|
||||
¤tOllamaSession,
|
||||
¤tOllamaAutoRefresh,
|
||||
@@ -617,6 +655,7 @@ func lockAndMergeAccountProbeExtra(ctx context.Context, client *dbent.Client, ac
|
||||
extra := copyJSONMap(normalizeJSONMap(account.Extra))
|
||||
for _, key := range []string{
|
||||
service.UpstreamBillingProbeEnabledExtraKey,
|
||||
service.UpstreamBillingRateSyncEnabledExtraKey,
|
||||
service.UpstreamBillingProbeExtraKey,
|
||||
service.OllamaCloudUsageSessionExtraKey,
|
||||
service.OllamaCloudUsageAutoRefreshExtraKey,
|
||||
@@ -624,21 +663,53 @@ func lockAndMergeAccountProbeExtra(ctx context.Context, client *dbent.Client, ac
|
||||
} {
|
||||
delete(extra, key)
|
||||
}
|
||||
probeExplicitlyDisabled := false
|
||||
probeAccount := account.Platform == service.PlatformOpenAI && account.Type == service.AccountTypeAPIKey
|
||||
if probeAccount && explicitProbeEnabled != nil {
|
||||
extra[service.UpstreamBillingProbeEnabledExtraKey] = *explicitProbeEnabled
|
||||
probeExplicitlyDisabled = !*explicitProbeEnabled
|
||||
} else if probeAccount {
|
||||
probeAccount := service.IsUpstreamBillingProbeIdentity(account.Platform, account.Type)
|
||||
probeEnabled := false
|
||||
probeEnabledPresent := false
|
||||
if probeAccount {
|
||||
if enabled, ok, err := decodeAccountExtraJSON(currentEnabled); err != nil {
|
||||
return nil, err
|
||||
} else if ok {
|
||||
extra[service.UpstreamBillingProbeEnabledExtraKey] = enabled
|
||||
if value, isBool := enabled.(bool); isBool && !value {
|
||||
probeExplicitlyDisabled = true
|
||||
}
|
||||
} else if value, isBool := enabled.(bool); ok && isBool {
|
||||
probeEnabled = value
|
||||
probeEnabledPresent = true
|
||||
}
|
||||
if explicitProbeEnabled != nil {
|
||||
probeEnabled = *explicitProbeEnabled
|
||||
probeEnabledPresent = true
|
||||
}
|
||||
}
|
||||
rateSyncEnabled := false
|
||||
rateSyncEnabledPresent := false
|
||||
if probeAccount {
|
||||
if enabled, ok, err := decodeAccountExtraJSON(currentRateSyncEnabled); err != nil {
|
||||
return nil, err
|
||||
} else if value, isBool := enabled.(bool); ok && isBool {
|
||||
rateSyncEnabled = value
|
||||
rateSyncEnabledPresent = true
|
||||
}
|
||||
if explicitRateSyncEnabled != nil {
|
||||
rateSyncEnabled = *explicitRateSyncEnabled
|
||||
rateSyncEnabledPresent = true
|
||||
}
|
||||
if explicitProbeEnabled != nil && !*explicitProbeEnabled {
|
||||
rateSyncEnabled = false
|
||||
rateSyncEnabledPresent = true
|
||||
}
|
||||
// 同步依赖探测,方向是单向的:探测关闭(或探测键缺失)一律把同步归零。
|
||||
// 不做反向推导——由 rate_sync=true 推出 probe=true 会让一条"同步开、探测键
|
||||
// 缺失"的僵尸记录在任意一次无关编辑时静默打开周期性外呼。需要同时打开两个
|
||||
// 开关的调用方(管理端编辑)自己显式传 explicitProbeEnabled=true。
|
||||
if !probeEnabled {
|
||||
rateSyncEnabled = false
|
||||
}
|
||||
if probeEnabledPresent {
|
||||
extra[service.UpstreamBillingProbeEnabledExtraKey] = probeEnabled
|
||||
}
|
||||
if rateSyncEnabledPresent {
|
||||
extra[service.UpstreamBillingRateSyncEnabledExtraKey] = rateSyncEnabled
|
||||
}
|
||||
}
|
||||
probeExplicitlyDisabled := probeEnabledPresent && !probeEnabled
|
||||
if identityUnchanged && !probeExplicitlyDisabled {
|
||||
if snapshot, ok, err := decodeAccountExtraJSON(currentSnapshot); err != nil {
|
||||
return nil, err
|
||||
@@ -709,7 +780,7 @@ func (r *accountRepository) UpdateCredentials(ctx context.Context, id int64, cre
|
||||
credentials = $1::jsonb,
|
||||
extra = CASE
|
||||
-- 凭证整体未变化 ⇒ Ollama 组身份必然未变化;顶层 DISTINCT 守卫防止
|
||||
-- 非 Ollama 账号的无变化持久化误清 openai 探测快照或重写 NULL extra。
|
||||
-- 非 Ollama 账号的无变化持久化误清探测快照或重写 NULL extra。
|
||||
WHEN platform IN ('openai', 'anthropic')
|
||||
AND type = 'apikey'
|
||||
AND credentials IS DISTINCT FROM $1::jsonb
|
||||
@@ -720,15 +791,14 @@ func (r *accountRepository) UpdateCredentials(ctx context.Context, id int64, cre
|
||||
AND `+ollamaCloudBaseURLMatchesSQL("$1::jsonb ->> 'base_url'")+`
|
||||
)
|
||||
)
|
||||
THEN (CASE
|
||||
WHEN platform = 'openai' THEN COALESCE(extra, '{}'::jsonb) - 'upstream_billing_probe'
|
||||
ELSE COALESCE(extra, '{}'::jsonb)
|
||||
END)
|
||||
THEN COALESCE(extra, '{}'::jsonb)
|
||||
- 'upstream_billing_probe'
|
||||
- 'ollama_cloud_usage_session'
|
||||
- 'ollama_cloud_usage_auto_refresh'
|
||||
- 'ollama_cloud_usage_snapshot'
|
||||
WHEN platform = 'openai'
|
||||
AND type = 'apikey'
|
||||
-- 上游倍率探测已放宽到全部 API-key 平台:凭证变化即视为探测
|
||||
-- 身份变化,丢弃 stale 快照。
|
||||
WHEN type = 'apikey'
|
||||
AND credentials IS DISTINCT FROM $1::jsonb
|
||||
THEN COALESCE(extra, '{}'::jsonb) - 'upstream_billing_probe'
|
||||
ELSE extra
|
||||
@@ -2528,21 +2598,25 @@ func (r *accountRepository) UpdateUpstreamBillingProbeSnapshot(
|
||||
ctx context.Context,
|
||||
account *service.Account,
|
||||
snapshot *service.UpstreamBillingProbeSnapshot,
|
||||
rateMultiplier *float64,
|
||||
) error {
|
||||
if account == nil || snapshot == nil {
|
||||
return service.ErrAccountNilInput
|
||||
}
|
||||
if snapshot.Status != service.UpstreamBillingProbeStatusOK {
|
||||
rateMultiplier = nil
|
||||
}
|
||||
if dbent.TxFromContext(ctx) == nil {
|
||||
tx, err := r.client.Tx(ctx)
|
||||
if errors.Is(err, dbent.ErrTxStarted) {
|
||||
return r.updateUpstreamBillingProbeSnapshotInTx(ctx, account, snapshot)
|
||||
return r.updateUpstreamBillingProbeSnapshotInTx(ctx, account, snapshot, rateMultiplier)
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
|
||||
if err := r.updateUpstreamBillingProbeSnapshotInTx(dbent.NewTxContext(ctx, tx), account, snapshot); err != nil {
|
||||
if err := r.updateUpstreamBillingProbeSnapshotInTx(dbent.NewTxContext(ctx, tx), account, snapshot, rateMultiplier); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
@@ -2553,13 +2627,14 @@ func (r *accountRepository) UpdateUpstreamBillingProbeSnapshot(
|
||||
r.syncSchedulerAccountSnapshot(ctx, account.ID)
|
||||
return nil
|
||||
}
|
||||
return r.updateUpstreamBillingProbeSnapshotInTx(ctx, account, snapshot)
|
||||
return r.updateUpstreamBillingProbeSnapshotInTx(ctx, account, snapshot, rateMultiplier)
|
||||
}
|
||||
|
||||
func (r *accountRepository) updateUpstreamBillingProbeSnapshotInTx(
|
||||
ctx context.Context,
|
||||
account *service.Account,
|
||||
snapshot *service.UpstreamBillingProbeSnapshot,
|
||||
rateMultiplier *float64,
|
||||
) error {
|
||||
payload, err := json.Marshal(map[string]any{service.UpstreamBillingProbeExtraKey: snapshot})
|
||||
if err != nil {
|
||||
@@ -2585,6 +2660,14 @@ func (r *accountRepository) updateUpstreamBillingProbeSnapshotInTx(
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var expectedRateSyncEnabled any
|
||||
if account.Extra != nil {
|
||||
expectedRateSyncEnabled = account.Extra[service.UpstreamBillingRateSyncEnabledExtraKey]
|
||||
}
|
||||
expectedRateSyncEnabledJSON, err := json.Marshal(expectedRateSyncEnabled)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
client := clientFromContext(ctx, r.client)
|
||||
proxyMatches, err := lockAndMatchProbeProxyIdentity(ctx, client, account)
|
||||
if err != nil {
|
||||
@@ -2599,7 +2682,16 @@ func (r *accountRepository) updateUpstreamBillingProbeSnapshotInTx(
|
||||
}
|
||||
result, err := client.ExecContext(ctx, `
|
||||
UPDATE accounts
|
||||
SET extra = COALESCE(extra, '{}'::jsonb) || $1::jsonb, updated_at = NOW()
|
||||
SET
|
||||
extra = COALESCE(extra, '{}'::jsonb) || $1::jsonb,
|
||||
rate_multiplier = CASE
|
||||
WHEN $10::numeric IS NOT NULL
|
||||
AND extra @> '{"upstream_billing_probe_enabled": true}'::jsonb
|
||||
AND extra @> '{"upstream_billing_rate_sync_enabled": true}'::jsonb
|
||||
THEN $10::numeric
|
||||
ELSE rate_multiplier
|
||||
END,
|
||||
updated_at = NOW()
|
||||
WHERE id = $2
|
||||
AND platform = $3
|
||||
AND type = $4
|
||||
@@ -2607,8 +2699,9 @@ func (r *accountRepository) updateUpstreamBillingProbeSnapshotInTx(
|
||||
AND proxy_id IS NOT DISTINCT FROM $6
|
||||
AND COALESCE(extra -> 'upstream_billing_probe', 'null'::jsonb) = $7::jsonb
|
||||
AND COALESCE(extra -> 'upstream_billing_probe_enabled', 'null'::jsonb) = $8::jsonb
|
||||
AND COALESCE(extra -> 'upstream_billing_rate_sync_enabled', 'null'::jsonb) = $9::jsonb
|
||||
AND deleted_at IS NULL
|
||||
`, string(payload), account.ID, account.Platform, account.Type, string(credentials), proxyID, string(expectedSnapshotJSON), string(expectedEnabledJSON))
|
||||
`, string(payload), account.ID, account.Platform, account.Type, string(credentials), proxyID, string(expectedSnapshotJSON), string(expectedEnabledJSON), string(expectedRateSyncEnabledJSON), rateMultiplier)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -2839,8 +2932,8 @@ func (r *accountRepository) BulkUpdate(ctx context.Context, ids []int64, updates
|
||||
args = append(args, pq.Array(ids))
|
||||
idx++
|
||||
if updates.ProbeEnabled != nil {
|
||||
whereClause += " AND platform = $" + itoa(idx) + " AND type = $" + itoa(idx+1)
|
||||
args = append(args, service.PlatformOpenAI, service.AccountTypeAPIKey)
|
||||
whereClause += " AND type = $" + itoa(idx)
|
||||
args = append(args, service.AccountTypeAPIKey)
|
||||
}
|
||||
query := "UPDATE accounts SET " + joinClauses(setClauses, ", ") + whereClause
|
||||
|
||||
@@ -3382,7 +3475,6 @@ func (r *accountRepository) ListDueUpstreamBillingProbeAccounts(ctx context.Cont
|
||||
FROM accounts
|
||||
WHERE deleted_at IS NULL
|
||||
AND status = 'active'
|
||||
AND platform = 'openai'
|
||||
AND type = 'apikey'
|
||||
AND extra @> '{"upstream_billing_probe_enabled": true}'::jsonb
|
||||
), parsed AS MATERIALIZED (
|
||||
|
||||
@@ -229,7 +229,7 @@ func TestLockAndMergeAccountProbeExtraCoalescesNullableOllamaGroupIdentity(t *te
|
||||
loaded, err := newAccountRepositoryWithSQL(tx.Client(), tx, nil).GetByID(ctx, account.ID)
|
||||
require.NoError(t, err)
|
||||
|
||||
merged, err := lockAndMergeAccountProbeExtra(ctx, tx.Client(), loaded, nil)
|
||||
merged, err := lockAndMergeAccountProbeExtra(ctx, tx.Client(), loaded, nil, nil)
|
||||
|
||||
require.NoError(t, err, "a NULL Ollama eligibility expression must scan as false")
|
||||
require.NotContains(t, merged, service.OllamaCloudUsageSessionExtraKey)
|
||||
|
||||
@@ -41,8 +41,8 @@ func TestUpdateUpstreamBillingProbeSnapshotRequiresSameIdentityAndSnapshot(t *te
|
||||
WithArgs(int64(9)).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"protocol", "host", "port", "username", "password", "status"}).
|
||||
AddRow("http", "127.0.0.1", 3128, "user", "pass", service.StatusActive))
|
||||
mock.ExpectExec(`(?s)`+regexp.QuoteMeta("UPDATE accounts")+`.*`+regexp.QuoteMeta("WHERE id = $2")+`.*`+regexp.QuoteMeta("AND platform = $3")+`.*`+regexp.QuoteMeta("AND type = $4")+`.*`+regexp.QuoteMeta("AND credentials = $5::jsonb")+`.*`+regexp.QuoteMeta("AND proxy_id IS NOT DISTINCT FROM $6")+`.*`+regexp.QuoteMeta("COALESCE(extra -> 'upstream_billing_probe', 'null'::jsonb) = $7::jsonb")+`.*`+regexp.QuoteMeta("COALESCE(extra -> 'upstream_billing_probe_enabled', 'null'::jsonb) = $8::jsonb")).
|
||||
WithArgs(sqlmock.AnyArg(), int64(17), service.PlatformOpenAI, service.AccountTypeAPIKey, `{"api_key":"sk-test","base_url":"http://127.0.0.1:8080"}`, int64(9), `{"status":"stale"}`, "null").
|
||||
mock.ExpectExec(`(?s)`+regexp.QuoteMeta("UPDATE accounts")+`.*`+regexp.QuoteMeta("WHERE id = $2")+`.*`+regexp.QuoteMeta("AND platform = $3")+`.*`+regexp.QuoteMeta("AND type = $4")+`.*`+regexp.QuoteMeta("AND credentials = $5::jsonb")+`.*`+regexp.QuoteMeta("AND proxy_id IS NOT DISTINCT FROM $6")+`.*`+regexp.QuoteMeta("COALESCE(extra -> 'upstream_billing_probe', 'null'::jsonb) = $7::jsonb")+`.*`+regexp.QuoteMeta("COALESCE(extra -> 'upstream_billing_probe_enabled', 'null'::jsonb) = $8::jsonb")+`.*`+regexp.QuoteMeta("COALESCE(extra -> 'upstream_billing_rate_sync_enabled', 'null'::jsonb) = $9::jsonb")).
|
||||
WithArgs(sqlmock.AnyArg(), int64(17), service.PlatformOpenAI, service.AccountTypeAPIKey, `{"api_key":"sk-test","base_url":"http://127.0.0.1:8080"}`, int64(9), `{"status":"stale"}`, "null", "null", nil).
|
||||
WillReturnResult(sqlmock.NewResult(0, tt.affected))
|
||||
if tt.affected > 0 {
|
||||
mock.ExpectExec(regexp.QuoteMeta("INSERT INTO scheduler_outbox")).
|
||||
@@ -75,7 +75,7 @@ func TestUpdateUpstreamBillingProbeSnapshotRequiresSameIdentityAndSnapshot(t *te
|
||||
}
|
||||
|
||||
txCtx := dbent.NewTxContext(context.Background(), tx)
|
||||
err = repo.UpdateUpstreamBillingProbeSnapshot(txCtx, account, &service.UpstreamBillingProbeSnapshot{Status: service.UpstreamBillingProbeStatusOK})
|
||||
err = repo.UpdateUpstreamBillingProbeSnapshot(txCtx, account, &service.UpstreamBillingProbeSnapshot{Status: service.UpstreamBillingProbeStatusOK}, nil)
|
||||
|
||||
if tt.wantErr != nil {
|
||||
require.ErrorIs(t, err, tt.wantErr)
|
||||
@@ -98,8 +98,8 @@ func TestUpdateUpstreamBillingProbeSnapshotCommitsSnapshotAndOutboxAtomically(t
|
||||
t.Cleanup(func() { _ = client.Close() })
|
||||
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectExec(`(?s)`+regexp.QuoteMeta("UPDATE accounts")+`.*`+regexp.QuoteMeta("AND credentials = $5::jsonb")+`.*`+regexp.QuoteMeta("AND proxy_id IS NOT DISTINCT FROM $6")+`.*`+regexp.QuoteMeta("COALESCE(extra -> 'upstream_billing_probe', 'null'::jsonb) = $7::jsonb")).
|
||||
WithArgs(sqlmock.AnyArg(), int64(17), service.PlatformOpenAI, service.AccountTypeAPIKey, `{"api_key":"sk-test"}`, nil, "null", "null").
|
||||
mock.ExpectExec(`(?s)`+regexp.QuoteMeta("UPDATE accounts")+`.*`+regexp.QuoteMeta("rate_multiplier = CASE")+`.*`+regexp.QuoteMeta("THEN $10::numeric")+`.*`+regexp.QuoteMeta("AND credentials = $5::jsonb")+`.*`+regexp.QuoteMeta("AND proxy_id IS NOT DISTINCT FROM $6")+`.*`+regexp.QuoteMeta("COALESCE(extra -> 'upstream_billing_probe', 'null'::jsonb) = $7::jsonb")).
|
||||
WithArgs(sqlmock.AnyArg(), int64(17), service.PlatformOpenAI, service.AccountTypeAPIKey, `{"api_key":"sk-test"}`, nil, "null", "true", "true", 0.065).
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
mock.ExpectExec(regexp.QuoteMeta("INSERT INTO scheduler_outbox")).
|
||||
WithArgs(service.SchedulerOutboxEventAccountChanged, int64(17), nil, nil, sqlmock.AnyArg()).
|
||||
@@ -112,9 +112,19 @@ func TestUpdateUpstreamBillingProbeSnapshotCommitsSnapshotAndOutboxAtomically(t
|
||||
Platform: service.PlatformOpenAI,
|
||||
Type: service.AccountTypeAPIKey,
|
||||
Credentials: map[string]any{"api_key": "sk-test"},
|
||||
Extra: map[string]any{
|
||||
service.UpstreamBillingProbeEnabledExtraKey: true,
|
||||
service.UpstreamBillingRateSyncEnabledExtraKey: true,
|
||||
},
|
||||
}
|
||||
rateMultiplier := 0.065
|
||||
|
||||
err = repo.UpdateUpstreamBillingProbeSnapshot(context.Background(), account, &service.UpstreamBillingProbeSnapshot{Status: service.UpstreamBillingProbeStatusOK})
|
||||
err = repo.UpdateUpstreamBillingProbeSnapshot(
|
||||
context.Background(),
|
||||
account,
|
||||
&service.UpstreamBillingProbeSnapshot{Status: service.UpstreamBillingProbeStatusOK},
|
||||
&rateMultiplier,
|
||||
)
|
||||
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, mock.ExpectationsWereMet())
|
||||
@@ -148,7 +158,7 @@ func TestUpdateUpstreamBillingProbeSnapshotRejectsChangedProxyIdentity(t *testin
|
||||
},
|
||||
}
|
||||
repo := newAccountRepositoryWithSQL(client, db, nil)
|
||||
err = repo.UpdateUpstreamBillingProbeSnapshot(dbent.NewTxContext(context.Background(), tx), account, &service.UpstreamBillingProbeSnapshot{Status: service.UpstreamBillingProbeStatusOK})
|
||||
err = repo.UpdateUpstreamBillingProbeSnapshot(dbent.NewTxContext(context.Background(), tx), account, &service.UpstreamBillingProbeSnapshot{Status: service.UpstreamBillingProbeStatusOK}, nil)
|
||||
|
||||
require.ErrorIs(t, err, service.ErrUpstreamBillingProbeIdentityChanged)
|
||||
mock.ExpectRollback()
|
||||
@@ -166,7 +176,7 @@ func TestUpdateUpstreamBillingProbeSnapshotRollsBackWhenOutboxFails(t *testing.T
|
||||
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectExec(`(?s)`+regexp.QuoteMeta("UPDATE accounts")+`.*`+regexp.QuoteMeta("AND proxy_id IS NOT DISTINCT FROM $6")+`.*`+regexp.QuoteMeta("COALESCE(extra -> 'upstream_billing_probe', 'null'::jsonb) = $7::jsonb")).
|
||||
WithArgs(sqlmock.AnyArg(), int64(18), service.PlatformOpenAI, service.AccountTypeAPIKey, `{"api_key":"sk-test"}`, nil, "null", "null").
|
||||
WithArgs(sqlmock.AnyArg(), int64(18), service.PlatformOpenAI, service.AccountTypeAPIKey, `{"api_key":"sk-test"}`, nil, "null", "true", "true", 0.7).
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
mock.ExpectExec(regexp.QuoteMeta("INSERT INTO scheduler_outbox")).WillReturnError(errors.New("outbox failed"))
|
||||
mock.ExpectRollback()
|
||||
@@ -177,9 +187,19 @@ func TestUpdateUpstreamBillingProbeSnapshotRollsBackWhenOutboxFails(t *testing.T
|
||||
Platform: service.PlatformOpenAI,
|
||||
Type: service.AccountTypeAPIKey,
|
||||
Credentials: map[string]any{"api_key": "sk-test"},
|
||||
Extra: map[string]any{
|
||||
service.UpstreamBillingProbeEnabledExtraKey: true,
|
||||
service.UpstreamBillingRateSyncEnabledExtraKey: true,
|
||||
},
|
||||
}
|
||||
rateMultiplier := 0.7
|
||||
|
||||
err = repo.UpdateUpstreamBillingProbeSnapshot(context.Background(), account, &service.UpstreamBillingProbeSnapshot{Status: service.UpstreamBillingProbeStatusOK})
|
||||
err = repo.UpdateUpstreamBillingProbeSnapshot(
|
||||
context.Background(),
|
||||
account,
|
||||
&service.UpstreamBillingProbeSnapshot{Status: service.UpstreamBillingProbeStatusOK},
|
||||
&rateMultiplier,
|
||||
)
|
||||
|
||||
require.EqualError(t, err, "outbox failed")
|
||||
require.NoError(t, mock.ExpectationsWereMet())
|
||||
|
||||
+51
@@ -153,3 +153,54 @@ func TestListDueUpstreamBillingProbeAccountsSelectsEarliestDueAcrossIDs(t *testi
|
||||
}
|
||||
require.Equal(t, want, got)
|
||||
}
|
||||
|
||||
// 探测资格放宽回归:任何 API-key 平台的启用账号都进入定时探测候选并按
|
||||
// 到期时间排序;OAuth 与未启用账号仍被排除。
|
||||
func TestListDueUpstreamBillingProbeAccountsIncludesAllAPIKeyPlatforms(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
tx := testEntTx(t)
|
||||
repo := newAccountRepositoryWithSQL(tx.Client(), tx, nil)
|
||||
now := time.Date(2026, time.July, 26, 3, 0, 0, 0, time.UTC)
|
||||
_, err := tx.ExecContext(ctx, `
|
||||
UPDATE accounts
|
||||
SET extra = extra - 'upstream_billing_probe_enabled' - 'upstream_billing_probe'
|
||||
`)
|
||||
require.NoError(t, err)
|
||||
|
||||
insert := func(name, platform, accountType, nextProbeAt string) int64 {
|
||||
t.Helper()
|
||||
var id int64
|
||||
extra := fmt.Sprintf(`{
|
||||
"upstream_billing_probe_enabled": true,
|
||||
"upstream_billing_probe": {"status": "ok", "next_probe_at": %q}
|
||||
}`, nextProbeAt)
|
||||
err := scanSingleRow(ctx, tx, `
|
||||
INSERT INTO accounts (name, platform, type, status, extra)
|
||||
VALUES ($1, $2, $3, 'active', $4::jsonb)
|
||||
RETURNING id
|
||||
`, []any{name, platform, accountType, extra}, &id)
|
||||
require.NoError(t, err)
|
||||
return id
|
||||
}
|
||||
|
||||
openaiDue := insert("probe-openai-due", "openai", service.AccountTypeAPIKey, "2026-07-26T02:57:00Z")
|
||||
anthropicDue := insert("probe-anthropic-due", "anthropic", service.AccountTypeAPIKey, "2026-07-26T02:58:00Z")
|
||||
grokDue := insert("probe-grok-due", "grok", service.AccountTypeAPIKey, "2026-07-26T02:59:00Z")
|
||||
// OAuth 账号即便误持有启用标记也不得入选。
|
||||
_ = insert("probe-grok-oauth-excluded", "grok", service.AccountTypeOAuth, "2026-07-26T02:59:00Z")
|
||||
// 未启用探测的 API-key 账号不入选。
|
||||
var disabledID int64
|
||||
err = scanSingleRow(ctx, tx, `
|
||||
INSERT INTO accounts (name, platform, type, status, extra)
|
||||
VALUES ('probe-grok-disabled', 'grok', $1, 'active', '{}'::jsonb)
|
||||
RETURNING id
|
||||
`, []any{service.AccountTypeAPIKey}, &disabledID)
|
||||
require.NoError(t, err)
|
||||
|
||||
accounts, err := repo.ListDueUpstreamBillingProbeAccounts(ctx, now, 20)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, accounts, 3)
|
||||
require.Equal(t, openaiDue, accounts[0].ID)
|
||||
require.Equal(t, anthropicDue, accounts[1].ID)
|
||||
require.Equal(t, grokDue, accounts[2].ID)
|
||||
}
|
||||
@@ -28,7 +28,8 @@ func TestAccountRepositoryListDueUpstreamBillingProbeAccountsBoundsQuery(t *test
|
||||
normalized := normalizeSQLWhitespace(capturedSQL)
|
||||
require.Contains(t, normalized, "deleted_at IS NULL")
|
||||
require.Contains(t, normalized, "status = 'active'")
|
||||
require.Contains(t, normalized, "platform = 'openai'")
|
||||
// 探测资格已放宽到全部 API-key 平台:候选 SQL 不得再按 platform 过滤。
|
||||
require.NotContains(t, normalized, "platform")
|
||||
require.Contains(t, normalized, "type = 'apikey'")
|
||||
require.Contains(t, normalized, `extra @> '{"upstream_billing_probe_enabled": true}'::jsonb`)
|
||||
require.Contains(t, normalized, "jsonb_path_query_first_tz")
|
||||
|
||||
@@ -81,8 +81,8 @@ func TestLockAndMergeAccountProbeExtraUsesCurrentDatabaseSnapshot(t *testing.T)
|
||||
|
||||
mock.ExpectQuery(`(?s)`+regexp.QuoteMeta("SELECT")+`.*`+regexp.QuoteMeta("FOR NO KEY UPDATE")).
|
||||
WithArgs(int64(27), service.PlatformOpenAI, service.AccountTypeAPIKey, `{"api_key":"sk-test"}`, nil).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"identity_unchanged", "ollama_group_unchanged", "ollama_proxy_unchanged", "enabled", "snapshot", "ollama_session", "ollama_auto", "ollama_snapshot"}).
|
||||
AddRow(tt.identityUnchanged, false, true, tt.databaseEnabled, tt.databaseSnapshot, nil, nil, nil))
|
||||
WillReturnRows(sqlmock.NewRows([]string{"identity_unchanged", "ollama_group_unchanged", "ollama_proxy_unchanged", "enabled", "rate_sync_enabled", "snapshot", "ollama_session", "ollama_auto", "ollama_snapshot"}).
|
||||
AddRow(tt.identityUnchanged, false, true, tt.databaseEnabled, nil, tt.databaseSnapshot, nil, nil, nil))
|
||||
|
||||
account := &service.Account{
|
||||
ID: 27,
|
||||
@@ -91,7 +91,7 @@ func TestLockAndMergeAccountProbeExtraUsesCurrentDatabaseSnapshot(t *testing.T)
|
||||
Credentials: map[string]any{"api_key": "sk-test"},
|
||||
Extra: tt.inputExtra,
|
||||
}
|
||||
got, err := lockAndMergeAccountProbeExtra(context.Background(), client, account, nil)
|
||||
got, err := lockAndMergeAccountProbeExtra(context.Background(), client, account, nil, nil)
|
||||
require.NoError(t, err)
|
||||
if tt.wantSnapshot == nil {
|
||||
require.NotContains(t, got, service.UpstreamBillingProbeExtraKey)
|
||||
@@ -104,6 +104,102 @@ func TestLockAndMergeAccountProbeExtraUsesCurrentDatabaseSnapshot(t *testing.T)
|
||||
}
|
||||
}
|
||||
|
||||
func probeBoolPtr(value bool) *bool {
|
||||
return &value
|
||||
}
|
||||
|
||||
// The probe switch drives the rate-sync switch and never the other way round:
|
||||
// syncing depends on probing, so a row where sync is on but the probe key is
|
||||
// missing must lose the sync flag instead of silently gaining periodic
|
||||
// outbound calls on the next unrelated edit.
|
||||
func TestLockAndMergeAccountProbeExtraNeverInfersProbeFromRateSync(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
databaseEnabled any
|
||||
databaseRateSync any
|
||||
explicitProbeEnabled *bool
|
||||
explicitRateSync *bool
|
||||
wantEnabled any
|
||||
wantRateSync any
|
||||
}{
|
||||
{
|
||||
name: "sync on with missing probe key zeroes sync and keeps probing off",
|
||||
databaseEnabled: nil,
|
||||
databaseRateSync: []byte(`true`),
|
||||
wantEnabled: nil,
|
||||
wantRateSync: false,
|
||||
},
|
||||
{
|
||||
name: "sync on with probe off zeroes sync",
|
||||
databaseEnabled: []byte(`false`),
|
||||
databaseRateSync: []byte(`true`),
|
||||
wantEnabled: false,
|
||||
wantRateSync: false,
|
||||
},
|
||||
{
|
||||
name: "both on in database stay on",
|
||||
databaseEnabled: []byte(`true`),
|
||||
databaseRateSync: []byte(`true`),
|
||||
wantEnabled: true,
|
||||
wantRateSync: true,
|
||||
},
|
||||
{
|
||||
name: "admin enabling both explicitly still turns probing on",
|
||||
databaseEnabled: nil,
|
||||
databaseRateSync: nil,
|
||||
explicitProbeEnabled: probeBoolPtr(true),
|
||||
explicitRateSync: probeBoolPtr(true),
|
||||
wantEnabled: true,
|
||||
wantRateSync: true,
|
||||
},
|
||||
{
|
||||
name: "explicit probe disable clears sync",
|
||||
databaseEnabled: []byte(`true`),
|
||||
databaseRateSync: []byte(`true`),
|
||||
explicitProbeEnabled: probeBoolPtr(false),
|
||||
wantEnabled: false,
|
||||
wantRateSync: false,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
db, mock, err := sqlmock.New()
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { _ = db.Close() })
|
||||
client := dbent.NewClient(dbent.Driver(entsql.OpenDB(dialect.Postgres, db)))
|
||||
t.Cleanup(func() { _ = client.Close() })
|
||||
|
||||
mock.ExpectQuery(`(?s)`+regexp.QuoteMeta("SELECT")+`.*`+regexp.QuoteMeta("FOR NO KEY UPDATE")).
|
||||
WithArgs(int64(31), service.PlatformOpenAI, service.AccountTypeAPIKey, `{"api_key":"sk-test"}`, nil).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"identity_unchanged", "ollama_group_unchanged", "ollama_proxy_unchanged", "enabled", "rate_sync_enabled", "snapshot", "ollama_session", "ollama_auto", "ollama_snapshot"}).
|
||||
AddRow(true, false, true, tt.databaseEnabled, tt.databaseRateSync, nil, nil, nil, nil))
|
||||
|
||||
account := &service.Account{
|
||||
ID: 31,
|
||||
Platform: service.PlatformOpenAI,
|
||||
Type: service.AccountTypeAPIKey,
|
||||
Credentials: map[string]any{"api_key": "sk-test"},
|
||||
}
|
||||
got, err := lockAndMergeAccountProbeExtra(
|
||||
context.Background(), client, account, tt.explicitProbeEnabled, tt.explicitRateSync,
|
||||
)
|
||||
require.NoError(t, err)
|
||||
if tt.wantEnabled == nil {
|
||||
require.NotContains(t, got, service.UpstreamBillingProbeEnabledExtraKey)
|
||||
} else {
|
||||
require.Equal(t, tt.wantEnabled, got[service.UpstreamBillingProbeEnabledExtraKey])
|
||||
}
|
||||
if tt.wantRateSync == nil {
|
||||
require.NotContains(t, got, service.UpstreamBillingRateSyncEnabledExtraKey)
|
||||
} else {
|
||||
require.Equal(t, tt.wantRateSync, got[service.UpstreamBillingRateSyncEnabledExtraKey])
|
||||
}
|
||||
require.NoError(t, mock.ExpectationsWereMet())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLockAndMergeAccountProbeExtraProtectsOllamaManagedFields(t *testing.T) {
|
||||
for _, identityUnchanged := range []bool{true, false} {
|
||||
t.Run(map[bool]string{true: "same identity keeps snapshot", false: "changed identity clears snapshot"}[identityUnchanged], func(t *testing.T) {
|
||||
@@ -115,8 +211,8 @@ func TestLockAndMergeAccountProbeExtraProtectsOllamaManagedFields(t *testing.T)
|
||||
|
||||
mock.ExpectQuery(`(?s)`+regexp.QuoteMeta("SELECT")+`.*`+regexp.QuoteMeta("FOR NO KEY UPDATE")).
|
||||
WithArgs(int64(29), service.PlatformAnthropic, service.AccountTypeAPIKey, `{"api_key":"key","base_url":"https://ollama.com"}`, nil).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"identity_unchanged", "ollama_group_unchanged", "ollama_proxy_unchanged", "enabled", "snapshot", "ollama_session", "ollama_auto", "ollama_snapshot"}).
|
||||
AddRow(identityUnchanged, identityUnchanged, true, nil, nil, []byte(`"local-ciphertext"`), []byte(`true`), []byte(`{"status":"ok"}`)))
|
||||
WillReturnRows(sqlmock.NewRows([]string{"identity_unchanged", "ollama_group_unchanged", "ollama_proxy_unchanged", "enabled", "rate_sync_enabled", "snapshot", "ollama_session", "ollama_auto", "ollama_snapshot"}).
|
||||
AddRow(identityUnchanged, identityUnchanged, true, nil, nil, nil, []byte(`"local-ciphertext"`), []byte(`true`), []byte(`{"status":"ok"}`)))
|
||||
|
||||
account := &service.Account{
|
||||
ID: 29, Platform: service.PlatformAnthropic, Type: service.AccountTypeAPIKey,
|
||||
@@ -127,7 +223,7 @@ func TestLockAndMergeAccountProbeExtraProtectsOllamaManagedFields(t *testing.T)
|
||||
service.OllamaCloudUsageSnapshotExtraKey: map[string]any{"status": "forged"},
|
||||
},
|
||||
}
|
||||
got, err := lockAndMergeAccountProbeExtra(context.Background(), client, account, nil)
|
||||
got, err := lockAndMergeAccountProbeExtra(context.Background(), client, account, nil, nil)
|
||||
require.NoError(t, err)
|
||||
if identityUnchanged {
|
||||
require.Equal(t, "local-ciphertext", got[service.OllamaCloudUsageSessionExtraKey])
|
||||
@@ -227,8 +323,8 @@ func TestBulkUpdateProbeEligibilityMismatchRollsBack(t *testing.T) {
|
||||
|
||||
enabled := true
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectExec(`(?s)UPDATE accounts SET extra = .* WHERE id = ANY\(\$2\) AND deleted_at IS NULL AND platform = \$3 AND type = \$4`).
|
||||
WithArgs(sqlmock.AnyArg(), `{27,28}`, service.PlatformOpenAI, service.AccountTypeAPIKey).
|
||||
mock.ExpectExec(`(?s)UPDATE accounts SET extra = .* WHERE id = ANY\(\$2\) AND deleted_at IS NULL AND type = \$3`).
|
||||
WithArgs(sqlmock.AnyArg(), `{27,28}`, service.AccountTypeAPIKey).
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
mock.ExpectRollback()
|
||||
|
||||
@@ -265,7 +361,7 @@ func TestUpdateCredentialsAtomicallyClearsProbeForOpenAIAPIKeyIdentityChange(t *
|
||||
require.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
|
||||
func TestUpdateWithUpstreamBillingProbeEnabledRollsBackWhenOutboxFails(t *testing.T) {
|
||||
func TestUpdateWithAccountBillingSettingsRollsBackWhenOutboxFails(t *testing.T) {
|
||||
db, mock, err := sqlmock.New()
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { _ = db.Close() })
|
||||
@@ -275,13 +371,13 @@ func TestUpdateWithUpstreamBillingProbeEnabledRollsBackWhenOutboxFails(t *testin
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectQuery(`(?s)`+regexp.QuoteMeta("SELECT")+`.*`+regexp.QuoteMeta("FOR NO KEY UPDATE")).
|
||||
WithArgs(int64(27), service.PlatformOpenAI, service.AccountTypeAPIKey, `{"api_key":"sk-test"}`, nil).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"identity_unchanged", "ollama_group_unchanged", "ollama_proxy_unchanged", "enabled", "snapshot", "ollama_session", "ollama_auto", "ollama_snapshot"}).
|
||||
AddRow(true, false, true, []byte(`true`), []byte(`{"status":"ok"}`), nil, nil, nil))
|
||||
WillReturnRows(sqlmock.NewRows([]string{"identity_unchanged", "ollama_group_unchanged", "ollama_proxy_unchanged", "enabled", "rate_sync_enabled", "snapshot", "ollama_session", "ollama_auto", "ollama_snapshot"}).
|
||||
AddRow(true, false, true, []byte(`true`), []byte(`true`), []byte(`{"status":"ok"}`), nil, nil, nil))
|
||||
mock.ExpectExec(`(?s)UPDATE .*accounts.*SET.*WHERE .*id.*`).
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
mock.ExpectQuery(`(?s)SELECT .* FROM "accounts" WHERE "id" = \$1`).
|
||||
WithArgs(int64(27)).
|
||||
WillReturnRows(updatedAccountRows(27, `{"upstream_billing_probe_enabled":false}`))
|
||||
WillReturnRows(updatedAccountRows(27, `{"upstream_billing_probe_enabled":false,"upstream_billing_rate_sync_enabled":false}`))
|
||||
mock.ExpectExec(regexp.QuoteMeta("INSERT INTO scheduler_outbox")).WillReturnError(errors.New("outbox failed"))
|
||||
mock.ExpectRollback()
|
||||
|
||||
@@ -301,10 +397,12 @@ func TestUpdateWithUpstreamBillingProbeEnabledRollsBackWhenOutboxFails(t *testin
|
||||
Schedulable: true,
|
||||
}
|
||||
|
||||
err = repo.UpdateWithUpstreamBillingProbeEnabled(context.Background(), account, false)
|
||||
probeDisabled := false
|
||||
err = repo.UpdateWithAccountBillingSettings(context.Background(), account, &probeDisabled, nil, nil)
|
||||
|
||||
require.EqualError(t, err, "outbox failed")
|
||||
require.Equal(t, false, account.Extra[service.UpstreamBillingProbeEnabledExtraKey])
|
||||
require.Equal(t, false, account.Extra[service.UpstreamBillingRateSyncEnabledExtraKey])
|
||||
require.NotContains(t, account.Extra, service.UpstreamBillingProbeExtraKey)
|
||||
require.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
|
||||
@@ -210,6 +210,12 @@ func (r *apiKeyRepository) GetByKeyForAuth(ctx context.Context, key string) (*se
|
||||
group.FieldPeakStart,
|
||||
group.FieldPeakEnd,
|
||||
group.FieldPeakRateMultiplier,
|
||||
// 分组利润控制:认证快照是调度门 enable 判定的直接来源,
|
||||
// 漏选会让门静默失效;新增快照分组字段时必须同步本投影,
|
||||
// 集成测试对账兜底。
|
||||
group.FieldProfitControlEnabled,
|
||||
group.FieldProfitMinMargin,
|
||||
group.FieldProfitSafetyBuffer,
|
||||
)
|
||||
}).
|
||||
Only(ctx)
|
||||
@@ -987,6 +993,9 @@ func groupEntityToService(g *dbent.Group) *service.Group {
|
||||
PeakStart: g.PeakStart,
|
||||
PeakEnd: g.PeakEnd,
|
||||
PeakRateMultiplier: g.PeakRateMultiplier,
|
||||
ProfitControlEnabled: g.ProfitControlEnabled,
|
||||
ProfitMinMargin: g.ProfitMinMargin,
|
||||
ProfitSafetyBuffer: g.ProfitSafetyBuffer,
|
||||
CreatedAt: g.CreatedAt,
|
||||
UpdatedAt: g.UpdatedAt,
|
||||
}
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
//go:build integration
|
||||
|
||||
package repository
|
||||
|
||||
// 投影漏列回归(repository 半程):真实 PostgreSQL 上认证专用
|
||||
// 查询 GetByKeyForAuth 的分组显式投影必须携带利润控制与计费字段。该查询是
|
||||
// 认证快照(进而是利润门 enable 判定)的唯一数据来源,漏选任何快照分组字段
|
||||
// 都会让对应功能在真实流量上静默失效。新增快照分组字段时必须同步扩展
|
||||
// GetByKeyForAuth 的 WithGroup Select 并在本测试补断言。
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestGetByKeyForAuthCarriesProfitControlProjection(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
suffix := time.Now().UnixNano()
|
||||
group := mustCreateGroup(t, integrationEntClient, &service.Group{
|
||||
Name: fmt.Sprintf("profit-proj-group-%d", suffix),
|
||||
Platform: service.PlatformOpenAI,
|
||||
RateMultiplier: 0.06,
|
||||
ProfitControlEnabled: true,
|
||||
ProfitMinMargin: 0.2,
|
||||
ProfitSafetyBuffer: 0.05,
|
||||
})
|
||||
user := mustCreateUser(t, integrationEntClient, &service.User{
|
||||
Email: fmt.Sprintf("profit-proj-%d@example.com", suffix), Concurrency: 5,
|
||||
})
|
||||
groupID := group.ID
|
||||
keyValue := fmt.Sprintf("sk-profit-proj-%d", suffix)
|
||||
apiKeyRepo := NewAPIKeyRepository(integrationEntClient, integrationDB)
|
||||
key := &service.APIKey{UserID: user.ID, GroupID: &groupID, Key: keyValue, Name: "profit-proj", Status: service.StatusActive}
|
||||
require.NoError(t, apiKeyRepo.Create(ctx, key))
|
||||
t.Cleanup(func() {
|
||||
_, err := integrationDB.ExecContext(ctx, "DELETE FROM auth_cache_invalidation_outbox WHERE cache_key = encode(sha256(convert_to($1, 'UTF8')), 'hex')", keyValue)
|
||||
require.NoError(t, err)
|
||||
_, err = integrationDB.ExecContext(ctx, "DELETE FROM api_keys WHERE id = $1", key.ID)
|
||||
require.NoError(t, err)
|
||||
_, err = integrationDB.ExecContext(ctx, "DELETE FROM users WHERE id = $1", user.ID)
|
||||
require.NoError(t, err)
|
||||
_, err = integrationDB.ExecContext(ctx, "DELETE FROM groups WHERE id = $1", group.ID)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
|
||||
got, err := apiKeyRepo.GetByKeyForAuth(ctx, keyValue)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, got.Group, "认证查询必须带出分组")
|
||||
|
||||
require.Equal(t, service.PlatformOpenAI, got.Group.Platform)
|
||||
require.InDelta(t, 0.06, got.Group.RateMultiplier, 1e-9)
|
||||
require.True(t, got.Group.ProfitControlEnabled, "profit_control_enabled 必须进入认证投影(投影漏列会让门静默失效)")
|
||||
require.InDelta(t, 0.2, got.Group.ProfitMinMargin, 1e-9)
|
||||
require.InDelta(t, 0.05, got.Group.ProfitSafetyBuffer, 1e-9)
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
//go:build integration
|
||||
|
||||
package repository
|
||||
|
||||
// migration 193 回归:groups 触发器的 durable 失效监视清单必须覆盖利润控制
|
||||
// 配置及 D 依赖的分组计价字段(正常后台保存走 InvalidateAuthCacheByGroupID 即时失效,触发器兜底
|
||||
// 直改 SQL / 更新与失效之间崩溃等 out-of-band 场景)。
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestAuthCacheInvalidationTrigger_ProfitControlColumns(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
suffix := time.Now().UnixNano()
|
||||
group := mustCreateGroup(t, integrationEntClient, &service.Group{
|
||||
Name: fmt.Sprintf("profit-trigger-group-%d", suffix), Platform: service.PlatformOpenAI, RateMultiplier: 1,
|
||||
})
|
||||
user := mustCreateUser(t, integrationEntClient, &service.User{
|
||||
Email: fmt.Sprintf("profit-trigger-%d@example.com", suffix), Concurrency: 5,
|
||||
})
|
||||
groupID := group.ID
|
||||
keyValue := fmt.Sprintf("sk-profit-trigger-%d", suffix)
|
||||
apiKeyRepo := NewAPIKeyRepository(integrationEntClient, integrationDB)
|
||||
key := &service.APIKey{UserID: user.ID, GroupID: &groupID, Key: keyValue, Name: "profit-trigger", Status: service.StatusActive}
|
||||
require.NoError(t, apiKeyRepo.Create(ctx, key))
|
||||
|
||||
sum := sha256.Sum256([]byte(keyValue))
|
||||
cacheKey := hex.EncodeToString(sum[:])
|
||||
clear := func() {
|
||||
_, err := integrationDB.ExecContext(ctx, "DELETE FROM auth_cache_invalidation_outbox WHERE cache_key = $1", cacheKey)
|
||||
require.NoError(t, err)
|
||||
}
|
||||
count := func() int {
|
||||
var value int
|
||||
require.NoError(t, integrationDB.QueryRowContext(ctx,
|
||||
"SELECT COUNT(*) FROM auth_cache_invalidation_outbox WHERE cache_key = $1", cacheKey).Scan(&value))
|
||||
return value
|
||||
}
|
||||
clear()
|
||||
t.Cleanup(clear)
|
||||
t.Cleanup(func() {
|
||||
_, err := integrationDB.ExecContext(ctx, "DELETE FROM api_keys WHERE id = $1", key.ID)
|
||||
require.NoError(t, err)
|
||||
_, err = integrationDB.ExecContext(ctx, "DELETE FROM users WHERE id = $1", user.ID)
|
||||
require.NoError(t, err)
|
||||
_, err = integrationDB.ExecContext(ctx, "DELETE FROM groups WHERE id = $1", group.ID)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
|
||||
_, err := integrationDB.ExecContext(ctx, "UPDATE groups SET name = name || '-cosmetic' WHERE id = $1", group.ID)
|
||||
require.NoError(t, err)
|
||||
require.Zero(t, count(), "cosmetic 更新不得入队(既有语义回归)")
|
||||
|
||||
_, err = integrationDB.ExecContext(ctx, "UPDATE groups SET profit_control_enabled = NOT profit_control_enabled WHERE id = $1", group.ID)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 1, count(), "profit_control_enabled 变更必须入队")
|
||||
clear()
|
||||
|
||||
_, err = integrationDB.ExecContext(ctx, "UPDATE groups SET profit_min_margin = 0.3 WHERE id = $1", group.ID)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 1, count(), "profit_min_margin 变更必须入队")
|
||||
clear()
|
||||
|
||||
_, err = integrationDB.ExecContext(ctx, "UPDATE groups SET profit_safety_buffer = 0.02 WHERE id = $1", group.ID)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 1, count(), "profit_safety_buffer 变更必须入队")
|
||||
clear()
|
||||
|
||||
_, err = integrationDB.ExecContext(ctx, "UPDATE groups SET profit_min_margin = profit_min_margin WHERE id = $1", group.ID)
|
||||
require.NoError(t, err)
|
||||
require.Zero(t, count(), "利润字段无实际变化的 UPDATE 不得入队")
|
||||
|
||||
for name, update := range map[string]string{
|
||||
"platform": "platform = 'anthropic'",
|
||||
"subscription_type": "subscription_type = 'subscription'",
|
||||
"rate_multiplier": "rate_multiplier = 0.9",
|
||||
"peak_rate_enabled": "peak_rate_enabled = true",
|
||||
"peak_start": "peak_start = '08:00'",
|
||||
"peak_end": "peak_end = '09:00'",
|
||||
"peak_rate_multiplier": "peak_rate_multiplier = 1.2",
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
clear()
|
||||
_, err := integrationDB.ExecContext(ctx, "UPDATE groups SET "+update+" WHERE id = $1", group.ID)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 1, count(), name+" 变更必须入队")
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -89,7 +89,10 @@ func mustCreateGroup(t *testing.T, client *dbent.Client, g *service.Group) *serv
|
||||
SetStatus(g.Status).
|
||||
SetSubscriptionType(g.SubscriptionType).
|
||||
SetRateMultiplier(g.RateMultiplier).
|
||||
SetIsExclusive(g.IsExclusive)
|
||||
SetIsExclusive(g.IsExclusive).
|
||||
SetProfitControlEnabled(g.ProfitControlEnabled).
|
||||
SetProfitMinMargin(g.ProfitMinMargin).
|
||||
SetProfitSafetyBuffer(g.ProfitSafetyBuffer)
|
||||
if g.Description != "" {
|
||||
create.SetDescription(g.Description)
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"time"
|
||||
@@ -31,7 +32,14 @@ func buildSessionKey(groupID int64, sessionHash string) string {
|
||||
|
||||
func (c *gatewayCache) GetSessionAccountID(ctx context.Context, groupID int64, sessionHash string) (int64, error) {
|
||||
key := buildSessionKey(groupID, sessionHash)
|
||||
return c.rdb.Get(ctx, key).Int64()
|
||||
accountID, err := c.rdb.Get(ctx, key).Int64()
|
||||
if err != nil {
|
||||
if errors.Is(err, redis.Nil) {
|
||||
return 0, service.ErrStickySessionNotFound
|
||||
}
|
||||
return 0, err
|
||||
}
|
||||
return accountID, nil
|
||||
}
|
||||
|
||||
func (c *gatewayCache) SetSessionAccountID(ctx context.Context, groupID int64, sessionHash string, accountID int64, ttl time.Duration) error {
|
||||
|
||||
@@ -8,7 +8,6 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/redis/go-redis/v9"
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/stretchr/testify/suite"
|
||||
)
|
||||
@@ -25,7 +24,7 @@ func (s *GatewayCacheSuite) SetupTest() {
|
||||
|
||||
func (s *GatewayCacheSuite) TestGetSessionAccountID_Missing() {
|
||||
_, err := s.cache.GetSessionAccountID(s.ctx, 1, "nonexistent")
|
||||
require.True(s.T(), errors.Is(err, redis.Nil), "expected redis.Nil for missing session")
|
||||
require.True(s.T(), errors.Is(err, service.ErrStickySessionNotFound), "expected ErrStickySessionNotFound for missing session")
|
||||
}
|
||||
|
||||
func (s *GatewayCacheSuite) TestSetAndGetSessionAccountID() {
|
||||
@@ -88,7 +87,7 @@ func (s *GatewayCacheSuite) TestDeleteSessionAccountID() {
|
||||
require.NoError(s.T(), s.cache.DeleteSessionAccountID(s.ctx, groupID, sessionID), "DeleteSessionAccountID")
|
||||
|
||||
_, err := s.cache.GetSessionAccountID(s.ctx, groupID, sessionID)
|
||||
require.True(s.T(), errors.Is(err, redis.Nil), "expected redis.Nil after delete")
|
||||
require.True(s.T(), errors.Is(err, service.ErrStickySessionNotFound), "expected ErrStickySessionNotFound after delete")
|
||||
}
|
||||
|
||||
func (s *GatewayCacheSuite) TestGetSessionAccountID_CorruptedValue() {
|
||||
@@ -101,7 +100,7 @@ func (s *GatewayCacheSuite) TestGetSessionAccountID_CorruptedValue() {
|
||||
|
||||
_, err := s.cache.GetSessionAccountID(s.ctx, groupID, sessionID)
|
||||
require.Error(s.T(), err, "expected error for corrupted value")
|
||||
require.False(s.T(), errors.Is(err, redis.Nil), "expected parsing error, not redis.Nil")
|
||||
require.False(s.T(), errors.Is(err, service.ErrStickySessionNotFound), "expected parsing error, not a miss")
|
||||
}
|
||||
|
||||
func TestGatewayCacheSuite(t *testing.T) {
|
||||
|
||||
@@ -102,7 +102,10 @@ func createGroupRecord(ctx context.Context, client *dbent.Client, groupIn *servi
|
||||
SetPeakRateEnabled(groupIn.PeakRateEnabled).
|
||||
SetPeakStart(groupIn.PeakStart).
|
||||
SetPeakEnd(groupIn.PeakEnd).
|
||||
SetPeakRateMultiplier(groupIn.PeakRateMultiplier)
|
||||
SetPeakRateMultiplier(groupIn.PeakRateMultiplier).
|
||||
SetProfitControlEnabled(groupIn.ProfitControlEnabled).
|
||||
SetProfitMinMargin(groupIn.ProfitMinMargin).
|
||||
SetProfitSafetyBuffer(groupIn.ProfitSafetyBuffer)
|
||||
if groupIn.DuplicateOperationID != "" {
|
||||
builder = builder.SetDuplicateOperationID(groupIn.DuplicateOperationID)
|
||||
}
|
||||
@@ -268,7 +271,10 @@ func (r *groupRepository) Update(ctx context.Context, groupIn *service.Group) er
|
||||
SetPeakRateEnabled(groupIn.PeakRateEnabled).
|
||||
SetPeakStart(groupIn.PeakStart).
|
||||
SetPeakEnd(groupIn.PeakEnd).
|
||||
SetPeakRateMultiplier(groupIn.PeakRateMultiplier)
|
||||
SetPeakRateMultiplier(groupIn.PeakRateMultiplier).
|
||||
SetProfitControlEnabled(groupIn.ProfitControlEnabled).
|
||||
SetProfitMinMargin(groupIn.ProfitMinMargin).
|
||||
SetProfitSafetyBuffer(groupIn.ProfitSafetyBuffer)
|
||||
|
||||
// 显式处理可空字段:nil 需要 clear,非 nil 需要 set。
|
||||
if groupIn.DailyLimitUSD != nil {
|
||||
|
||||
@@ -231,8 +231,7 @@ func invalidateProxyProbeSnapshots(ctx context.Context, exec sqlExecutor, proxyI
|
||||
WHERE proxy_id = $1
|
||||
AND type = 'apikey'
|
||||
AND (
|
||||
(platform = 'openai'
|
||||
AND extra ? 'upstream_billing_probe'
|
||||
(extra ? 'upstream_billing_probe'
|
||||
AND extra -> 'upstream_billing_probe' <> 'null'::jsonb)
|
||||
OR (platform IN ('openai', 'anthropic')
|
||||
AND extra ? 'ollama_cloud_usage_snapshot'
|
||||
@@ -747,7 +746,7 @@ func (r *proxyRepository) sweepOneExpiredProxyOnExec(ctx context.Context, exec s
|
||||
rows, err = exec.QueryContext(ctx, `
|
||||
UPDATE accounts SET proxy_id=NULL, proxy_fallback_origin_id=$1,
|
||||
extra=CASE
|
||||
WHEN platform='openai' AND type='apikey' AND extra ? 'upstream_billing_probe'
|
||||
WHEN type='apikey' AND extra ? 'upstream_billing_probe'
|
||||
THEN extra - 'upstream_billing_probe'
|
||||
ELSE extra
|
||||
END,
|
||||
@@ -758,7 +757,7 @@ func (r *proxyRepository) sweepOneExpiredProxyOnExec(ctx context.Context, exec s
|
||||
rows, err = exec.QueryContext(ctx, `
|
||||
UPDATE accounts SET proxy_id=$2, proxy_fallback_origin_id=$1,
|
||||
extra=CASE
|
||||
WHEN platform='openai' AND type='apikey' AND extra ? 'upstream_billing_probe'
|
||||
WHEN type='apikey' AND extra ? 'upstream_billing_probe'
|
||||
THEN extra - 'upstream_billing_probe'
|
||||
ELSE extra
|
||||
END,
|
||||
|
||||
@@ -33,7 +33,7 @@ func TestProxyUpdateInvalidatesBoundProbeSnapshotsAndEnqueuesOutboxAtomically(t
|
||||
WithArgs(int64(9)).
|
||||
WillReturnResult(sqlmock.NewResult(0, 0))
|
||||
expectProxyUpdateReload(mock, 9, "new.example", "user", "pass")
|
||||
mock.ExpectQuery(`(?s)UPDATE accounts.*- 'upstream_billing_probe'.*- 'ollama_cloud_usage_snapshot'.*type = 'apikey'.*platform = 'openai'.*extra \? 'upstream_billing_probe'.*platform IN \('openai', 'anthropic'\).*extra \? 'ollama_cloud_usage_snapshot'.*RETURNING id`).
|
||||
mock.ExpectQuery(`(?s)UPDATE accounts.*- 'upstream_billing_probe'.*- 'ollama_cloud_usage_snapshot'.*type = 'apikey'.*extra \? 'upstream_billing_probe'.*platform IN \('openai', 'anthropic'\).*extra \? 'ollama_cloud_usage_snapshot'.*RETURNING id`).
|
||||
WithArgs(int64(9)).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(int64(17)).AddRow(int64(18)))
|
||||
mock.ExpectExec(regexp.QuoteMeta("INSERT INTO scheduler_outbox (event_type, account_id, group_id, payload)")).
|
||||
@@ -76,7 +76,7 @@ func TestProxyUpdateRollsBackWhenProbeInvalidationOutboxFails(t *testing.T) {
|
||||
WithArgs(int64(9)).
|
||||
WillReturnResult(sqlmock.NewResult(0, 0))
|
||||
expectProxyUpdateReload(mock, 9, "new.example", "", "")
|
||||
mock.ExpectQuery(`(?s)UPDATE accounts.*- 'upstream_billing_probe'.*- 'ollama_cloud_usage_snapshot'.*type = 'apikey'.*platform = 'openai'.*extra \? 'upstream_billing_probe'.*platform IN \('openai', 'anthropic'\).*extra \? 'ollama_cloud_usage_snapshot'.*RETURNING id`).
|
||||
mock.ExpectQuery(`(?s)UPDATE accounts.*- 'upstream_billing_probe'.*- 'ollama_cloud_usage_snapshot'.*type = 'apikey'.*extra \? 'upstream_billing_probe'.*platform IN \('openai', 'anthropic'\).*extra \? 'ollama_cloud_usage_snapshot'.*RETURNING id`).
|
||||
WithArgs(int64(9)).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(int64(17)))
|
||||
mock.ExpectExec(regexp.QuoteMeta("INSERT INTO scheduler_outbox (event_type, account_id, group_id, payload)")).
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
//go:build unit
|
||||
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// TestSchedulerCachePreservesRateMultiplier 钉死账号调度快照的两份 payload
|
||||
// (full + metadata)都必须保留 RateMultiplier。
|
||||
//
|
||||
// 为什么值得一条专门的护栏:分组利润门对 nil RateMultiplier 是 fail-closed
|
||||
// (保守拒绝),与全系统其他地方不同——Account.BillingRateMultiplier() 对同样
|
||||
// 的 nil 返回 1.0,字段注释也写着「nil 表示按 1.0 处理」。DB 列有 Default(1.0)
|
||||
// 且非 nillable,因此 nil 只可能来自缓存反序列化缺字段。
|
||||
// buildSchedulerMetadataAccount 是显式字段清单,将来任何一次快照结构调整漏掉
|
||||
// 这一项,对启用利润控制的分组就是全组 no available accounts——而且是静默的。
|
||||
// 这条测试让那种漏列在 CI 就变红。
|
||||
func TestSchedulerCachePreservesRateMultiplier(t *testing.T) {
|
||||
rate := 0.75
|
||||
account := service.Account{
|
||||
ID: 9001,
|
||||
Name: "profit-gate-rate",
|
||||
Platform: service.PlatformOpenAI,
|
||||
Type: service.AccountTypeAPIKey,
|
||||
Status: service.StatusActive,
|
||||
Schedulable: true,
|
||||
Concurrency: 2,
|
||||
RateMultiplier: &rate,
|
||||
}
|
||||
|
||||
t.Run("metadata payload keeps the field", func(t *testing.T) {
|
||||
meta := buildSchedulerMetadataAccount(account)
|
||||
require.NotNil(t, meta.RateMultiplier, "metadata 快照漏掉 rate_multiplier 会让利润门 fail-closed 全组拒绝")
|
||||
require.Equal(t, rate, *meta.RateMultiplier)
|
||||
})
|
||||
|
||||
t.Run("both payloads survive a decode round-trip", func(t *testing.T) {
|
||||
full, meta, err := marshalSchedulerCacheAccount(account)
|
||||
require.NoError(t, err)
|
||||
|
||||
for name, payload := range map[string][]byte{"full": full, "metadata": meta} {
|
||||
decoded, decodeErr := decodeCachedAccount(payload)
|
||||
require.NoError(t, decodeErr, name)
|
||||
require.NotNil(t, decoded.RateMultiplier, "%s payload 反序列化后 rate_multiplier 不得为 nil", name)
|
||||
require.Equal(t, rate, *decoded.RateMultiplier, name)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("zero rate survives as zero rather than nil", func(t *testing.T) {
|
||||
// 0 是合法值(该账号上游成本为 0),绝不能被当成缺字段丢掉:
|
||||
// 丢成 nil 后利润门会把一个本该必然放行的账号判成越线。
|
||||
zero := 0.0
|
||||
zeroAccount := account
|
||||
zeroAccount.ID = 9002
|
||||
zeroAccount.RateMultiplier = &zero
|
||||
|
||||
_, meta, err := marshalSchedulerCacheAccount(zeroAccount)
|
||||
require.NoError(t, err)
|
||||
decoded, err := decodeCachedAccount(meta)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, decoded.RateMultiplier)
|
||||
require.Equal(t, 0.0, *decoded.RateMultiplier)
|
||||
})
|
||||
|
||||
t.Run("SetAccount then GetAccount preserves the field", func(t *testing.T) {
|
||||
cache := newSchedulerCacheUnit(t)
|
||||
ctx := context.Background()
|
||||
require.NoError(t, cache.SetAccount(ctx, &account))
|
||||
|
||||
got, err := cache.GetAccount(ctx, account.ID)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, got)
|
||||
require.NotNil(t, got.RateMultiplier, "端到端缓存读写后 rate_multiplier 不得丢失")
|
||||
require.Equal(t, rate, *got.RateMultiplier)
|
||||
})
|
||||
}
|
||||
+152
-3
@@ -30,7 +30,7 @@ func TestAccountUpdatePreservesConcurrentProbeSnapshot(t *testing.T) {
|
||||
require.NoError(t, repo.UpdateUpstreamBillingProbeSnapshot(ctx, stale, &service.UpstreamBillingProbeSnapshot{
|
||||
Status: service.UpstreamBillingProbeStatusOK,
|
||||
LastAttemptAt: time.Now().UTC(),
|
||||
}))
|
||||
}, nil))
|
||||
|
||||
stale.Name = "ordinary-edit"
|
||||
require.NoError(t, repo.Update(ctx, stale))
|
||||
@@ -46,6 +46,115 @@ func TestAccountUpdatePreservesConcurrentProbeSnapshot(t *testing.T) {
|
||||
require.NotContains(t, disabled.Extra, service.UpstreamBillingProbeExtraKey)
|
||||
}
|
||||
|
||||
func TestAdminAccountEditPreservesRateSynchronizedAfterLoad(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
tx := testEntTx(t)
|
||||
repo := newAccountRepositoryWithSQL(tx.Client(), tx, nil)
|
||||
initialRate := 0.1
|
||||
account := mustCreateAccount(t, tx.Client(), &service.Account{
|
||||
Name: "probe-rate-concurrent-edit",
|
||||
Platform: service.PlatformOpenAI,
|
||||
Type: service.AccountTypeAPIKey,
|
||||
RateMultiplier: &initialRate,
|
||||
Credentials: map[string]any{"api_key": "sk-test"},
|
||||
Extra: map[string]any{
|
||||
service.UpstreamBillingProbeEnabledExtraKey: true,
|
||||
service.UpstreamBillingRateSyncEnabledExtraKey: true,
|
||||
},
|
||||
})
|
||||
|
||||
staleAdminEdit, err := repo.GetByID(ctx, account.ID)
|
||||
require.NoError(t, err)
|
||||
probeAccount, err := repo.GetByID(ctx, account.ID)
|
||||
require.NoError(t, err)
|
||||
|
||||
synchronizedRate := 0.2
|
||||
require.NoError(t, repo.UpdateUpstreamBillingProbeSnapshot(ctx, probeAccount, &service.UpstreamBillingProbeSnapshot{
|
||||
Status: service.UpstreamBillingProbeStatusOK,
|
||||
LastAttemptAt: time.Now().UTC(),
|
||||
}, &synchronizedRate))
|
||||
|
||||
staleAdminEdit.Name = "name-only-edit"
|
||||
require.NoError(t, repo.UpdateWithAccountBillingSettings(ctx, staleAdminEdit, nil, nil, nil))
|
||||
|
||||
got, err := repo.GetByID(ctx, account.ID)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "name-only-edit", got.Name)
|
||||
require.NotNil(t, got.RateMultiplier)
|
||||
require.Equal(t, synchronizedRate, *got.RateMultiplier)
|
||||
}
|
||||
|
||||
func TestProbeSnapshotSyncsRateOnlyForSuccessfulEnabledAccount(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
tx := testEntTx(t)
|
||||
repo := newAccountRepositoryWithSQL(tx.Client(), tx, nil)
|
||||
initialRate := 0.25
|
||||
account := mustCreateAccount(t, tx.Client(), &service.Account{
|
||||
Name: "probe-rate-sync",
|
||||
Platform: service.PlatformGemini,
|
||||
Type: service.AccountTypeAPIKey,
|
||||
RateMultiplier: &initialRate,
|
||||
Credentials: map[string]any{"api_key": "sk-test"},
|
||||
Extra: map[string]any{
|
||||
service.UpstreamBillingProbeEnabledExtraKey: true,
|
||||
service.UpstreamBillingRateSyncEnabledExtraKey: true,
|
||||
},
|
||||
})
|
||||
|
||||
loaded, err := repo.GetByID(ctx, account.ID)
|
||||
require.NoError(t, err)
|
||||
syncedRate := 0.065
|
||||
require.NoError(t, repo.UpdateUpstreamBillingProbeSnapshot(ctx, loaded, &service.UpstreamBillingProbeSnapshot{
|
||||
Status: service.UpstreamBillingProbeStatusOK,
|
||||
LastAttemptAt: time.Now().UTC(),
|
||||
}, &syncedRate))
|
||||
|
||||
got, err := repo.GetByID(ctx, account.ID)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, got.RateMultiplier)
|
||||
require.Equal(t, syncedRate, *got.RateMultiplier)
|
||||
|
||||
failedRate := 0.9
|
||||
require.NoError(t, repo.UpdateUpstreamBillingProbeSnapshot(ctx, got, &service.UpstreamBillingProbeSnapshot{
|
||||
Status: service.UpstreamBillingProbeStatusFailed,
|
||||
LastAttemptAt: time.Now().UTC(),
|
||||
}, &failedRate))
|
||||
got, err = repo.GetByID(ctx, account.ID)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, got.RateMultiplier)
|
||||
require.Equal(t, syncedRate, *got.RateMultiplier)
|
||||
|
||||
require.NoError(t, repo.UpdateExtra(ctx, account.ID, map[string]any{
|
||||
service.UpstreamBillingRateSyncEnabledExtraKey: false,
|
||||
}))
|
||||
manual, err := repo.GetByID(ctx, account.ID)
|
||||
require.NoError(t, err)
|
||||
manualProbeRate := 0.4
|
||||
require.NoError(t, repo.UpdateUpstreamBillingProbeSnapshot(ctx, manual, &service.UpstreamBillingProbeSnapshot{
|
||||
Status: service.UpstreamBillingProbeStatusOK,
|
||||
LastAttemptAt: time.Now().UTC(),
|
||||
}, &manualProbeRate))
|
||||
got, err = repo.GetByID(ctx, account.ID)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, got.RateMultiplier)
|
||||
require.Equal(t, syncedRate, *got.RateMultiplier)
|
||||
|
||||
require.NoError(t, repo.UpdateExtra(ctx, account.ID, map[string]any{
|
||||
service.UpstreamBillingProbeEnabledExtraKey: false,
|
||||
service.UpstreamBillingRateSyncEnabledExtraKey: false,
|
||||
}))
|
||||
disabled, err := repo.GetByID(ctx, account.ID)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, repo.UpdateUpstreamBillingProbeSnapshot(ctx, disabled, &service.UpstreamBillingProbeSnapshot{
|
||||
Status: service.UpstreamBillingProbeStatusOK,
|
||||
LastAttemptAt: time.Now().UTC(),
|
||||
}, &manualProbeRate))
|
||||
got, err = repo.GetByID(ctx, account.ID)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, got.RateMultiplier)
|
||||
require.Equal(t, syncedRate, *got.RateMultiplier)
|
||||
}
|
||||
|
||||
func TestAccountUpdatePreservesConcurrentProbeEnableFlag(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
tx := testEntTx(t)
|
||||
@@ -166,7 +275,7 @@ func TestProbeSnapshotCASIncludesLoadedEnabledState(t *testing.T) {
|
||||
err = repo.UpdateUpstreamBillingProbeSnapshot(ctx, inFlight, &service.UpstreamBillingProbeSnapshot{
|
||||
Status: service.UpstreamBillingProbeStatusOK,
|
||||
LastAttemptAt: time.Now().UTC(),
|
||||
})
|
||||
}, nil)
|
||||
if tt.wantConflict {
|
||||
require.ErrorIs(t, err, service.ErrUpstreamBillingProbeIdentityChanged)
|
||||
} else {
|
||||
@@ -183,6 +292,46 @@ func TestProbeSnapshotCASIncludesLoadedEnabledState(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestProbeSnapshotCASProtectsManualRateAfterSyncDisabled(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
tx := testEntTx(t)
|
||||
repo := newAccountRepositoryWithSQL(tx.Client(), tx, nil)
|
||||
initialRate := 0.25
|
||||
account := mustCreateAccount(t, tx.Client(), &service.Account{
|
||||
Name: "probe-sync-cas",
|
||||
Platform: service.PlatformAnthropic,
|
||||
Type: service.AccountTypeAPIKey,
|
||||
RateMultiplier: &initialRate,
|
||||
Credentials: map[string]any{"api_key": "sk-test"},
|
||||
Extra: map[string]any{
|
||||
service.UpstreamBillingProbeEnabledExtraKey: true,
|
||||
service.UpstreamBillingRateSyncEnabledExtraKey: true,
|
||||
},
|
||||
})
|
||||
|
||||
inFlight, err := repo.GetByID(ctx, account.ID)
|
||||
require.NoError(t, err)
|
||||
manual, err := repo.GetByID(ctx, account.ID)
|
||||
require.NoError(t, err)
|
||||
manualRate := 0.8
|
||||
syncDisabled := false
|
||||
require.NoError(t, repo.UpdateWithAccountBillingSettings(ctx, manual, nil, &syncDisabled, &manualRate))
|
||||
|
||||
probedRate := 0.1
|
||||
err = repo.UpdateUpstreamBillingProbeSnapshot(ctx, inFlight, &service.UpstreamBillingProbeSnapshot{
|
||||
Status: service.UpstreamBillingProbeStatusOK,
|
||||
LastAttemptAt: time.Now().UTC(),
|
||||
}, &probedRate)
|
||||
require.ErrorIs(t, err, service.ErrUpstreamBillingProbeIdentityChanged)
|
||||
|
||||
got, err := repo.GetByID(ctx, account.ID)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, got.RateMultiplier)
|
||||
require.Equal(t, manualRate, *got.RateMultiplier)
|
||||
require.Equal(t, false, got.Extra[service.UpstreamBillingRateSyncEnabledExtraKey])
|
||||
require.NotContains(t, got.Extra, service.UpstreamBillingProbeExtraKey)
|
||||
}
|
||||
|
||||
func boolPtr(value bool) *bool {
|
||||
return &value
|
||||
}
|
||||
@@ -249,7 +398,7 @@ func TestProxyIdentityUpdateInvalidatesProbeAndRejectsInFlightSnapshot(t *testin
|
||||
err = accountRepo.UpdateUpstreamBillingProbeSnapshot(ctx, inFlight, &service.UpstreamBillingProbeSnapshot{
|
||||
Status: service.UpstreamBillingProbeStatusOK,
|
||||
LastAttemptAt: time.Now().UTC(),
|
||||
})
|
||||
}, nil)
|
||||
require.ErrorIs(t, err, service.ErrUpstreamBillingProbeIdentityChanged)
|
||||
|
||||
rows, err := tx.QueryContext(ctx, `
|
||||
|
||||
@@ -859,6 +859,49 @@ func (r *userRepository) DeductBalance(ctx context.Context, id int64, amount flo
|
||||
return nil
|
||||
}
|
||||
|
||||
// DeductAvailableBalance atomically deducts min(amount, max(balance, 0)).
|
||||
// Unlike DeductBalance, this refund-specific operation never increases an
|
||||
// existing deficit or permits a concurrent deduction to cause an overdraft.
|
||||
func (r *userRepository) DeductAvailableBalance(ctx context.Context, id int64, amount float64) (deducted float64, err error) {
|
||||
if amount < 0 {
|
||||
return 0, fmt.Errorf("deduction amount must be nonnegative")
|
||||
}
|
||||
const updateSQL = `
|
||||
WITH target AS (
|
||||
SELECT id, balance
|
||||
FROM users
|
||||
WHERE id = $2 AND deleted_at IS NULL
|
||||
FOR UPDATE
|
||||
), updated AS (
|
||||
UPDATE users AS u
|
||||
SET balance = target.balance - LEAST($1, GREATEST(target.balance, 0)), updated_at = NOW()
|
||||
FROM target
|
||||
WHERE u.id = target.id AND u.deleted_at IS NULL
|
||||
RETURNING target.balance - u.balance AS deducted
|
||||
)
|
||||
SELECT deducted FROM updated
|
||||
`
|
||||
rows, err := clientFromContext(ctx, r.client).QueryContext(ctx, updateSQL, amount, id)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
defer func() {
|
||||
if closeErr := rows.Close(); closeErr != nil && err == nil {
|
||||
err = closeErr
|
||||
}
|
||||
}()
|
||||
if !rows.Next() {
|
||||
if rowsErr := rows.Err(); rowsErr != nil {
|
||||
return 0, rowsErr
|
||||
}
|
||||
return 0, service.ErrUserNotFound
|
||||
}
|
||||
if err := rows.Scan(&deducted); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return deducted, rows.Err()
|
||||
}
|
||||
|
||||
// AdjustBalance 原子地把 delta 累加到余额上,结果为负时整条语句不生效。
|
||||
// 相比"读余额 → 算新值 → 整行写回",这里把读与写压进同一条 UPDATE,
|
||||
// 并发的计费扣款不会被旧快照覆盖。
|
||||
|
||||
@@ -4,6 +4,7 @@ package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -479,6 +480,30 @@ func (s *UserRepoSuite) TestDeductBalance_AllowsOverdraft() {
|
||||
s.Require().InDelta(-5.0, got.Balance, 1e-6, "Balance should be -5.0 after overdraft")
|
||||
}
|
||||
|
||||
func (s *UserRepoSuite) TestDeductAvailableBalance_ClampsToNonnegativeBalance() {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
balance float64
|
||||
requested float64
|
||||
wantDeduct float64
|
||||
wantBalance float64
|
||||
}{
|
||||
{name: "enough balance", balance: 10, requested: 4, wantDeduct: 4, wantBalance: 6},
|
||||
{name: "insufficient balance", balance: 5, requested: 10, wantDeduct: 5, wantBalance: 0},
|
||||
{name: "negative balance unchanged", balance: -3, requested: 10, wantDeduct: 0, wantBalance: -3},
|
||||
} {
|
||||
s.Run(tc.name, func() {
|
||||
user := s.mustCreateUser(&service.User{Email: "available-" + strings.ReplaceAll(tc.name, " ", "-") + "@test.com", Balance: tc.balance})
|
||||
deducted, err := s.repo.DeductAvailableBalance(s.ctx, user.ID, tc.requested)
|
||||
s.Require().NoError(err)
|
||||
s.Require().InDelta(tc.wantDeduct, deducted, 1e-6)
|
||||
got, err := s.repo.GetByID(s.ctx, user.ID)
|
||||
s.Require().NoError(err)
|
||||
s.Require().InDelta(tc.wantBalance, got.Balance, 1e-6)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// --- Concurrency ---
|
||||
|
||||
func (s *UserRepoSuite) TestUpdateConcurrency() {
|
||||
|
||||
@@ -314,19 +314,23 @@ func TestAPIContracts(t *testing.T) {
|
||||
name: "GET /api/v1/groups/available",
|
||||
setup: func(t *testing.T, deps *contractDeps) {
|
||||
t.Helper()
|
||||
// 普通用户可见的分组列表不应包含内部字段(如 model_routing/account_count)。
|
||||
// 普通用户可见的分组列表不应包含内部字段(如 model_routing/account_count),
|
||||
// 也不得包含利润控制配置——它与同响应的 rate_multiplier 相乘即可反推上游成本上限。
|
||||
deps.groupRepo.SetActive([]service.Group{
|
||||
{
|
||||
ID: 10,
|
||||
Name: "Group One",
|
||||
Description: "desc",
|
||||
Platform: service.PlatformAnthropic,
|
||||
RateMultiplier: 1.5,
|
||||
PeakRateMultiplier: 1.0,
|
||||
IsExclusive: false,
|
||||
Status: service.StatusActive,
|
||||
SubscriptionType: service.SubscriptionTypeStandard,
|
||||
ModelRoutingEnabled: true,
|
||||
ID: 10,
|
||||
Name: "Group One",
|
||||
Description: "desc",
|
||||
Platform: service.PlatformAnthropic,
|
||||
RateMultiplier: 1.5,
|
||||
PeakRateMultiplier: 1.0,
|
||||
IsExclusive: false,
|
||||
Status: service.StatusActive,
|
||||
SubscriptionType: service.SubscriptionTypeStandard,
|
||||
ProfitControlEnabled: true,
|
||||
ProfitMinMargin: 0.3,
|
||||
ProfitSafetyBuffer: 0.05,
|
||||
ModelRoutingEnabled: true,
|
||||
ModelRouting: map[string][]int64{
|
||||
"claude-3-*": []int64{101, 102},
|
||||
},
|
||||
@@ -922,6 +926,9 @@ func TestAPIContracts(t *testing.T) {
|
||||
"openai_advanced_scheduler_effective_weight_previous_response": "5",
|
||||
"openai_advanced_scheduler_effective_weight_session_sticky": "3",
|
||||
"openai_codex_user_agent": "",
|
||||
"openai_codex_client_version": "",
|
||||
"openai_codex_client_version_synced": "",
|
||||
"openai_codex_version_auto_sync_enabled": true,
|
||||
"openai_fast_policy_settings": {
|
||||
"rules": []
|
||||
},
|
||||
@@ -1212,6 +1219,9 @@ func TestAPIContracts(t *testing.T) {
|
||||
"openai_advanced_scheduler_effective_weight_previous_response": "5",
|
||||
"openai_advanced_scheduler_effective_weight_session_sticky": "3",
|
||||
"openai_codex_user_agent": "",
|
||||
"openai_codex_client_version": "",
|
||||
"openai_codex_client_version_synced": "",
|
||||
"openai_codex_version_auto_sync_enabled": true,
|
||||
"openai_fast_policy_settings": {
|
||||
"rules": []
|
||||
},
|
||||
@@ -1819,6 +1829,16 @@ func (s *stubAccountRepo) Update(ctx context.Context, account *service.Account)
|
||||
return errors.New("not implemented")
|
||||
}
|
||||
|
||||
func (s *stubAccountRepo) UpdateWithAccountBillingSettings(
|
||||
ctx context.Context,
|
||||
account *service.Account,
|
||||
probeEnabled *bool,
|
||||
rateSyncEnabled *bool,
|
||||
rateMultiplier *float64,
|
||||
) error {
|
||||
return errors.New("not implemented")
|
||||
}
|
||||
|
||||
func (s *stubAccountRepo) Delete(ctx context.Context, id int64) error {
|
||||
return errors.New("not implemented")
|
||||
}
|
||||
|
||||
@@ -437,6 +437,7 @@ func registerOpenAIOAuthRoutes(admin *gin.RouterGroup, h *handler.Handlers) {
|
||||
openai.POST("/create-from-oauth", h.Admin.OpenAIOAuth.CreateAccountFromOAuth)
|
||||
openai.POST("/create-from-codex-pat", h.Admin.OpenAIOAuth.CreateAccountFromCodexPAT)
|
||||
openai.GET("/accounts/:id/quota", h.Admin.OpenAIOAuth.QueryQuota)
|
||||
openai.POST("/accounts/:id/quota/refresh", h.Admin.OpenAIOAuth.RefreshQuota)
|
||||
openai.POST("/accounts/:id/reset-quota", h.Admin.OpenAIOAuth.ResetQuota)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -131,11 +131,25 @@ type AccountDuplicateRepository interface {
|
||||
CreateWithAccountGroups(ctx context.Context, account *Account, groups []AccountGroup) error
|
||||
}
|
||||
|
||||
// AccountBillingSettingsRepository applies an admin edit without overwriting a
|
||||
// rate_multiplier that a successful upstream probe synchronized after the edit
|
||||
// form was loaded. A nil rateMultiplier means the request did not edit it.
|
||||
type AccountBillingSettingsRepository interface {
|
||||
UpdateWithAccountBillingSettings(
|
||||
ctx context.Context,
|
||||
account *Account,
|
||||
probeEnabled *bool,
|
||||
rateSyncEnabled *bool,
|
||||
rateMultiplier *float64,
|
||||
) error
|
||||
}
|
||||
|
||||
// AdminAccountRepository makes the account-duplication write capability an explicit
|
||||
// construction dependency without forcing read-only gateway test doubles to implement it.
|
||||
type AdminAccountRepository interface {
|
||||
AccountRepository
|
||||
AccountDuplicateRepository
|
||||
AccountBillingSettingsRepository
|
||||
}
|
||||
|
||||
// AccountBulkUpdate describes the fields that can be updated in a bulk operation.
|
||||
|
||||
@@ -653,8 +653,9 @@ func (s *AccountTestService) testOpenAIAccountConnection(c *gin.Context, account
|
||||
req.Header.Set("User-Agent", codexCLIUserAgent)
|
||||
}
|
||||
setOpenAIChatGPTAccountHeaders(req.Header, credentialAccount)
|
||||
// 与真实转发一致:originator 与最终 User-Agent 首段配套,否则上游 404(issue #3901)。
|
||||
enforceCodexIdentityHeaders(req.Header)
|
||||
// 与真实转发一致:账号级自定义 UA 同样作为管理员显式配置传入,否则测试用的身份
|
||||
// 与该账号真实出站的身份不是同一个(issue #3901 的配对不变式由收口保证)。
|
||||
enforceCodexIdentityHeadersWithUA(req.Header, credentialAccount.GetOpenAIUserAgent())
|
||||
}
|
||||
|
||||
// 账号级请求头覆写:测试请求与真实转发保持一致的最终头
|
||||
@@ -1866,8 +1867,9 @@ func (s *AccountTestService) testOpenAIImageOAuth(c *gin.Context, ctx context.Co
|
||||
req.Header.Set("User-Agent", codexCLIUserAgent)
|
||||
}
|
||||
setOpenAIChatGPTAccountHeaders(req.Header, credentialAccount)
|
||||
// 与真实转发一致:originator 与最终 User-Agent 首段配套(原 opencode 与 Codex UA 错配会 404,issue #3901)。
|
||||
enforceCodexIdentityHeaders(req.Header)
|
||||
// 与真实转发一致:账号级自定义 UA 同样作为管理员显式配置传入,否则测试用的身份
|
||||
// 与该账号真实出站的身份不是同一个(issue #3901 的配对不变式由收口保证)。
|
||||
enforceCodexIdentityHeadersWithUA(req.Header, credentialAccount.GetOpenAIUserAgent())
|
||||
|
||||
proxyURL := ""
|
||||
if account.ProxyID != nil && account.Proxy != nil {
|
||||
|
||||
@@ -113,7 +113,7 @@ const (
|
||||
openAIProbeCacheTTL = 10 * time.Minute
|
||||
grokProbeRetryTTL = 1 * time.Minute
|
||||
grokFreeQuotaWindow = 24 * time.Hour
|
||||
openAICodexProbeVersion = "0.144.1"
|
||||
openAICodexProbeVersion = codexCLIVersion // 与网关出站身份同源,避免两处硬编码版本各自漂移
|
||||
)
|
||||
|
||||
// UsageCache 封装账户使用量相关的缓存
|
||||
@@ -767,9 +767,10 @@ func (s *AccountUsageService) probeOpenAICodexSnapshot(ctx context.Context, acco
|
||||
req.Header.Set("User-Agent", strings.TrimSpace(fp.UserAgent))
|
||||
}
|
||||
}
|
||||
// 与真实转发一致:originator 与最终 User-Agent(可能来自指纹缓存,如 codex-tui)首段配套,
|
||||
// 否则探针被上游 404(issue #3901)。
|
||||
enforceCodexIdentityHeaders(req.Header)
|
||||
// 与真实转发一致:账号级自定义 UA 同样作为管理员显式配置传入。
|
||||
// 上面写进 header 的指纹缓存 UA 只在强制统一被关闭时才参与配对(保持回滚后的历史语义);
|
||||
// 强制统一开启时客户端身份不参与构造,探针与真实转发用同一套规范身份出站。
|
||||
enforceCodexIdentityHeadersWithUA(req.Header, account.GetOpenAIUserAgent())
|
||||
setOpenAIChatGPTAccountHeaders(req.Header, account)
|
||||
|
||||
proxyURL := ""
|
||||
|
||||
@@ -455,6 +455,7 @@ func normalizeGrokMediaEligibilityUpdateExtra(account *Account, input *UpdateAcc
|
||||
func buildAccountForCreate(input *CreateAccountInput, accountExtra map[string]any) (*Account, error) {
|
||||
// Probe/session state is system-managed. New accounts always start with automatic refresh disabled.
|
||||
delete(accountExtra, UpstreamBillingProbeEnabledExtraKey)
|
||||
delete(accountExtra, UpstreamBillingRateSyncEnabledExtraKey)
|
||||
delete(accountExtra, UpstreamBillingProbeExtraKey)
|
||||
delete(accountExtra, OllamaCloudUsageSessionExtraKey)
|
||||
delete(accountExtra, OllamaCloudUsageAutoRefreshExtraKey)
|
||||
@@ -594,10 +595,6 @@ func (s *adminServiceImpl) CreateAccount(ctx context.Context, input *CreateAccou
|
||||
return account, nil
|
||||
}
|
||||
|
||||
type accountProbeEnabledAtomicUpdater interface {
|
||||
UpdateWithUpstreamBillingProbeEnabled(context.Context, *Account, bool) error
|
||||
}
|
||||
|
||||
func (s *adminServiceImpl) UpdateAccount(ctx context.Context, id int64, input *UpdateAccountInput) (*Account, error) {
|
||||
account, err := s.accountRepo.GetByID(ctx, id)
|
||||
if err != nil {
|
||||
@@ -667,7 +664,8 @@ func (s *adminServiceImpl) UpdateAccount(ctx context.Context, id int64, input *U
|
||||
}
|
||||
// Extra 使用 map:需要区分“未提供(nil)”与“显式清空({})”。
|
||||
// 关闭配额限制时前端会删除 quota_* 键并提交 extra:{},此时也必须落库。
|
||||
var requestedProbeEnabledUpdate *bool
|
||||
requestedProbeEnabledUpdate := input.ProbeEnabled
|
||||
requestedRateSyncEnabledUpdate := input.RateSyncEnabled
|
||||
if input.Extra != nil {
|
||||
requestedProbeEnabled, hasRequestedProbeEnabled := normalizedExtra[UpstreamBillingProbeEnabledExtraKey]
|
||||
if hasRequestedProbeEnabled {
|
||||
@@ -675,9 +673,13 @@ func (s *adminServiceImpl) UpdateAccount(ctx context.Context, id int64, input *U
|
||||
if !ok {
|
||||
return nil, infraerrors.BadRequest("INVALID_UPSTREAM_BILLING_PROBE_ENABLED", "upstream_billing_probe_enabled must be a boolean")
|
||||
}
|
||||
if requestedProbeEnabledUpdate != nil && *requestedProbeEnabledUpdate != enabled {
|
||||
return nil, infraerrors.BadRequest("CONFLICTING_UPSTREAM_BILLING_PROBE_ENABLED", "conflicting upstream_billing_probe_enabled values")
|
||||
}
|
||||
requestedProbeEnabledUpdate = &enabled
|
||||
}
|
||||
delete(normalizedExtra, UpstreamBillingProbeEnabledExtraKey)
|
||||
delete(normalizedExtra, UpstreamBillingRateSyncEnabledExtraKey)
|
||||
delete(normalizedExtra, UpstreamBillingProbeExtraKey)
|
||||
delete(normalizedExtra, OllamaCloudUsageSessionExtraKey)
|
||||
delete(normalizedExtra, OllamaCloudUsageAutoRefreshExtraKey)
|
||||
@@ -691,6 +693,7 @@ func (s *adminServiceImpl) UpdateAccount(ctx context.Context, id int64, input *U
|
||||
"quota_weekly_start",
|
||||
grokBillingExtraKey,
|
||||
UpstreamBillingProbeEnabledExtraKey,
|
||||
UpstreamBillingRateSyncEnabledExtraKey,
|
||||
UpstreamBillingProbeExtraKey,
|
||||
OllamaCloudUsageSessionExtraKey,
|
||||
OllamaCloudUsageAutoRefreshExtraKey,
|
||||
@@ -700,13 +703,6 @@ func (s *adminServiceImpl) UpdateAccount(ctx context.Context, id int64, input *U
|
||||
normalizedExtra[key] = v
|
||||
}
|
||||
}
|
||||
if hasRequestedProbeEnabled {
|
||||
if isUpstreamBillingProbeAccount(account) {
|
||||
normalizedExtra[UpstreamBillingProbeEnabledExtraKey] = requestedProbeEnabled
|
||||
} else {
|
||||
delete(normalizedExtra, UpstreamBillingProbeEnabledExtraKey)
|
||||
}
|
||||
}
|
||||
account.Extra = normalizedExtra
|
||||
if account.Platform == PlatformAntigravity && wasOveragesEnabled && !account.IsOveragesEnabled() {
|
||||
delete(account.Extra, "antigravity_credits_overages") // 清理旧版 overages 运行态
|
||||
@@ -726,6 +722,35 @@ func (s *adminServiceImpl) UpdateAccount(ctx context.Context, id int64, input *U
|
||||
ComputeQuotaResetAt(account.Extra)
|
||||
NormalizeFixedQuotaWindows(account.Extra)
|
||||
}
|
||||
if requestedRateSyncEnabledUpdate != nil && *requestedRateSyncEnabledUpdate {
|
||||
if requestedProbeEnabledUpdate != nil && !*requestedProbeEnabledUpdate {
|
||||
return nil, infraerrors.BadRequest(
|
||||
"UPSTREAM_BILLING_RATE_SYNC_REQUIRES_PROBE",
|
||||
"upstream billing rate sync requires upstream billing probe",
|
||||
)
|
||||
}
|
||||
enabled := true
|
||||
requestedProbeEnabledUpdate = &enabled
|
||||
}
|
||||
if requestedProbeEnabledUpdate != nil && !*requestedProbeEnabledUpdate {
|
||||
disabled := false
|
||||
requestedRateSyncEnabledUpdate = &disabled
|
||||
}
|
||||
if (requestedProbeEnabledUpdate != nil && *requestedProbeEnabledUpdate) ||
|
||||
(requestedRateSyncEnabledUpdate != nil && *requestedRateSyncEnabledUpdate) {
|
||||
if !isUpstreamBillingProbeAccount(account) {
|
||||
return nil, ErrUpstreamBillingProbeAccountInvalid
|
||||
}
|
||||
}
|
||||
if account.Extra == nil && (requestedProbeEnabledUpdate != nil || requestedRateSyncEnabledUpdate != nil) {
|
||||
account.Extra = make(map[string]any)
|
||||
}
|
||||
if requestedProbeEnabledUpdate != nil {
|
||||
account.Extra[UpstreamBillingProbeEnabledExtraKey] = *requestedProbeEnabledUpdate
|
||||
}
|
||||
if requestedRateSyncEnabledUpdate != nil {
|
||||
account.Extra[UpstreamBillingRateSyncEnabledExtraKey] = *requestedRateSyncEnabledUpdate
|
||||
}
|
||||
// 影子代理恒继承母账号(由 propagateProxyToShadows 同步),不接受独立编辑——外审 B/P1;
|
||||
// 否则要等母账号下次改 proxy 才被覆盖,期间影子会出现"有时继承、有时独立"的漂移。
|
||||
if input.ProxyID != nil && !account.IsCredentialShadow() {
|
||||
@@ -741,6 +766,7 @@ func (s *adminServiceImpl) UpdateAccount(ctx context.Context, id int64, input *U
|
||||
delete(account.Extra, UpstreamBillingProbeExtraKey)
|
||||
if !isUpstreamBillingProbeAccount(account) {
|
||||
delete(account.Extra, UpstreamBillingProbeEnabledExtraKey)
|
||||
delete(account.Extra, UpstreamBillingRateSyncEnabledExtraKey)
|
||||
}
|
||||
}
|
||||
if account.Extra != nil {
|
||||
@@ -766,6 +792,13 @@ func (s *adminServiceImpl) UpdateAccount(ctx context.Context, id int64, input *U
|
||||
if *input.RateMultiplier < 0 {
|
||||
return nil, errors.New("rate_multiplier must be >= 0")
|
||||
}
|
||||
// 同步开启时倍率归上游所有,手工值活不过下一次成功探测(表现为"改了又自己
|
||||
// 变回去"),与批量路径一样直接拒绝。判断的是本次请求生效后的状态:上面
|
||||
// 已把请求携带的两个开关落进 account.Extra,所以"同一请求关闭同步 + 改倍率"
|
||||
// (用户显式收回所有权)会走到这里时读到 false,正常放行。
|
||||
if upstreamBillingRateSyncEnabled(account) {
|
||||
return nil, ErrUpstreamBillingRateSyncConflict
|
||||
}
|
||||
account.RateMultiplier = input.RateMultiplier
|
||||
}
|
||||
if input.LoadFactor != nil {
|
||||
@@ -806,23 +839,40 @@ func (s *adminServiceImpl) UpdateAccount(ctx context.Context, id int64, input *U
|
||||
}
|
||||
}
|
||||
|
||||
probeEnabledAppliedAtomically := false
|
||||
if requestedProbeEnabledUpdate != nil && isUpstreamBillingProbeAccount(account) {
|
||||
if updater, ok := s.accountRepo.(accountProbeEnabledAtomicUpdater); ok {
|
||||
if err := updater.UpdateWithUpstreamBillingProbeEnabled(ctx, account, *requestedProbeEnabledUpdate); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
probeEnabledAppliedAtomically = true
|
||||
}
|
||||
billingSettingsAppliedAtomically := false
|
||||
updater := s.accountBillingRepo
|
||||
if updater == nil {
|
||||
// Unit tests and narrow internal callers may construct adminServiceImpl
|
||||
// directly; production wiring requires this capability through
|
||||
// AdminAccountRepository.
|
||||
updater, _ = s.accountRepo.(AccountBillingSettingsRepository)
|
||||
}
|
||||
if !probeEnabledAppliedAtomically {
|
||||
if updater != nil {
|
||||
if err := updater.UpdateWithAccountBillingSettings(
|
||||
ctx,
|
||||
account,
|
||||
requestedProbeEnabledUpdate,
|
||||
requestedRateSyncEnabledUpdate,
|
||||
input.RateMultiplier,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
billingSettingsAppliedAtomically = true
|
||||
}
|
||||
if !billingSettingsAppliedAtomically {
|
||||
if err := s.accountRepo.Update(ctx, account); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if requestedProbeEnabledUpdate != nil && isUpstreamBillingProbeAccount(account) {
|
||||
if err := s.accountRepo.UpdateExtra(ctx, account.ID, map[string]any{
|
||||
UpstreamBillingProbeEnabledExtraKey: *requestedProbeEnabledUpdate,
|
||||
}); err != nil {
|
||||
if (requestedProbeEnabledUpdate != nil || requestedRateSyncEnabledUpdate != nil) &&
|
||||
isUpstreamBillingProbeAccount(account) {
|
||||
settings := make(map[string]any, 2)
|
||||
if requestedProbeEnabledUpdate != nil {
|
||||
settings[UpstreamBillingProbeEnabledExtraKey] = *requestedProbeEnabledUpdate
|
||||
}
|
||||
if requestedRateSyncEnabledUpdate != nil {
|
||||
settings[UpstreamBillingRateSyncEnabledExtraKey] = *requestedRateSyncEnabledUpdate
|
||||
}
|
||||
if err := s.accountRepo.UpdateExtra(ctx, account.ID, settings); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
@@ -854,6 +904,9 @@ func (s *adminServiceImpl) UpdateAccount(ctx context.Context, id int64, input *U
|
||||
// UpdateAccountExtra 仅对 Extra JSONB 做 key 级合并,避免覆盖其它运行态键
|
||||
// (如 model_rate_limits / passive_usage_* 等)。
|
||||
func (s *adminServiceImpl) UpdateAccountExtra(ctx context.Context, id int64, updates map[string]any) error {
|
||||
delete(updates, UpstreamBillingProbeEnabledExtraKey)
|
||||
delete(updates, UpstreamBillingRateSyncEnabledExtraKey)
|
||||
delete(updates, UpstreamBillingProbeExtraKey)
|
||||
delete(updates, OllamaCloudUsageSessionExtraKey)
|
||||
delete(updates, OllamaCloudUsageAutoRefreshExtraKey)
|
||||
delete(updates, OllamaCloudUsageSnapshotExtraKey)
|
||||
@@ -877,6 +930,7 @@ func (s *adminServiceImpl) UpdateAccountExtra(ctx context.Context, id int64, upd
|
||||
func (s *adminServiceImpl) BulkUpdateAccounts(ctx context.Context, input *BulkUpdateAccountsInput) (*BulkUpdateAccountsResult, error) {
|
||||
// Managed probe/session state may only enter through dedicated typed endpoints.
|
||||
delete(input.Extra, UpstreamBillingProbeEnabledExtraKey)
|
||||
delete(input.Extra, UpstreamBillingRateSyncEnabledExtraKey)
|
||||
delete(input.Extra, UpstreamBillingProbeExtraKey)
|
||||
delete(input.Extra, OllamaCloudUsageSessionExtraKey)
|
||||
delete(input.Extra, OllamaCloudUsageAutoRefreshExtraKey)
|
||||
@@ -910,7 +964,7 @@ func (s *adminServiceImpl) BulkUpdateAccounts(ctx context.Context, input *BulkUp
|
||||
|
||||
// 预取所有目标账号,供凭据守卫/代理守卫/混合渠道检查共用,避免多次 DB 查询。
|
||||
var cachedTargets []*Account
|
||||
if len(input.Credentials) > 0 || input.ProxyID != nil || needMixedChannelCheck || hasLongContextBillingUpdate || input.ProbeEnabled != nil {
|
||||
if len(input.Credentials) > 0 || input.ProxyID != nil || needMixedChannelCheck || hasLongContextBillingUpdate || input.ProbeEnabled != nil || input.RateMultiplier != nil {
|
||||
loaded, err := s.accountRepo.GetByIDs(ctx, input.AccountIDs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -996,6 +1050,21 @@ func (s *adminServiceImpl) BulkUpdateAccounts(ctx context.Context, input *BulkUp
|
||||
if *input.RateMultiplier < 0 {
|
||||
return nil, errors.New("rate_multiplier must be >= 0")
|
||||
}
|
||||
syncEnabledCount := 0
|
||||
for _, account := range cachedTargets {
|
||||
if account == nil || account.Extra == nil {
|
||||
continue
|
||||
}
|
||||
enabled, _ := account.Extra[UpstreamBillingRateSyncEnabledExtraKey].(bool)
|
||||
if enabled {
|
||||
syncEnabledCount++
|
||||
}
|
||||
}
|
||||
if syncEnabledCount > 0 {
|
||||
return nil, ErrUpstreamBillingRateSyncBulkConflict.WithMetadata(map[string]string{
|
||||
"count": strconv.Itoa(syncEnabledCount),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// 校验并规范化请求头覆写配置(批量路径为 JSONB 顶层 key 合并,直接校验增量即可)
|
||||
@@ -1014,6 +1083,9 @@ func (s *adminServiceImpl) BulkUpdateAccounts(ctx context.Context, input *BulkUp
|
||||
repoUpdates.Extra = make(map[string]any)
|
||||
}
|
||||
repoUpdates.Extra[UpstreamBillingProbeEnabledExtraKey] = *input.ProbeEnabled
|
||||
if !*input.ProbeEnabled {
|
||||
repoUpdates.Extra[UpstreamBillingRateSyncEnabledExtraKey] = false
|
||||
}
|
||||
}
|
||||
if updatesUpstreamBillingProbeIdentity(input.Credentials) || input.ProxyID != nil {
|
||||
if repoUpdates.Extra == nil {
|
||||
|
||||
@@ -17,6 +17,101 @@ func (r *upstreamBillingProbeAdminRepo) ListShadowsByParent(context.Context, int
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
type accountBillingSettingsAdminRepo struct {
|
||||
*upstreamBillingProbeAccountRepo
|
||||
concurrentRate *float64
|
||||
lastExplicitRate *float64
|
||||
updateCalls int
|
||||
}
|
||||
|
||||
func (r *accountBillingSettingsAdminRepo) UpdateWithAccountBillingSettings(
|
||||
_ context.Context,
|
||||
account *Account,
|
||||
probeEnabled *bool,
|
||||
rateSyncEnabled *bool,
|
||||
rateMultiplier *float64,
|
||||
) error {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
|
||||
current := r.accounts[account.ID]
|
||||
if current == nil {
|
||||
return ErrAccountNotFound
|
||||
}
|
||||
updated := *account
|
||||
updated.Credentials = mergeMap(nil, account.Credentials)
|
||||
updated.Extra = mergeMap(nil, account.Extra)
|
||||
if updated.Extra == nil {
|
||||
updated.Extra = make(map[string]any)
|
||||
}
|
||||
if probeEnabled != nil {
|
||||
updated.Extra[UpstreamBillingProbeEnabledExtraKey] = *probeEnabled
|
||||
}
|
||||
if rateSyncEnabled != nil {
|
||||
updated.Extra[UpstreamBillingRateSyncEnabledExtraKey] = *rateSyncEnabled
|
||||
}
|
||||
switch {
|
||||
case rateMultiplier != nil:
|
||||
value := *rateMultiplier
|
||||
updated.RateMultiplier = &value
|
||||
r.lastExplicitRate = &value
|
||||
case r.concurrentRate != nil:
|
||||
value := *r.concurrentRate
|
||||
updated.RateMultiplier = &value
|
||||
r.lastExplicitRate = nil
|
||||
default:
|
||||
updated.RateMultiplier = cloneAccountValuePointer(current.RateMultiplier)
|
||||
r.lastExplicitRate = nil
|
||||
}
|
||||
r.accounts[account.ID] = &updated
|
||||
r.updateCalls++
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestUpdateAccountRoutesRateIntentThroughAtomicBillingUpdater(t *testing.T) {
|
||||
accountID := int64(109)
|
||||
initialRate := 0.1
|
||||
concurrentRate := 0.2
|
||||
repo := &accountBillingSettingsAdminRepo{
|
||||
upstreamBillingProbeAccountRepo: &upstreamBillingProbeAccountRepo{accounts: map[int64]*Account{
|
||||
accountID: {
|
||||
ID: accountID,
|
||||
Name: "before",
|
||||
Platform: PlatformOpenAI,
|
||||
Type: AccountTypeAPIKey,
|
||||
Status: StatusActive,
|
||||
RateMultiplier: &initialRate,
|
||||
Extra: map[string]any{
|
||||
UpstreamBillingProbeEnabledExtraKey: true,
|
||||
UpstreamBillingRateSyncEnabledExtraKey: true,
|
||||
},
|
||||
},
|
||||
}},
|
||||
concurrentRate: &concurrentRate,
|
||||
}
|
||||
svc := &adminServiceImpl{accountRepo: repo}
|
||||
|
||||
updated, err := svc.UpdateAccount(context.Background(), accountID, &UpdateAccountInput{Name: "after"})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 1, repo.updateCalls)
|
||||
require.Nil(t, repo.lastExplicitRate)
|
||||
require.Equal(t, concurrentRate, *updated.RateMultiplier)
|
||||
|
||||
// 手工倍率只有在同步不再开启时才被接受,所以同一请求先关闭同步再设值
|
||||
// (同步仍开启时的手工倍率由 TestUpdateAccountRejectsManualRateWhileRateSyncEnabled 覆盖)。
|
||||
zero := 0.0
|
||||
syncDisabled := false
|
||||
updated, err = svc.UpdateAccount(context.Background(), accountID, &UpdateAccountInput{
|
||||
RateSyncEnabled: &syncDisabled,
|
||||
RateMultiplier: &zero,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 2, repo.updateCalls)
|
||||
require.NotNil(t, repo.lastExplicitRate)
|
||||
require.Zero(t, *repo.lastExplicitRate)
|
||||
require.Zero(t, *updated.RateMultiplier)
|
||||
}
|
||||
|
||||
func TestCreateAccountDropsManagedUpstreamBillingProbeState(t *testing.T) {
|
||||
repo := &upstreamBillingProbeAccountRepo{}
|
||||
svc := &adminServiceImpl{accountRepo: repo}
|
||||
@@ -28,13 +123,15 @@ func TestCreateAccountDropsManagedUpstreamBillingProbeState(t *testing.T) {
|
||||
Credentials: map[string]any{"api_key": "sk-test"},
|
||||
SkipDefaultGroupBind: true,
|
||||
Extra: map[string]any{
|
||||
UpstreamBillingProbeEnabledExtraKey: true,
|
||||
UpstreamBillingProbeExtraKey: map[string]any{"status": "ok"},
|
||||
UpstreamBillingProbeEnabledExtraKey: true,
|
||||
UpstreamBillingRateSyncEnabledExtraKey: true,
|
||||
UpstreamBillingProbeExtraKey: map[string]any{"status": "ok"},
|
||||
},
|
||||
})
|
||||
|
||||
require.NoError(t, err)
|
||||
require.NotContains(t, created.Extra, UpstreamBillingProbeEnabledExtraKey)
|
||||
require.NotContains(t, created.Extra, UpstreamBillingRateSyncEnabledExtraKey)
|
||||
require.NotContains(t, created.Extra, UpstreamBillingProbeExtraKey)
|
||||
}
|
||||
|
||||
@@ -73,8 +170,9 @@ func TestUpdateAccountPreservesManagedUpstreamBillingProbeStateForUnrelatedEdit(
|
||||
Type: AccountTypeAPIKey,
|
||||
Status: StatusActive,
|
||||
Extra: map[string]any{
|
||||
UpstreamBillingProbeEnabledExtraKey: true,
|
||||
UpstreamBillingProbeExtraKey: map[string]any{"status": "ok"},
|
||||
UpstreamBillingProbeEnabledExtraKey: true,
|
||||
UpstreamBillingRateSyncEnabledExtraKey: true,
|
||||
UpstreamBillingProbeExtraKey: map[string]any{"status": "ok"},
|
||||
},
|
||||
},
|
||||
}}
|
||||
@@ -86,6 +184,7 @@ func TestUpdateAccountPreservesManagedUpstreamBillingProbeStateForUnrelatedEdit(
|
||||
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, true, updated.Extra[UpstreamBillingProbeEnabledExtraKey])
|
||||
require.Equal(t, true, updated.Extra[UpstreamBillingRateSyncEnabledExtraKey])
|
||||
require.Contains(t, updated.Extra, UpstreamBillingProbeExtraKey)
|
||||
require.Equal(t, "value", updated.Extra["custom"])
|
||||
}
|
||||
@@ -196,8 +295,9 @@ func TestUpdateAccountInvalidatesProbeSnapshotWhenUpstreamIdentityChanges(t *tes
|
||||
"base_url": "https://old.example",
|
||||
},
|
||||
Extra: map[string]any{
|
||||
UpstreamBillingProbeEnabledExtraKey: true,
|
||||
UpstreamBillingProbeExtraKey: map[string]any{"status": "ok"},
|
||||
UpstreamBillingProbeEnabledExtraKey: true,
|
||||
UpstreamBillingRateSyncEnabledExtraKey: true,
|
||||
UpstreamBillingProbeExtraKey: map[string]any{"status": "ok"},
|
||||
},
|
||||
},
|
||||
}}
|
||||
@@ -210,6 +310,7 @@ func TestUpdateAccountInvalidatesProbeSnapshotWhenUpstreamIdentityChanges(t *tes
|
||||
require.Equal(t, true, updated.Extra[UpstreamBillingProbeEnabledExtraKey])
|
||||
} else {
|
||||
require.NotContains(t, updated.Extra, UpstreamBillingProbeEnabledExtraKey)
|
||||
require.NotContains(t, updated.Extra, UpstreamBillingRateSyncEnabledExtraKey)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -289,16 +390,149 @@ func TestUpdateAccountAcceptsProbeEnabledAndRejectsInjectedSnapshot(t *testing.T
|
||||
svc := &adminServiceImpl{accountRepo: repo}
|
||||
updated, err := svc.UpdateAccount(context.Background(), accountID, &UpdateAccountInput{
|
||||
Extra: map[string]any{
|
||||
UpstreamBillingProbeEnabledExtraKey: true,
|
||||
UpstreamBillingProbeExtraKey: map[string]any{"status": "ok"},
|
||||
UpstreamBillingProbeEnabledExtraKey: true,
|
||||
UpstreamBillingRateSyncEnabledExtraKey: true,
|
||||
UpstreamBillingProbeExtraKey: map[string]any{"status": "ok"},
|
||||
},
|
||||
})
|
||||
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, true, updated.Extra[UpstreamBillingProbeEnabledExtraKey])
|
||||
require.NotContains(t, updated.Extra, UpstreamBillingRateSyncEnabledExtraKey)
|
||||
require.NotContains(t, updated.Extra, UpstreamBillingProbeExtraKey)
|
||||
}
|
||||
|
||||
func TestUpdateAccountRateSyncControlsProbeAndManualMode(t *testing.T) {
|
||||
accountID := int64(151)
|
||||
repo := &upstreamBillingProbeAccountRepo{accounts: map[int64]*Account{
|
||||
accountID: {
|
||||
ID: accountID,
|
||||
Platform: PlatformGemini,
|
||||
Type: AccountTypeAPIKey,
|
||||
Status: StatusActive,
|
||||
Extra: map[string]any{},
|
||||
},
|
||||
}}
|
||||
svc := &adminServiceImpl{accountRepo: repo}
|
||||
|
||||
syncEnabled := true
|
||||
updated, err := svc.UpdateAccount(context.Background(), accountID, &UpdateAccountInput{
|
||||
RateSyncEnabled: &syncEnabled,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, true, updated.Extra[UpstreamBillingProbeEnabledExtraKey])
|
||||
require.Equal(t, true, updated.Extra[UpstreamBillingRateSyncEnabledExtraKey])
|
||||
|
||||
syncEnabled = false
|
||||
updated, err = svc.UpdateAccount(context.Background(), accountID, &UpdateAccountInput{
|
||||
RateSyncEnabled: &syncEnabled,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, true, updated.Extra[UpstreamBillingProbeEnabledExtraKey])
|
||||
require.Equal(t, false, updated.Extra[UpstreamBillingRateSyncEnabledExtraKey])
|
||||
}
|
||||
|
||||
// 单账号编辑必须和批量路径语义一致:同步开启时倍率归上游所有,手工值会在下一次
|
||||
// 成功探测时被覆盖,因此直接拒绝而不是静默接受。
|
||||
func TestUpdateAccountRejectsManualRateWhileRateSyncEnabled(t *testing.T) {
|
||||
newRepo := func(accountID int64, extra map[string]any) *upstreamBillingProbeAccountRepo {
|
||||
initialRate := 0.25
|
||||
return &upstreamBillingProbeAccountRepo{accounts: map[int64]*Account{
|
||||
accountID: {
|
||||
ID: accountID,
|
||||
Platform: PlatformOpenAI,
|
||||
Type: AccountTypeAPIKey,
|
||||
Status: StatusActive,
|
||||
RateMultiplier: &initialRate,
|
||||
Extra: extra,
|
||||
},
|
||||
}}
|
||||
}
|
||||
manualRate := 3.5
|
||||
syncEnabled := map[string]any{
|
||||
UpstreamBillingProbeEnabledExtraKey: true,
|
||||
UpstreamBillingRateSyncEnabledExtraKey: true,
|
||||
}
|
||||
|
||||
t.Run("sync enabled rejects manual rate", func(t *testing.T) {
|
||||
accountID := int64(153)
|
||||
repo := newRepo(accountID, mergeMap(nil, syncEnabled))
|
||||
|
||||
_, err := (&adminServiceImpl{accountRepo: repo}).UpdateAccount(context.Background(), accountID, &UpdateAccountInput{
|
||||
RateMultiplier: &manualRate,
|
||||
})
|
||||
|
||||
require.ErrorIs(t, err, ErrUpstreamBillingRateSyncConflict)
|
||||
require.Equal(t, 0.25, *repo.accounts[accountID].RateMultiplier)
|
||||
})
|
||||
|
||||
t.Run("enabling sync in the same request rejects manual rate", func(t *testing.T) {
|
||||
accountID := int64(154)
|
||||
repo := newRepo(accountID, map[string]any{})
|
||||
enable := true
|
||||
|
||||
_, err := (&adminServiceImpl{accountRepo: repo}).UpdateAccount(context.Background(), accountID, &UpdateAccountInput{
|
||||
RateSyncEnabled: &enable,
|
||||
RateMultiplier: &manualRate,
|
||||
})
|
||||
|
||||
require.ErrorIs(t, err, ErrUpstreamBillingRateSyncConflict)
|
||||
require.Equal(t, 0.25, *repo.accounts[accountID].RateMultiplier)
|
||||
})
|
||||
|
||||
// 用户显式收回所有权:同一请求关闭同步并改倍率必须放行。
|
||||
t.Run("disabling sync in the same request allows manual rate", func(t *testing.T) {
|
||||
accountID := int64(155)
|
||||
repo := newRepo(accountID, mergeMap(nil, syncEnabled))
|
||||
disable := false
|
||||
|
||||
updated, err := (&adminServiceImpl{accountRepo: repo}).UpdateAccount(context.Background(), accountID, &UpdateAccountInput{
|
||||
RateSyncEnabled: &disable,
|
||||
RateMultiplier: &manualRate,
|
||||
})
|
||||
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, false, updated.Extra[UpstreamBillingRateSyncEnabledExtraKey])
|
||||
require.NotNil(t, updated.RateMultiplier)
|
||||
require.Equal(t, manualRate, *updated.RateMultiplier)
|
||||
})
|
||||
|
||||
t.Run("sync disabled allows manual rate", func(t *testing.T) {
|
||||
accountID := int64(156)
|
||||
repo := newRepo(accountID, map[string]any{UpstreamBillingProbeEnabledExtraKey: true})
|
||||
|
||||
updated, err := (&adminServiceImpl{accountRepo: repo}).UpdateAccount(context.Background(), accountID, &UpdateAccountInput{
|
||||
RateMultiplier: &manualRate,
|
||||
})
|
||||
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, updated.RateMultiplier)
|
||||
require.Equal(t, manualRate, *updated.RateMultiplier)
|
||||
})
|
||||
}
|
||||
|
||||
func TestUpdateAccountRejectsSyncWithExplicitlyDisabledProbe(t *testing.T) {
|
||||
accountID := int64(152)
|
||||
repo := &upstreamBillingProbeAccountRepo{accounts: map[int64]*Account{
|
||||
accountID: {
|
||||
ID: accountID,
|
||||
Platform: PlatformAnthropic,
|
||||
Type: AccountTypeAPIKey,
|
||||
Status: StatusActive,
|
||||
},
|
||||
}}
|
||||
probeEnabled := false
|
||||
syncEnabled := true
|
||||
|
||||
_, err := (&adminServiceImpl{accountRepo: repo}).UpdateAccount(context.Background(), accountID, &UpdateAccountInput{
|
||||
ProbeEnabled: &probeEnabled,
|
||||
RateSyncEnabled: &syncEnabled,
|
||||
})
|
||||
|
||||
require.Error(t, err)
|
||||
require.Empty(t, repo.updates[accountID])
|
||||
}
|
||||
|
||||
func TestUpdateAccountExplicitProbeDisableUsesDedicatedExtraUpdate(t *testing.T) {
|
||||
accountID := int64(113)
|
||||
repo := &upstreamBillingProbeAccountRepo{accounts: map[int64]*Account{
|
||||
@@ -321,6 +555,7 @@ func TestUpdateAccountExplicitProbeDisableUsesDedicatedExtraUpdate(t *testing.T)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, repo.updates[accountID], 1)
|
||||
require.Equal(t, false, repo.updates[accountID][0][UpstreamBillingProbeEnabledExtraKey])
|
||||
require.Equal(t, false, repo.updates[accountID][0][UpstreamBillingRateSyncEnabledExtraKey])
|
||||
}
|
||||
|
||||
func TestUpdateAccountExplicitUnchangedProbeEnabledStillUsesDedicatedExtraUpdate(t *testing.T) {
|
||||
@@ -364,15 +599,36 @@ func TestUpdateAccountRejectsInvalidProbeEnabled(t *testing.T) {
|
||||
require.Error(t, err)
|
||||
}
|
||||
|
||||
func TestUpdateAccountExtraDropsManagedBillingProbeFields(t *testing.T) {
|
||||
accountID := int64(153)
|
||||
repo := &upstreamBillingProbeAccountRepo{accounts: map[int64]*Account{
|
||||
accountID: {ID: accountID, Platform: PlatformOpenAI, Type: AccountTypeAPIKey},
|
||||
}}
|
||||
|
||||
err := (&adminServiceImpl{accountRepo: repo}).UpdateAccountExtra(context.Background(), accountID, map[string]any{
|
||||
"custom": "value",
|
||||
UpstreamBillingProbeEnabledExtraKey: true,
|
||||
UpstreamBillingRateSyncEnabledExtraKey: true,
|
||||
UpstreamBillingProbeExtraKey: map[string]any{"status": "ok"},
|
||||
})
|
||||
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "value", repo.accounts[accountID].Extra["custom"])
|
||||
require.NotContains(t, repo.accounts[accountID].Extra, UpstreamBillingProbeEnabledExtraKey)
|
||||
require.NotContains(t, repo.accounts[accountID].Extra, UpstreamBillingRateSyncEnabledExtraKey)
|
||||
require.NotContains(t, repo.accounts[accountID].Extra, UpstreamBillingProbeExtraKey)
|
||||
}
|
||||
|
||||
func TestBulkUpdateAccountsDropsManagedUpstreamBillingProbeState(t *testing.T) {
|
||||
repo := &upstreamBillingProbeAccountRepo{}
|
||||
svc := &adminServiceImpl{accountRepo: repo}
|
||||
input := &BulkUpdateAccountsInput{
|
||||
AccountIDs: []int64{1},
|
||||
Extra: map[string]any{
|
||||
"custom": "value",
|
||||
UpstreamBillingProbeEnabledExtraKey: true,
|
||||
UpstreamBillingProbeExtraKey: map[string]any{"status": "ok"},
|
||||
"custom": "value",
|
||||
UpstreamBillingProbeEnabledExtraKey: true,
|
||||
UpstreamBillingRateSyncEnabledExtraKey: true,
|
||||
UpstreamBillingProbeExtraKey: map[string]any{"status": "ok"},
|
||||
},
|
||||
}
|
||||
|
||||
@@ -383,6 +639,7 @@ func TestBulkUpdateAccountsDropsManagedUpstreamBillingProbeState(t *testing.T) {
|
||||
require.Len(t, repo.bulkUpdates, 1)
|
||||
require.Equal(t, "value", repo.bulkUpdates[0].Extra["custom"])
|
||||
require.NotContains(t, repo.bulkUpdates[0].Extra, UpstreamBillingProbeEnabledExtraKey)
|
||||
require.NotContains(t, repo.bulkUpdates[0].Extra, UpstreamBillingRateSyncEnabledExtraKey)
|
||||
require.NotContains(t, repo.bulkUpdates[0].Extra, UpstreamBillingProbeExtraKey)
|
||||
}
|
||||
|
||||
@@ -403,6 +660,9 @@ func TestBulkUpdateAccountsAcceptsDedicatedUpstreamBillingProbeSetting(t *testin
|
||||
require.Equal(t, 2, result.Success)
|
||||
require.Len(t, repo.bulkUpdates, 1)
|
||||
require.Equal(t, enabled, repo.bulkUpdates[0].Extra[UpstreamBillingProbeEnabledExtraKey])
|
||||
if !enabled {
|
||||
require.Equal(t, false, repo.bulkUpdates[0].Extra[UpstreamBillingRateSyncEnabledExtraKey])
|
||||
}
|
||||
require.NotNil(t, repo.bulkUpdates[0].ProbeEnabled)
|
||||
require.Equal(t, enabled, *repo.bulkUpdates[0].ProbeEnabled)
|
||||
})
|
||||
|
||||
@@ -300,10 +300,7 @@ func (s *adminServiceImpl) CreateGroup(ctx context.Context, input *CreateGroupIn
|
||||
return nil, errors.New("rate_multiplier must be > 0")
|
||||
}
|
||||
|
||||
platform := input.Platform
|
||||
if platform == "" {
|
||||
platform = PlatformAnthropic
|
||||
}
|
||||
platform := NormalizeGroupPlatform(input.Platform)
|
||||
maxReasoningEffort, err := normalizeMaxReasoningEffortForPlatform(platform, input.MaxReasoningEffort)
|
||||
if err != nil {
|
||||
return nil, infraerrors.Newf(http.StatusBadRequest, "INVALID_MAX_REASONING_EFFORT", "%v", err)
|
||||
@@ -375,6 +372,20 @@ func (s *adminServiceImpl) CreateGroup(ctx context.Context, input *CreateGroupIn
|
||||
return nil, err
|
||||
}
|
||||
|
||||
profitMinMargin := 0.0
|
||||
if input.ProfitMinMargin != nil {
|
||||
profitMinMargin = *input.ProfitMinMargin
|
||||
}
|
||||
profitSafetyBuffer := 0.0
|
||||
if input.ProfitSafetyBuffer != nil {
|
||||
profitSafetyBuffer = *input.ProfitSafetyBuffer
|
||||
}
|
||||
// 利润控制与高峰倍率同一收口顺序:先按平台归一化(不支持的平台重置),再校验。
|
||||
profitControlEnabled, profitMinMargin, profitSafetyBuffer := NormalizeProfitControlConfig(platform, input.ProfitControlEnabled, profitMinMargin, profitSafetyBuffer)
|
||||
if err := ValidateProfitControlConfig(platform, profitControlEnabled, profitMinMargin, profitSafetyBuffer); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 校验降级分组
|
||||
if input.FallbackGroupID != nil {
|
||||
if err := s.validateFallbackGroup(ctx, 0, *input.FallbackGroupID); err != nil {
|
||||
@@ -456,6 +467,9 @@ func (s *adminServiceImpl) CreateGroup(ctx context.Context, input *CreateGroupIn
|
||||
PeakStart: peakStart,
|
||||
PeakEnd: peakEnd,
|
||||
PeakRateMultiplier: peakRateMultiplier,
|
||||
ProfitControlEnabled: profitControlEnabled,
|
||||
ProfitMinMargin: profitMinMargin,
|
||||
ProfitSafetyBuffer: profitSafetyBuffer,
|
||||
ImagePrice1K: imagePrice1K,
|
||||
ImagePrice2K: imagePrice2K,
|
||||
ImagePrice4K: imagePrice4K,
|
||||
@@ -708,6 +722,21 @@ func (s *adminServiceImpl) UpdateGroup(ctx context.Context, id int64, input *Upd
|
||||
if err := ValidatePeakRateConfig(group.SubscriptionType, group.PeakRateEnabled, group.PeakStart, group.PeakEnd, group.PeakRateMultiplier); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if input.ProfitControlEnabled != nil {
|
||||
group.ProfitControlEnabled = *input.ProfitControlEnabled
|
||||
}
|
||||
if input.ProfitMinMargin != nil {
|
||||
group.ProfitMinMargin = *input.ProfitMinMargin
|
||||
}
|
||||
if input.ProfitSafetyBuffer != nil {
|
||||
group.ProfitSafetyBuffer = *input.ProfitSafetyBuffer
|
||||
}
|
||||
// 利润控制与高峰同一收口:按合并后的最终平台归一化(转到不支持平台时静默重置),
|
||||
// 再对合并后的最终配置统一校验,防止部分字段更新拼出非法组合入库。
|
||||
group.ProfitControlEnabled, group.ProfitMinMargin, group.ProfitSafetyBuffer = NormalizeProfitControlConfig(group.Platform, group.ProfitControlEnabled, group.ProfitMinMargin, group.ProfitSafetyBuffer)
|
||||
if err := ValidateProfitControlConfig(group.Platform, group.ProfitControlEnabled, group.ProfitMinMargin, group.ProfitSafetyBuffer); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if input.ImagePrice1K != nil {
|
||||
group.ImagePrice1K = normalizePrice(input.ImagePrice1K)
|
||||
}
|
||||
|
||||
@@ -88,6 +88,9 @@ func cloneGroupForDuplicate(source *Group, operationID string) *Group {
|
||||
PeakStart: source.PeakStart,
|
||||
PeakEnd: source.PeakEnd,
|
||||
PeakRateMultiplier: source.PeakRateMultiplier,
|
||||
ProfitControlEnabled: source.ProfitControlEnabled,
|
||||
ProfitMinMargin: source.ProfitMinMargin,
|
||||
ProfitSafetyBuffer: source.ProfitSafetyBuffer,
|
||||
IsExclusive: source.IsExclusive,
|
||||
Status: duplicateGroupInactiveStatus,
|
||||
DuplicateOperationID: operationID,
|
||||
|
||||
@@ -264,6 +264,10 @@ type CreateGroupInput struct {
|
||||
MaxReasoningEffort string
|
||||
// ReasoningEffortMappings OpenAI/Codex 推理强度精确映射。
|
||||
ReasoningEffortMappings []ReasoningEffortMapping
|
||||
// 分组利润控制(五个 token 平台分组可启用;margin/buffer 为小数,nil 按 0 处理)
|
||||
ProfitControlEnabled bool
|
||||
ProfitMinMargin *float64
|
||||
ProfitSafetyBuffer *float64
|
||||
// 从指定分组复制账号(创建分组后在同一事务内绑定)
|
||||
CopyAccountsFromGroupIDs []int64
|
||||
}
|
||||
@@ -325,6 +329,10 @@ type UpdateGroupInput struct {
|
||||
MaxReasoningEffort *string
|
||||
// ReasoningEffortMappings nil 表示不修改,空数组表示清空,非空数组表示替换。
|
||||
ReasoningEffortMappings *[]ReasoningEffortMapping
|
||||
// 分组利润控制(nil 表示不修改;margin/buffer 为小数)
|
||||
ProfitControlEnabled *bool
|
||||
ProfitMinMargin *float64
|
||||
ProfitSafetyBuffer *float64
|
||||
// 从指定分组复制账号(同步操作:先清空当前分组的账号绑定,再绑定源分组的账号)
|
||||
CopyAccountsFromGroupIDs []int64
|
||||
}
|
||||
@@ -376,6 +384,8 @@ type UpdateAccountInput struct {
|
||||
GroupIDs *[]int64
|
||||
ExpiresAt *int64
|
||||
AutoPauseOnExpired *bool
|
||||
ProbeEnabled *bool
|
||||
RateSyncEnabled *bool
|
||||
SkipMixedChannelCheck bool // 跳过混合渠道检查(用户已确认风险)
|
||||
}
|
||||
|
||||
@@ -617,6 +627,7 @@ type adminServiceImpl struct {
|
||||
groupDuplicateRepo GroupDuplicateRepository
|
||||
accountRepo AccountRepository
|
||||
accountDuplicateRepo AccountDuplicateRepository
|
||||
accountBillingRepo AccountBillingSettingsRepository
|
||||
proxyRepo ProxyRepository
|
||||
apiKeyRepo APIKeyRepository
|
||||
redeemCodeRepo RedeemCodeRepository
|
||||
@@ -675,6 +686,7 @@ func NewAdminService(
|
||||
groupDuplicateRepo: groupRepo,
|
||||
accountRepo: accountRepo,
|
||||
accountDuplicateRepo: accountRepo,
|
||||
accountBillingRepo: accountRepo,
|
||||
proxyRepo: proxyRepo,
|
||||
apiKeyRepo: apiKeyRepo,
|
||||
redeemCodeRepo: redeemCodeRepo,
|
||||
|
||||
@@ -5,9 +5,11 @@ package service
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/pagination"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
@@ -153,6 +155,38 @@ func TestAdminService_BulkUpdateAccounts_AllSuccessIDs(t *testing.T) {
|
||||
require.Len(t, result.Results, 3)
|
||||
}
|
||||
|
||||
func TestAdminService_BulkUpdateAccounts_RejectsRateChangeForSyncedAccounts(t *testing.T) {
|
||||
repo := &accountRepoStubForBulkUpdate{
|
||||
getByIDsAccounts: []*Account{
|
||||
{
|
||||
ID: 1,
|
||||
Extra: map[string]any{
|
||||
UpstreamBillingProbeEnabledExtraKey: true,
|
||||
UpstreamBillingRateSyncEnabledExtraKey: true,
|
||||
},
|
||||
},
|
||||
{ID: 2, Extra: map[string]any{}},
|
||||
},
|
||||
}
|
||||
svc := &adminServiceImpl{accountRepo: repo}
|
||||
rateMultiplier := 0.5
|
||||
|
||||
result, err := svc.BulkUpdateAccounts(context.Background(), &BulkUpdateAccountsInput{
|
||||
AccountIDs: []int64{1, 2},
|
||||
RateMultiplier: &rateMultiplier,
|
||||
})
|
||||
|
||||
require.Nil(t, result)
|
||||
require.Error(t, err)
|
||||
var appErr *infraerrors.ApplicationError
|
||||
require.ErrorAs(t, err, &appErr)
|
||||
require.Equal(t, int32(http.StatusConflict), appErr.Code)
|
||||
require.Equal(t, "UPSTREAM_BILLING_RATE_SYNC_BULK_CONFLICT", appErr.Reason)
|
||||
require.Equal(t, "1", appErr.Metadata["count"])
|
||||
require.True(t, repo.getByIDsCalled)
|
||||
require.Empty(t, repo.bulkUpdateIDs, "rate conflict must be rejected before any write")
|
||||
}
|
||||
|
||||
// TestAdminService_BulkUpdateAccounts_PartialFailureIDs 验证部分失败时 success_ids/failed_ids 正确。
|
||||
func TestAdminService_BulkUpdateAccounts_PartialFailureIDs(t *testing.T) {
|
||||
repo := &accountRepoStubForBulkUpdate{
|
||||
|
||||
@@ -41,14 +41,20 @@ func TestAdminService_CreateCompositeGroupCopiesAccountsFromConcreteGroups(t *te
|
||||
svc := &adminServiceImpl{groupRepo: groupRepo}
|
||||
|
||||
group, err := svc.CreateGroup(context.Background(), &CreateGroupInput{
|
||||
Name: "Composite",
|
||||
Platform: PlatformComposite,
|
||||
RateMultiplier: 1,
|
||||
Name: "Composite",
|
||||
Platform: PlatformComposite,
|
||||
RateMultiplier: 1,
|
||||
MaxReasoningEffort: "medium",
|
||||
ReasoningEffortMappings: []ReasoningEffortMapping{
|
||||
{From: "max", To: "xhigh"},
|
||||
},
|
||||
CopyAccountsFromGroupIDs: []int64{10, 20, 10},
|
||||
})
|
||||
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, PlatformComposite, groupRepo.created.Platform)
|
||||
require.Equal(t, "medium", groupRepo.created.MaxReasoningEffort)
|
||||
require.Equal(t, []ReasoningEffortMapping{{From: "max", To: "xhigh"}}, groupRepo.created.ReasoningEffortMappings)
|
||||
require.Equal(t, int64(99), group.ID)
|
||||
require.Equal(t, int64(2), group.AccountCount)
|
||||
require.ElementsMatch(t, []int64{10, 20}, copiedFrom)
|
||||
@@ -82,13 +88,19 @@ func TestAdminService_UpdateCompositeGroupCopiesAccountsFromConcreteGroups(t *te
|
||||
},
|
||||
}
|
||||
svc := &adminServiceImpl{groupRepo: groupRepo}
|
||||
maxReasoningEffort := "low"
|
||||
reasoningEffortMappings := []ReasoningEffortMapping{{From: "max", To: "high"}}
|
||||
|
||||
group, err := svc.UpdateGroup(context.Background(), 99, &UpdateGroupInput{
|
||||
MaxReasoningEffort: &maxReasoningEffort,
|
||||
ReasoningEffortMappings: &reasoningEffortMappings,
|
||||
CopyAccountsFromGroupIDs: []int64{10, 20},
|
||||
})
|
||||
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, PlatformComposite, group.Platform)
|
||||
require.Equal(t, "low", group.MaxReasoningEffort)
|
||||
require.Equal(t, reasoningEffortMappings, group.ReasoningEffortMappings)
|
||||
require.Equal(t, int64(99), clearedGroupID)
|
||||
require.ElementsMatch(t, []int64{10, 20}, copiedFrom)
|
||||
require.Equal(t, int64(99), boundGroupID)
|
||||
|
||||
@@ -141,6 +141,7 @@ func TestDuplicateAccountCopiesConfigurationAndResetsRuntimeState(t *testing.T)
|
||||
SessionWindowStatus: "active",
|
||||
}
|
||||
source.Extra[UpstreamBillingProbeEnabledExtraKey] = true
|
||||
source.Extra[UpstreamBillingRateSyncEnabledExtraKey] = true
|
||||
source.Extra[UpstreamBillingProbeExtraKey] = map[string]any{"status": "ok"}
|
||||
require.NoError(t, repo.Create(ctx, source))
|
||||
|
||||
@@ -162,6 +163,7 @@ func TestDuplicateAccountCopiesConfigurationAndResetsRuntimeState(t *testing.T)
|
||||
"quota_limit": float64(1000),
|
||||
"codex_cli_only": true,
|
||||
}, duplicate.Extra)
|
||||
require.NotContains(t, duplicate.Extra, UpstreamBillingRateSyncEnabledExtraKey)
|
||||
require.NotNil(t, duplicate.ExpiresAt)
|
||||
require.True(t, source.ExpiresAt.Equal(*duplicate.ExpiresAt))
|
||||
require.Equal(t, source.Notes, duplicate.Notes)
|
||||
|
||||
@@ -114,6 +114,17 @@ type APIKeyAuthGroupSnapshot struct {
|
||||
PeakStart string `json:"peak_start"`
|
||||
PeakEnd string `json:"peak_end"`
|
||||
PeakRateMultiplier float64 `json:"peak_rate_multiplier"`
|
||||
|
||||
// 分组利润控制:调度准入门在直连热路径上读的就是这份快照——门解析
|
||||
// (resolveOpenAIProfitControlGate / resolveProfitControlGroup)优先取
|
||||
// 认证中间件放入 ctx 的 Group,而它正是本快照物化出来的对象,生产绝大
|
||||
// 多数流量走的都是这条路;只有 composite/模型路由等被调度分组与认证分组
|
||||
// 不一致时才回源 schedulerSnapshot。
|
||||
// 因此这三个字段与 GetByKeyForAuth 的投影都不得删减:漏掉任何一个,
|
||||
// 门会拿到零值 ProfitControlEnabled=false 而静默失效(有集成测试兜底)。
|
||||
ProfitControlEnabled bool `json:"profit_control_enabled"`
|
||||
ProfitMinMargin float64 `json:"profit_min_margin"`
|
||||
ProfitSafetyBuffer float64 `json:"profit_safety_buffer"`
|
||||
}
|
||||
|
||||
// APIKeyAuthCacheEntry 缓存条目,支持负缓存
|
||||
|
||||
@@ -14,7 +14,7 @@ import (
|
||||
"github.com/dgraph-io/ristretto"
|
||||
)
|
||||
|
||||
const apiKeyAuthSnapshotVersion = 17 // v17: include the OpenAI group Live gate
|
||||
const apiKeyAuthSnapshotVersion = 18 // v18: include group profit control fields (force refresh of pre-fix snapshots)
|
||||
|
||||
type apiKeyAuthCacheConfig struct {
|
||||
l1Size int
|
||||
@@ -420,6 +420,9 @@ func (s *APIKeyService) snapshotFromAPIKey(ctx context.Context, apiKey *APIKey)
|
||||
PeakStart: apiKey.Group.PeakStart,
|
||||
PeakEnd: apiKey.Group.PeakEnd,
|
||||
PeakRateMultiplier: apiKey.Group.PeakRateMultiplier,
|
||||
ProfitControlEnabled: apiKey.Group.ProfitControlEnabled,
|
||||
ProfitMinMargin: apiKey.Group.ProfitMinMargin,
|
||||
ProfitSafetyBuffer: apiKey.Group.ProfitSafetyBuffer,
|
||||
}
|
||||
}
|
||||
return snapshot
|
||||
@@ -507,6 +510,9 @@ func (s *APIKeyService) snapshotToAPIKey(key string, snapshot *APIKeyAuthSnapsho
|
||||
PeakStart: snapshot.Group.PeakStart,
|
||||
PeakEnd: snapshot.Group.PeakEnd,
|
||||
PeakRateMultiplier: snapshot.Group.PeakRateMultiplier,
|
||||
ProfitControlEnabled: snapshot.Group.ProfitControlEnabled,
|
||||
ProfitMinMargin: snapshot.Group.ProfitMinMargin,
|
||||
ProfitSafetyBuffer: snapshot.Group.ProfitSafetyBuffer,
|
||||
}
|
||||
}
|
||||
s.compileAPIKeyIPRules(apiKey)
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
package service
|
||||
|
||||
// 投影漏列回归(service 半程):认证快照 build → L2 JSON 序列化
|
||||
// → 反序列化 → 还原 apiKey.Group → 请求 ctx → 利润门解析,全链路保真。
|
||||
// repository 半程(真实 GetByKeyForAuth 投影)见
|
||||
// internal/repository/api_key_repo_profit_projection_integration_test.go。
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func profitAuthTestAPIKey() *APIKey {
|
||||
groupID := int64(50)
|
||||
return &APIKey{
|
||||
ID: 82,
|
||||
UserID: 40,
|
||||
GroupID: &groupID,
|
||||
Name: "profit-auth-roundtrip",
|
||||
Status: StatusActive,
|
||||
User: &User{
|
||||
ID: 40,
|
||||
Email: "profit@test.local",
|
||||
Status: StatusActive,
|
||||
Concurrency: 5,
|
||||
},
|
||||
Group: &Group{
|
||||
ID: groupID,
|
||||
Name: "VIP-roundtrip",
|
||||
Platform: PlatformOpenAI,
|
||||
Status: StatusActive,
|
||||
Hydrated: true,
|
||||
RateMultiplier: 0.06,
|
||||
SubscriptionType: SubscriptionTypeStandard,
|
||||
PeakRateEnabled: false,
|
||||
ProfitControlEnabled: true,
|
||||
ProfitMinMargin: 0.2,
|
||||
ProfitSafetyBuffer: 0.05,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// 快照构建 → L2 JSON 往返 → 还原 → 装门:利润字段必须全程保真,阈值与
|
||||
// 计费同源(0.06 × (1−0.25) = 0.045)。
|
||||
func TestAPIKeyAuthSnapshotProfitControlRoundtrip(t *testing.T) {
|
||||
svc := &APIKeyService{}
|
||||
apiKey := profitAuthTestAPIKey()
|
||||
|
||||
snapshot := svc.snapshotFromAPIKey(context.Background(), apiKey)
|
||||
require.NotNil(t, snapshot)
|
||||
require.Equal(t, apiKeyAuthSnapshotVersion, snapshot.Version)
|
||||
require.Equal(t, 18, snapshot.Version, "v18 起认证快照携带利润控制字段")
|
||||
|
||||
// 模拟 L2 缓存的完整 JSON 往返(与 apiKeyCache.SetAuthCache/GetAuthCache 同构)。
|
||||
payload, err := json.Marshal(&APIKeyAuthCacheEntry{Snapshot: snapshot})
|
||||
require.NoError(t, err)
|
||||
var restored APIKeyAuthCacheEntry
|
||||
require.NoError(t, json.Unmarshal(payload, &restored))
|
||||
|
||||
materialized, used, err := svc.applyAuthCacheEntry(apiKey.Key, &restored)
|
||||
require.NoError(t, err)
|
||||
require.True(t, used)
|
||||
require.NotNil(t, materialized.Group)
|
||||
require.True(t, materialized.Group.Hydrated)
|
||||
require.True(t, materialized.Group.ProfitControlEnabled)
|
||||
require.InDelta(t, 0.2, materialized.Group.ProfitMinMargin, 1e-12)
|
||||
require.InDelta(t, 0.05, materialized.Group.ProfitSafetyBuffer, 1e-12)
|
||||
require.InDelta(t, 0.06, materialized.Group.RateMultiplier, 1e-12)
|
||||
|
||||
// 中间件语义:materialized.Group 进请求 ctx → 门必须按快照配置装上。
|
||||
ctx := context.WithValue(context.Background(), ctxkey.Group, materialized.Group)
|
||||
gwSvc := &OpenAIGatewayService{}
|
||||
gate := gwSvc.resolveOpenAIProfitControlGate(ctx, materialized.GroupID)
|
||||
require.NotNil(t, gate, "还原后的认证分组必须能装门(投影漏列时本断言最先失败)")
|
||||
require.InDelta(t, 0.06*(1-0.25), gate.threshold, 1e-12)
|
||||
}
|
||||
|
||||
// 旧版本快照(v16 及更早,无利润字段保真保证)必须被淘汰回源,不得复用。
|
||||
func TestAPIKeyAuthSnapshotOldVersionEvicted(t *testing.T) {
|
||||
svc := &APIKeyService{}
|
||||
snapshot := svc.snapshotFromAPIKey(context.Background(), profitAuthTestAPIKey())
|
||||
require.NotNil(t, snapshot)
|
||||
snapshot.Version = 16
|
||||
|
||||
materialized, used, err := svc.applyAuthCacheEntry("sk-old", &APIKeyAuthCacheEntry{Snapshot: snapshot})
|
||||
require.NoError(t, err)
|
||||
require.False(t, used, "版本不匹配的缓存条目必须淘汰并回源重建")
|
||||
require.Nil(t, materialized)
|
||||
}
|
||||
@@ -296,8 +296,8 @@ func TestAPIKeyService_SnapshotRoundTrip_PreservesReasoningEffortPolicy(t *testi
|
||||
},
|
||||
Group: &Group{
|
||||
ID: groupID,
|
||||
Name: "openai",
|
||||
Platform: PlatformOpenAI,
|
||||
Name: "composite",
|
||||
Platform: PlatformComposite,
|
||||
Status: StatusActive,
|
||||
SubscriptionType: SubscriptionTypeStandard,
|
||||
RateMultiplier: 1,
|
||||
@@ -313,6 +313,7 @@ func TestAPIKeyService_SnapshotRoundTrip_PreservesReasoningEffortPolicy(t *testi
|
||||
|
||||
require.NotNil(t, roundTrip)
|
||||
require.NotNil(t, roundTrip.Group)
|
||||
require.Equal(t, PlatformComposite, roundTrip.Group.Platform)
|
||||
require.Equal(t, "medium", roundTrip.Group.MaxReasoningEffort)
|
||||
require.Equal(t, apiKey.Group.ReasoningEffortMappings, roundTrip.Group.ReasoningEffortMappings)
|
||||
}
|
||||
|
||||
@@ -115,15 +115,17 @@ func TestShouldCreateAccount(t *testing.T) {
|
||||
|
||||
func TestReconcileCRSUpstreamBillingProbeExtra(t *testing.T) {
|
||||
remote := map[string]any{
|
||||
"crs_account_id": "remote-1",
|
||||
UpstreamBillingProbeEnabledExtraKey: true,
|
||||
UpstreamBillingProbeExtraKey: map[string]any{"status": "remote"},
|
||||
"crs_account_id": "remote-1",
|
||||
UpstreamBillingProbeEnabledExtraKey: true,
|
||||
UpstreamBillingRateSyncEnabledExtraKey: true,
|
||||
UpstreamBillingProbeExtraKey: map[string]any{"status": "remote"},
|
||||
}
|
||||
|
||||
t.Run("create drops remote managed fields", func(t *testing.T) {
|
||||
extra := mergeMap(nil, remote)
|
||||
reconcileCRSUpstreamBillingProbeExtra(nil, PlatformOpenAI, AccountTypeAPIKey, map[string]any{"api_key": "new"}, extra)
|
||||
require.NotContains(t, extra, UpstreamBillingProbeEnabledExtraKey)
|
||||
require.NotContains(t, extra, UpstreamBillingRateSyncEnabledExtraKey)
|
||||
require.NotContains(t, extra, UpstreamBillingProbeExtraKey)
|
||||
})
|
||||
|
||||
@@ -132,8 +134,9 @@ func TestReconcileCRSUpstreamBillingProbeExtra(t *testing.T) {
|
||||
Type: AccountTypeAPIKey,
|
||||
Credentials: map[string]any{"api_key": "local", "base_url": "http://127.0.0.1:8080"},
|
||||
Extra: map[string]any{
|
||||
UpstreamBillingProbeEnabledExtraKey: false,
|
||||
UpstreamBillingProbeExtraKey: map[string]any{"status": "local"},
|
||||
UpstreamBillingProbeEnabledExtraKey: false,
|
||||
UpstreamBillingRateSyncEnabledExtraKey: false,
|
||||
UpstreamBillingProbeExtraKey: map[string]any{"status": "local"},
|
||||
},
|
||||
}
|
||||
|
||||
@@ -141,31 +144,62 @@ func TestReconcileCRSUpstreamBillingProbeExtra(t *testing.T) {
|
||||
extra := mergeMap(existing.Extra, remote)
|
||||
reconcileCRSUpstreamBillingProbeExtra(existing, existing.Platform, existing.Type, mergeMap(existing.Credentials, nil), extra)
|
||||
require.Equal(t, false, extra[UpstreamBillingProbeEnabledExtraKey])
|
||||
require.Equal(t, false, extra[UpstreamBillingRateSyncEnabledExtraKey])
|
||||
require.Equal(t, map[string]any{"status": "local"}, extra[UpstreamBillingProbeExtraKey])
|
||||
})
|
||||
|
||||
t.Run("same identity preserves enabled rate sync", func(t *testing.T) {
|
||||
enabled := *existing
|
||||
enabled.Extra = mergeMap(existing.Extra, map[string]any{
|
||||
UpstreamBillingProbeEnabledExtraKey: true,
|
||||
UpstreamBillingRateSyncEnabledExtraKey: true,
|
||||
})
|
||||
extra := mergeMap(enabled.Extra, remote)
|
||||
reconcileCRSUpstreamBillingProbeExtra(&enabled, enabled.Platform, enabled.Type, mergeMap(enabled.Credentials, nil), extra)
|
||||
require.Equal(t, true, extra[UpstreamBillingProbeEnabledExtraKey])
|
||||
require.Equal(t, true, extra[UpstreamBillingRateSyncEnabledExtraKey])
|
||||
})
|
||||
|
||||
t.Run("identity change keeps enabled and clears snapshot", func(t *testing.T) {
|
||||
extra := mergeMap(existing.Extra, remote)
|
||||
reconcileCRSUpstreamBillingProbeExtra(existing, PlatformOpenAI, AccountTypeAPIKey, map[string]any{"api_key": "changed"}, extra)
|
||||
require.Equal(t, false, extra[UpstreamBillingProbeEnabledExtraKey])
|
||||
require.Equal(t, false, extra[UpstreamBillingRateSyncEnabledExtraKey])
|
||||
require.NotContains(t, extra, UpstreamBillingProbeExtraKey)
|
||||
})
|
||||
|
||||
// API-key 平台间切换:探测资格保留(放宽后不再限 OpenAI),开关沿用本地值,
|
||||
// 但平台属于探测身份,快照必须作废。
|
||||
for _, target := range []struct {
|
||||
name string
|
||||
platform string
|
||||
}{
|
||||
{name: "anthropic api key", platform: PlatformAnthropic},
|
||||
{name: "gemini api key", platform: PlatformGemini},
|
||||
} {
|
||||
t.Run(target.name+" keeps enabled and clears snapshot", func(t *testing.T) {
|
||||
extra := mergeMap(existing.Extra, remote)
|
||||
reconcileCRSUpstreamBillingProbeExtra(existing, target.platform, AccountTypeAPIKey, existing.Credentials, extra)
|
||||
require.Equal(t, false, extra[UpstreamBillingProbeEnabledExtraKey])
|
||||
require.Equal(t, false, extra[UpstreamBillingRateSyncEnabledExtraKey])
|
||||
require.NotContains(t, extra, UpstreamBillingProbeExtraKey)
|
||||
})
|
||||
}
|
||||
|
||||
for _, target := range []struct {
|
||||
name string
|
||||
platform string
|
||||
typeName string
|
||||
}{
|
||||
{name: "anthropic oauth", platform: PlatformAnthropic, typeName: AccountTypeOAuth},
|
||||
{name: "anthropic api key", platform: PlatformAnthropic, typeName: AccountTypeAPIKey},
|
||||
{name: "openai oauth", platform: PlatformOpenAI, typeName: AccountTypeOAuth},
|
||||
{name: "gemini oauth", platform: PlatformGemini, typeName: AccountTypeOAuth},
|
||||
{name: "gemini api key", platform: PlatformGemini, typeName: AccountTypeAPIKey},
|
||||
} {
|
||||
t.Run(target.name+" removes inapplicable state", func(t *testing.T) {
|
||||
extra := mergeMap(existing.Extra, remote)
|
||||
reconcileCRSUpstreamBillingProbeExtra(existing, target.platform, target.typeName, existing.Credentials, extra)
|
||||
require.NotContains(t, extra, UpstreamBillingProbeEnabledExtraKey)
|
||||
require.NotContains(t, extra, UpstreamBillingRateSyncEnabledExtraKey)
|
||||
require.NotContains(t, extra, UpstreamBillingProbeExtraKey)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1162,6 +1162,7 @@ func reconcileCRSUpstreamBillingProbeExtra(
|
||||
) {
|
||||
for _, key := range []string{
|
||||
UpstreamBillingProbeEnabledExtraKey,
|
||||
UpstreamBillingRateSyncEnabledExtraKey,
|
||||
UpstreamBillingProbeExtraKey,
|
||||
OllamaCloudUsageSessionExtraKey,
|
||||
OllamaCloudUsageAutoRefreshExtraKey,
|
||||
@@ -1173,9 +1174,14 @@ func reconcileCRSUpstreamBillingProbeExtra(
|
||||
return
|
||||
}
|
||||
target := &Account{Platform: targetPlatform, Type: targetType, Credentials: targetCredentials}
|
||||
if targetPlatform == PlatformOpenAI && targetType == AccountTypeAPIKey {
|
||||
if IsUpstreamBillingProbeIdentity(targetPlatform, targetType) {
|
||||
probeEnabled := false
|
||||
if enabled, ok := existing.Extra[UpstreamBillingProbeEnabledExtraKey]; ok {
|
||||
extra[UpstreamBillingProbeEnabledExtraKey] = enabled
|
||||
probeEnabled, _ = enabled.(bool)
|
||||
}
|
||||
if enabled, ok := existing.Extra[UpstreamBillingRateSyncEnabledExtraKey].(bool); ok {
|
||||
extra[UpstreamBillingRateSyncEnabledExtraKey] = enabled && probeEnabled
|
||||
}
|
||||
if reflect.DeepEqual(upstreamBillingProbeIdentity(existing), upstreamBillingProbeIdentity(target)) {
|
||||
if snapshot, ok := existing.Extra[UpstreamBillingProbeExtraKey]; ok {
|
||||
|
||||
@@ -526,6 +526,16 @@ const (
|
||||
// 当客户端 UA 被识别为浏览器(Chrome/Firefox/Safari/Edge 等)时,转发给 OpenAI 上游前会替换为此值,
|
||||
// 用于避免 Cloudflare 对浏览器型 UA 的质询拦截。
|
||||
SettingKeyOpenAICodexUserAgent = "openai_codex_user_agent"
|
||||
// SettingKeyOpenAICodexClientVersion 网关对 ChatGPT 上游声明的 Codex 客户端版本号(管理员覆写)。
|
||||
// 空值表示跟随自动同步值;自动同步也没有结果时回退到内置常量。
|
||||
// 上游在容量紧张时按客户端身份分优先级降载,陈旧版本会被优先丢弃,故该值需保持跟随官方发布。
|
||||
SettingKeyOpenAICodexClientVersion = "openai_codex_client_version"
|
||||
// SettingKeyOpenAICodexClientVersionSynced 自动同步任务写入的官方 Codex 最新稳定版版本号。
|
||||
// 由 OpenAICodexVersionSyncService 独占写入,面板只读展示;管理员覆写请用
|
||||
// SettingKeyOpenAICodexClientVersion。
|
||||
SettingKeyOpenAICodexClientVersionSynced = "openai_codex_client_version_synced"
|
||||
// SettingKeyOpenAICodexVersionAutoSyncEnabled 是否启用 Codex 客户端版本号自动同步(默认 true)。
|
||||
SettingKeyOpenAICodexVersionAutoSyncEnabled = "openai_codex_version_auto_sync_enabled"
|
||||
// SettingKeyOpenAIAllowClaudeCodeCodexPlugin 已废弃:历史全局开关只作为升级迁移输入读取。
|
||||
// 迁移后等价规则写入 SettingKeyCodexCLIOnlyWhitelist,不再参与运行时判定。
|
||||
SettingKeyOpenAIAllowClaudeCodeCodexPlugin = "openai_allow_claude_code_codex_plugin"
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey"
|
||||
)
|
||||
|
||||
// withGatewayProfitControlGate installs the gate only for explicitly marked
|
||||
// token requests. This keeps media, metadata, and models-list paths outside
|
||||
// the profit-control surface by construction.
|
||||
func (s *GatewayService) withGatewayProfitControlGate(ctx context.Context, groupID *int64) context.Context {
|
||||
if _, ok := gatewayTokenRequestPricingAtFromContext(ctx); !ok || groupID == nil || *groupID <= 0 {
|
||||
return ctx
|
||||
}
|
||||
if existing, ok := ctx.Value(openAIProfitControlGateCtxKey{}).(*openAIProfitControlGate); ok && existing != nil && existing.groupID == *groupID {
|
||||
return ctx
|
||||
}
|
||||
|
||||
group, err := s.resolveProfitControlGroup(ctx, *groupID)
|
||||
if err != nil {
|
||||
slog.Warn("profit_control_group_load_failed", "group_id", *groupID, "error", err)
|
||||
return s.clearForeignProfitControlGate(ctx, groupID)
|
||||
}
|
||||
if group == nil || !group.ProfitControlEnabled || !profitControlPlatformSupported(group.Platform) {
|
||||
return s.clearForeignProfitControlGate(ctx, groupID)
|
||||
}
|
||||
|
||||
pricingAt, _ := gatewayTokenRequestPricingAtFromContext(ctx)
|
||||
billingGroup := gatewayTokenRequestBillingGroupFromContext(ctx)
|
||||
if billingGroup == nil {
|
||||
if ctxGroup, ok := ctx.Value(ctxkey.Group).(*Group); ok && IsGroupContextValid(ctxGroup) {
|
||||
billingGroup = ctxGroup
|
||||
} else {
|
||||
billingGroup = group
|
||||
}
|
||||
}
|
||||
|
||||
downstream := billingGroup.RateMultiplier
|
||||
if userID, _ := ctx.Value(ctxkey.UserID).(int64); userID > 0 {
|
||||
downstream = s.ResolveUserGroupRateMultiplier(ctx, userID, billingGroup.ID, billingGroup.RateMultiplier)
|
||||
}
|
||||
downstream *= billingGroup.PeakMultiplierAt(pricingAt)
|
||||
threshold := clampProfitControlThreshold(downstream * (1 - group.ProfitMinMargin - group.ProfitSafetyBuffer))
|
||||
|
||||
gate := &openAIProfitControlGate{
|
||||
groupID: group.ID,
|
||||
platform: group.Platform,
|
||||
threshold: threshold,
|
||||
pricingAt: pricingAt,
|
||||
}
|
||||
openAIProfitControlObserverInstance.recordInstall(gate.groupID, gate.platform, gate.threshold)
|
||||
return context.WithValue(ctx, openAIProfitControlGateCtxKey{}, gate)
|
||||
}
|
||||
|
||||
func (s *GatewayService) clearForeignProfitControlGate(ctx context.Context, groupID *int64) context.Context {
|
||||
existing, ok := ctx.Value(openAIProfitControlGateCtxKey{}).(*openAIProfitControlGate)
|
||||
if !ok || existing == nil || groupID == nil || existing.groupID == *groupID {
|
||||
return ctx
|
||||
}
|
||||
return context.WithValue(ctx, openAIProfitControlGateCtxKey{}, (*openAIProfitControlGate)(nil))
|
||||
}
|
||||
|
||||
func (s *GatewayService) resolveProfitControlGroup(ctx context.Context, groupID int64) (*Group, error) {
|
||||
if group, ok := ctx.Value(ctxkey.Group).(*Group); ok && IsGroupContextValid(group) && group.ID == groupID {
|
||||
return group, nil
|
||||
}
|
||||
if s.schedulerSnapshot != nil {
|
||||
// Lite 读取:门只用平台/倍率/利润/高峰字段,不需要账号计数聚合。
|
||||
return s.schedulerSnapshot.GetGroupByIDLite(ctx, groupID)
|
||||
}
|
||||
return s.resolveGroupByID(ctx, groupID)
|
||||
}
|
||||
|
||||
// GatewayProfitControlVetoLatest performs the terminal post-slot check against
|
||||
// the latest scheduler snapshot. Snapshot read failures are deliberately
|
||||
// fail-open to preserve availability, but are observable.
|
||||
func (s *GatewayService) GatewayProfitControlVetoLatest(ctx context.Context, selected *Account) (*Account, bool, string) {
|
||||
return profitControlVetoLatest(ctx, selected, s.schedulerSnapshot)
|
||||
}
|
||||
|
||||
func profitControlVetoLatest(ctx context.Context, selected *Account, snapshot *SchedulerSnapshotService) (*Account, bool, string) {
|
||||
gate, _ := ctx.Value(openAIProfitControlGateCtxKey{}).(*openAIProfitControlGate)
|
||||
if gate == nil || selected == nil {
|
||||
return selected, false, ""
|
||||
}
|
||||
latest := selected
|
||||
if snapshot != nil {
|
||||
refreshed, err := snapshot.GetAccount(ctx, selected.ID)
|
||||
if err != nil || refreshed == nil {
|
||||
slog.Warn("profit_control_account_refresh_failed", "group_id", gate.groupID, "platform", gate.platform, "account_id", selected.ID, "error", err)
|
||||
openAIProfitControlObserverInstance.recordRefreshFailure(gate.groupID, gate.platform, gate.threshold)
|
||||
} else if !refreshed.UpdatedAt.Before(selected.UpdatedAt) {
|
||||
// 选号路径可能已做过 DB recheck,selected 比缓存快照更新鲜;只有
|
||||
// 快照不落后时才替换,避免终检把新鲜账号换回较旧的缓存对象。
|
||||
latest = refreshed
|
||||
}
|
||||
}
|
||||
vetoed, reason := openAIProfitControlVetoReason(ctx, latest)
|
||||
return latest, vetoed, reason
|
||||
}
|
||||
|
||||
func (s *GatewayService) isGatewayAccountProfitEligible(ctx context.Context, account *Account) bool {
|
||||
vetoed, _ := openAIProfitControlVetoReason(ctx, account)
|
||||
return !vetoed
|
||||
}
|
||||
|
||||
func gatewayProfitControlGateActive(ctx context.Context) bool {
|
||||
gate, _ := ctx.Value(openAIProfitControlGateCtxKey{}).(*openAIProfitControlGate)
|
||||
return gate != nil
|
||||
}
|
||||
@@ -0,0 +1,477 @@
|
||||
//go:build unit
|
||||
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func gatewayProfitTestGroup(id int64, platform string) *Group {
|
||||
return &Group{
|
||||
ID: id,
|
||||
Name: "profit-" + platform,
|
||||
Platform: platform,
|
||||
Status: StatusActive,
|
||||
Hydrated: true,
|
||||
RateMultiplier: 0.5,
|
||||
SubscriptionType: SubscriptionTypeStandard,
|
||||
ProfitControlEnabled: true,
|
||||
ProfitMinMargin: 0,
|
||||
ProfitSafetyBuffer: 0,
|
||||
}
|
||||
}
|
||||
|
||||
func gatewayProfitTestContext(group *Group) context.Context {
|
||||
ctx := context.WithValue(context.Background(), ctxkey.Group, group)
|
||||
ctx, _ = WithGatewayTokenRequestPricing(ctx)
|
||||
return ctx
|
||||
}
|
||||
|
||||
func gatewayProfitTestAccount(id int64, platform string, rate float64, groupID int64) Account {
|
||||
return Account{
|
||||
ID: id,
|
||||
Name: "account",
|
||||
Platform: platform,
|
||||
Type: AccountTypeAPIKey,
|
||||
Status: StatusActive,
|
||||
Schedulable: true,
|
||||
Concurrency: 2,
|
||||
Priority: 1,
|
||||
RateMultiplier: &rate,
|
||||
AccountGroups: []AccountGroup{{AccountID: id, GroupID: groupID}},
|
||||
GroupIDs: []int64{groupID},
|
||||
}
|
||||
}
|
||||
|
||||
func TestGatewayProfitControlInstallsForFivePlatformsOnlyOnTokenRequests(t *testing.T) {
|
||||
for _, platform := range []string{
|
||||
PlatformOpenAI,
|
||||
PlatformAnthropic,
|
||||
PlatformGemini,
|
||||
PlatformGrok,
|
||||
PlatformAntigravity,
|
||||
} {
|
||||
t.Run(platform, func(t *testing.T) {
|
||||
group := gatewayProfitTestGroup(101, platform)
|
||||
groupID := group.ID
|
||||
svc := &GatewayService{}
|
||||
|
||||
tokenCtx := svc.withGatewayProfitControlGate(gatewayProfitTestContext(group), &groupID)
|
||||
gate, _ := tokenCtx.Value(openAIProfitControlGateCtxKey{}).(*openAIProfitControlGate)
|
||||
require.NotNil(t, gate)
|
||||
require.Equal(t, platform, gate.platform)
|
||||
require.InDelta(t, 0.5, gate.threshold, 1e-12)
|
||||
|
||||
metadataCtx := context.WithValue(context.Background(), ctxkey.Group, group)
|
||||
metadataCtx = svc.withGatewayProfitControlGate(metadataCtx, &groupID)
|
||||
gate, _ = metadataCtx.Value(openAIProfitControlGateCtxKey{}).(*openAIProfitControlGate)
|
||||
require.Nil(t, gate, "未显式标记为 token 请求的入口不得装门")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGatewayProfitControlCompositeBillingUsesScheduledMemberConfig(t *testing.T) {
|
||||
billingGroup := &Group{
|
||||
ID: 201,
|
||||
Platform: PlatformComposite,
|
||||
Status: StatusActive,
|
||||
Hydrated: true,
|
||||
RateMultiplier: 0.4,
|
||||
SubscriptionType: SubscriptionTypeStandard,
|
||||
}
|
||||
memberGroup := gatewayProfitTestGroup(202, PlatformAnthropic)
|
||||
memberGroup.RateMultiplier = 99
|
||||
memberGroup.ProfitMinMargin = 0.25
|
||||
|
||||
ctx := context.WithValue(context.Background(), ctxkey.Group, billingGroup)
|
||||
ctx, pricingAt := WithGatewayTokenRequestPricing(ctx)
|
||||
svc := &GatewayService{
|
||||
schedulerSnapshot: NewSchedulerSnapshotService(
|
||||
nil,
|
||||
nil,
|
||||
nil,
|
||||
profitControlGroupRepo{group: memberGroup},
|
||||
nil,
|
||||
),
|
||||
}
|
||||
ctx = svc.withGatewayProfitControlGate(ctx, &memberGroup.ID)
|
||||
gate, _ := ctx.Value(openAIProfitControlGateCtxKey{}).(*openAIProfitControlGate)
|
||||
require.NotNil(t, gate)
|
||||
require.Equal(t, memberGroup.ID, gate.groupID)
|
||||
require.Equal(t, PlatformAnthropic, gate.platform)
|
||||
require.Equal(t, pricingAt, gate.pricingAt)
|
||||
require.InDelta(t, 0.4*(1-0.25), gate.threshold, 1e-12, "D 必须取 composite 计费父分组,margin 取被调度成员分组")
|
||||
}
|
||||
|
||||
func TestGatewayProfitControlGroupLoadFailureClearsForeignGate(t *testing.T) {
|
||||
billingGroup := &Group{
|
||||
ID: 211,
|
||||
Platform: PlatformComposite,
|
||||
Status: StatusActive,
|
||||
Hydrated: true,
|
||||
RateMultiplier: 0.4,
|
||||
SubscriptionType: SubscriptionTypeStandard,
|
||||
}
|
||||
targetGroupID := int64(212)
|
||||
ctx := gatewayProfitTestContext(billingGroup)
|
||||
ctx = context.WithValue(ctx, openAIProfitControlGateCtxKey{}, &openAIProfitControlGate{
|
||||
groupID: 210,
|
||||
platform: PlatformAnthropic,
|
||||
threshold: 0.1,
|
||||
})
|
||||
svc := &GatewayService{
|
||||
schedulerSnapshot: NewSchedulerSnapshotService(
|
||||
nil,
|
||||
nil,
|
||||
nil,
|
||||
profitControlFailingGroupRepo{},
|
||||
nil,
|
||||
),
|
||||
}
|
||||
|
||||
ctx = svc.withGatewayProfitControlGate(ctx, &targetGroupID)
|
||||
gate, ok := ctx.Value(openAIProfitControlGateCtxKey{}).(*openAIProfitControlGate)
|
||||
require.True(t, ok)
|
||||
require.Nil(t, gate, "加载新分组失败时必须清除其他分组遗留的门")
|
||||
|
||||
account := gatewayProfitTestAccount(213, PlatformAnthropic, 0.8, targetGroupID)
|
||||
require.True(t, svc.isGatewayAccountProfitEligible(ctx, &account), "配置读取失败按既定语义 fail-open")
|
||||
}
|
||||
|
||||
type profitControlFailingGroupRepo struct {
|
||||
GroupRepository
|
||||
}
|
||||
|
||||
func (profitControlFailingGroupRepo) GetByIDLite(context.Context, int64) (*Group, error) {
|
||||
return nil, errors.New("group cache unavailable")
|
||||
}
|
||||
|
||||
// 见 profitControlGroupRepo.GetByID:利润门必须走不带账号计数聚合的 lite 读取。
|
||||
func (profitControlFailingGroupRepo) GetByID(context.Context, int64) (*Group, error) {
|
||||
panic("profit control gate must read groups via GetByIDLite (no account-count aggregation)")
|
||||
}
|
||||
|
||||
func TestGatewayProfitControlLegacyMixedAndRoutedSelection(t *testing.T) {
|
||||
t.Run("legacy single-platform selection", func(t *testing.T) {
|
||||
group := gatewayProfitTestGroup(111, PlatformGrok)
|
||||
cheap := gatewayProfitTestAccount(1, PlatformGrok, 0.2, group.ID)
|
||||
expensive := gatewayProfitTestAccount(2, PlatformGrok, 0.8, group.ID)
|
||||
repo := &mockAccountRepoForPlatform{
|
||||
accounts: []Account{expensive, cheap},
|
||||
accountsByID: map[int64]*Account{cheap.ID: &cheap, expensive.ID: &expensive},
|
||||
}
|
||||
svc := &GatewayService{
|
||||
accountRepo: repo,
|
||||
cache: &mockGatewayCacheForPlatform{},
|
||||
cfg: testConfig(),
|
||||
}
|
||||
|
||||
selected, err := svc.SelectAccountForModelWithExclusions(
|
||||
gatewayProfitTestContext(group), &group.ID, "", "", nil,
|
||||
)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, cheap.ID, selected.ID)
|
||||
|
||||
_, err = svc.SelectAccountForModelWithExclusions(
|
||||
gatewayProfitTestContext(group), &group.ID, "", "", map[int64]struct{}{cheap.ID: {}},
|
||||
)
|
||||
require.Error(t, err)
|
||||
require.ErrorIs(t, err, ErrNoAvailableAccounts)
|
||||
})
|
||||
|
||||
t.Run("mixed routing filters the routed account", func(t *testing.T) {
|
||||
group := gatewayProfitTestGroup(112, PlatformAnthropic)
|
||||
group.ModelRoutingEnabled = true
|
||||
group.ModelRouting = map[string][]int64{"claude-test": {2, 1}}
|
||||
cheap := gatewayProfitTestAccount(1, PlatformAntigravity, 0.2, group.ID)
|
||||
cheap.Extra = map[string]any{"mixed_scheduling": true}
|
||||
cheap.Credentials = map[string]any{"model_mapping": map[string]any{"claude-test": "claude-test"}}
|
||||
expensive := gatewayProfitTestAccount(2, PlatformAnthropic, 0.8, group.ID)
|
||||
repo := &mockAccountRepoForPlatform{
|
||||
accounts: []Account{expensive, cheap},
|
||||
accountsByID: map[int64]*Account{cheap.ID: &cheap, expensive.ID: &expensive},
|
||||
}
|
||||
svc := &GatewayService{
|
||||
accountRepo: repo,
|
||||
cache: &mockGatewayCacheForPlatform{},
|
||||
cfg: testConfig(),
|
||||
}
|
||||
|
||||
selected, err := svc.SelectAccountForModelWithExclusions(
|
||||
gatewayProfitTestContext(group), &group.ID, "", "claude-test", nil,
|
||||
)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, cheap.ID, selected.ID)
|
||||
})
|
||||
}
|
||||
|
||||
func TestGatewayProfitControlLoadAwareSelectionAndFailover(t *testing.T) {
|
||||
group := gatewayProfitTestGroup(121, PlatformGrok)
|
||||
cheap := gatewayProfitTestAccount(1, PlatformGrok, 0.2, group.ID)
|
||||
expensive := gatewayProfitTestAccount(2, PlatformGrok, 0.8, group.ID)
|
||||
repo := &mockAccountRepoForPlatform{
|
||||
accounts: []Account{expensive, cheap},
|
||||
accountsByID: map[int64]*Account{cheap.ID: &cheap, expensive.ID: &expensive},
|
||||
}
|
||||
cfg := &config.Config{RunMode: config.RunModeStandard}
|
||||
cfg.Gateway.Scheduling.LoadBatchEnabled = true
|
||||
svc := &GatewayService{
|
||||
accountRepo: repo,
|
||||
cache: &mockGatewayCacheForPlatform{},
|
||||
cfg: cfg,
|
||||
concurrencyService: NewConcurrencyService(stubConcurrencyCache{}),
|
||||
}
|
||||
|
||||
result, err := svc.SelectAccountWithLoadAwareness(
|
||||
gatewayProfitTestContext(group), &group.ID, "", "", nil, "", 0,
|
||||
)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, result)
|
||||
require.Equal(t, cheap.ID, result.Account.ID)
|
||||
if result.ReleaseFunc != nil {
|
||||
result.ReleaseFunc()
|
||||
}
|
||||
|
||||
result, err = svc.SelectAccountWithLoadAwareness(
|
||||
gatewayProfitTestContext(group),
|
||||
&group.ID,
|
||||
"",
|
||||
"",
|
||||
map[int64]struct{}{cheap.ID: {}},
|
||||
"",
|
||||
0,
|
||||
)
|
||||
require.Nil(t, result)
|
||||
require.Error(t, err)
|
||||
require.ErrorIs(t, err, ErrNoAvailableAccounts)
|
||||
}
|
||||
|
||||
func TestGatewayProfitControlStickyVetoKeepsBindingUntilRateRecovers(t *testing.T) {
|
||||
group := gatewayProfitTestGroup(131, PlatformAnthropic)
|
||||
expensive := gatewayProfitTestAccount(1, PlatformAnthropic, 0.8, group.ID)
|
||||
cheap := gatewayProfitTestAccount(2, PlatformAnthropic, 0.2, group.ID)
|
||||
repo := &mockAccountRepoForPlatform{
|
||||
accounts: []Account{expensive, cheap},
|
||||
accountsByID: map[int64]*Account{expensive.ID: &expensive, cheap.ID: &cheap},
|
||||
}
|
||||
cache := &mockGatewayCacheForPlatform{
|
||||
sessionBindings: map[string]int64{"sticky-profit": expensive.ID},
|
||||
}
|
||||
svc := &GatewayService{
|
||||
accountRepo: repo,
|
||||
cache: cache,
|
||||
cfg: testConfig(),
|
||||
}
|
||||
ctx := gatewayProfitTestContext(group)
|
||||
|
||||
selected, err := svc.SelectAccountForModelWithExclusions(ctx, &group.ID, "sticky-profit", "", nil)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, cheap.ID, selected.ID)
|
||||
require.Equal(t, expensive.ID, cache.sessionBindings["sticky-profit"], "候选过滤不得覆盖旧粘性绑定")
|
||||
|
||||
require.NoError(t, svc.BindStickySessionAfterProfitAdmission(
|
||||
svc.withGatewayProfitControlGate(ctx, &group.ID),
|
||||
&group.ID,
|
||||
"sticky-profit",
|
||||
cheap.ID,
|
||||
))
|
||||
require.Equal(t, expensive.ID, cache.sessionBindings["sticky-profit"], "终检通过的 fallback 账号也不得覆盖旧绑定")
|
||||
require.Zero(t, cache.deletedSessions["sticky-profit"])
|
||||
|
||||
recovered := expensive
|
||||
recoveredRate := 0.2
|
||||
recovered.RateMultiplier = &recoveredRate
|
||||
repo.accounts[0] = recovered
|
||||
repo.accountsByID[recovered.ID] = &repo.accounts[0]
|
||||
|
||||
selected, err = svc.SelectAccountForModelWithExclusions(ctx, &group.ID, "sticky-profit", "", nil)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, recovered.ID, selected.ID, "倍率恢复后应重新命中原粘性账号")
|
||||
require.Zero(t, cache.deletedSessions["sticky-profit"])
|
||||
}
|
||||
|
||||
type gatewayProfitSnapshotCache struct {
|
||||
SchedulerCache
|
||||
account *Account
|
||||
err error
|
||||
}
|
||||
|
||||
func (c *gatewayProfitSnapshotCache) GetAccount(context.Context, int64) (*Account, error) {
|
||||
return c.account, c.err
|
||||
}
|
||||
|
||||
type gatewayProfitAccountRepo struct {
|
||||
AccountRepository
|
||||
account *Account
|
||||
err error
|
||||
}
|
||||
|
||||
func (r gatewayProfitAccountRepo) GetByID(context.Context, int64) (*Account, error) {
|
||||
return r.account, r.err
|
||||
}
|
||||
|
||||
func TestGatewayProfitControlTerminalRefreshUsesReplacementObject(t *testing.T) {
|
||||
selected := gatewayProfitTestAccount(141, PlatformGemini, 0.2, 1)
|
||||
replacement := selected
|
||||
expensiveRate := 0.8
|
||||
replacement.RateMultiplier = &expensiveRate
|
||||
|
||||
snapshot := NewSchedulerSnapshotService(
|
||||
&gatewayProfitSnapshotCache{account: &replacement},
|
||||
nil,
|
||||
gatewayProfitAccountRepo{},
|
||||
nil,
|
||||
nil,
|
||||
)
|
||||
ctx := context.WithValue(context.Background(), openAIProfitControlGateCtxKey{}, &openAIProfitControlGate{
|
||||
groupID: 1,
|
||||
platform: PlatformGemini,
|
||||
threshold: 0.5,
|
||||
})
|
||||
|
||||
latest, vetoed, reason := profitControlVetoLatest(ctx, &selected, snapshot)
|
||||
require.Same(t, &replacement, latest)
|
||||
require.True(t, vetoed)
|
||||
require.Equal(t, openAIProfitFilterReasonThreshold, reason)
|
||||
require.InDelta(t, 0.2, *selected.RateMultiplier, 1e-12, "测试必须替换缓存对象,不能原地修改旧指针")
|
||||
}
|
||||
|
||||
func TestGatewayProfitControlTerminalRefreshFallsBackFromCacheToDatabase(t *testing.T) {
|
||||
selected := gatewayProfitTestAccount(145, PlatformAnthropic, 0.2, 1)
|
||||
replacement := selected
|
||||
expensiveRate := 0.8
|
||||
replacement.RateMultiplier = &expensiveRate
|
||||
|
||||
snapshot := NewSchedulerSnapshotService(
|
||||
&gatewayProfitSnapshotCache{err: errors.New("cache unavailable")},
|
||||
nil,
|
||||
gatewayProfitAccountRepo{account: &replacement},
|
||||
nil,
|
||||
nil,
|
||||
)
|
||||
ctx := context.WithValue(context.Background(), openAIProfitControlGateCtxKey{}, &openAIProfitControlGate{
|
||||
groupID: 1,
|
||||
platform: PlatformAnthropic,
|
||||
threshold: 0.5,
|
||||
})
|
||||
|
||||
latest, vetoed, reason := profitControlVetoLatest(ctx, &selected, snapshot)
|
||||
require.Same(t, &replacement, latest)
|
||||
require.True(t, vetoed, "缓存读取失败时必须继续从数据库重读,不能直接使用选号旧对象")
|
||||
require.Equal(t, openAIProfitFilterReasonThreshold, reason)
|
||||
}
|
||||
|
||||
func TestGatewayProfitControlTerminalRefreshFailureFallsBackToSelectedObject(t *testing.T) {
|
||||
selected := gatewayProfitTestAccount(151, PlatformAntigravity, 0.2, 1)
|
||||
snapshot := NewSchedulerSnapshotService(
|
||||
&gatewayProfitSnapshotCache{err: errors.New("cache unavailable")},
|
||||
nil,
|
||||
gatewayProfitAccountRepo{err: errors.New("database unavailable")},
|
||||
nil,
|
||||
nil,
|
||||
)
|
||||
ctx := context.WithValue(context.Background(), openAIProfitControlGateCtxKey{}, &openAIProfitControlGate{
|
||||
groupID: 1,
|
||||
platform: PlatformAntigravity,
|
||||
threshold: 0.5,
|
||||
})
|
||||
|
||||
latest, vetoed, reason := profitControlVetoLatest(ctx, &selected, snapshot)
|
||||
require.Same(t, &selected, latest)
|
||||
require.False(t, vetoed)
|
||||
require.Empty(t, reason)
|
||||
}
|
||||
|
||||
// 选号结果携带门:门安装在调度栈局部 ctx 上,handler 必须经
|
||||
// ContextWithSelectionProfitGate 重放后终检与准入后绑定才可见(评审修复回归)。
|
||||
func TestGatewayProfitControlSelectionCarriesGateToHandlerContext(t *testing.T) {
|
||||
group := gatewayProfitTestGroup(1, PlatformAnthropic)
|
||||
svc := &GatewayService{}
|
||||
expensive := gatewayProfitTestAccount(161, PlatformAnthropic, 0.9, group.ID)
|
||||
|
||||
gateCtx := svc.withGatewayProfitControlGate(gatewayProfitTestContext(group), &group.ID)
|
||||
selection, err := svc.newSelectionResult(gateCtx, &expensive, true, nil, nil)
|
||||
require.NoError(t, err)
|
||||
require.True(t, selection.ProfitGateActive(), "选号结果必须携带调度栈内生效的门")
|
||||
|
||||
// 修复前的缺陷形态:handler 原始 ctx 不含门,终检退化为空操作。
|
||||
_, vetoed, _ := svc.GatewayProfitControlVetoLatest(context.Background(), &expensive)
|
||||
require.False(t, vetoed, "对照组:不重放门时终检确实看不到门")
|
||||
|
||||
handlerCtx := ContextWithSelectionProfitGate(context.Background(), selection)
|
||||
latest, vetoed, reason := svc.GatewayProfitControlVetoLatest(handlerCtx, &expensive)
|
||||
require.True(t, vetoed, "重放门后终检必须真实生效")
|
||||
require.Equal(t, openAIProfitFilterReasonThreshold, reason)
|
||||
require.NotNil(t, latest)
|
||||
|
||||
// 无门选号不携带门,重放为无操作。
|
||||
plain, err := svc.newSelectionResult(context.Background(), &expensive, true, nil, nil)
|
||||
require.NoError(t, err)
|
||||
require.False(t, plain.ProfitGateActive())
|
||||
require.Equal(t, context.Background(), ContextWithSelectionProfitGate(context.Background(), plain))
|
||||
}
|
||||
|
||||
// 生图意图不关门(H1/H2 回归锚点):/v1/responses 混合请求即使带生图声明,
|
||||
// token 定价上下文照常装配,共享门照常安装并否决越线账号。
|
||||
func TestGatewayProfitControlImageIntentDoesNotDisableGate(t *testing.T) {
|
||||
group := gatewayProfitTestGroup(2, PlatformAnthropic)
|
||||
svc := &GatewayService{}
|
||||
expensive := gatewayProfitTestAccount(162, PlatformAnthropic, 0.9, group.ID)
|
||||
|
||||
ctx := gatewayProfitTestContext(group)
|
||||
ctx = WithOpenAIImageGenerationIntent(ctx)
|
||||
gateCtx := svc.withGatewayProfitControlGate(ctx, &group.ID)
|
||||
require.False(t, svc.isGatewayAccountProfitEligible(gateCtx, &expensive),
|
||||
"请求体里的生图声明(含被动 image_gen namespace)不得关闭利润门")
|
||||
}
|
||||
|
||||
// 无门时准入后绑定回退官方 eager 语义;门下读失败保守不写(评审 M-Bind 回归)。
|
||||
func TestGatewayProfitControlAfterAdmissionBindSemantics(t *testing.T) {
|
||||
groupID := int64(3)
|
||||
expensiveID := int64(171)
|
||||
cheapID := int64(172)
|
||||
|
||||
t.Run("eager without gate", func(t *testing.T) {
|
||||
cache := &mockGatewayCacheForPlatform{sessionBindings: map[string]int64{"s": expensiveID}}
|
||||
svc := &GatewayService{cache: cache}
|
||||
require.NoError(t, svc.BindStickySessionAfterProfitAdmission(context.Background(), &groupID, "s", cheapID))
|
||||
require.Equal(t, cheapID, cache.sessionBindings["s"], "无门时保持既有 eager 绑定行为")
|
||||
})
|
||||
|
||||
t.Run("gated read failure is conservative", func(t *testing.T) {
|
||||
// mock 的 miss 返回非 sentinel 错误,等价于 Redis 读失败:门下保守不写。
|
||||
cache := &mockGatewayCacheForPlatform{sessionBindings: map[string]int64{}}
|
||||
svc := &GatewayService{cache: cache}
|
||||
gate := &openAIProfitControlGate{groupID: groupID, platform: PlatformAnthropic, threshold: 0.5}
|
||||
gateCtx := context.WithValue(context.Background(), openAIProfitControlGateCtxKey{}, gate)
|
||||
require.NoError(t, svc.BindStickySessionAfterProfitAdmission(gateCtx, &groupID, "absent", cheapID))
|
||||
require.NotContains(t, cache.sessionBindings, "absent")
|
||||
})
|
||||
|
||||
t.Run("gated sentinel miss binds", func(t *testing.T) {
|
||||
cache := &sentinelMissGatewayCache{mockGatewayCacheForPlatform: &mockGatewayCacheForPlatform{sessionBindings: map[string]int64{}}}
|
||||
svc := &GatewayService{cache: cache}
|
||||
gate := &openAIProfitControlGate{groupID: groupID, platform: PlatformAnthropic, threshold: 0.5}
|
||||
gateCtx := context.WithValue(context.Background(), openAIProfitControlGateCtxKey{}, gate)
|
||||
require.NoError(t, svc.BindStickySessionAfterProfitAdmission(gateCtx, &groupID, "fresh", cheapID))
|
||||
require.Equal(t, cheapID, cache.sessionBindings["fresh"], "门下无既有绑定(sentinel miss)应建立粘性")
|
||||
})
|
||||
}
|
||||
|
||||
// sentinelMissGatewayCache 让 miss 返回与真实仓库一致的 ErrStickySessionNotFound。
|
||||
type sentinelMissGatewayCache struct {
|
||||
*mockGatewayCacheForPlatform
|
||||
}
|
||||
|
||||
func (c *sentinelMissGatewayCache) GetSessionAccountID(ctx context.Context, groupID int64, sessionHash string) (int64, error) {
|
||||
if id, ok := c.sessionBindings[sessionHash]; ok {
|
||||
return id, nil
|
||||
}
|
||||
return 0, ErrStickySessionNotFound
|
||||
}
|
||||
@@ -345,6 +345,53 @@ func TestGatewayServiceRecordUsage_PeakRateAffectsTokenModeImageOutputTokens(t *
|
||||
require.InDelta(t, expectedActual, userRepo.lastAmount, 1e-12)
|
||||
}
|
||||
|
||||
func TestGatewayServiceRecordUsage_UsesExplicitPricingAtForPeakRate(t *testing.T) {
|
||||
for _, platform := range []string{PlatformAnthropic, PlatformGemini, PlatformGrok, PlatformAntigravity} {
|
||||
t.Run(platform, func(t *testing.T) {
|
||||
groupID := int64(903)
|
||||
usageRepo := &openAIRecordUsageLogRepoStub{inserted: true}
|
||||
userRepo := &openAIRecordUsageUserRepoStub{}
|
||||
svc := newGatewayRecordUsageServiceForTest(usageRepo, userRepo, &openAIRecordUsageSubRepoStub{})
|
||||
svc.resolver = newOpenAITokenImageChannelPricingResolverForTest(t, groupID, "gemini-image")
|
||||
|
||||
pricingAt := time.Date(2026, time.January, 1, 0, 30, 0, 0, time.UTC)
|
||||
err := svc.RecordUsage(context.Background(), &RecordUsageInput{
|
||||
Result: &ForwardResult{
|
||||
RequestID: "gateway_explicit_pricing_at_" + platform,
|
||||
Model: "gemini-image",
|
||||
ImageCount: 1,
|
||||
Usage: ClaudeUsage{
|
||||
InputTokens: 1000,
|
||||
OutputTokens: 600,
|
||||
ImageOutputTokens: 100,
|
||||
},
|
||||
},
|
||||
APIKey: &APIKey{
|
||||
ID: 803,
|
||||
GroupID: i64p(groupID),
|
||||
Group: &Group{
|
||||
ID: groupID,
|
||||
Platform: platform,
|
||||
RateMultiplier: 1.0,
|
||||
SubscriptionType: SubscriptionTypeSubscription,
|
||||
PeakRateEnabled: true,
|
||||
PeakStart: "00:00",
|
||||
PeakEnd: "01:00",
|
||||
PeakRateMultiplier: 3.0,
|
||||
},
|
||||
},
|
||||
User: &User{ID: 603},
|
||||
Account: &Account{ID: 703, Platform: platform},
|
||||
PricingAt: pricingAt,
|
||||
})
|
||||
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, usageRepo.lastLog)
|
||||
require.Equal(t, 3.0, usageRepo.lastLog.RateMultiplier)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGatewayServiceRecordUsage_UsageLogWriteErrorDoesNotSkipBilling(t *testing.T) {
|
||||
usageRepo := &openAIRecordUsageLogRepoStub{inserted: false, err: MarkUsageLogCreateNotPersisted(context.Canceled)}
|
||||
userRepo := &openAIRecordUsageUserRepoStub{}
|
||||
@@ -530,9 +577,10 @@ func TestGatewayServiceRecordUsage_DroppedUsageLogFallsBackToSyncCreate(t *testi
|
||||
require.NoError(t, usageRepo.lastCtxErr)
|
||||
}
|
||||
|
||||
func TestGatewayServiceRecordUsage_BillingErrorSkipsUsageLogWrite(t *testing.T) {
|
||||
func TestGatewayServiceRecordUsage_BillingErrorWritesUnsettledUsageLog(t *testing.T) {
|
||||
usageRepo := &openAIRecordUsageLogRepoStub{}
|
||||
billingRepo := &openAIRecordUsageBillingRepoStub{err: context.DeadlineExceeded}
|
||||
billingErr := errors.New("billing tx failed")
|
||||
billingRepo := &openAIRecordUsageBillingRepoStub{err: billingErr}
|
||||
userRepo := &openAIRecordUsageUserRepoStub{}
|
||||
subRepo := &openAIRecordUsageSubRepoStub{}
|
||||
svc := newGatewayRecordUsageServiceWithBillingRepoForTest(usageRepo, billingRepo, userRepo, subRepo)
|
||||
@@ -552,9 +600,16 @@ func TestGatewayServiceRecordUsage_BillingErrorSkipsUsageLogWrite(t *testing.T)
|
||||
Account: &Account{ID: 705},
|
||||
})
|
||||
|
||||
require.Error(t, err)
|
||||
require.ErrorIs(t, err, billingErr)
|
||||
require.Equal(t, 1, billingRepo.calls)
|
||||
require.Equal(t, 0, usageRepo.calls)
|
||||
require.Equal(t, 1, usageRepo.calls)
|
||||
require.NotNil(t, usageRepo.lastLog)
|
||||
require.Equal(t, 10, usageRepo.lastLog.InputTokens)
|
||||
require.Equal(t, 6, usageRepo.lastLog.OutputTokens)
|
||||
require.Greater(t, usageRepo.lastLog.InputCost, 0.0)
|
||||
require.Greater(t, usageRepo.lastLog.OutputCost, 0.0)
|
||||
require.Greater(t, usageRepo.lastLog.TotalCost, 0.0)
|
||||
require.Zero(t, usageRepo.lastLog.ActualCost)
|
||||
}
|
||||
|
||||
func TestGatewayServiceRecordUsage_ReasoningEffortPersisted(t *testing.T) {
|
||||
|
||||
Loaded 100 of 202 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user